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
159,339
<p>I'm not sure if the term's actually "Array Addition". </p> <p>I'm trying to understand what does the following line do:</p> <pre><code>int var[2 + 1] = {2, 1}; </code></pre> <p>How is that different from <code>int var[3]</code>?</p> <p>I've been using Java for several years, so I'd appreciate if explained using Java-friendly words.</p> <p>Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here. </p>
[ { "answer_id": 159352, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>How is that different from <code>int var[3]</code>?</p>\n</blockquote>\n\n<p>In no way that I can see.</p>\n" }, { "answer_id": 159355, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 0, "selected": false, "text": "<p>It is any different from <code>int var[3]</code>. The compiler will evaluate <code>2 + 1</code> and replace it with <code>3</code> during compilation.</p>\n" }, { "answer_id": 159363, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "<p><code>var[2 + 1]</code> is not different from <code>var[3]</code>. The author probably wanted to emphasize that var array will hold 2 data items and a terminating zero.</p>\n" }, { "answer_id": 159365, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 0, "selected": false, "text": "<p>It isn't any different; it is <code>int var[3]</code>.</p>\n\n<p>Someone might write their array like this when writing <code>char</code> arrays in order to add space for the terminating <code>0</code>.</p>\n\n<pre><code>char four[4 + 1] = \"1234\"; \n</code></pre>\n\n<p>It doesn't seem to make any sense working with an <code>int</code> array.</p>\n" }, { "answer_id": 159368, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>This creates an array of 3 integers. You're right, there is no difference whether you express it as<br><code>2 + 1</code> or <code>3</code>, as long as the value is compile-time constant.</p>\n\n<p>The right side of the <code>=</code> is an initializer list and it tells the compiler how to fill the array. The first value is <code>2</code>, the second <code>1</code> and the third is <code>0</code> since no more values are specified.</p>\n\n<p>The zero fill only happens when you use an initializer list. Otherwise there is no guarantee of that the array has any particular values.</p>\n\n<p>I've seen this done with char arrays, to emphasize that one <code>char</code> is reserved for a string terminator, but never for an <code>int</code> array.</p>\n" }, { "answer_id": 159385, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": true, "text": "<p>It's not different. C++ allows expressions (even non-constant expressions) in the subscripts of array declarations (with some limitations; anything other than the initial subscript on a multi-dimensional array must be constant).</p>\n\n<pre>int var[]; // illegal\nint var[] = {2,1}; // automatically sized to 2\nint var[3] = {2,1}; // equivalent to {2,1,0}: anything not specified is zero\nint var[3]; // however, with no initializer, nothing is initialized to zero</pre>\n\n<p>Perhaps the code you are reading writes <code>2 + 1</code> instead of <code>3</code> as a reminder that a trailing <code>0</code> is intentional.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24280/" ]
I'm not sure if the term's actually "Array Addition". I'm trying to understand what does the following line do: ``` int var[2 + 1] = {2, 1}; ``` How is that different from `int var[3]`? I've been using Java for several years, so I'd appreciate if explained using Java-friendly words. Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here.
It's not different. C++ allows expressions (even non-constant expressions) in the subscripts of array declarations (with some limitations; anything other than the initial subscript on a multi-dimensional array must be constant). ``` int var[]; // illegal int var[] = {2,1}; // automatically sized to 2 int var[3] = {2,1}; // equivalent to {2,1,0}: anything not specified is zero int var[3]; // however, with no initializer, nothing is initialized to zero ``` Perhaps the code you are reading writes `2 + 1` instead of `3` as a reminder that a trailing `0` is intentional.
159,359
<p>I know we cannot do this at class level but at method level we can always do this. </p> <pre><code>var myList=new List&lt;string&gt; // or something else like this </code></pre> <p>This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression. So compiler doesn't need to do type guessing. (correct me if i am wrong).</p> <p>so question remains WHY NOT at class level while its allowed at method level</p>
[ { "answer_id": 159401, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>The compiler guys just didn't implement the support.</p>\n\n<p>It's entirely compiler magic, and the compiler doesn't actually put something into IL that says \"figure out the type at runtime\", it knows the type and builds it in, so it could've done that for members as well.</p>\n\n<p>It just doesn't.</p>\n\n<p>I'm pretty sure that if you asked an actual compiler guy on the C# compiler team, you'd get something official, but there's no magic happening here and it should be possible to do the same for members fields.</p>\n" }, { "answer_id": 159559, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 1, "selected": false, "text": "<p>The <code>var</code> keyword was invented specific to support anonymous types. You are generally NOT going to declare anonymous types at the class level, and thus it was not implemented.</p>\n\n<p>Your example statement</p>\n\n<pre><code>var myList=new List&lt;string&gt;\n</code></pre>\n\n<p>is not a very good example of how to use the <code>var</code> keyword since it's not for the intended purpose.</p>\n" }, { "answer_id": 159574, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>It's not as simple as implementing <strong>var</strong> in a method since you also have to take into acccount different modifiers and attributes like so:</p>\n\n<pre><code>[MyAttribute()] protected internal readonly var list = new List&lt;T&gt;();\n</code></pre>\n\n<p>What I would really have liked is a type-inferenced <strong>const</strong>!</p>\n\n<pre><code>public const notFoundStatus = 404; // int\n</code></pre>\n" }, { "answer_id": 874198, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 4, "selected": true, "text": "<p>There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not.</p>\n\n<p>See Eric Lippert's blog for an in-depth explanation: <a href=\"http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx\" rel=\"nofollow noreferrer\">Why no var on fields?</a></p>\n" }, { "answer_id": 15872114, "author": "vinay Dubey", "author_id": 2256281, "author_profile": "https://Stackoverflow.com/users/2256281", "pm_score": 0, "selected": false, "text": "<p>Pass List Type in Generic</p>\n\n<pre><code>class Class1\n{\n public void genmethod&lt;T&gt;(T i,int Count)\n {\n\n\n List&lt;string&gt; list = i as List&lt;string&gt;;\n\n for (int j = 0; j &lt; Count; j++)\n {\n Console.WriteLine(list[j]);\n }\n }\n static void Main(string[] args)\n {\n Class1 c = new Class1();\n c.genmethod&lt;string&gt;(\"str\",0);\n List&lt;string&gt; l = new List&lt;string&gt;();\n l.Add(\"a\");\n l.Add(\"b\");\n l.Add(\"c\");\n l.Add(\"d\");\n c.genmethod&lt;List&lt;string&gt;&gt;(l,l.Count);\n\n Console.WriteLine(\"abc\");\n Console.ReadLine();\n }\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22858/" ]
I know we cannot do this at class level but at method level we can always do this. ``` var myList=new List<string> // or something else like this ``` This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression. So compiler doesn't need to do type guessing. (correct me if i am wrong). so question remains WHY NOT at class level while its allowed at method level
There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not. See Eric Lippert's blog for an in-depth explanation: [Why no var on fields?](http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx)
159,373
<p>Using .Net 3.0 and VS2005. </p> <p>The objects in question are consumed from a WCF service then serialized back into XML for a legacy API. So rather than serializing the TestObject, it was serializing .TestObject which was missing the [XmlRoot] attribute; however, all the [Xml*] attributes for the child elements were in the generated proxy code so they worked just fine. So all the child elements worked just fine, but the enclosing element did not because the [XmlRoot] attribute wasn't included in the generated proxy code. The original object that included the [XmlRoot] attribute serializes fine manually.</p> <p><strong>Can I have the proxy code include the [XmlRoot] attribute so the generated proxy class serializes correctly as well?</strong> If I can't do that I suspect I'll have to use [XmlType] but that causes minor havoc requiring me to change other components so I would prefer the former. I also want to avoid having to manually edit the autogenerated proxy class.</p> <p>Here is some sample code (I have included the client and the service in the same app because this is quick and for test purposes. Comment out the service referencing code and add the service reference while running the app, then uncomment the service code and run.)</p> <pre><code>namespace SerializationTest { class Program { static void Main( string[] args ) { Type serviceType = typeof( TestService ); using (ServiceHost host = new ServiceHost( serviceType, new Uri[] { new Uri( "http://localhost:8080/" ) } )) { ServiceMetadataBehavior behaviour = new ServiceMetadataBehavior(); behaviour.HttpGetEnabled = true; host.Description.Behaviors.Add( behaviour ); host.AddServiceEndpoint( serviceType, new BasicHttpBinding(), "TestService" ); host.AddServiceEndpoint( typeof( IMetadataExchange ), new BasicHttpBinding(), "MEX" ); host.Open(); TestServiceClient client = new TestServiceClient(); localhost.TestObject to = client.GetObject(); String XmlizedString = null; using (MemoryStream memoryStream = new MemoryStream()) { XmlSerializer xs = new XmlSerializer( typeof( localhost.TestObject ) ); using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream)) { xs.Serialize( xmlWriter, to ); memoryStream = (MemoryStream)xmlWriter.BaseStream; XmlizedString = Encoding.UTF8.GetString( memoryStream.ToArray() ); Console.WriteLine( XmlizedString ); } } } Console.ReadKey(); } } [Serializable] [XmlRoot( "SomethingElse" )] public class TestObject { private bool _worked; public TestObject() { Worked = true; } [XmlAttribute( AttributeName = "AttributeWorked" )] public bool Worked { get { return _worked; } set { _worked = value; } } } [ServiceContract] public class TestService { [OperationContract] [XmlSerializerFormat] public TestObject GetObject() { return new TestObject(); } } } </code></pre> <p>Here is the Xml this generates.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" AttributeWorked="true" /&gt; </code></pre>
[ { "answer_id": 177169, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": -1, "selected": true, "text": "<p>I found someone who provides a means to solve this situation:</p>\n\n<p><a href=\"http://www.request-response.com/blog/PermaLink,guid,efa4e231-ddf1-48f4-9a26-54363e799d42.aspx\" rel=\"nofollow noreferrer\">Matevz Gacnik's Weblog</a></p>\n\n<p>Using that approach of <code>XmlAttributeOverrides</code>, I wrote the following:</p>\n\n<pre><code> private static XmlSerializer GetOverridedSerializer()\n {\n // set overrides for TestObject element\n XmlAttributes attrsTestObject = new XmlAttributes();\n XmlRootAttribute rootTestObject = new XmlRootAttribute(\"SomethingElse\");\n attrsTestObject.XmlRoot = rootTestObject;\n\n // create overrider\n XmlAttributeOverrides xOver = new XmlAttributeOverrides();\n xOver.Add(typeof(localhost.TestObject), attrsTestObject);\n\n XmlSerializer xSer = new XmlSerializer(typeof(localhost.TestObject), xOver);\n return xSer;\n }\n</code></pre>\n\n<p>Just put that method in the <code>Program</code> class of your example, and replace the following line in <code>Main()</code>:</p>\n\n<pre><code> //XmlSerializer xs = new XmlSerializer(typeof(localhost.TestObject));\n XmlSerializer xs = GetOverridedSerializer();\n</code></pre>\n\n<p>And then run to see the results.</p>\n\n<p>Here is what I got:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;&lt;SomethingElse xmlns:xsi=\"http://www.w3.o\nrg/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" Attribu\nteWorked=\"true\" /&gt;\n</code></pre>\n" }, { "answer_id": 1031423, "author": "graffic", "author_id": 15987, "author_profile": "https://Stackoverflow.com/users/15987", "pm_score": 1, "selected": false, "text": "<p><strong>== IF ==</strong></p>\n\n<p>This is only for the <code>XmlRoot</code> attribute. The <code>XmlSerializer</code> has one constructor where you can specify the <code>XmlRoot</code> attribute.</p>\n\n<p>Kudos to csgero for pointing it. His comment should be the solution.</p>\n\n<pre><code>XmlSerializer Constructor (Type, XmlRootAttribute)\n</code></pre>\n\n<blockquote>\n <p>Initializes a new instance of the\n <code>XmlSerializer</code> class that can serialize\n objects of the specified type into XML\n documents, and deserialize an XML\n document into object of the specified\n type. It also specifies the class to\n use as the XML root element.</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24279/" ]
Using .Net 3.0 and VS2005. The objects in question are consumed from a WCF service then serialized back into XML for a legacy API. So rather than serializing the TestObject, it was serializing .TestObject which was missing the [XmlRoot] attribute; however, all the [Xml\*] attributes for the child elements were in the generated proxy code so they worked just fine. So all the child elements worked just fine, but the enclosing element did not because the [XmlRoot] attribute wasn't included in the generated proxy code. The original object that included the [XmlRoot] attribute serializes fine manually. **Can I have the proxy code include the [XmlRoot] attribute so the generated proxy class serializes correctly as well?** If I can't do that I suspect I'll have to use [XmlType] but that causes minor havoc requiring me to change other components so I would prefer the former. I also want to avoid having to manually edit the autogenerated proxy class. Here is some sample code (I have included the client and the service in the same app because this is quick and for test purposes. Comment out the service referencing code and add the service reference while running the app, then uncomment the service code and run.) ``` namespace SerializationTest { class Program { static void Main( string[] args ) { Type serviceType = typeof( TestService ); using (ServiceHost host = new ServiceHost( serviceType, new Uri[] { new Uri( "http://localhost:8080/" ) } )) { ServiceMetadataBehavior behaviour = new ServiceMetadataBehavior(); behaviour.HttpGetEnabled = true; host.Description.Behaviors.Add( behaviour ); host.AddServiceEndpoint( serviceType, new BasicHttpBinding(), "TestService" ); host.AddServiceEndpoint( typeof( IMetadataExchange ), new BasicHttpBinding(), "MEX" ); host.Open(); TestServiceClient client = new TestServiceClient(); localhost.TestObject to = client.GetObject(); String XmlizedString = null; using (MemoryStream memoryStream = new MemoryStream()) { XmlSerializer xs = new XmlSerializer( typeof( localhost.TestObject ) ); using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream)) { xs.Serialize( xmlWriter, to ); memoryStream = (MemoryStream)xmlWriter.BaseStream; XmlizedString = Encoding.UTF8.GetString( memoryStream.ToArray() ); Console.WriteLine( XmlizedString ); } } } Console.ReadKey(); } } [Serializable] [XmlRoot( "SomethingElse" )] public class TestObject { private bool _worked; public TestObject() { Worked = true; } [XmlAttribute( AttributeName = "AttributeWorked" )] public bool Worked { get { return _worked; } set { _worked = value; } } } [ServiceContract] public class TestService { [OperationContract] [XmlSerializerFormat] public TestObject GetObject() { return new TestObject(); } } } ``` Here is the Xml this generates. ``` <?xml version="1.0" encoding="utf-8"?> <TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" AttributeWorked="true" /> ```
I found someone who provides a means to solve this situation: [Matevz Gacnik's Weblog](http://www.request-response.com/blog/PermaLink,guid,efa4e231-ddf1-48f4-9a26-54363e799d42.aspx) Using that approach of `XmlAttributeOverrides`, I wrote the following: ``` private static XmlSerializer GetOverridedSerializer() { // set overrides for TestObject element XmlAttributes attrsTestObject = new XmlAttributes(); XmlRootAttribute rootTestObject = new XmlRootAttribute("SomethingElse"); attrsTestObject.XmlRoot = rootTestObject; // create overrider XmlAttributeOverrides xOver = new XmlAttributeOverrides(); xOver.Add(typeof(localhost.TestObject), attrsTestObject); XmlSerializer xSer = new XmlSerializer(typeof(localhost.TestObject), xOver); return xSer; } ``` Just put that method in the `Program` class of your example, and replace the following line in `Main()`: ``` //XmlSerializer xs = new XmlSerializer(typeof(localhost.TestObject)); XmlSerializer xs = GetOverridedSerializer(); ``` And then run to see the results. Here is what I got: ``` <?xml version="1.0" encoding="utf-8"?><SomethingElse xmlns:xsi="http://www.w3.o rg/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Attribu teWorked="true" /> ```
159,393
<p>I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?</p>
[ { "answer_id": 159452, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 5, "selected": true, "text": "<p>There are a few things to consider first:</p>\n\n<ol>\n<li>Firstly, your PHP user may not have access to Apache's log files.</li>\n<li>Secondly, PHP and Apache aren't going to tell you where said log file is,</li>\n<li>Lastly, Apache log files can get quite large.</li>\n</ol>\n\n<p>However, if none of these apply, you can use the normal file reading commands to do it.\nThe easiest way to get the last error is</p>\n\n<pre><code>$contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES);\nif (is_array($contents)) {\n echo end($contents);\n}\nunset($contents);\n</code></pre>\n\n<p>There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader.</p>\n\n<p>One last comment: PHP also has an ini setting to redirect PHP errors to a log file: <code>error_log = /path/to/error.log</code></p>\n\n<p>You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php_flag notation:</p>\n\n<pre><code>php_flag error_log /web/mysite/logs/error.log\n</code></pre>\n" }, { "answer_id": 159457, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<p>there are piles of php scripts that do this, just do a google search for examples. if you want to roll your own, it's nothing more complex than reading any other file. just make sure you know the location of your logfiles (defined in the httpd.conf file) and the <a href=\"http://httpd.apache.org/docs/2.0/logs.html\" rel=\"nofollow noreferrer\">format your log files</a> are in. the format is also defined in httpd.conf</p>\n" }, { "answer_id": 163861, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 4, "selected": false, "text": "<p>for anyone else looking for a sample script, i threw something together, it's got the basics:</p>\n\n<pre><code>&lt;?php\nexec('tail /usr/local/apache/logs/error_log', $output);\n?&gt;\n&lt;Table border=\"1\"&gt;\n &lt;tr&gt;\n &lt;th&gt;Date&lt;/th&gt;\n &lt;th&gt;Type&lt;/th&gt;\n &lt;th&gt;Client&lt;/th&gt;\n &lt;th&gt;Message&lt;/th&gt;\n &lt;/tr&gt;\n&lt;?\n foreach($output as $line) {\n // sample line: [Wed Oct 01 15:07:23 2008] [error] [client 76.246.51.127] PHP 99. Debugger-&gt;handleError() /home/gsmcms/public_html/central/cake/libs/debugger.php:0\n preg_match('~^\\[(.*?)\\]~', $line, $date);\n if(empty($date[1])) {\n continue;\n }\n preg_match('~\\] \\[([a-z]*?)\\] \\[~', $line, $type);\n preg_match('~\\] \\[client ([0-9\\.]*)\\]~', $line, $client);\n preg_match('~\\] (.*)$~', $line, $message);\n ?&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?=$date[1]?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?=$type[1]?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?=$client[1]?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?=$message[1]?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?\n }\n?&gt;\n&lt;/table&gt;\n</code></pre>\n" }, { "answer_id": 354153, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Have you tried biterScripting ? I am a system admin and I have been using to parse logs. It is univx style scripting. biterScripting.com -> Free download.</p>\n" }, { "answer_id": 4496086, "author": "Ben Haley", "author_id": 431079, "author_profile": "https://Stackoverflow.com/users/431079", "pm_score": 2, "selected": false, "text": "<p>Here's a small-ish class that makes it easy to read a number of characters from the back of a large file w/o overloading memory. The test setting lets you see it in action cannibalizing itself.</p>\n\n<pre><code>BigFile.php\n&lt;?php\n$run_test = true;\n$test_file = 'BigFile.php';\n\nclass BigFile\n{\nprivate $file_handle;\n\n/**\n * \n * Load the file from a filepath \n * @param string $path_to_file\n * @throws Exception if path cannot be read from\n */\npublic function __construct( $path_to_log )\n{\n if( is_readable($path_to_log) )\n {\n $this-&gt;file_handle = fopen( $path_to_log, 'r');\n }\n else\n {\n throw new Exception(\"The file path to the file is not valid\");\n } \n}\n\n/**\n * \n * 'Finish your breakfast' - Jay Z's homme Strict\n */\npublic function __destruct()\n{\n fclose($this-&gt;file_handle); \n}\n\n/**\n * \n * Returns a number of characters from the end of a file w/o loading the entire file into memory\n * @param integer $number_of_characters_to_get\n * @return string $characters\n */\npublic function getFromEnd( $number_of_characters_to_get )\n{\n $offset = -1*$number_of_characters_to_get;\n $text = \"\";\n\n fseek( $this-&gt;file_handle, $offset , SEEK_END);\n\n while(!feof($this-&gt;file_handle))\n {\n $text .= fgets($this-&gt;file_handle);\n }\n\n return $text;\n}\n}\n\nif( $run_test )\n{\n$number_of_characters_to_get = 100000; \n$bf = new BigFile($test_file);\n$text = $bf-&gt;getFromEnd( $number_of_characters_to_get );\necho \"$test_file has the following $number_of_characters_to_get characters at the end: \n &lt;br/&gt; &lt;pre&gt;$text&lt;/pre&gt;\";\n}\n\n?&gt; \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?
There are a few things to consider first: 1. Firstly, your PHP user may not have access to Apache's log files. 2. Secondly, PHP and Apache aren't going to tell you where said log file is, 3. Lastly, Apache log files can get quite large. However, if none of these apply, you can use the normal file reading commands to do it. The easiest way to get the last error is ``` $contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES); if (is_array($contents)) { echo end($contents); } unset($contents); ``` There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader. One last comment: PHP also has an ini setting to redirect PHP errors to a log file: `error_log = /path/to/error.log` You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php\_flag notation: ``` php_flag error_log /web/mysite/logs/error.log ```
159,423
<p>I'm currently writing a simple .sh script to parse an Exim log file for strings matching " o' ". Currently, when viewing output.txt, all that is there is a 0 printed on every line(606 lines). I'm guessing my logic is wrong, as awk does not throw any errors.</p> <p>Here is my code(updated for concatenation and counter issues). Edit: I've adopted some new code from dmckee's answer that I'm now working with over the old code in favor of simplicity.</p> <pre><code>awk '/o'\''/ { line = "&gt; "; for(i = 20; i &lt;= 33; i++) { line = line " " $i; } print line; }' /var/log/exim/main.log &gt; output.txt </code></pre> <p>Any ideas? </p> <p>EDIT: For clarity's sake, I'm grepping for "o'" in email addresses, because ' is an illegal character in email addresses(and in our databases, appears only with o'-prefixed names).</p> <p>EDIT 2: As per commentary request, here is a sanitized sample of some desired output:</p> <pre><code>[xxx.xxx.xxx.xxx] kathleen.o'[email protected] &lt;kathleen.o'[email protected]&gt; routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] julie.o'[email protected] &lt;julie.o'[email protected]&gt; routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] james.o'[email protected] &lt;james.o'[email protected]&gt; routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] daniel_o'[email protected] &lt;aniel_o'[email protected]&gt; routing defer (-51): retry time not reached </code></pre> <p>The reason I'm starting at 20 in my loop is because everything before the 20th field is just standard log information that isn't needed for my purposes here. All I need is everything from the IP and beyond for this solution(the messages for each 550 error are different for each mail server in use out there. I'm compiling a list of common ones)</p>
[ { "answer_id": 159450, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p><code>+</code> means numerical addition in awk. If you want to concatenate, just place the constants and/or expressions separated with spaces.</p>\n\n<p>So, this</p>\n\n<pre><code>line += \" \" + $i\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>line = line \" \" $i\n</code></pre>\n\n<p>EDIT: <em>Iff</em> exim log files (I am more into Postfix :) are separated by a single space, isn't the following more simple:</p>\n\n<pre><code>grep -F o\\' /var/log/exim/main.log | cut -d\\ -f20-33 &gt;output.txt\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 159501, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": true, "text": "<p>There is no real need for the grep here. Let awk select the matching lines for you (and fixing your concatenation bug as per ΤΖΩΤΖΙΟΥ):</p>\n\n<pre><code>awk '/o'\\''/ {\n line = \"&gt; \";\n for(i = 20; i &lt;= 33; i++) {\n line = line \" \" $i;\n }\n print line;\n }' /var/log/exim/main.log &gt; output.txt\n</code></pre>\n\n<p>Of course, you end up needing some weird escaping if you do it at the promp like above. It is cleaner in a script...</p>\n\n<hr>\n\n<p>Edit: On the first pass I missed the += problem...</p>\n\n<p>Also assuming that the line you gave above is partial, as it has only 13ish fields (by default fields are white space delimited). </p>\n" }, { "answer_id": 159560, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 1, "selected": false, "text": "<p>\"'\" is not illegal in local parts. From <a href=\"http://www.ietf.org/rfc/rfc2821.txt\" rel=\"nofollow noreferrer\">RFC2821</a>, section 4.1.2:</p>\n\n<pre><code>Local-part = Dot-string / Quoted-string\n\nDot-string = Atom *(\".\" Atom)\n\nAtom = 1*atext\n</code></pre>\n\n<p>2821 further references <a href=\"http://www.ietf.org/rfc/rfc2822.txt\" rel=\"nofollow noreferrer\">RFC2822</a> for non-locally-defined elements, so:</p>\n\n<pre><code>atext = ALPHA / DIGIT / ; Any character except controls,\n \"!\" / \"#\" / ; SP, and specials.\n \"$\" / \"%\" / ; Used for atoms\n \"&amp;\" / \"'\" /\n \"*\" / \"+\" /\n \"-\" / \"/\" /\n \"=\" / \"?\" /\n \"^\" / \"_\" /\n \"`\" / \"{\" /\n \"|\" / \"}\" /\n \"~\"\n</code></pre>\n\n<p>In other words, \"'\" is a perfectly legal unquoted characted to have in an email localpart. Now, it may not be legal <strong>at your site</strong>, but that's not what you said.</p>\n\n<p>Sorry for not staying directly on topic, but I wanted to correct your assertion.</p>\n" }, { "answer_id": 159722, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Off task, and simpler still: python.</p>\n\n<pre><code>import fileinput\nfor line in fileinput.input():\n if \"'\" in line:\n fields = line.split(' ')\n print \"&gt; \", ' '.join( fields[20:34] )\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153/" ]
I'm currently writing a simple .sh script to parse an Exim log file for strings matching " o' ". Currently, when viewing output.txt, all that is there is a 0 printed on every line(606 lines). I'm guessing my logic is wrong, as awk does not throw any errors. Here is my code(updated for concatenation and counter issues). Edit: I've adopted some new code from dmckee's answer that I'm now working with over the old code in favor of simplicity. ``` awk '/o'\''/ { line = "> "; for(i = 20; i <= 33; i++) { line = line " " $i; } print line; }' /var/log/exim/main.log > output.txt ``` Any ideas? EDIT: For clarity's sake, I'm grepping for "o'" in email addresses, because ' is an illegal character in email addresses(and in our databases, appears only with o'-prefixed names). EDIT 2: As per commentary request, here is a sanitized sample of some desired output: ``` [xxx.xxx.xxx.xxx] kathleen.o'[email protected] <kathleen.o'[email protected]> routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] julie.o'[email protected] <julie.o'[email protected]> routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] james.o'[email protected] <james.o'[email protected]> routing defer (-51): retry time not reached [xxx.xxx.xxx.xxx] daniel_o'[email protected] <aniel_o'[email protected]> routing defer (-51): retry time not reached ``` The reason I'm starting at 20 in my loop is because everything before the 20th field is just standard log information that isn't needed for my purposes here. All I need is everything from the IP and beyond for this solution(the messages for each 550 error are different for each mail server in use out there. I'm compiling a list of common ones)
There is no real need for the grep here. Let awk select the matching lines for you (and fixing your concatenation bug as per ΤΖΩΤΖΙΟΥ): ``` awk '/o'\''/ { line = "> "; for(i = 20; i <= 33; i++) { line = line " " $i; } print line; }' /var/log/exim/main.log > output.txt ``` Of course, you end up needing some weird escaping if you do it at the promp like above. It is cleaner in a script... --- Edit: On the first pass I missed the += problem... Also assuming that the line you gave above is partial, as it has only 13ish fields (by default fields are white space delimited).
159,456
<p>I have a database in the following format:</p> <pre><code> ID TYPE SUBTYPE COUNT MONTH 1 A Z 1 7/1/2008 1 A Z 3 7/1/2008 2 B C 2 7/2/2008 1 A Z 3 7/2/2008 </code></pre> <p>Can I use SQL to convert it into this:</p> <pre><code>ID A_Z B_C MONTH 1 4 0 7/1/2008 2 0 2 7/2/2008 1 0 3 7/2/2008 </code></pre> <p>So, the <code>TYPE</code>, <code>SUBTYPE</code> are concatenated into new columns and <code>COUNT</code> is summed where the <code>ID</code> and <code>MONTH</code> match.</p> <p>Any tips would be appreciated. Is this possible in SQL or should I program it manually?</p> <p>The database is SQL Server 2005. </p> <p>Assume there are 100s of <code>TYPES</code> and <code>SUBTYPES</code> so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.</p>
[ { "answer_id": 159488, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 3, "selected": false, "text": "<pre><code>select id,\nsum(case when type = 'A' and subtype = 'Z' then [count] else 0 end) as A_Z,\nsum(case when type = 'B' and subtype = 'C' then [count] else 0 end) as B_C,\nmonth\nfrom tbl_why_would_u_do_this\ngroup by id, month\n</code></pre>\n\n<p>You change requirements more than our marketing team! If you want it to be dynamic you'll need to fall back on a sproc.</p>\n" }, { "answer_id": 159803, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 6, "selected": true, "text": "<p>SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL</p>\n\n<pre><code>/*\nCREATE TABLE [dbo].[stackoverflow_159456](\n [ID] [int] NOT NULL,\n [TYPE] [char](1) NOT NULL,\n [SUBTYPE] [char](1) NOT NULL,\n [COUNT] [int] NOT NULL,\n [MONTH] [datetime] NOT NULL\n) ON [PRIMARY]\n*/\n\nDECLARE @sql AS varchar(max)\nDECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique\nDECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique\n\nSELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']'\n ,@select_list = COALESCE(@select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']'\nFROM (\n SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE\n FROM stackoverflow_159456\n) AS PIVOT_CODES\n\nSET @sql = '\n;WITH p AS (\n SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT]\n FROM stackoverflow_159456\n GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE\n)\nSELECT ID, [MONTH], ' + @select_list + '\nFROM p\nPIVOT (\n SUM([COUNT])\n FOR PIVOT_CODE IN (\n ' + @pivot_list + '\n )\n) AS pvt\n'\n\nEXEC (@sql)\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23133/" ]
I have a database in the following format: ``` ID TYPE SUBTYPE COUNT MONTH 1 A Z 1 7/1/2008 1 A Z 3 7/1/2008 2 B C 2 7/2/2008 1 A Z 3 7/2/2008 ``` Can I use SQL to convert it into this: ``` ID A_Z B_C MONTH 1 4 0 7/1/2008 2 0 2 7/2/2008 1 0 3 7/2/2008 ``` So, the `TYPE`, `SUBTYPE` are concatenated into new columns and `COUNT` is summed where the `ID` and `MONTH` match. Any tips would be appreciated. Is this possible in SQL or should I program it manually? The database is SQL Server 2005. Assume there are 100s of `TYPES` and `SUBTYPES` so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.
SQL Server 2005 offers a very useful PIVOT and UNPIVOT operator which allow you to make this code maintenance-free using PIVOT and some code generation/dynamic SQL ``` /* CREATE TABLE [dbo].[stackoverflow_159456]( [ID] [int] NOT NULL, [TYPE] [char](1) NOT NULL, [SUBTYPE] [char](1) NOT NULL, [COUNT] [int] NOT NULL, [MONTH] [datetime] NOT NULL ) ON [PRIMARY] */ DECLARE @sql AS varchar(max) DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + PIVOT_CODE + ']' ,@select_list = COALESCE(@select_list + ', ', '') + 'ISNULL([' + PIVOT_CODE + '], 0) AS [' + PIVOT_CODE + ']' FROM ( SELECT DISTINCT [TYPE] + '_' + SUBTYPE AS PIVOT_CODE FROM stackoverflow_159456 ) AS PIVOT_CODES SET @sql = ' ;WITH p AS ( SELECT ID, [MONTH], [TYPE] + ''_'' + SUBTYPE AS PIVOT_CODE, SUM([COUNT]) AS [COUNT] FROM stackoverflow_159456 GROUP BY ID, [MONTH], [TYPE] + ''_'' + SUBTYPE ) SELECT ID, [MONTH], ' + @select_list + ' FROM p PIVOT ( SUM([COUNT]) FOR PIVOT_CODE IN ( ' + @pivot_list + ' ) ) AS pvt ' EXEC (@sql) ```
159,469
<p>Hopefully, I can explain this issue properly. I have 3 classes that deals with my entities.</p> <pre><code>@MappedSuperclass public abstract class Swab implements ISwab { ... private Collection&lt;SwabAccounts&gt; accounts; ... } @Entity @Table(name="switches") @DiscriminatorColumn(name="type") @DiscriminatorValue(value="DMS500") public class DmsSwab extends Swab implements ISwab, Serializable { ... private ObjectPool pool; ... @Transient public ObjectPool getPool(){ return pool; } ... } @Entity(name="swab_accounts") public class SwabAccounts implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int swab_account_id; private int swab_id; ... } </code></pre> <p>And in a EJB a query is being doing this way</p> <pre><code> DmsSwab dms = em.find(DmsSwab.class, 2); List&lt;Swab&gt; s = new ArrayList&lt;Swab&gt;(1); s.add(dms); </code></pre> <p>My persistence.xml looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="dflow-pu" transaction-type="RESOURCE_LOCAL"&gt; &lt;provider&gt;oracle.toplink.essentials.PersistenceProvider&lt;/provider&gt; &lt;class&gt;com.dcom.sap.dms.DmsSwab&lt;/class&gt; &lt;class&gt;com.dcom.sap.jpa.SwabAccounts&lt;/class&gt; &lt;properties&gt; &lt;property name="toplink.jdbc.user" value="dflow"/&gt; &lt;property name="toplink.jdbc.password" value="dflow"/&gt; &lt;property name="toplink.jdbc.url" value="jdbc:mysql://itcd-400447:3306/dflow"/&gt; &lt;property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>I get this error:</p> <pre><code>java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. com.dcom.sap.SwabException: java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. Caused by: java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.findInternal(EntityManagerImpl.java:306) at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.find(EntityManagerImpl.java:148) </code></pre> <p>I am running netbeans 6.1 with the version of glassfish that comes with it. MySql 5.0.</p>
[ { "answer_id": 162898, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 1, "selected": false, "text": "<p>According to the error message and what I figure from your code, the error seems to be in the persistence.xml file, can you be a bit more verbose ?</p>\n" }, { "answer_id": 3315708, "author": "Andy", "author_id": 399930, "author_profile": "https://Stackoverflow.com/users/399930", "pm_score": 3, "selected": false, "text": "<p>define this entity in class tag inside the persistence.xml</p>\n" }, { "answer_id": 12152106, "author": "clebertx", "author_id": 1187644, "author_profile": "https://Stackoverflow.com/users/1187644", "pm_score": 0, "selected": false, "text": "<p>I had the same error and, complementing the information above, my case was a ClassLoader issue. My app has three files. A ejb-module.jar which depends on app-lib.jar (library that contains pojo and database entities) and a web-module.war which depends on app-lib.jar. </p>\n\n<p>In the deployment, the app-lib.jar was loaded twice by the glassfish. Googling, I found out that I should copy the app-lib.jar to a \"shared\" lib in the glassfish domain. I've copied the postgresql.jar to \"domain-dir/lib\" and my app-lib.jar to \"domain-dir/lib/applibs\". Have it done, the app worked like a charm. </p>\n\n<p>The used explanation can be found here: <a href=\"http://docs.oracle.com/cd/E19798-01/821-1752/beade/index.html\" rel=\"nofollow\">http://docs.oracle.com/cd/E19798-01/821-1752/beade/index.html</a></p>\n" }, { "answer_id": 43619011, "author": "Mario Barreto MX", "author_id": 7921419, "author_profile": "https://Stackoverflow.com/users/7921419", "pm_score": 0, "selected": false, "text": "<p>I solved this issue creating a ContextListener in to my Web App, invoking the close of the entity manager factory at destroy context, :</p>\n\n<pre><code>public void contextDestroyed(ServletContextEvent servletContextEvent) {\n try {\n logger.info(\"contextDestroyed...\");\n LifeCycleManager lifeCycleManager = ServiceLocator.getLifeCycleManager();\n lifeCycleManager.closeEntityManagerFactory();\n\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n }\n}\n</code></pre>\n\n<p>I also create a bean with name LifeCycleManager and inside them invoke a DAO method to close the entity manager factory:</p>\n\n<pre><code>public void closeEntityManagerFactory() throws BusinessException {\n logger.info(\"closeEntityManager\");\n try {\n logger.info(\"closing entity manager factory...\");\n genericDAO.closeEntityManagerFactory();\n logger.info(\"Entity manager factiry closed\");\n } catch (Exception e) {\n throw new BusinessException(BusinessErrorCode.CODIGO_EJEMPLO_01, Severity.ERROR);\n }\n }\n</code></pre>\n\n<p>Inside the DAO:</p>\n\n<p>...</p>\n\n<pre><code>@Autowired\nprivate EntityManagerFactory entityManagerFactory;\n</code></pre>\n\n<p>...</p>\n\n<pre><code>public void closeEntityManagerFactory() {\n logger.info(\"closing entity manager factory\");\n getEntityManagerFactory().close();\n logger.info(\"entity manager factory closed\"); \n }\n</code></pre>\n\n<p>Using this each time I deploy a change from my eclipse environment the destroy context is invoked.\nI hope could help you guys, my environment is WebLogic Server 11gR1 and JPA 1.0.</p>\n" }, { "answer_id": 62947368, "author": "ldt", "author_id": 5819521, "author_profile": "https://Stackoverflow.com/users/5819521", "pm_score": 0, "selected": false, "text": "<p>Mario was right when he mentions <strong>EntityManagerFactory</strong> here.</p>\n<p>Both:</p>\n<blockquote>\n<p><strong>java.lang.IllegalArgumentException</strong>: Unknown entity bean class...</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p><strong>java.lang.IllegalStateException</strong>: This web container has not yet been started...</p>\n</blockquote>\n<p>These exceptions occur when you redeploy a web application multiple times but didn't close <strong>EntityManagerFactory</strong> properly.</p>\n<p>follow <a href=\"https://www.deadcoderising.com/execute-code-on-webapp-startup-and-shutdown-using-servletcontextlistener/#:%7E:text=ServletContextListener%20is%20an%20interface%20that,filters%20and%20servlets%20are%20initialized.\" rel=\"nofollow noreferrer\">this instruction</a> to register <strong>ServletContextListener</strong> and <a href=\"https://stackoverflow.com/a/44519903/5819521\">this instruction</a> to close <strong>EntityManagerFactory</strong> properly.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
Hopefully, I can explain this issue properly. I have 3 classes that deals with my entities. ``` @MappedSuperclass public abstract class Swab implements ISwab { ... private Collection<SwabAccounts> accounts; ... } @Entity @Table(name="switches") @DiscriminatorColumn(name="type") @DiscriminatorValue(value="DMS500") public class DmsSwab extends Swab implements ISwab, Serializable { ... private ObjectPool pool; ... @Transient public ObjectPool getPool(){ return pool; } ... } @Entity(name="swab_accounts") public class SwabAccounts implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int swab_account_id; private int swab_id; ... } ``` And in a EJB a query is being doing this way ``` DmsSwab dms = em.find(DmsSwab.class, 2); List<Swab> s = new ArrayList<Swab>(1); s.add(dms); ``` My persistence.xml looks like this: ``` <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="dflow-pu" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <class>com.dcom.sap.dms.DmsSwab</class> <class>com.dcom.sap.jpa.SwabAccounts</class> <properties> <property name="toplink.jdbc.user" value="dflow"/> <property name="toplink.jdbc.password" value="dflow"/> <property name="toplink.jdbc.url" value="jdbc:mysql://itcd-400447:3306/dflow"/> <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/> </properties> </persistence-unit> </persistence> ``` I get this error: ``` java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. com.dcom.sap.SwabException: java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. Caused by: java.lang.IllegalArgumentException: Unknown entity bean class: class com.dcom.sap.dms.DmsSwab, please verify that this class has been marked with the @Entity annotation. at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.findInternal(EntityManagerImpl.java:306) at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerImpl.find(EntityManagerImpl.java:148) ``` I am running netbeans 6.1 with the version of glassfish that comes with it. MySql 5.0.
define this entity in class tag inside the persistence.xml
159,506
<p>Can I programatically set the position of a WPF ListBox's scrollbar? By default, I want it to go in the center.</p>
[ { "answer_id": 159525, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": -1, "selected": false, "text": "<p>I don't think ListBoxes have that, but ListViews have the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.ensurevisible.aspx\" rel=\"nofollow noreferrer\">EnsureVisible</a> method that moves the scrollbar to the place needed in order to make sure an item is shown.</p>\n" }, { "answer_id": 159565, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<pre><code>Dim cnt as Integer = myListBox.Items.Count\nDim midPoint as Integer = cnt\\2\nmyListBox.ScrollIntoView(myListBox.Items(midPoint))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>myListBox.SelectedIndex = midPoint\n</code></pre>\n\n<p>It depends on if you want the middle item just shown, or selected.</p>\n" }, { "answer_id": 3029266, "author": "Zamboni", "author_id": 174682, "author_profile": "https://Stackoverflow.com/users/174682", "pm_score": 4, "selected": true, "text": "<p>To move the vertical scroll bar in a ListBox do the following: </p>\n\n<ol>\n<li>Name your list box (x:Name=\"myListBox\")</li>\n<li>Add Loaded event for the Window (Loaded=\"Window_Loaded\")</li>\n<li>Implement Loaded event using method: ScrollToVerticalOffset</li>\n</ol>\n\n<p>Here is a working sample:</p>\n\n<p>XAML:</p>\n\n<pre><code>&lt;Window x:Class=\"ListBoxScrollPosition.Views.MainView\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Loaded=\"Window_Loaded\"\n Title=\"Main Window\" Height=\"100\" Width=\"200\"&gt;\n &lt;DockPanel&gt;\n &lt;Grid&gt;\n &lt;ListBox x:Name=\"myListBox\"&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Zamboni&lt;/ListBoxItem&gt;\n &lt;/ListBox&gt;\n &lt;/Grid&gt;\n &lt;/DockPanel&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n // Get the border of the listview (first child of a listview)\n Decorator border = VisualTreeHelper.GetChild(myListBox, 0) as Decorator;\n if (border != null)\n {\n // Get scrollviewer\n ScrollViewer scrollViewer = border.Child as ScrollViewer;\n if (scrollViewer != null)\n {\n // center the Scroll Viewer...\n double center = scrollViewer.ScrollableHeight / 2.0;\n scrollViewer.ScrollToVerticalOffset(center);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 11196632, "author": "karol", "author_id": 1480984, "author_profile": "https://Stackoverflow.com/users/1480984", "pm_score": 0, "selected": false, "text": "<p>I've just changed a bit code of Zamboni and added position calculation.</p>\n\n<pre><code>var border = VisualTreeHelper.GetChild(list, 0) as Decorator;\nif (border == null) return;\nvar scrollViewer = border.Child as ScrollViewer;\nif (scrollViewer == null) return;\nscrollViewer.ScrollToVerticalOffset((scrollViewer.ScrollableHeight/list.Items.Count)*\n (list.Items.IndexOf(list.SelectedItem) + 1));\n</code></pre>\n" }, { "answer_id": 59187611, "author": "user1523904", "author_id": 1523904, "author_profile": "https://Stackoverflow.com/users/1523904", "pm_score": 0, "selected": false, "text": "<p>I have a ListView named MusicList. MusicList automatically moves to the next element after playing a music. I create an event handler for Player.Ended event as follows (a la Zamboni):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> if (MusicList.HasItems)\n {\n Decorator border = VisualTreeHelper.GetChild(MusicList, 0) as Decorator;\n if (border != null)\n {\n ScrollViewer scrollViewer = border.Child as ScrollViewer;\n if (scrollViewer != null)\n {\n MusicList.ScrollIntoView(MusicList.SelectedItem);\n }\n }\n }\n</code></pre>\n\n<p>You get the next element seen at the bottom.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
Can I programatically set the position of a WPF ListBox's scrollbar? By default, I want it to go in the center.
To move the vertical scroll bar in a ListBox do the following: 1. Name your list box (x:Name="myListBox") 2. Add Loaded event for the Window (Loaded="Window\_Loaded") 3. Implement Loaded event using method: ScrollToVerticalOffset Here is a working sample: XAML: ``` <Window x:Class="ListBoxScrollPosition.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Window_Loaded" Title="Main Window" Height="100" Width="200"> <DockPanel> <Grid> <ListBox x:Name="myListBox"> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> <ListBoxItem>Zamboni</ListBoxItem> </ListBox> </Grid> </DockPanel> </Window> ``` C# ``` private void Window_Loaded(object sender, RoutedEventArgs e) { // Get the border of the listview (first child of a listview) Decorator border = VisualTreeHelper.GetChild(myListBox, 0) as Decorator; if (border != null) { // Get scrollviewer ScrollViewer scrollViewer = border.Child as ScrollViewer; if (scrollViewer != null) { // center the Scroll Viewer... double center = scrollViewer.ScrollableHeight / 2.0; scrollViewer.ScrollToVerticalOffset(center); } } } ```
159,523
<p>When I call <code>Response.Redirect(someUrl)</code> I get the following HttpException:</p> <blockquote> <p>Cannot redirect after HTTP headers have been sent.</p> </blockquote> <p>Why do I get this? And how can I fix this issue?</p>
[ { "answer_id": 159529, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>A Redirect can only happen if the first line in an HTTP message is \"<code>HTTP/1.x 3xx Redirect Reason</code>\".</p>\n\n<p>If you already called <code>Response.Write()</code> or set some headers, it'll be too late for a redirect. You can try calling <code>Response.Headers.Clear()</code> before the Redirect to see if that helps.</p>\n" }, { "answer_id": 159538, "author": "Samuel Meacham", "author_id": 23886, "author_profile": "https://Stackoverflow.com/users/23886", "pm_score": 8, "selected": true, "text": "<p>According to the MSDN documentation for <code>Response.Redirect(string url)</code>, it will throw an HttpException when \"a redirection is attempted after the HTTP headers have been sent\". Since <code>Response.Redirect(string url)</code> uses the Http \"Location\" response header (<a href=\"http://en.wikipedia.org/wiki/HTTP_headers#Responses\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/HTTP_headers#Responses</a>), calling it will cause the headers to be sent to the client. This means that if you call it a second time, or if you call it after you've caused the headers to be sent in some other way, you'll get the HttpException.</p>\n\n<p>One way to guard against calling Response.Redirect() multiple times is to check the <code>Response.IsRequestBeingRedirected</code> property (bool) before calling it.</p>\n\n<pre><code>// Causes headers to be sent to the client (Http \"Location\" response header)\nResponse.Redirect(\"http://www.stackoverflow.com\");\nif (!Response.IsRequestBeingRedirected)\n // Will not be called\n Response.Redirect(\"http://www.google.com\");\n</code></pre>\n" }, { "answer_id": 159543, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 4, "selected": false, "text": "<p>Once you send any content at all to the client, the HTTP headers have already been sent. A <code>Response.Redirect()</code> call works by sending special information in the headers that make the browser ask for a different URL. </p>\n\n<p>Since the headers were already sent, asp.net can't do what you want (modify the headers)</p>\n\n<p>You can get around this by a) either doing the Redirect before you do anything else, or b) try using <code>Response.Buffer = true</code> before you do anything else, to make sure that no output is sent to the client until the whole page is done executing.</p>\n" }, { "answer_id": 810729, "author": "Nathan", "author_id": 6062, "author_profile": "https://Stackoverflow.com/users/6062", "pm_score": 0, "selected": false, "text": "<p>The redirect function probably works by using the 'refresh' http header (and maybe using a 30X code as well). Once the headers have been sent to the client, there is not way for the server to append that redirect command, its too late.</p>\n" }, { "answer_id": 810781, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Just check if you have set the buffering option to false (by default its true). For response.redirect to work,</p>\n\n<ol>\n<li>Buffering should be true,</li>\n<li>you should not have sent more data using response.write which exceeds the default buffer size (in which case it will flush itself causing the headers to be sent) therefore disallowing you to redirect.</li>\n</ol>\n" }, { "answer_id": 2061908, "author": "DucDigital", "author_id": 168501, "author_profile": "https://Stackoverflow.com/users/168501", "pm_score": 1, "selected": false, "text": "<p>There is one simple answer for this:\nYou have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error. </p>\n\n<p>Just check your code for posible output or you can put the header on top of your method so it will be send first.</p>\n" }, { "answer_id": 2292333, "author": "Brad", "author_id": 276495, "author_profile": "https://Stackoverflow.com/users/276495", "pm_score": 1, "selected": false, "text": "<p>If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location.replace or location.href, etc.) to redirect to whatever URL you want. Of course, that depends on what HTML has already been sent down.</p>\n" }, { "answer_id": 14214537, "author": "SamsonOnNet", "author_id": 1958024, "author_profile": "https://Stackoverflow.com/users/1958024", "pm_score": 1, "selected": false, "text": "<p>My Issue got resolved by adding the Exception Handler to handle\n\"Cannot redirect after HTTP headers have been sent\". this Error as shown below code</p>\n\n<pre><code>catch (System.Threading.ThreadAbortException)\n {\n // To Handle HTTP Exception \"Cannot redirect after HTTP headers have been sent\".\n }\n catch (Exception e)\n {//Here you can put your context.response.redirect(\"page.aspx\");}\n</code></pre>\n" }, { "answer_id": 29383317, "author": "Aashish Garg", "author_id": 4605106, "author_profile": "https://Stackoverflow.com/users/4605106", "pm_score": 0, "selected": false, "text": "<p>If you get Cannot redirect after HTTP headers have been sent then try this below code. </p>\n\n<pre><code>HttpContext.Current.Server.ClearError();\n// Response.Headers.Clear();\nHttpContext.Current.Response.Redirect(\"/Home/Login\",false);\n</code></pre>\n" }, { "answer_id": 33454002, "author": "utilsit", "author_id": 2769513, "author_profile": "https://Stackoverflow.com/users/2769513", "pm_score": 1, "selected": false, "text": "<p>I solved the problem using:\nResponse.RedirectToRoute(\"CultureEnabled\", RouteData.Values);\ninstead of Response.Redirect.</p>\n" }, { "answer_id": 36173422, "author": "Vasilis", "author_id": 6103150, "author_profile": "https://Stackoverflow.com/users/6103150", "pm_score": 2, "selected": false, "text": "<p>Using \n<code>return RedirectPermanent(myUrl)</code> worked for me</p>\n" }, { "answer_id": 40020986, "author": "1_bug", "author_id": 1385292, "author_profile": "https://Stackoverflow.com/users/1385292", "pm_score": 1, "selected": false, "text": "<p>Be sure that you don't use <code>Response</code>s' methods like <code>Response.Flush();</code> before your redirecting part.</p>\n" }, { "answer_id": 40372440, "author": "Dipanki Jadav", "author_id": 2845214, "author_profile": "https://Stackoverflow.com/users/2845214", "pm_score": 2, "selected": false, "text": "<p>You can also use below mentioned code </p>\n\n<pre><code>Response.Write(\"&lt;script type='text/javascript'&gt;\"); Response.Write(\"window.location = '\" + redirect url + \"'&lt;/script&gt;\");Response.Flush();\n</code></pre>\n" }, { "answer_id": 48010988, "author": "user9150083", "author_id": 9150083, "author_profile": "https://Stackoverflow.com/users/9150083", "pm_score": -1, "selected": false, "text": "<p>There are 2 ways to fix this:</p>\n\n<ol>\n<li><p>Just add a <code>return</code> statement after your <code>Response.Redirect(someUrl);</code>\n( if the method signature is not \"void\", you will have to return that \"type\", of course )\nas so:</p>\n\n<p>Response.Redirect(\"Login.aspx\");</p>\n\n<p>return;</p></li>\n</ol>\n\n<p>Note the return allows the server to perform the redirect...without it, the server wants to continue executing the rest of your code...</p>\n\n<ol start=\"2\">\n<li>Make your <code>Response.Redirect(someUrl)</code> the LAST executed statement in the method that is throwing the exception. Replace your <code>Response.Redirect(someUrl)</code> with a string VARIABLE named \"someUrl\", and set it to the redirect location... as follows:</li>\n</ol>\n\n<p><code>//......some code</code></p>\n\n<pre><code>string someUrl = String.Empty\n</code></pre>\n\n<p>.....some logic</p>\n\n<pre><code>if (x=y)\n{\n // comment (original location of Response.Redirect(\"Login.aspx\");)\n someUrl = \"Login.aspx\";\n}\n</code></pre>\n\n<p>......more code</p>\n\n<p>// MOVE your Response.Redirect to HERE (the end of the method):</p>\n\n<pre><code>Response.Redirect(someUrl);\nreturn; \n</code></pre>\n" }, { "answer_id": 51516613, "author": "Ram Samuj", "author_id": 10132852, "author_profile": "https://Stackoverflow.com/users/10132852", "pm_score": 1, "selected": false, "text": "<p><b> Error</b>\nCannot redirect after HTTP headers have been sent.<br></p>\n\n<p>System.Web.HttpException (0x80004005): Cannot redirect after HTTP headers have been sent.<br><br></p>\n\n<p><b>Suggestion</b><br><br>\nIf we use asp.net mvc and working on same controller and redirect to different Action then you do not need to write.. <br><b> Response.Redirect(\"ActionName\",\"ControllerName\");</b><br> its better to use only <br><b> return RedirectToAction(\"ActionName\");</b><br> or <br> return View(\"ViewName\");<br></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23886/" ]
When I call `Response.Redirect(someUrl)` I get the following HttpException: > > Cannot redirect after HTTP headers have been sent. > > > Why do I get this? And how can I fix this issue?
According to the MSDN documentation for `Response.Redirect(string url)`, it will throw an HttpException when "a redirection is attempted after the HTTP headers have been sent". Since `Response.Redirect(string url)` uses the Http "Location" response header (<http://en.wikipedia.org/wiki/HTTP_headers#Responses>), calling it will cause the headers to be sent to the client. This means that if you call it a second time, or if you call it after you've caused the headers to be sent in some other way, you'll get the HttpException. One way to guard against calling Response.Redirect() multiple times is to check the `Response.IsRequestBeingRedirected` property (bool) before calling it. ``` // Causes headers to be sent to the client (Http "Location" response header) Response.Redirect("http://www.stackoverflow.com"); if (!Response.IsRequestBeingRedirected) // Will not be called Response.Redirect("http://www.google.com"); ```
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
[ { "answer_id": 159819, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>What fastcgi interface are you using and how. Is it flup? If yes, paste the way you spawn the server and how it's hooked into nginx. Without that information it's just guessing what could go wrong.</p>\n\n<p>Possible problems:</p>\n\n<ul>\n<li>nginx is buggy. At least lighttpd has horrible fastcgi bugs, I wouldn't wonder if nginx has some too :)</li>\n<li>Django is dying with a traceback in an internal system that is not properly catched and closes the fastcgi server which you can't see from the client. In that situation wrap the fastcgi server application call and try/except it to print the exception.</li>\n</ul>\n\n<p>But server log and config would be great.</p>\n" }, { "answer_id": 675015, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>try to raise \"gzip_buffers\" may help.</p>\n\n<p>see here:\n<a href=\"http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl\" rel=\"nofollow noreferrer\">http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl</a></p>\n" }, { "answer_id": 1172861, "author": "Frozenskys", "author_id": 142848, "author_profile": "https://Stackoverflow.com/users/142848", "pm_score": 0, "selected": false, "text": "<p>I'm running very similar configurations to this both on my webhost (Webfaction) and on a local Ubuntu dev server and I don't see any problems. I'm guessing it's a time-out or full buffer that's causing this.</p>\n\n<p>Can you post the output of the nginx error log? Also what version of nginx are you using?</p>\n\n<p>As a side note it may be worth looking at <a href=\"http://code.google.com/p/django-logging/wiki/Overview\" rel=\"nofollow noreferrer\">django-logging</a> to find out what your fastcgi process is doing.</p>\n" }, { "answer_id": 4515898, "author": "dwc", "author_id": 57301, "author_profile": "https://Stackoverflow.com/users/57301", "pm_score": 3, "selected": false, "text": "<p>Check your error logs for \"Permission denied\" errors writing to <code>.../nginx/tmp/...</code> files. Nginx will work fine unless it needs temporary space, and that typically happens at 32K boundaries. If you find these errors, make sure the tmp directory is writable by the user nginx runs as.</p>\n" }, { "answer_id": 5218788, "author": "Falken", "author_id": 194443, "author_profile": "https://Stackoverflow.com/users/194443", "pm_score": 3, "selected": false, "text": "<p>I had the same exact problem running Nagios on nginx. I stumbled upon your question while googling for an answer, and reading \"permission denied\" related answers it struck me (and perhaps it will help you) : </p>\n\n<ul>\n<li><p>Nginx error.log was reporting :</p>\n\n<p>2011/03/07 11:36:02 [crit] 30977#0: *225952 open() \"/var/lib/nginx/fastcgi/2/65/0000002652\" failed (13: Permission denied)</p></li>\n<li><p>so I just ran # chown -R www-data:www-data /var/lib/nginx/fastcgi</p></li>\n<li><p>Fixed ! (and thank you for your indirect help)</p></li>\n</ul>\n" }, { "answer_id": 6033063, "author": "rewritten", "author_id": 384417, "author_profile": "https://Stackoverflow.com/users/384417", "pm_score": 2, "selected": false, "text": "<p>FastCGI is not to blame for this. </p>\n\n<p>I ran into exactly the same issue using nginx/gunicorn. Reducing the response size to less than 32k (in the specific case using the <code>spaceless</code> tag in the template) solved it.</p>\n\n<p>As dwc says, it's probably a hard limit due to the way nginx uses address space.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2933/" ]
I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it) Details: I'm using flup, and spawning the fastcgi server with the following command: ``` python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid ``` The nginx config is as follows: ``` # search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } ```
Check your error logs for "Permission denied" errors writing to `.../nginx/tmp/...` files. Nginx will work fine unless it needs temporary space, and that typically happens at 32K boundaries. If you find these errors, make sure the tmp directory is writable by the user nginx runs as.
159,554
<p>I'm looking for a built-in function/extended function in T-SQL for string manipulation similar to the <code>String.Format</code> method in .NET.</p>
[ { "answer_id": 159579, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>Raw t-sql is limited to CHARINDEX(), PATINDEX(), REPLACE(), and SUBSTRING() for string manipulation. But with sql server 2005 and later you can set up user defined functions that run in .Net, which means setting up a string.format() UDF shouldn't be too tough.</p>\n" }, { "answer_id": 159900, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": -1, "selected": false, "text": "<p>Not exactly, but I would check out some of the <a href=\"http://www.simple-talk.com/author/robyn-page-and-phil-factor/\" rel=\"nofollow noreferrer\">articles</a> on string handling (amongst other things) by \"Phil Factor\" (geddit?) on Simple Talk.</p>\n" }, { "answer_id": 836894, "author": "jj.", "author_id": 103131, "author_profile": "https://Stackoverflow.com/users/103131", "pm_score": 2, "selected": false, "text": "<p>There is a way, but it has its limitations. You can use the <code>FORMATMESSAGE()</code> function. It allows you to format a string using formatting similar to the <code>printf()</code> function in C. </p>\n\n<p>However, the biggest limitation is that it will only work with messages in the sys.messages table. Here's an article about it: <a href=\"http://msdn.microsoft.com/en-us/library/ms186788.aspx\" rel=\"nofollow noreferrer\">microsoft_library_ms186788</a></p>\n\n<p>It's kind of a shame there isn't an easier way to do this, because there are times when you want to format a string/varchar in the database. Hopefully you are only looking to format a string in a standard way and can use the <code>sys.messages</code> table.</p>\n\n<p>Coincidentally, you could also use the <code>RAISERROR()</code> function with a very low severity, the documentation for raiseerror even mentions doing this, but the results are only printed. So you wouldn't be able to do anything with the resulting value (from what I understand).</p>\n\n<p>Good luck! </p>\n" }, { "answer_id": 1153194, "author": "Josh", "author_id": 123234, "author_profile": "https://Stackoverflow.com/users/123234", "pm_score": 6, "selected": false, "text": "<p>take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms175014.aspx\" rel=\"noreferrer\">xp_sprintf</a>. example below.</p>\n\n<pre><code>DECLARE @ret_string varchar (255)\nEXEC xp_sprintf @ret_string OUTPUT, \n 'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'\nPRINT @ret_string\n</code></pre>\n\n<p>Result looks like this:</p>\n\n<pre><code>INSERT INTO table1 VALUES (1, 2)\n</code></pre>\n\n<hr>\n\n<p>Just found an issue with the max size (255 char limit) of the string with this so there is an <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=65584\" rel=\"noreferrer\">alternative function</a> you can use:</p>\n\n<pre><code>create function dbo.fnSprintf (@s varchar(MAX), \n @params varchar(MAX), @separator char(1) = ',')\nreturns varchar(MAX)\nas\nbegin\ndeclare @p varchar(MAX)\ndeclare @paramlen int\n\nset @params = @params + @separator\nset @paramlen = len(@params)\nwhile not @params = ''\nbegin\n set @p = left(@params+@separator, charindex(@separator, @params)-1)\n set @s = STUFF(@s, charindex('%s', @s), 2, @p)\n set @params = substring(@params, len(@p)+2, @paramlen)\nend\nreturn @s\nend\n</code></pre>\n\n<p>To get the same result as above you call the function as follows:</p>\n\n<pre><code>print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)\n</code></pre>\n" }, { "answer_id": 4502764, "author": "Karthik D V", "author_id": 550359, "author_profile": "https://Stackoverflow.com/users/550359", "pm_score": 4, "selected": false, "text": "<p>I have created a user defined function to mimic the string.format functionality.\nYou can use it.</p>\n<p><a href=\"http://stringformat-in-sql.blogspot.com/\" rel=\"nofollow noreferrer\">stringformat-in-sql</a></p>\n<p>UPDATE:<br/>\nThis version allows the user to change the delimitter.</p>\n<pre><code>-- DROP function will loose the security settings.\nIF object_id('[dbo].[svfn_FormatString]') IS NOT NULL\n DROP FUNCTION [dbo].[svfn_FormatString]\nGO\n\nCREATE FUNCTION [dbo].[svfn_FormatString]\n(\n @Format NVARCHAR(4000),\n @Parameters NVARCHAR(4000),\n @Delimiter CHAR(1) = ','\n)\nRETURNS NVARCHAR(MAX)\nAS\nBEGIN\n /*\n Name: [dbo].[svfn_FormatString]\n Creation Date: 12/18/2020\n\n Purpose: Returns the formatted string (Just like in C-Sharp)\n\n Input Parameters: @Format = The string to be Formatted\n @Parameters = The comma separated list of parameters\n @Delimiter = The delimitter to be used in the formatting process\n\n Format: @Format = N'Hi {0}, Welcome to our site {1}. Thank you {0}'\n @Parameters = N'Karthik,google.com'\n @Delimiter = ',' \n Examples:\n SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik,google.com', default)\n SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik;google.com', ';')\n */\n DECLARE @Message NVARCHAR(400)\n DECLARE @ParamTable TABLE ( Id INT IDENTITY(0,1), Paramter VARCHAR(1000))\n\n SELECT @Message = @Format\n\n ;WITH CTE (StartPos, EndPos) AS\n (\n SELECT 1, CHARINDEX(@Delimiter, @Parameters)\n UNION ALL\n SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter, @Parameters, EndPos + (LEN(@Delimiter)))\n FROM CTE\n WHERE EndPos &gt; 0\n )\n\n INSERT INTO @ParamTable ( Paramter )\n SELECT\n [Id] = SUBSTRING(@Parameters, StartPos, CASE WHEN EndPos &gt; 0 THEN EndPos - StartPos ELSE 4000 END )\n FROM CTE\n\n UPDATE @ParamTable \n SET \n @Message = REPLACE(@Message, '{'+ CONVERT(VARCHAR, Id) + '}', Paramter )\n\n RETURN @Message\nEND\n</code></pre>\n" }, { "answer_id": 4514667, "author": "BraveNewMath", "author_id": 551811, "author_profile": "https://Stackoverflow.com/users/551811", "pm_score": 0, "selected": false, "text": "<p>here's what I found with my experiments using the built-in</p>\n\n<p>FORMATMESSAGE() function</p>\n\n<pre><code>sp_addmessage @msgnum=50001,@severity=1,@msgText='Hello %s you are #%d',@replace='replace'\nSELECT FORMATMESSAGE(50001, 'Table1', 5)\n</code></pre>\n\n<p>when you call up sp_addmessage, your message template gets stored into the system table master.dbo.sysmessages (verified on SQLServer 2000). </p>\n\n<p>You must manage addition and removal of template strings from the table yourself, which is awkward if all you really want is output a quick message to the results screen.</p>\n\n<p>The solution provided by Kathik DV, looks interesting but doesn't work with SQL Server 2000, so i altered it a bit, and this version should work with all versions of SQL Server:</p>\n\n<pre><code>IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL\n DROP FUNCTION [dbo].[FormatString]\nGO\n/***************************************************\nObject Name : FormatString\nPurpose : Returns the formatted string.\nOriginal Author : Karthik D V http://stringformat-in-sql.blogspot.com/\nSample Call:\nSELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )\n*******************************************/\nCREATE FUNCTION [dbo].[FormatString](\n@Format NVARCHAR(4000) ,\n@Parameters NVARCHAR(4000)\n)\nRETURNS NVARCHAR(4000)\nAS\nBEGIN\n --DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'\n DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)\n DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )\n Declare @startPos int, @endPos int\n SELECT @Message = @Format, @Delimiter = ','\n\n --handle first parameter\n set @endPos=CHARINDEX(@Delimiter,@Parameters)\n if (@endPos=0 and @Parameters is not null) --there is only one parameter\n insert into @ParamTable (Parameter) values(@Parameters)\n else begin\n insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)\n end\n\n while @endPos&gt;0\n Begin\n --insert a row for each parameter in the \n set @startPos = @endPos + LEN(@Delimiter)\n set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)\n if (@endPos&gt;0)\n insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,@endPos)\n else\n insert into @ParamTable (Parameter) select substring(@Parameters,@startPos,4000) \n End\n\n UPDATE @ParamTable SET @Message = REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )\n RETURN @Message\nEND\nGo\n grant execute,references on dbo.formatString to public\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>print dbo.formatString('hello {0}... you are {1}','world,good')\n--result: hello world... you are good\n</code></pre>\n" }, { "answer_id": 4948646, "author": "SP007", "author_id": 610194, "author_profile": "https://Stackoverflow.com/users/610194", "pm_score": 2, "selected": false, "text": "<p>I think there is small correction while calculating end position.</p>\n\n<p>Here is correct function</p>\n\n<pre><code>**&gt;&gt;**IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL\nDROP FUNCTION [dbo].[FormatString]\nGO\n/***************************************************\nObject Name : FormatString\nPurpose : Returns the formatted string.\nOriginal Author : Karthik D V http://stringformat-in-sql.blogspot.com/\nSample Call:\nSELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )\n*******************************************/\nCREATE FUNCTION [dbo].[FormatString](\n @Format NVARCHAR(4000) ,\n @Parameters NVARCHAR(4000)\n)\nRETURNS NVARCHAR(4000)\nAS\nBEGIN\n --DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'\n DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)\n DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )\n Declare @startPos int, @endPos int\n SELECT @Message = @Format, @Delimiter = ','**&gt;&gt;**\n\n --handle first parameter\n set @endPos=CHARINDEX(@Delimiter,@Parameters)\n if (@endPos=0 and @Parameters is not null) --there is only one parameter\n insert into @ParamTable (Parameter) values(@Parameters)\n else begin\n insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)\n end\n\n while @endPos&gt;0\n Begin\n --insert a row for each parameter in the \n set @startPos = @endPos + LEN(@Delimiter)\n set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)\n if (@endPos&gt;0)\n insert into @ParamTable (Parameter) \n select substring(@Parameters,@startPos,@endPos - @startPos)\n else\n insert into @ParamTable (Parameter) \n select substring(@Parameters,@startPos,4000) \n End\n\n UPDATE @ParamTable SET @Message = \n REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )\n RETURN @Message\nEND\nGo\ngrant execute,references on dbo.formatString to public \n</code></pre>\n" }, { "answer_id": 20123854, "author": "pelegk1", "author_id": 2437079, "author_profile": "https://Stackoverflow.com/users/2437079", "pm_score": -1, "selected": false, "text": "<p>this is bad approach. you should work with assembly dll's, in which will do the same for you with better performance.</p>\n" }, { "answer_id": 28240424, "author": "Vadim Loboda", "author_id": 623190, "author_profile": "https://Stackoverflow.com/users/623190", "pm_score": 2, "selected": false, "text": "<p>One more idea. </p>\n\n<p>Although this is not a universal solution - it is simple and works, at least for me :)</p>\n\n<p>For one placeholder {0}:</p>\n\n<pre><code>create function dbo.Format1\n(\n @String nvarchar(4000),\n @Param0 sql_variant\n)\nreturns nvarchar(4000)\nas\nbegin\n declare @Null nvarchar(4) = N'NULL';\n\n return replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000))); \nend\n</code></pre>\n\n<p>For two placeholders {0} and {1}:</p>\n\n<pre><code>create function dbo.Format2\n(\n @String nvarchar(4000),\n @Param0 sql_variant,\n @Param1 sql_variant\n)\nreturns nvarchar(4000)\nas\nbegin\n declare @Null nvarchar(4) = N'NULL';\n\n set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));\n return replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000))); \nend\n</code></pre>\n\n<p>For three placeholders {0}, {1} and {2}:</p>\n\n<pre><code>create function dbo.Format3\n(\n @String nvarchar(4000),\n @Param0 sql_variant,\n @Param1 sql_variant,\n @Param2 sql_variant\n)\nreturns nvarchar(4000)\nas\nbegin\n declare @Null nvarchar(4) = N'NULL';\n\n set @String = replace(@String, N'{0}', cast(isnull(@Param0, @Null) as nvarchar(4000)));\n set @String = replace(@String, N'{1}', cast(isnull(@Param1, @Null) as nvarchar(4000))); \n return replace(@String, N'{2}', cast(isnull(@Param2, @Null) as nvarchar(4000)));\nend\n</code></pre>\n\n<p>and so on...</p>\n\n<p>Such an approach allows us to use these functions in SELECT statement and with parameters of nvarchar, number, bit and datetime datatypes. </p>\n\n<p>For example:</p>\n\n<pre><code>declare @Param0 nvarchar(10) = N'IPSUM' ,\n @Param1 int = 1234567 ,\n @Param2 datetime2(0) = getdate();\n\nselect dbo.Format3(N'Lorem {0} dolor, {1} elit at {2}', @Param0, @Param1, @Param2); \n</code></pre>\n" }, { "answer_id": 30260729, "author": "g2server", "author_id": 2293226, "author_profile": "https://Stackoverflow.com/users/2293226", "pm_score": 7, "selected": false, "text": "<p>If you are using SQL Server 2012 and above, you can use <code>FORMATMESSAGE</code>. eg.</p>\n\n<pre><code>DECLARE @s NVARCHAR(50) = 'World';\nDECLARE @d INT = 123;\nSELECT FORMATMESSAGE('Hello %s, %d', @s, @d)\n-- RETURNS 'Hello World, 123'\n</code></pre>\n\n<hr>\n\n<p>More examples from MSDN: <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/formatmessage-transact-sql\" rel=\"noreferrer\">FORMATMESSAGE</a></p>\n\n<pre><code>SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);\nSELECT FORMATMESSAGE('Signed int with leading zero %020i', 5);\nSELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);\nSELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);\nSELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);\nSELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);\nSELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);\nSELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);\nSELECT FORMATMESSAGE('Hello %s!', 'TEST');\nSELECT FORMATMESSAGE('Hello %20s!', 'TEST');\nSELECT FORMATMESSAGE('Hello %-20s!', 'TEST');\nSELECT FORMATMESSAGE('Hello %20s!', 'TEST');\n</code></pre>\n\n<p>NOTES:</p>\n\n<ul>\n<li>Undocumented in 2012</li>\n<li>Limited to 2044 characters</li>\n<li>To escape the % sign, you need to double it. </li>\n<li>If you are logging errors in extended events, calling <code>FORMATMESSAGE</code> comes up as a (harmless) error</li>\n</ul>\n" }, { "answer_id": 43696634, "author": "Tejasvi Hegde", "author_id": 1726296, "author_profile": "https://Stackoverflow.com/users/1726296", "pm_score": 1, "selected": false, "text": "<p>Here is my version. Can be extended to accommodate more number of parameters and can extend formatting based on type. Currently only date and datetime types are formatted.</p>\n\n<p>Example:</p>\n\n<pre><code>select dbo.FormatString('some string %s some int %s date %s','\"abcd\"',100,cast(getdate() as date),DEFAULT,DEFAULT)\nselect dbo.FormatString('some string %s some int %s date time %s','\"abcd\"',100,getdate(),DEFAULT,DEFAULT)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>some string \"abcd\" some int 100 date 29-Apr-2017\nsome string \"abcd\" some int 100 date time 29-Apr-2017 19:40\n</code></pre>\n\n<p>Functions:</p>\n\n<pre><code>create function dbo.FormatValue(@param sql_variant)\nreturns nvarchar(100)\nbegin\n/*\nTejasvi Hegde, 29-April-2017\nCan extend formatting here.\n*/\n declare @result nvarchar(100)\n\n if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('date'))\n begin\n select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')\n end\n else if (SQL_VARIANT_PROPERTY(@param,'BaseType') in ('datetime','datetime2'))\n begin\n select @result = REPLACE(CONVERT(CHAR(11), @param, 106), ' ', '-')+' '+CONVERT(VARCHAR(5),@param,108)\n end\n else\n begin\n select @result = cast(@param as nvarchar(100))\n end\n return @result\n\n/*\nBaseType:\nbigint\nbinary\nchar\ndate\ndatetime\ndatetime2\ndatetimeoffset\ndecimal\nfloat\nint\nmoney\nnchar\nnumeric\nnvarchar\nreal\nsmalldatetime\nsmallint\nsmallmoney\ntime\ntinyint\nuniqueidentifier\nvarbinary\nvarchar\n*/ \n\nend;\n\n\ncreate function dbo.FormatString(\n @format nvarchar(4000)\n ,@param1 sql_variant = null\n ,@param2 sql_variant = null\n ,@param3 sql_variant = null\n ,@param4 sql_variant = null\n ,@param5 sql_variant = null\n )\nreturns nvarchar(4000)\nbegin\n/*\nTejasvi Hegde, 29-April-2017\n\nselect dbo.FormatString('some string value %s some int %s date %s','\"abcd\"',100,cast(getdate() as date),DEFAULT,DEFAULT)\nselect dbo.FormatString('some string value %s some int %s date time %s','\"abcd\"',100,getdate(),DEFAULT,DEFAULT)\n*/\n\n declare @result nvarchar(4000)\n\n select @param1 = dbo.formatValue(@param1)\n ,@param2 = dbo.formatValue(@param2)\n ,@param3 = dbo.formatValue(@param3)\n ,@param4 = dbo.formatValue(@param4)\n ,@param5 = dbo.formatValue(@param5)\n\n select @param2 = cast(@param2 as nvarchar)\n EXEC xp_sprintf @result OUTPUT,@format , @param1, @param2, @param3, @param4, @param5\n\n return @result\n\nend;\n</code></pre>\n" }, { "answer_id": 47703620, "author": "jmoreno", "author_id": 234954, "author_profile": "https://Stackoverflow.com/users/234954", "pm_score": 0, "selected": false, "text": "<p>At the moment this doesn't really exist (although you can of course write your own). There is an open connect bug for it: <a href=\"https://connect.microsoft.com/SQLServer/Feedback/Details/3130221\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/SQLServer/Feedback/Details/3130221</a>, which as of this writing has just 1 vote. </p>\n" }, { "answer_id": 59577544, "author": "Brijesh Kumar Tripathi", "author_id": 9203434, "author_profile": "https://Stackoverflow.com/users/9203434", "pm_score": 2, "selected": false, "text": "<p>Actually there is no built in function similar to string.Format function of .NET is available in SQL server. </p>\n\n<p>There is a function <strong>FORMATMESSAGE()</strong> in SQL server but it mimics to printf() function of C not string.Format function of .NET.</p>\n\n<pre><code>SELECT FORMATMESSAGE('This is the %s and this is the %s.', 'first variable', 'second variable') AS Result\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking for a built-in function/extended function in T-SQL for string manipulation similar to the `String.Format` method in .NET.
If you are using SQL Server 2012 and above, you can use `FORMATMESSAGE`. eg. ``` DECLARE @s NVARCHAR(50) = 'World'; DECLARE @d INT = 123; SELECT FORMATMESSAGE('Hello %s, %d', @s, @d) -- RETURNS 'Hello World, 123' ``` --- More examples from MSDN: [FORMATMESSAGE](https://learn.microsoft.com/en-us/sql/t-sql/functions/formatmessage-transact-sql) ``` SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11); SELECT FORMATMESSAGE('Signed int with leading zero %020i', 5); SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55); SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50); SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50); SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50); SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50); SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50); SELECT FORMATMESSAGE('Hello %s!', 'TEST'); SELECT FORMATMESSAGE('Hello %20s!', 'TEST'); SELECT FORMATMESSAGE('Hello %-20s!', 'TEST'); SELECT FORMATMESSAGE('Hello %20s!', 'TEST'); ``` NOTES: * Undocumented in 2012 * Limited to 2044 characters * To escape the % sign, you need to double it. * If you are logging errors in extended events, calling `FORMATMESSAGE` comes up as a (harmless) error
159,567
<p>How do I parse the first, middle, and last name out of a fullname field with SQL? </p> <p>I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name. </p> <p>The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'.</p> <p>I'm interested in some practical solutions to get me 90% of the way there. As it has been stated, this is a complex problem, so I'll handle special cases individually.</p>
[ { "answer_id": 159595, "author": "Josh Millard", "author_id": 13600, "author_profile": "https://Stackoverflow.com/users/13600", "pm_score": 3, "selected": false, "text": "<p>Unless you have very, very well-behaved data, this is a non-trivial challenge. A naive approach would be to tokenize on whitespace and assume that a three-token result is [first, middle, last] and a two-token result is [first, last], but you're going to have to deal with multi-word surnames (e.g. \"Van Buren\") and multiple middle names.</p>\n" }, { "answer_id": 159607, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>Are you sure the Full Legal Name will always include First, Middle and Last? I know people that have only one name as Full Legal Name, and honestly I am not sure if that's their First or Last Name. :-) I also know people that have more than one Fisrt names in their legal name, but don't have a Middle name. And there are some people that have multiple Middle names.</p>\n\n<p>Then there's also the order of the names in the Full Legal Name. As far as I know, in some Asian cultures the Last Name comes first in the Full Legal Name.</p>\n\n<p>On a more practical note, you could split the Full Name on whitespace and threat the first token as First name and the last token (or the only token in case of only one name) as Last name. Though this assumes that the order will be always the same.</p>\n" }, { "answer_id": 159626, "author": "Bartek Szabat", "author_id": 23774, "author_profile": "https://Stackoverflow.com/users/23774", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Get a sql regex function. Sample: <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163473.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163473.aspx</a></li>\n<li>Extract names using regular expressions. </li>\n</ol>\n\n<p>I recommend Expresso for learnin/building/testing regular expressions. <a href=\"http://www.codeproject.com/KB/dotnet/expresso.aspx\" rel=\"nofollow noreferrer\">Old free version</a>, <a href=\"http://www.ultrapico.com/Expresso.htm\" rel=\"nofollow noreferrer\">new commercial version</a></p>\n" }, { "answer_id": 159628, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 3, "selected": false, "text": "<p>It's difficult to answer without knowing how the \"full name\" is formatted.</p>\n\n<p>It could be \"Last Name, First Name Middle Name\" or \"First Name Middle Name Last Name\", etc.</p>\n\n<p>Basically you'll have to use the <strong>SUBSTRING</strong> function</p>\n\n<pre><code>SUBSTRING ( expression , start , length )\n</code></pre>\n\n<p>And probably the <strong>CHARINDEX</strong> function </p>\n\n<pre><code>CHARINDEX (substr, expression)\n</code></pre>\n\n<p>To figure out the start and length for each part you want to extract.</p>\n\n<p>So let's say the format is \"First Name Last Name\" you could (untested.. but should be close) : </p>\n\n<pre><code>SELECT \nSUBSTRING(fullname, 1, CHARINDEX(' ', fullname) - 1) AS FirstName, \nSUBSTRING(fullname, CHARINDEX(' ', fullname) + 1, len(fullname)) AS LastName\nFROM YourTable\n</code></pre>\n" }, { "answer_id": 159664, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Reverse the problem, add columns to hold the individual pieces and combine them to get the full name.</p>\n\n<p>The reason this will be the <em>best</em> answer is that there is no guaranteed way to figure out a person has registered as their first name, and what is their middle name.</p>\n\n<p>For instance, how would you split this?</p>\n\n<pre><code>Jan Olav Olsen Heggelien\n</code></pre>\n\n<p>This, while being fictious, is a legal name in Norway, and could, but would not have to, be split like this:</p>\n\n<pre><code>First name: Jan Olav\nMiddle name: Olsen\nLast name: Heggelien\n</code></pre>\n\n<p>or, like this:</p>\n\n<pre><code>First name: Jan Olav\nLast name: Olsen Heggelien\n</code></pre>\n\n<p>or, like this:</p>\n\n<pre><code>First name: Jan\nMiddle name: Olav\nLast name: Olsen Heggelien\n</code></pre>\n\n<p>I would imagine similar occurances can be found in most languages.</p>\n\n<p>So instead of trying to interpreting data which does not have enough information to get it right, store the correct interpretation, and combine to get the full name.</p>\n" }, { "answer_id": 159676, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about SQL server, but in postgres you could do something like this:</p>\n\n<pre><code>SELECT \n SUBSTRING(fullname, '(\\\\w+)') as firstname,\n SUBSTRING(fullname, '\\\\w+\\\\s(\\\\w+)\\\\s\\\\w+') as middle,\n COALESCE(SUBSTRING(fullname, '\\\\w+\\\\s\\\\w+\\\\s(\\\\w+)'), SUBSTRING(fullname, '\\\\w+\\\\s(\\\\w+)')) as lastname\nFROM \npublic.person\n</code></pre>\n\n<p>The regex expressions could probably be a bit more concise; but you get the point. This does by the way not work for persons having two double names (in the Netherlands we have this a lot 'Jan van der Ploeg') so I'd be very careful with the results.</p>\n" }, { "answer_id": 159707, "author": "Marc Bernier", "author_id": 23569, "author_profile": "https://Stackoverflow.com/users/23569", "pm_score": 1, "selected": false, "text": "<p>Like #1 said, it's not trivial. Hyphenated last names, initials, double names, inverse name sequence and a variety of other anomalies can ruin your carefully crafted function.</p>\n\n<p>You could use a 3rd party library (plug/disclaimer - I worked on this product):</p>\n\n<p><a href=\"http://www.melissadata.com/nameobject/nameobject.htm\" rel=\"nofollow noreferrer\">http://www.melissadata.com/nameobject/nameobject.htm</a></p>\n" }, { "answer_id": 159742, "author": "Ben", "author_id": 16424, "author_profile": "https://Stackoverflow.com/users/16424", "pm_score": 1, "selected": false, "text": "<p>I would do this as an iterative process. </p>\n\n<p>1) Dump the table to a flat file to work with.</p>\n\n<p>2) Write a simple program to break up your Names using a space as separator where firsts token is the first name, if there are 3 token then token 2 is middle name and token 3 is last name. If there are 2 tokens then the second token is the last name. (Perl, Java, or C/C++, language doesn't matter)</p>\n\n<p>3) Eyeball the results. Look for names that don't fit this rule. </p>\n\n<p>4) Using that example, create a new rule to handle that exception...</p>\n\n<p>5) Rinse and Repeat</p>\n\n<p>Eventually you will get a program that fixes all your data.</p>\n" }, { "answer_id": 159760, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 8, "selected": true, "text": "<p>Here is a self-contained example, with easily manipulated test data. </p>\n\n<p>With this example, if you have a name with more than three parts, then all the \"extra\" stuff will get put in the LAST_NAME field. An exception is made for specific strings that are identified as \"titles\", such as \"DR\", \"MRS\", and \"MR\".</p>\n\n<p>If the middle name is missing, then you just get FIRST_NAME and LAST_NAME (MIDDLE_NAME will be NULL).</p>\n\n<p>You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL.</p>\n\n<p><strong>Edit-- Handle the following special cases:</strong></p>\n\n<p><strong>1 - The NAME field is NULL</strong></p>\n\n<p><strong>2 - The NAME field contains leading / trailing spaces</strong></p>\n\n<p><strong>3 - The NAME field has > 1 consecutive space within the name</strong></p>\n\n<p><strong>4 - The NAME field contains ONLY the first name</strong></p>\n\n<p><strong>5 - Include the original full name in the final output as a separate column, for readability</strong></p>\n\n<p><strong>6 - Handle a specific list of prefixes as a separate \"title\" column</strong></p>\n\n<pre><code>SELECT\n FIRST_NAME.ORIGINAL_INPUT_DATA\n ,FIRST_NAME.TITLE\n ,FIRST_NAME.FIRST_NAME\n ,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)\n THEN NULL --no more spaces? assume rest is the last name\n ELSE SUBSTRING(\n FIRST_NAME.REST_OF_NAME\n ,1\n ,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1\n )\n END AS MIDDLE_NAME\n ,SUBSTRING(\n FIRST_NAME.REST_OF_NAME\n ,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)\n ,LEN(FIRST_NAME.REST_OF_NAME)\n ) AS LAST_NAME\nFROM\n ( \n SELECT\n TITLE.TITLE\n ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)\n THEN TITLE.REST_OF_NAME --No space? return the whole thing\n ELSE SUBSTRING(\n TITLE.REST_OF_NAME\n ,1\n ,CHARINDEX(' ',TITLE.REST_OF_NAME)-1\n )\n END AS FIRST_NAME\n ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME) \n THEN NULL --no spaces @ all? then 1st name is all we have\n ELSE SUBSTRING(\n TITLE.REST_OF_NAME\n ,CHARINDEX(' ',TITLE.REST_OF_NAME)+1\n ,LEN(TITLE.REST_OF_NAME)\n )\n END AS REST_OF_NAME\n ,TITLE.ORIGINAL_INPUT_DATA\n FROM\n ( \n SELECT\n --if the first three characters are in this list,\n --then pull it as a \"title\". otherwise return NULL for title.\n CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')\n THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3)))\n ELSE NULL\n END AS TITLE\n --if you change the list, don't forget to change it here, too.\n --so much for the DRY prinicple...\n ,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')\n THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME))))\n ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME))\n END AS REST_OF_NAME\n ,TEST_DATA.ORIGINAL_INPUT_DATA\n FROM\n (\n SELECT\n --trim leading &amp; trailing spaces before trying to process\n --disallow extra spaces *within* the name\n REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME\n ,FULL_NAME AS ORIGINAL_INPUT_DATA\n FROM\n (\n --if you use this, then replace the following\n --block with your actual table\n SELECT 'GEORGE W BUSH' AS FULL_NAME\n UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME\n UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME\n UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME\n UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME\n UNION SELECT 'TOMMY' AS FULL_NAME\n UNION SELECT 'BILLY' AS FULL_NAME\n UNION SELECT NULL AS FULL_NAME\n UNION SELECT ' ' AS FULL_NAME\n UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME\n UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME\n UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME\n UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME\n UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME \n ) RAW_DATA\n ) TEST_DATA\n ) TITLE\n ) FIRST_NAME\n</code></pre>\n" }, { "answer_id": 159765, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I once made a 500 character regular expression to parse first, last and middle names from an arbitrary string. Even with that honking regex, it only got around 97% accuracy due to the complete inconsistency of the input. Still, better than nothing.</p>\n" }, { "answer_id": 159767, "author": "Kluge", "author_id": 8752, "author_profile": "https://Stackoverflow.com/users/8752", "pm_score": 0, "selected": false, "text": "<p>Subject to the caveats that have already been raised regarding spaces in names and other anomalies, the following code will at least handle 98% of names. (Note: messy SQL because I don't have a regex option in the database I use.)</p>\n\n<p>**Warning: messy SQL follows:</p>\n\n<pre><code>create table parsname (fullname char(50), name1 char(30), name2 char(30), name3 char(30), name4 char(40));\ninsert into parsname (fullname) select fullname from ImportTable;\nupdate parsname set name1 = substring(fullname, 1, locate(' ', fullname)),\n fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))\n where locate(' ', rtrim(fullname)) &gt; 0;\nupdate parsname set name2 = substring(fullname, 1, locate(' ', fullname)),\n fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))\n where locate(' ', rtrim(fullname)) &gt; 0;\nupdate parsname set name3 = substring(fullname, 1, locate(' ', fullname)),\n fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))\n where locate(' ', rtrim(fullname)) &gt; 0;\nupdate parsname set name4 = substring(fullname, 1, locate(' ', fullname)),\n fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))\n where locate(' ', rtrim(fullname)) &gt; 0;\n// fullname now contains the last word in the string.\nselect fullname as FirstName, '' as MiddleName, '' as LastName from parsname where fullname is not null and name1 is null and name2 is null\nunion all\nselect name1 as FirstName, name2 as MiddleName, fullname as LastName from parsname where name1 is not null and name3 is null\n</code></pre>\n\n<p>The code works by creating a temporary table (parsname) and tokenizing the fullname by spaces. Any names ending up with values in name3 or name4 are non-conforming and will need to be dealt with differently.</p>\n" }, { "answer_id": 159980, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 0, "selected": false, "text": "<p>Here's a stored procedure that will put the first word found into First Name, the last word into Last Name and everything in between into Middle Name.</p>\n\n<pre><code>create procedure [dbo].[import_ParseName]\n( \n @FullName nvarchar(max),\n @FirstName nvarchar(255) output,\n @MiddleName nvarchar(255) output,\n @LastName nvarchar(255) output\n)\nas\nbegin\n\nset @FirstName = ''\nset @MiddleName = ''\nset @LastName = '' \nset @FullName = ltrim(rtrim(@FullName))\n\ndeclare @ReverseFullName nvarchar(max)\nset @ReverseFullName = reverse(@FullName)\n\ndeclare @lengthOfFullName int\ndeclare @endOfFirstName int\ndeclare @beginningOfLastName int\n\nset @lengthOfFullName = len(@FullName)\nset @endOfFirstName = charindex(' ', @FullName)\nset @beginningOfLastName = @lengthOfFullName - charindex(' ', @ReverseFullName) + 1\n\nset @FirstName = case when @endOfFirstName &lt;&gt; 0 \n then substring(@FullName, 1, @endOfFirstName - 1) \n else ''\n end\n\nset @MiddleName = case when (@endOfFirstName &lt;&gt; 0 and @beginningOfLastName &lt;&gt; 0 and @beginningOfLastName &gt; @endOfFirstName)\n then ltrim(rtrim(substring(@FullName, @endOfFirstName , @beginningOfLastName - @endOfFirstName))) \n else ''\n end\n\nset @LastName = case when @beginningOfLastName &lt;&gt; 0 \n then substring(@FullName, @beginningOfLastName + 1 , @lengthOfFullName - @beginningOfLastName)\n else ''\n end\n\nreturn\n\nend \n</code></pre>\n\n<p>And here's me calling it.</p>\n\n<pre><code>DECLARE @FirstName nvarchar(255),\n @MiddleName nvarchar(255),\n @LastName nvarchar(255)\n\nEXEC [dbo].[import_ParseName]\n @FullName = N'Scott The Other Scott Kowalczyk',\n @FirstName = @FirstName OUTPUT,\n @MiddleName = @MiddleName OUTPUT,\n @LastName = @LastName OUTPUT\n\nprint @FirstName \nprint @MiddleName\nprint @LastName \n\noutput:\n\nScott\nThe Other Scott\nKowalczyk\n</code></pre>\n" }, { "answer_id": 160033, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>As everyone else says, you can't from a simple programmatic way.</p>\n\n<p>Consider these examples:</p>\n\n<ul>\n<li><p>President \"George Herbert Walker Bush\" (First Middle Middle Last)</p></li>\n<li><p>Presidential assassin \"John Wilkes Booth\" (First Middle\nLast)</p></li>\n<li><p>Guitarist \"Eddie Van Halen\" (First Last Last)</p></li>\n<li><p>And his mom probably calls him Edward Lodewijk Van Halen (First\nMiddle Last Last)</p></li>\n<li><p>Famed castaway \"Mary Ann Summers\" (First First Last)</p></li>\n<li><p><a href=\"http://www.abqjournal.com/abqnews/index.php?option=com_content&amp;task=view&amp;id=8728&amp;Itemid=2\" rel=\"nofollow noreferrer\">New Mexico GOP chairman</a> \"Fernando C de Baca\" (First Last Last Last)</p></li>\n</ul>\n" }, { "answer_id": 1408989, "author": "Ken Williams", "author_id": 169947, "author_profile": "https://Stackoverflow.com/users/169947", "pm_score": 0, "selected": false, "text": "<p>We of course all understand that there's no perfect way to solve this problem, but some solutions can get you farther than others. </p>\n\n<p>In particular, it's pretty easy to go beyond simple whitespace-splitters if you just have some lists of common prefixes (Mr, Dr, Mrs, etc.), infixes (von, de, del, etc.), suffixes (Jr, III, Sr, etc.) and so on. It's also helpful if you have some lists of common first names (in various languages/cultures, if your names are diverse) so that you can guess whether a word in the middle is likely to be part of the last name or not.</p>\n\n<p>BibTeX also implements some heuristics that get you part of the way there; they're encapsulated in the <code>Text::BibTeX::Name</code> perl module. Here's a quick code sample that does a reasonable job.</p>\n\n<pre><code>use Text::BibTeX;\nuse Text::BibTeX::Name;\n$name = \"Dr. Mario Luis de Luigi Jr.\";\n$name =~ s/^\\s*([dm]rs?.?|miss)\\s+//i;\n$dr=$1;\n$n=Text::BibTeX::Name-&gt;new($name);\nprint join(\"\\t\", $dr, map \"@{[ $n-&gt;part($_) ]}\", qw(first von last jr)), \"\\n\";\n</code></pre>\n" }, { "answer_id": 1656234, "author": "Jonathon Hill", "author_id": 168815, "author_profile": "https://Stackoverflow.com/users/168815", "pm_score": 1, "selected": false, "text": "<p>If you are trying to parse apart a human name in PHP, I recommend <a href=\"http://jonathonhill.net/2009-10-31/human-name-parsing-in-php/\" rel=\"nofollow noreferrer\">Keith Beckman's nameparse.php script</a>.</p>\n\n<p>Copy in case site goes down: </p>\n\n<pre><code>&lt;?\n/*\nName: nameparse.php\nVersion: 0.2a\nDate: 030507\nFirst: 030407\nLicense: GNU General Public License v2\nBugs: If one of the words in the middle name is Ben (or St., for that matter),\n or any other possible last-name prefix, the name MUST be entered in\n last-name-first format. If the last-name parsing routines get ahold\n of any prefix, they tie up the rest of the name up to the suffix. i.e.:\n\n William Ben Carey would yield 'Ben Carey' as the last name, while,\n Carey, William Ben would yield 'Carey' as last and 'Ben' as middle.\n\n This is a problem inherent in the prefix-parsing routines algorithm,\n and probably will not be fixed. It's not my fault that there's some\n odd overlap between various languages. Just don't name your kids\n 'Something Ben Something', and you should be alright.\n\n*/\n\nfunction norm_str($string) {\n return trim(strtolower(\n str_replace('.','',$string)));\n }\n\nfunction in_array_norm($needle,$haystack) {\n return in_array(norm_str($needle),$haystack);\n }\n\nfunction parse_name($fullname) {\n $titles = array('dr','miss','mr','mrs','ms','judge');\n $prefices = array('ben','bin','da','dal','de','del','der','de','e',\n 'la','le','san','st','ste','van','vel','von');\n $suffices = array('esq','esquire','jr','sr','2','ii','iii','iv');\n\n $pieces = explode(',',preg_replace('/\\s+/',' ',trim($fullname)));\n $n_pieces = count($pieces);\n\n switch($n_pieces) {\n case 1: // array(title first middles last suffix)\n $subp = explode(' ',trim($pieces[0]));\n $n_subp = count($subp);\n for($i = 0; $i &lt; $n_subp; $i++) {\n $curr = trim($subp[$i]);\n $next = trim($subp[$i+1]);\n\n if($i == 0 &amp;&amp; in_array_norm($curr,$titles)) {\n $out['title'] = $curr;\n continue;\n }\n\n if(!$out['first']) {\n $out['first'] = $curr;\n continue;\n }\n\n if($i == $n_subp-2 &amp;&amp; $next &amp;&amp; in_array_norm($next,$suffices)) {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n $out['suffix'] = $next;\n break;\n }\n\n if($i == $n_subp-1) {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if(in_array_norm($curr,$prefices)) {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if($next == 'y' || $next == 'Y') {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if($out['last']) {\n $out['last'] .= \" $curr\";\n continue;\n }\n\n if($out['middle']) {\n $out['middle'] .= \" $curr\";\n }\n else {\n $out['middle'] = $curr;\n }\n }\n break;\n case 2:\n switch(in_array_norm($pieces[1],$suffices)) {\n case TRUE: // array(title first middles last,suffix)\n $subp = explode(' ',trim($pieces[0]));\n $n_subp = count($subp);\n for($i = 0; $i &lt; $n_subp; $i++) {\n $curr = trim($subp[$i]);\n $next = trim($subp[$i+1]);\n\n if($i == 0 &amp;&amp; in_array_norm($curr,$titles)) {\n $out['title'] = $curr;\n continue;\n }\n\n if(!$out['first']) {\n $out['first'] = $curr;\n continue;\n }\n\n if($i == $n_subp-1) {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if(in_array_norm($curr,$prefices)) {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if($next == 'y' || $next == 'Y') {\n if($out['last']) {\n $out['last'] .= \" $curr\";\n }\n else {\n $out['last'] = $curr;\n }\n continue;\n }\n\n if($out['last']) {\n $out['last'] .= \" $curr\";\n continue;\n }\n\n if($out['middle']) {\n $out['middle'] .= \" $curr\";\n }\n else {\n $out['middle'] = $curr;\n }\n } \n $out['suffix'] = trim($pieces[1]);\n break;\n case FALSE: // array(last,title first middles suffix)\n $subp = explode(' ',trim($pieces[1]));\n $n_subp = count($subp);\n for($i = 0; $i &lt; $n_subp; $i++) {\n $curr = trim($subp[$i]);\n $next = trim($subp[$i+1]);\n\n if($i == 0 &amp;&amp; in_array_norm($curr,$titles)) {\n $out['title'] = $curr;\n continue;\n }\n\n if(!$out['first']) {\n $out['first'] = $curr;\n continue;\n }\n\n if($i == $n_subp-2 &amp;&amp; $next &amp;&amp;\n in_array_norm($next,$suffices)) {\n if($out['middle']) {\n $out['middle'] .= \" $curr\";\n }\n else {\n $out['middle'] = $curr;\n }\n $out['suffix'] = $next;\n break;\n }\n\n if($i == $n_subp-1 &amp;&amp; in_array_norm($curr,$suffices)) {\n $out['suffix'] = $curr;\n continue;\n }\n\n if($out['middle']) {\n $out['middle'] .= \" $curr\";\n }\n else {\n $out['middle'] = $curr;\n }\n }\n $out['last'] = $pieces[0];\n break;\n }\n unset($pieces);\n break;\n case 3: // array(last,title first middles,suffix)\n $subp = explode(' ',trim($pieces[1]));\n $n_subp = count($subp);\n for($i = 0; $i &lt; $n_subp; $i++) {\n $curr = trim($subp[$i]);\n $next = trim($subp[$i+1]);\n if($i == 0 &amp;&amp; in_array_norm($curr,$titles)) {\n $out['title'] = $curr;\n continue;\n }\n\n if(!$out['first']) {\n $out['first'] = $curr;\n continue;\n }\n\n if($out['middle']) {\n $out['middle'] .= \" $curr\";\n }\n else {\n $out['middle'] = $curr;\n }\n }\n\n $out['last'] = trim($pieces[0]);\n $out['suffix'] = trim($pieces[2]);\n break;\n default: // unparseable\n unset($pieces);\n break;\n }\n\n return $out;\n }\n\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 4833614, "author": "Jonathan Wood", "author_id": 522663, "author_profile": "https://Stackoverflow.com/users/522663", "pm_score": 0, "selected": false, "text": "<p>The biggest problem I ran into doing this was cases like \"Bob R. Smith, Jr.\". The algorithm I used is posted at <a href=\"http://www.blackbeltcoder.com/Articles/strings/splitting-a-name-into-first-and-last-names\" rel=\"nofollow\">http://www.blackbeltcoder.com/Articles/strings/splitting-a-name-into-first-and-last-names</a>. My code is in C# but you could port it if you must have in SQL.</p>\n" }, { "answer_id": 34507330, "author": "hajili", "author_id": 1217045, "author_profile": "https://Stackoverflow.com/users/1217045", "pm_score": 3, "selected": false, "text": "<p>Alternative simple way is to use <code>parsename</code> :</p>\n\n<pre><code>select full_name,\n parsename(replace(full_name, ' ', '.'), 3) as FirstName,\n parsename(replace(full_name, ' ', '.'), 2) as MiddleName,\n parsename(replace(full_name, ' ', '.'), 1) as LastName \nfrom YourTableName\n</code></pre>\n\n<p><a href=\"https://dba.stackexchange.com/a/42398/83480\">source</a></p>\n" }, { "answer_id": 38261211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This Will Work in Case String Is FirstName/MiddleName/LastName</p>\n\n<pre><code>Select \n\nDISTINCT NAMES ,\n\n SUBSTRING(NAMES , 1, CHARINDEX(' ', NAMES) - 1) as FirstName,\n\n RTRIM(LTRIM(REPLACE(REPLACE(NAMES,SUBSTRING(NAMES , 1, CHARINDEX(' ', NAMES) - 1),''),REVERSE( LEFT( REVERSE(NAMES), CHARINDEX(' ', REVERSE(NAMES))-1 ) ),'')))as MiddleName,\n\n REVERSE( LEFT( REVERSE(NAMES), CHARINDEX(' ', REVERSE(NAMES))-1 ) ) as LastName\n\nFrom TABLENAME\n</code></pre>\n" }, { "answer_id": 44426622, "author": "CharlieNoTomatoes", "author_id": 3545738, "author_profile": "https://Stackoverflow.com/users/3545738", "pm_score": 0, "selected": false, "text": "<p>The work by @JosephStyons and @Digs is great! I used parts of their work to create a new function for SQL Server 2016 and newer. This one also handles suffixes, as well as prefixes.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[NameParser]\n(\n @name nvarchar(100)\n)\nRETURNS TABLE\nAS\nRETURN (\n\nWITH prep AS (\n SELECT \n original = @name,\n cleanName = REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(@name)),' ',' '),' ',' '), '.', ''), ',', '')\n)\nSELECT\n prep.original,\n aux.prefix,\n firstName.firstName,\n middleName.middleName,\n lastName.lastName,\n aux.suffix\nFROM\n prep\n CROSS APPLY (\n SELECT \n prefix =\n CASE \n WHEN LEFT(prep.cleanName, 3) IN ('MR ', 'MS ', 'DR ', 'FR ')\n THEN LEFT(prep.cleanName, 2)\n WHEN LEFT(prep.cleanName, 4) IN ('MRS ', 'LRD ', 'SIR ')\n THEN LEFT(prep.cleanName, 3)\n WHEN LEFT(prep.cleanName, 5) IN ('LORD ', 'LADY ', 'MISS ', 'PROF ')\n THEN LEFT(prep.cleanName, 4)\n ELSE ''\n END,\n suffix =\n CASE \n WHEN RIGHT(prep.cleanName, 3) IN (' JR', ' SR', ' II', ' IV')\n THEN RIGHT(prep.cleanName, 2)\n WHEN RIGHT(prep.cleanName, 4) IN (' III', ' ESQ')\n THEN RIGHT(prep.cleanName, 3)\n ELSE ''\n END\n ) aux\n CROSS APPLY (\n SELECT\n baseName = LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))),\n numParts = (SELECT COUNT(1) FROM STRING_SPLIT(LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))), ' '))\n ) core\n CROSS APPLY (\n SELECT\n firstName = \n CASE\n WHEN core.numParts &lt;= 1 THEN core.baseName\n ELSE LEFT(core.baseName, CHARINDEX(' ', core.baseName, 1) - 1) \n END\n\n ) firstName\n CROSS APPLY (\n SELECT\n remainder = \n CASE\n WHEN core.numParts &lt;= 1 THEN ''\n ELSE LTRIM(SUBSTRING(core.baseName, LEN(firstName.firstName) + 1, 999999))\n END\n ) work1\n CROSS APPLY (\n SELECT\n middleName = \n CASE\n WHEN core.numParts &lt;= 2 THEN ''\n ELSE LEFT(work1.remainder, CHARINDEX(' ', work1.remainder, 1) - 1) \n END\n ) middleName\n CROSS APPLY (\n SELECT\n lastName = \n CASE\n WHEN core.numParts &lt;= 1 THEN ''\n ELSE LTRIM(SUBSTRING(work1.remainder, LEN(middleName.middleName) + 1, 999999))\n END\n ) lastName\n)\n\nGO\n\nSELECT * FROM dbo.NameParser('Madonna')\nSELECT * FROM dbo.NameParser('Will Smith')\nSELECT * FROM dbo.NameParser('Neil Degrasse Tyson')\nSELECT * FROM dbo.NameParser('Dr. Neil Degrasse Tyson')\nSELECT * FROM dbo.NameParser('Mr. Hyde')\nSELECT * FROM dbo.NameParser('Mrs. Thurston Howell, III')\n</code></pre>\n" }, { "answer_id": 48332386, "author": "James A.", "author_id": 9236942, "author_profile": "https://Stackoverflow.com/users/9236942", "pm_score": 0, "selected": false, "text": "<p>Check this query in Athena for only one-space separated string (e.g. first name and middle name combination):</p>\n\n<p><code>SELECT name, REVERSE( SUBSTR( REVERSE(name), 1, STRPOS(REVERSE(name), ' ') ) ) AS middle_name \nFROM name_table</code></p>\n\n<p>If you expect to have two or more spaces, you can easily extend the above query. </p>\n" }, { "answer_id": 55521279, "author": "Gus Lopez", "author_id": 9498689, "author_profile": "https://Stackoverflow.com/users/9498689", "pm_score": 0, "selected": false, "text": "<p>Based on @hajili's contribution (which is a creative use of the parsename function, intended to parse the name of an object that is period-separated), I modified it so it can handle cases where the data doesn't containt a middle name or when the name is \"John and Jane Doe\". It's not 100% perfect but it's compact and might do the trick depending on the business case.</p>\n\n<pre><code>SELECT NAME,\nCASE WHEN parsename(replace(NAME, ' ', '.'), 4) IS NOT NULL THEN \n parsename(replace(NAME, ' ', '.'), 4) ELSE\n CASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN \n parsename(replace(NAME, ' ', '.'), 3) ELSE\n parsename(replace(NAME, ' ', '.'), 2) end END as FirstName\n ,\nCASE WHEN parsename(replace(NAME, ' ', '.'), 3) IS NOT NULL THEN \n parsename(replace(NAME, ' ', '.'), 2) ELSE NULL END as MiddleName,\n parsename(replace(NAME, ' ', '.'), 1) as LastName\nfrom {@YourTableName}\n</code></pre>\n" }, { "answer_id": 56321076, "author": "Mukesh Pandey", "author_id": 7774013, "author_profile": "https://Stackoverflow.com/users/7774013", "pm_score": 2, "selected": false, "text": "<p>This query is working fine.</p>\n\n<pre><code>SELECT name\n ,Ltrim(SubString(name, 1, Isnull(Nullif(CHARINDEX(' ', name), 0), 1000))) AS FirstName\n ,Ltrim(SUBSTRING(name, CharIndex(' ', name), CASE \n WHEN (CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)) &lt;= 0\n THEN 0\n ELSE CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)\n END)) AS MiddleName\n ,Ltrim(SUBSTRING(name, Isnull(Nullif(CHARINDEX(' ', name, Charindex(' ', name) + 1), 0), CHARINDEX(' ', name)), CASE \n WHEN Charindex(' ', name) = 0\n THEN 0\n ELSE LEN(name)\n END)) AS LastName\nFROM yourtableName\n</code></pre>\n" }, { "answer_id": 57056287, "author": "Vinay Maurya", "author_id": 6620695, "author_profile": "https://Stackoverflow.com/users/6620695", "pm_score": 0, "selected": false, "text": "<p>Employee table has column \"Name\" and we had to split it into First, Middle and Last Name. This query will handle to keep middle name as null if name column has value of two words like 'James Thomas'.</p>\n\n<pre><code>UPDATE Employees\nSET [First Name] = CASE \n WHEN (len(name) - len(Replace(name, '.', ''))) = 2\n THEN PARSENAME(Name, 3)\n WHEN (len(name) - len(Replace(name, '.', ''))) = 1\n THEN PARSENAME(Name, 2)\n ELSE PARSENAME(Name, 1)\n END\n ,[Middle Name] = CASE \n WHEN (len(name) - len(Replace(name, '.', ''))) = 2\n THEN PARSENAME(Name, 2)\n ELSE NULL\n END\n ,[Last Name] = CASE \n WHEN (len(name) - len(Replace(name, '.', ''))) = 2\n THEN PARSENAME(Name, 1)\n WHEN (len(name) - len(Replace(name, '.', ''))) = 1\n THEN PARSENAME(Name, 1)\n ELSE NULL\n END GO\n\nUPDATE Employee\nSET [Name] = Replace([Name], '.', ' ') GO\n</code></pre>\n" }, { "answer_id": 68506141, "author": "DeFlanko", "author_id": 4006015, "author_profile": "https://Stackoverflow.com/users/4006015", "pm_score": 0, "selected": false, "text": "<p>I wanted to post an update to the suggestion by hajili, but this response was too long for a comment on that suggestion.</p>\n<p>Our issue was &quot;Lastname,Firstname Middlename&quot; with some last name's with a space in them.</p>\n<p>So we came up with:</p>\n<pre><code>,FullName = CUST.FULLNAME\n,LastName = PARSENAME(REPLACE(CUST.FULLNAME, ',', '.'),2)\n,FirstName = (CASE WHEN PARSENAME(REPLACE(CUST.FULLNAME, ',', '.'),1) LIKE '% %' THEN PARSENAME(REPLACE(PARSENAME(REPLACE(CUST.FULLNAME, ',', '.'),1), ' ', '.'),2) ELSE PARSENAME(REPLACE(CUST.FULLNAME, ',', '.'),1) END)\n,MiddleName = (CASE WHEN PARSENAME(REPLACE(CUST.FULLNAME, ' ', '.'),1) LIKE '%,%' THEN NULL ELSE PARSENAME(REPLACE(CUST.FULLNAME, ' ', '.'),1) END)\n</code></pre>\n" }, { "answer_id": 74514607, "author": "Mayur Kadbhane", "author_id": 9811370, "author_profile": "https://Stackoverflow.com/users/9811370", "pm_score": 0, "selected": false, "text": "<p>SELECT SUBSTRING_INDEX(name, ' ', 1) as fname, SUBSTRING_INDEX(SUBSTRING_INDEX(name, ' ', 2), ' ', -1) as mname, SUBSTRING_INDEX(name, ' ', -1) as lname FROM Person</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73794/" ]
How do I parse the first, middle, and last name out of a fullname field with SQL? I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name. The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'. I'm interested in some practical solutions to get me 90% of the way there. As it has been stated, this is a complex problem, so I'll handle special cases individually.
Here is a self-contained example, with easily manipulated test data. With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST\_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR". If the middle name is missing, then you just get FIRST\_NAME and LAST\_NAME (MIDDLE\_NAME will be NULL). You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL. **Edit-- Handle the following special cases:** **1 - The NAME field is NULL** **2 - The NAME field contains leading / trailing spaces** **3 - The NAME field has > 1 consecutive space within the name** **4 - The NAME field contains ONLY the first name** **5 - Include the original full name in the final output as a separate column, for readability** **6 - Handle a specific list of prefixes as a separate "title" column** ``` SELECT FIRST_NAME.ORIGINAL_INPUT_DATA ,FIRST_NAME.TITLE ,FIRST_NAME.FIRST_NAME ,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME) THEN NULL --no more spaces? assume rest is the last name ELSE SUBSTRING( FIRST_NAME.REST_OF_NAME ,1 ,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1 ) END AS MIDDLE_NAME ,SUBSTRING( FIRST_NAME.REST_OF_NAME ,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME) ,LEN(FIRST_NAME.REST_OF_NAME) ) AS LAST_NAME FROM ( SELECT TITLE.TITLE ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME) THEN TITLE.REST_OF_NAME --No space? return the whole thing ELSE SUBSTRING( TITLE.REST_OF_NAME ,1 ,CHARINDEX(' ',TITLE.REST_OF_NAME)-1 ) END AS FIRST_NAME ,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME) THEN NULL --no spaces @ all? then 1st name is all we have ELSE SUBSTRING( TITLE.REST_OF_NAME ,CHARINDEX(' ',TITLE.REST_OF_NAME)+1 ,LEN(TITLE.REST_OF_NAME) ) END AS REST_OF_NAME ,TITLE.ORIGINAL_INPUT_DATA FROM ( SELECT --if the first three characters are in this list, --then pull it as a "title". otherwise return NULL for title. CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS') THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3))) ELSE NULL END AS TITLE --if you change the list, don't forget to change it here, too. --so much for the DRY prinicple... ,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS') THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME)))) ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME)) END AS REST_OF_NAME ,TEST_DATA.ORIGINAL_INPUT_DATA FROM ( SELECT --trim leading & trailing spaces before trying to process --disallow extra spaces *within* the name REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME ,FULL_NAME AS ORIGINAL_INPUT_DATA FROM ( --if you use this, then replace the following --block with your actual table SELECT 'GEORGE W BUSH' AS FULL_NAME UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME UNION SELECT 'TOMMY' AS FULL_NAME UNION SELECT 'BILLY' AS FULL_NAME UNION SELECT NULL AS FULL_NAME UNION SELECT ' ' AS FULL_NAME UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME ) RAW_DATA ) TEST_DATA ) TITLE ) FIRST_NAME ```
159,590
<p>I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.</p> <p>So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help.</p> <ul> <li>Are there general rules?</li> <li>Is there a "pattern"?</li> </ul>
[ { "answer_id": 159619, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 5, "selected": false, "text": "<p>Strive to make your recursive call <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"noreferrer\">Tail Recursion</a> (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.</p>\n" }, { "answer_id": 159641, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 3, "selected": false, "text": "<p>Search google for \"Continuation passing style.\" There is a general procedure for converting to a tail recursive style; there is also a general procedure for turning tail recursive functions into loops.</p>\n" }, { "answer_id": 159649, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": false, "text": "<p>One pattern to look for is a recursion call at the end of the function (so called tail-recursion). This can easily be replaced with a while. For example, the function foo:</p>\n\n<pre><code>void foo(Node* node)\n{\n if(node == NULL)\n return;\n // Do something with node...\n foo(node-&gt;left);\n foo(node-&gt;right);\n}\n</code></pre>\n\n<p>ends with a call to foo. This can be replaced with:</p>\n\n<pre><code>void foo(Node* node)\n{\n while(node != NULL)\n {\n // Do something with node...\n foo(node-&gt;left);\n node = node-&gt;right;\n }\n}\n</code></pre>\n\n<p>which eliminates the second recursive call.</p>\n" }, { "answer_id": 159682, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 5, "selected": false, "text": "<p>Well, in general, recursion can be mimicked as iteration by simply using a storage variable. Note that recursion and iteration are generally equivalent; one can almost always be converted to the other. A tail-recursive function is very easily converted to an iterative one. Just make the accumulator variable a local one, and iterate instead of recurse. Here's an example in C++ (C were it not for the use of a default argument):</p>\n\n<pre><code>// tail-recursive\nint factorial (int n, int acc = 1)\n{\n if (n == 1)\n return acc;\n else\n return factorial(n - 1, acc * n);\n}\n\n// iterative\nint factorial (int n)\n{\n int acc = 1;\n for (; n &gt; 1; --n)\n acc *= n;\n return acc;\n}\n</code></pre>\n\n<p>Knowing me, I probably made a mistake in the code, but the idea is there.</p>\n" }, { "answer_id": 159692, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 6, "selected": false, "text": "<p>Really, the most common way to do it is to keep your own stack. Here's a recursive quicksort function in C:</p>\n\n<pre><code>void quicksort(int* array, int left, int right)\n{\n if(left &gt;= right)\n return;\n\n int index = partition(array, left, right);\n quicksort(array, left, index - 1);\n quicksort(array, index + 1, right);\n}\n</code></pre>\n\n<p>Here's how we could make it iterative by keeping our own stack:</p>\n\n<pre><code>void quicksort(int *array, int left, int right)\n{\n int stack[1024];\n int i=0;\n\n stack[i++] = left;\n stack[i++] = right;\n\n while (i &gt; 0)\n {\n right = stack[--i];\n left = stack[--i];\n\n if (left &gt;= right)\n continue;\n\n int index = partition(array, left, right);\n stack[i++] = left;\n stack[i++] = index - 1;\n stack[i++] = index + 1;\n stack[i++] = right;\n }\n}\n</code></pre>\n\n<p>Obviously, this example doesn't check stack boundaries... and really you could size the stack based on the worst case given left and and right values. But you get the idea.</p>\n" }, { "answer_id": 159777, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 10, "selected": true, "text": "<p>Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.</p>\n<pre class=\"lang-js prettyprint-override\"><code>var stack = [];\nstack.push(firstObject);\n\n// while not empty\nwhile (stack.length) {\n\n // Pop off end of stack.\n obj = stack.pop();\n\n // Do stuff.\n // Push other objects on the stack as needed.\n ...\n\n}\n</code></pre>\n<p>Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:</p>\n<pre><code>foo(first);\nfoo(second);\n</code></pre>\n<p>has to be replaced by</p>\n<pre><code>stack.push(second);\nstack.push(first);\n</code></pre>\n<p>Edit: The article <a href=\"http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf\" rel=\"noreferrer\">Stacks and Recursion Elimination</a> (or <a href=\"https://web.archive.org/web/20120227170843/http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf\" rel=\"noreferrer\">Article Backup link</a>) goes into more details on this subject.</p>\n" }, { "answer_id": 4113966, "author": "ARC", "author_id": 499314, "author_profile": "https://Stackoverflow.com/users/499314", "pm_score": 4, "selected": false, "text": "<p>Even using stack will not convert a recursive algorithm into iterative. Normal recursion is function based recursion and if we use stack then it becomes stack based recursion. But its still recursion.</p>\n\n<p>For recursive algorithms, space complexity is O(N) and time complexity is O(N). \nFor iterative algorithms, space complexity is O(1) and time complexity is O(N). </p>\n\n<p>But if we use stack things in terms of complexity remains same. I think only tail recursion can be converted into iteration.</p>\n" }, { "answer_id": 7185450, "author": "Tae-Sung Shin", "author_id": 749973, "author_profile": "https://Stackoverflow.com/users/749973", "pm_score": 3, "selected": false, "text": "<p>Just killing time... A recursive function </p>\n\n<pre><code>void foo(Node* node)\n{\n if(node == NULL)\n return;\n // Do something with node...\n foo(node-&gt;left);\n foo(node-&gt;right);\n}\n</code></pre>\n\n<p>can be converted to</p>\n\n<pre><code>void foo(Node* node)\n{\n if(node == NULL)\n return;\n\n // Do something with node...\n\n stack.push(node-&gt;right);\n stack.push(node-&gt;left);\n\n while(!stack.empty()) {\n node1 = stack.pop();\n if(node1 == NULL)\n continue;\n // Do something with node1...\n stack.push(node1-&gt;right); \n stack.push(node1-&gt;left);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 8512072, "author": "T. Webster", "author_id": 266457, "author_profile": "https://Stackoverflow.com/users/266457", "pm_score": 6, "selected": false, "text": "<p>It seems nobody has addressed where the recursive function calls itself more than once in the body, and handles returning to a specific point in the recursion (i.e. not primitive-recursive). It is said that <a href=\"https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration/933979#comment10514125_933979\">every recursion can be turned into iteration</a>, so it appears that this should be possible.</p>\n\n<p>I just came up with a C# example of how to do this. Suppose you have the following recursive function, which acts like a postorder traversal, and that AbcTreeNode is a 3-ary tree with pointers a, b, c.</p>\n\n<pre><code>public static void AbcRecursiveTraversal(this AbcTreeNode x, List&lt;int&gt; list) {\n if (x != null) {\n AbcRecursiveTraversal(x.a, list);\n AbcRecursiveTraversal(x.b, list);\n AbcRecursiveTraversal(x.c, list);\n list.Add(x.key);//finally visit root\n }\n}\n</code></pre>\n\n<p>The iterative solution:</p>\n\n<pre><code> int? address = null;\n AbcTreeNode x = null;\n x = root;\n address = A;\n stack.Push(x);\n stack.Push(null) \n\n while (stack.Count &gt; 0) {\n bool @return = x == null;\n\n if (@return == false) {\n\n switch (address) {\n case A:// \n stack.Push(x);\n stack.Push(B);\n x = x.a;\n address = A;\n break;\n case B:\n stack.Push(x);\n stack.Push(C);\n x = x.b;\n address = A;\n break;\n case C:\n stack.Push(x);\n stack.Push(null);\n x = x.c;\n address = A;\n break;\n case null:\n list_iterative.Add(x.key);\n @return = true;\n break;\n }\n\n }\n\n\n if (@return == true) {\n address = (int?)stack.Pop();\n x = (AbcTreeNode)stack.Pop();\n }\n\n\n }\n</code></pre>\n" }, { "answer_id": 10650611, "author": "Ajay Manas", "author_id": 1403074, "author_profile": "https://Stackoverflow.com/users/1403074", "pm_score": 2, "selected": false, "text": "<p>Recursion is nothing but the process of calling of one function from the other only this process is done by calling of a function by itself. As we know when one function calls the other function the first function saves its state(its variables) and then passes the control to the called function. The called function can be called by using the same name of variables ex fun1(a) can call fun2(a). \nWhen we do recursive call nothing new happens. One function calls itself by passing the same type and similar in name variables(but obviously the values stored in variables are different,only the name remains same.)to itself. But before every call the function saves its state and this process of saving continues. The SAVING IS DONE ON A STACK.</p>\n\n<p>NOW THE STACK COMES INTO PLAY.</p>\n\n<p>So if you write an iterative program and save the state on a stack each time and then pop out the values from stack when needed, you have successfully converted a recursive program into an iterative one!</p>\n\n<p>The proof is simple and analytical.</p>\n\n<p>In recursion the computer maintains a stack and in iterative version you will have to manually maintain the stack.</p>\n\n<p>Think over it, just convert a depth first search(on graphs) recursive program into a dfs iterative program.</p>\n\n<p>All the best!</p>\n" }, { "answer_id": 10719044, "author": "naiem", "author_id": 981646, "author_profile": "https://Stackoverflow.com/users/981646", "pm_score": 3, "selected": false, "text": "<p>Generally the technique to avoid stack overflow is for recursive functions is called trampoline technique which is widely adopted by Java devs.</p>\n\n<p>However, for C# there is a little helper method <a href=\"http://qualityofdata.com/2012/02/03/how-to-run-most-of-the-recursive-functions-iteratively/\" rel=\"noreferrer\">here</a> that turns your recursive function to iterative without requiring to change logic or make the code in-comprehensible. C# is such a nice language that amazing stuff is possible with it.</p>\n\n<p>It works by wrapping parts of the method by a helper method. For example the following recursive function:</p>\n\n<pre><code>int Sum(int index, int[] array)\n{\n //This is the termination condition\n if (int &gt;= array.Length)\n //This is the returning value when termination condition is true\n return 0;\n\n//This is the recursive call\n var sumofrest = Sum(index+1, array);\n\n//This is the work to do with the current item and the\n //result of recursive call\n return array[index]+sumofrest;\n}\n</code></pre>\n\n<p>Turns into:</p>\n\n<pre><code>int Sum(int[] ar)\n{\n return RecursionHelper&lt;int&gt;.CreateSingular(i =&gt; i &gt;= ar.Length, i =&gt; 0)\n .RecursiveCall((i, rv) =&gt; i + 1)\n .Do((i, rv) =&gt; ar[i] + rv)\n .Execute(0);\n}\n</code></pre>\n" }, { "answer_id": 16281550, "author": "Chethan", "author_id": 377762, "author_profile": "https://Stackoverflow.com/users/377762", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf\" rel=\"noreferrer\">stacks and recursion elimination</a> article captures the idea of externalizing the stack frame on heap, but does not provide a <strong>straightforward and repeatable</strong> way to convert. Below is one.</p>\n\n<p>While converting to iterative code, one must be aware that the recursive call may happen from an arbitrarily deep code block. Its not just the parameters, but also the point to return to the logic that remains to be executed and the state of variables which participate in subsequent conditionals, which matter. Below is a very simple way to convert to iterative code with least changes. </p>\n\n<p>Consider this recursive code:</p>\n\n<pre><code>struct tnode\n{\n tnode(int n) : data(n), left(0), right(0) {}\n tnode *left, *right;\n int data;\n};\n\nvoid insertnode_recur(tnode *node, int num)\n{\n if(node-&gt;data &lt;= num)\n {\n if(node-&gt;right == NULL)\n node-&gt;right = new tnode(num);\n else\n insertnode(node-&gt;right, num);\n }\n else\n {\n if(node-&gt;left == NULL)\n node-&gt;left = new tnode(num);\n else\n insertnode(node-&gt;left, num);\n } \n}\n</code></pre>\n\n<p>Iterative code:</p>\n\n<pre><code>// Identify the stack variables that need to be preserved across stack \n// invocations, that is, across iterations and wrap them in an object\nstruct stackitem \n{ \n stackitem(tnode *t, int n) : node(t), num(n), ra(0) {}\n tnode *node; int num;\n int ra; //to point of return\n};\n\nvoid insertnode_iter(tnode *node, int num) \n{\n vector&lt;stackitem&gt; v;\n //pushing a stackitem is equivalent to making a recursive call.\n v.push_back(stackitem(node, num));\n\n while(v.size()) \n {\n // taking a modifiable reference to the stack item makes prepending \n // 'si.' to auto variables in recursive logic suffice\n // e.g., instead of num, replace with si.num.\n stackitem &amp;si = v.back(); \n switch(si.ra)\n {\n // this jump simulates resuming execution after return from recursive \n // call \n case 1: goto ra1;\n case 2: goto ra2;\n default: break;\n } \n\n if(si.node-&gt;data &lt;= si.num)\n {\n if(si.node-&gt;right == NULL)\n si.node-&gt;right = new tnode(si.num);\n else\n {\n // replace a recursive call with below statements\n // (a) save return point, \n // (b) push stack item with new stackitem, \n // (c) continue statement to make loop pick up and start \n // processing new stack item, \n // (d) a return point label\n // (e) optional semi-colon, if resume point is an end \n // of a block.\n\n si.ra=1;\n v.push_back(stackitem(si.node-&gt;right, si.num));\n continue; \nra1: ; \n }\n }\n else\n {\n if(si.node-&gt;left == NULL)\n si.node-&gt;left = new tnode(si.num);\n else\n {\n si.ra=2; \n v.push_back(stackitem(si.node-&gt;left, si.num));\n continue;\nra2: ;\n }\n }\n\n v.pop_back();\n }\n}\n</code></pre>\n\n<p>Notice how the structure of the code still remains true to the recursive logic and modifications are minimal, resulting in less number of bugs. For comparison, I have marked the changes with ++ and --. Most of the new inserted blocks except v.push_back, are common to any converted iterative logic </p>\n\n<pre><code>void insertnode_iter(tnode *node, int num) \n{\n</code></pre>\n\n<p><code>+++++++++++++++++++++++++</code></p>\n\n<pre><code> vector&lt;stackitem&gt; v;\n v.push_back(stackitem(node, num));\n\n while(v.size())\n {\n stackitem &amp;si = v.back(); \n switch(si.ra)\n {\n case 1: goto ra1;\n case 2: goto ra2;\n default: break;\n } \n</code></pre>\n\n<p><code>------------------------</code></p>\n\n<pre><code> if(si.node-&gt;data &lt;= si.num)\n {\n if(si.node-&gt;right == NULL)\n si.node-&gt;right = new tnode(si.num);\n else\n {\n</code></pre>\n\n<p><code>+++++++++++++++++++++++++</code></p>\n\n<pre><code> si.ra=1;\n v.push_back(stackitem(si.node-&gt;right, si.num));\n continue; \nra1: ; \n</code></pre>\n\n<p><code>-------------------------</code></p>\n\n<pre><code> }\n }\n else\n {\n if(si.node-&gt;left == NULL)\n si.node-&gt;left = new tnode(si.num);\n else\n {\n</code></pre>\n\n<p><code>+++++++++++++++++++++++++</code></p>\n\n<pre><code> si.ra=2; \n v.push_back(stackitem(si.node-&gt;left, si.num));\n continue;\nra2: ;\n</code></pre>\n\n<p><code>-------------------------</code></p>\n\n<pre><code> }\n }\n</code></pre>\n\n<p><code>+++++++++++++++++++++++++</code></p>\n\n<pre><code> v.pop_back();\n }\n</code></pre>\n\n<p><code>-------------------------</code></p>\n\n<pre><code>}\n</code></pre>\n" }, { "answer_id": 18026165, "author": "Rick Giuly", "author_id": 2593312, "author_profile": "https://Stackoverflow.com/users/2593312", "pm_score": 0, "selected": false, "text": "<p>A rough description of how a system takes any recursive function and executes it using a stack:</p>\n\n<p>This intended to show the idea without details. Consider this function that would print out nodes of a graph:</p>\n\n<pre><code>function show(node)\n0. if isleaf(node):\n1. print node.name\n2. else:\n3. show(node.left)\n4. show(node)\n5. show(node.right)\n</code></pre>\n\n<p>For example graph:\nA->B\nA->C\nshow(A) would print B, A, C</p>\n\n<p>Function calls mean save the local state and the continuation point so you can come back, and then jump the the function you want to call.</p>\n\n<p>For example, suppose show(A) begins to run. The function call on line 3. show(B) means\n - Add item to the stack meaning \"you'll need to continue at line 2 with local variable state node=A\"\n - Goto line 0 with node=B.</p>\n\n<p>To execute code, the system runs through the instructions. When a function call is encountered, the system pushes information it needs to come back to where it was, runs the function code, and when the function completes, pops the information about where it needs to go to continue.</p>\n" }, { "answer_id": 27210176, "author": "eold", "author_id": 395744, "author_profile": "https://Stackoverflow.com/users/395744", "pm_score": 0, "selected": false, "text": "<p>This <a href=\"https://secweb.cs.odu.edu/~zeil/cs361/web/website/Lectures/recursionConversion/page/recursionConversion.html\" rel=\"nofollow\">link</a> provides some explanation and proposes the idea of keeping \"location\" to be able to get to the exact place between several recursive calls:</p>\n\n<p>However, all these examples describe scenarios in which a recursive call is made a <em>fixed</em> amount of times. Things get trickier when you have something like:</p>\n\n<pre><code>function rec(...) {\n for/while loop {\n var x = rec(...)\n // make a side effect involving return value x\n }\n}\n</code></pre>\n" }, { "answer_id": 38264992, "author": "jxh", "author_id": 315052, "author_profile": "https://Stackoverflow.com/users/315052", "pm_score": 2, "selected": false, "text": "<p>A <a href=\"https://stackoverflow.com/q/38263100/315052\">question</a> that had been closed as a duplicate of this one had a very specific data structure:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7Ktr0.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7Ktr0.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The node had the following structure:</p>\n\n<pre><code>typedef struct {\n int32_t type;\n int32_t valueint;\n double valuedouble;\n struct cNODE *next;\n struct cNODE *prev;\n struct cNODE *child;\n} cNODE;\n</code></pre>\n\n<p>The recursive deletion function looked like:</p>\n\n<pre><code>void cNODE_Delete(cNODE *c) {\n cNODE*next;\n while (c) {\n next=c-&gt;next;\n if (c-&gt;child) { \n cNODE_Delete(c-&gt;child)\n }\n free(c);\n c=next;\n }\n}\n</code></pre>\n\n<p>In general, it is not always possible to avoid a stack for recursive functions that invoke itself more than one time (or even once). However, for this particular structure, it is possible. The idea is to flatten all the nodes into a single list. This is accomplished by putting the current node's <code>child</code> at the end of the top row's list.</p>\n\n<pre><code>void cNODE_Delete (cNODE *c) {\n cNODE *tmp, *last = c;\n while (c) {\n while (last-&gt;next) {\n last = last-&gt;next; /* find last */\n }\n if ((tmp = c-&gt;child)) {\n c-&gt;child = NULL; /* append child to last */\n last-&gt;next = tmp;\n tmp-&gt;prev = last;\n }\n tmp = c-&gt;next; /* remove current */\n free(c);\n c = tmp;\n }\n}\n</code></pre>\n\n<p>This technique can be applied to any data linked structure that can be reduce to a DAG with a deterministic topological ordering. The current nodes children are rearranged so that the last child adopts all of the other children. Then the current node can be deleted and traversal can then iterate to the remaining child.</p>\n" }, { "answer_id": 45677628, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 3, "selected": false, "text": "<p>Thinking of things that actually need a stack:</p>\n\n<p>If we consider the pattern of recursion as:</p>\n\n<pre><code>if(task can be done directly) {\n return result of doing task directly\n} else {\n split task into two or more parts\n solve for each part (possibly by recursing)\n return result constructed by combining these solutions\n}\n</code></pre>\n\n<p>For example, the classic Tower of Hanoi</p>\n\n<pre><code>if(the number of discs to move is 1) {\n just move it\n} else {\n move n-1 discs to the spare peg\n move the remaining disc to the target peg\n move n-1 discs from the spare peg to the target peg, using the current peg as a spare\n}\n</code></pre>\n\n<p>This can be translated into a loop working on an explicit stack, by restating it as:</p>\n\n<pre><code>place seed task on stack\nwhile stack is not empty \n take a task off the stack\n if(task can be done directly) {\n Do it\n } else {\n Split task into two or more parts\n Place task to consolidate results on stack\n Place each task on stack\n }\n}\n</code></pre>\n\n<p>For Tower of Hanoi this becomes:</p>\n\n<pre><code>stack.push(new Task(size, from, to, spare));\nwhile(! stack.isEmpty()) {\n task = stack.pop();\n if(task.size() = 1) {\n just move it\n } else {\n stack.push(new Task(task.size() -1, task.spare(), task,to(), task,from()));\n stack.push(new Task(1, task.from(), task.to(), task.spare()));\n stack.push(new Task(task.size() -1, task.from(), task.spare(), task.to()));\n }\n}\n</code></pre>\n\n<p>There is considerable flexibility here as to how you define your stack. You can make your stack a list of <code>Command</code> objects that do sophisticated things. Or you can go the opposite direction and make it a list of simpler types (e.g. a \"task\" might be 4 elements on a stack of <code>int</code>, rather than one element on a stack of <code>Task</code>).</p>\n\n<p>All this means is that the memory for the stack is in the heap rather than in the Java execution stack, but this can be useful in that you have more control over it.</p>\n" }, { "answer_id": 47277833, "author": "Dagang", "author_id": 404264, "author_profile": "https://Stackoverflow.com/users/404264", "pm_score": 1, "selected": false, "text": "<p>There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my <a href=\"http://www.cnblogs.com/weidagang2046/p/lazy-iterator.html%7D\" rel=\"nofollow noreferrer\">Converting Recursive Traversal to Iterator</a>.</p>\n" }, { "answer_id": 50857115, "author": "L_J", "author_id": 5968255, "author_profile": "https://Stackoverflow.com/users/5968255", "pm_score": 1, "selected": false, "text": "<p>Another simple and complete example of turning the recursive function into iterative one using the stack.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;stack&gt;\nusing namespace std;\n\nint GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); }\n\nstruct Par\n{\n int a, b;\n Par() : Par(0, 0) {}\n Par(int _a, int _b) : a(_a), b(_b) {}\n};\n\nint GCDIter(int a, int b)\n{\n stack&lt;Par&gt; rcstack;\n\n if (b == 0)\n return a;\n rcstack.push(Par(b, a % b));\n\n Par p;\n while (!rcstack.empty()) \n {\n p = rcstack.top();\n rcstack.pop();\n if (p.b == 0)\n continue;\n rcstack.push(Par(p.b, p.a % p.b));\n }\n\n return p.a;\n}\n\nint main()\n{\n //cout &lt;&lt; GCD(24, 36) &lt;&lt; endl;\n cout &lt;&lt; GCDIter(81, 36) &lt;&lt; endl;\n\n cin.get();\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 61473850, "author": "divs1210", "author_id": 1163490, "author_profile": "https://Stackoverflow.com/users/1163490", "pm_score": 1, "selected": false, "text": "<p>My examples are in Clojure, but should be fairly easy to translate to any language.</p>\n\n<p>Given this function that <code>StackOverflow</code>s for large values of n:</p>\n\n<pre><code>(defn factorial [n]\n (if (&lt; n 2)\n 1\n (*' n (factorial (dec n)))))\n</code></pre>\n\n<p>we can define a version that uses its own stack in the following manner:</p>\n\n<pre><code>(defn factorial [n]\n (loop [n n\n stack []]\n (if (&lt; n 2)\n (return 1 stack)\n ;; else loop with new values\n (recur (dec n)\n ;; push function onto stack\n (cons (fn [n-1!]\n (*' n n-1!))\n stack)))))\n</code></pre>\n\n<p>where <code>return</code> is defined as:</p>\n\n<pre><code>(defn return\n [v stack]\n (reduce (fn [acc f]\n (f acc))\n v\n stack))\n</code></pre>\n\n<p>This works for more complex functions too, for example the <a href=\"https://en.wikipedia.org/wiki/Ackermann_function\" rel=\"nofollow noreferrer\">ackermann function</a>:</p>\n\n<pre><code>(defn ackermann [m n]\n (cond\n (zero? m)\n (inc n)\n\n (zero? n)\n (recur (dec m) 1)\n\n :else\n (recur (dec m)\n (ackermann m (dec n)))))\n</code></pre>\n\n<p>can be transformed into:</p>\n\n<pre><code>(defn ackermann [m n]\n (loop [m m\n n n\n stack []]\n (cond\n (zero? m)\n (return (inc n) stack)\n\n (zero? n)\n (recur (dec m) 1 stack)\n\n :else\n (recur m\n (dec n)\n (cons #(ackermann (dec m) %)\n stack)))))\n</code></pre>\n" }, { "answer_id": 68208998, "author": "shalom", "author_id": 6074164, "author_profile": "https://Stackoverflow.com/users/6074164", "pm_score": 0, "selected": false, "text": "<p>This is an old question but I want to add a different aspect as a solution. I'm currently working on a project in which I used the flood fill algorithm using C#. Normally, I implemented this algorithm with recursion at first, but obviously, it caused a stack overflow. After that, I changed the method from recursion to iteration. Yes, It worked and I was no longer getting the stack overflow error. But this time, since I applied the flood fill method to very large structures, the program was going into an infinite loop. For this reason, it occurred to me that the function may have re-entered the places it had already visited. As a definitive solution to this, I decided to use a dictionary for visited points. If that node(x,y) has already been added to the stack structure for the first time, that node(x,y) will be saved in the dictionary as the key. Even if the same node is tried to be added again later, it won't be added to the stack structure because the node is already in the dictionary. Let's see on pseudo-code:</p>\n<pre><code>startNode = pos(x,y)\n\nStack stack = new Stack();\n\nDictionary visited&lt;pos, bool&gt; = new Dictionary();\n\nstack.Push(startNode);\n\nwhile(stack.count != 0){\n currentNode = stack.Pop();\n if \"check currentNode if not available\"\n continue;\n if \"check if already handled\"\n continue;\n else if \"run if it must be wanted thing should be handled\" \n // make something with pos currentNode.X and currentNode.X \n \n // then add its neighbor nodes to the stack to iterate\n // but at first check if it has already been visited.\n \n if(!visited.Contains(pos(x-1,y)))\n visited[pos(x-1,y)] = true;\n stack.Push(pos(x-1,y));\n if(!visited.Contains(pos(x+1,y)))\n ...\n if(!visited.Contains(pos(x,y+1)))\n ...\n if(!visited.Contains(pos(x,y-1)))\n ...\n}\n\n</code></pre>\n" }, { "answer_id": 68872963, "author": "Todd", "author_id": 7915759, "author_profile": "https://Stackoverflow.com/users/7915759", "pm_score": 2, "selected": false, "text": "<h3>TLDR</h3>\n<p>You can compare the source code below, before and after to intuitively understand the approach without reading this whole answer.</p>\n<p>I ran into issues with some multi-key quicksort code I was using to process very large blocks of text to produce suffix arrays. The code would abort due to the extreme depth of recursion required. With this approach, the termination issues were resolved. After conversion the maximum number of frames required for some jobs could be captured, which was between 10K and 100K, taking from 1M to 6M memory. Not an optimum solution, there are more effective ways to produce suffix arrays. But anyway, here's the approach used.</p>\n<h3>The approach</h3>\n<p>A general way to convert a recursive function to an iterative solution that will apply to any case is to mimic the process natively compiled code uses during a function call and the return from the call.</p>\n<p>Taking an example that requires a somewhat involved approach, we have the multi-key quicksort algorithm. This function has three successive recursive calls, and after each call, execution begins at the next line.</p>\n<p>The state of the function is captured in the stack frame, which is pushed onto the execution stack. When <code>sort()</code> is called from within itself and returns, the stack frame present at the time of the call is restored. In that way all the variables have the same values as they did before the call - unless they were modified by the call.</p>\n<h3>Recursive function</h3>\n<pre class=\"lang-py prettyprint-override\"><code>def sort(a: list_view, d: int):\n if len(a) &lt;= 1:\n return\n p = pivot(a, d)\n i, j = partition(a, d, p)\n sort(a[0:i], d)\n sort(a[i:j], d + 1)\n sort(a[j:len(a)], d)\n</code></pre>\n<p>Taking this model, and mimicking it, a list is set up to act as the stack. In this example tuples are used to mimic frames. If this were encoded in C, structs could be used. The data can be contained within a data structure instead of just pushing one value at a time.</p>\n<h3>Reimplemented as &quot;iterative&quot;</h3>\n<pre class=\"lang-py prettyprint-override\"><code># Assume `a` is view-like object where slices reference\n# the same internal list of strings.\n\ndef sort(a: list_view):\n stack = []\n stack.append((LEFT, a, 0)) # Initial frame.\n\n while len(stack) &gt; 0:\n frame = stack.pop() \n\n if len(frame[1]) &lt;= 1: # Guard.\n continue\n\n stage = frame[0] # Where to jump to.\n\n if stage == LEFT: \n _, a, d = frame # a - array/list, d - depth.\n p = pivot(a, d)\n i, j = partition(a, d, p)\n stack.append((MID, a, i, j, d)) # Where to go after &quot;return&quot;.\n stack.append((LEFT, a[0:i], d)) # Simulate function call.\n\n elif stage == MID: # Picking up here after &quot;call&quot;\n _, a, i, j, d = frame # State before &quot;call&quot; restored.\n stack.append((RIGHT, a, i, j, d)) # Set up for next &quot;return&quot;.\n stack.append((LEFT, a[i:j], d + 1)) # Split list and &quot;recurse&quot;.\n\n elif stage == RIGHT:\n _, a, _, j, d = frame\n stack.append((LEFT, a[j:len(a)], d)\n\n else:\n pass\n</code></pre>\n<p>When a function call is made, information on where to begin execution after the function returns is included in the stack frame. In this example, <code>if/elif/else</code> blocks represent the points where execution begins after return from a call. In C this could be implemented as a <code>switch</code> statement.</p>\n<p>In the example, the blocks are given labels; they're arbitrarily labeled by how the list is partitioned within each block. The first block, &quot;LEFT&quot; splits the list on the left side. The &quot;MID&quot; section represents the block that splits the list in the middle, etc.</p>\n<p>With this approach, mimicking a call takes two steps. First a frame is pushed onto the stack that will cause execution to resume in the block following the current one after the &quot;call&quot; &quot;returns&quot;. A value in the frame indicates which <code>if/elif/else</code> section to fall into on the loop that follows the &quot;call&quot;.</p>\n<p>Then the &quot;call&quot; frame is pushed onto the stack. This sends execution to the first, &quot;LEFT&quot;, block in most cases for this specific example. This is where the actual sorting is done regardless which section of the list was split to get there.</p>\n<p>Before the looping begins, the primary frame pushed at the top of the function represents the initial call. Then on each iteration, a frame is popped. The &quot;LEFT/MID/RIGHT&quot; value/label from the frame is used to fall into the correct block of the <code>if/elif/else</code> statement. The frame is used to restore the state of the variables needed for the current operation, then on the next iteration the return frame is popped, sending execution to the subsequent section.</p>\n<h3>Return values</h3>\n<p>If the recursive function returns a value used by itself, it can be treated the same way as other variables. Just create a field in the stack frame for it. If a &quot;callee&quot; is returning a value, it checks the stack to see if it has any entries; and if so, updates the return value in the frame on the top of the stack. For an example of this <a href=\"https://stackoverflow.com/a/69429522/7915759\">you can check this other example</a> of this same approach to recursive to iterative conversion.</p>\n<h3>Conclusion</h3>\n<p>Methods like this that convert recursive functions to iterative functions, are essentially also &quot;recursive&quot;. Instead of the process stack being utilized for actual function calls, another programmatically implemented stack takes its place.</p>\n<p>What is gained? Perhaps some marginal improvements in speed. Or it could serve as a way to get around stack limitations imposed by some compilers and/or execution environments (stack pointer hitting the guard page). In some cases, the amount of data pushed onto the stack can be reduced. Do the gains offset the complexity introduced in the code by mimicking something that we get automatically with the recursive implementation?</p>\n<p>In the case of the sorting algorithm, finding a way to implement this particular one without a stack could be challenging, plus there are so many iterative sorting algorithms available that are much faster. It's been said that any recursive algorithm can be implemented iteratively. Sure... but some algorithms don't convert well without being modified to such a degree that they're no longer the same algorithm.</p>\n<p>It may not be such a great idea to convert recursive algorithms just for the sake of converting them. Anyway, for what it's worth, the above approach is a generic way of converting that should apply to just about anything.</p>\n<p>If you find you really need an iterative version of a recursive function that doesn't use a memory eating stack of its own, the best approach may be to scrap the code and write your own using the description from a scholarly article, or work it out on paper and then code it from scratch, or other ground up approach.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems. So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help. * Are there general rules? * Is there a "pattern"?
Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own. ```js var stack = []; stack.push(firstObject); // while not empty while (stack.length) { // Pop off end of stack. obj = stack.pop(); // Do stuff. // Push other objects on the stack as needed. ... } ``` Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack: ``` foo(first); foo(second); ``` has to be replaced by ``` stack.push(second); stack.push(first); ``` Edit: The article [Stacks and Recursion Elimination](http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf) (or [Article Backup link](https://web.archive.org/web/20120227170843/http://cs.saddleback.edu/rwatkins/CS2B/Lab%20Exercises/Stacks%20and%20Recursion%20Lab.pdf)) goes into more details on this subject.
159,594
<p>I've organized my code hierarchically and I find myself crawling up the tree using code like the following.</p> <pre><code>File clientFolder = task.getActionPlan().getClientFile().getClient().getDocumentsFolder(); </code></pre> <p>I'm not drilling down into the <code>task</code> object; I'm drilling up to its parents, so I don't think I'm losing anything in terms of encapsulation; but a flag is going off in the back of my mind telling me there's something dirty about doing it this way.</p> <p>Is this wrong?</p>
[ { "answer_id": 159608, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 0, "selected": false, "text": "<p><strong>The biggest flag in the world.</strong> </p>\n\n<p>You cannot check easily if any of those invokations returns a null object thus making tracking any sort of error next to impossible!</p>\n\n<p>getClientFile() may return null and then getClient() will fail and when you are catching this, assuming you are try-catching you won't have a clue as to which one failed.</p>\n" }, { "answer_id": 159612, "author": "rice", "author_id": 23933, "author_profile": "https://Stackoverflow.com/users/23933", "pm_score": 0, "selected": false, "text": "<p>How likely is it to get nulls or invalid results? That code is dependent on the successful return of many functions and it could be harder to sort out errors like null pointer exception.</p>\n\n<p>It's also bad for the debugger: less informative since you have to run the functions rather than just watching a few local variables, and awkward to step into the later functions in the chain.</p>\n" }, { "answer_id": 159614, "author": "devlord", "author_id": 16454, "author_profile": "https://Stackoverflow.com/users/16454", "pm_score": 0, "selected": false, "text": "<p>Yes. It's not best practice. For one thing, if there's a bug, it's harder to find it. For example, your exception handler might display a stack trace that shows that you have a NullReferenceException on line 121, but which of these methods is returning null? You'd have to dig into the code to find out.</p>\n" }, { "answer_id": 159618, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "<p>This is a subjective question but I don't think there's anything wrong with it up to a point. For instance if the chain extends beyond the readable aread of the editor then you should introduce some locals. For instance, on my browser I can't see the last 3 calls so I have no idea what you're doing :).</p>\n" }, { "answer_id": 159622, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 0, "selected": false, "text": "<p>Well it depends. You shouldn't have to reach through an object like that.\nIf you control the implementations of those methods, I'd recommend refactoring so that you don't have to do that.</p>\n\n<p>Otherwise, I see no harm in doing what you're doing. It's certainly better than </p>\n\n<pre><code>ActionPlan AP = task.getActionPlan();\nClientFile CF = AP.getClientFile();\nClient C = CF.getClient();\nDocFolder DF = C.getDocumentsFolder();\n</code></pre>\n" }, { "answer_id": 159630, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Well, every indirection adds one point where it could go wrong.</p>\n\n<p>In particular, any of the methods in this chain could return a null (in theory, in your case you might have methods that cannot possibly do that), and when that happens you'll know it happened <em>to one of those methods</em>, but not <em>which one</em>.</p>\n\n<p>So if there is any chance any of the methods could return a null, I'd at least split the chain at those points, and store in intermediate variables, and break it up into individual lines, so that a crash report would give me a line number to look at.</p>\n\n<p>Apart from that I can't see any obvious problems with it. If you have, or can make, guarantees that the null-reference won't be a problem, it would do what you want.</p>\n\n<p>What about readability? Would it be clearer if you added named variables? Always write code like you intend it to be read by a fellow programmer, and only incidentally be interpreted by a compiler.</p>\n\n<p>In this case I would have to read the chain of method calls and figure out... ok, it gets a document, it's the document of a client, the client is coming from a ... file... right, and the file is from an action plan, etc. Long chains might make it less readable than, say, this:</p>\n\n<pre><code>ActionPlan taskPlan = task.GetActionPlan();\nClientFile clientFileOfTaskPlan = taskPlan.GetClientFile();\nClient clientOfTaskPlan = clientFileOfTaskPlan.GetClient();\nFile clientFolder = clientOfTaskPlan.getDocumentsFolder();\n</code></pre>\n\n<p>I guess it comes down to personal opinion on this matter.</p>\n" }, { "answer_id": 159634, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 0, "selected": false, "text": "<p>It is not bad as such, but you might get problems reading this in 6 month. Or a co-worker might get problems maintaining / writing code, because the chain of your objects is quite... long.</p>\n\n<p>And I recon that you do not have to introduce variables in your code. So the objects do know all they need to jump from method to method. (Here arises the question if you did not overengineer a little bit, but who am I to tell?)</p>\n\n<p>I would introduce a kind of \"convenience methods\". Imagine you got a method in your \"task\" - object something like</p>\n\n<pre><code> task.getClientFromActionPlan();\n</code></pre>\n\n<p>You then surely could use</p>\n\n<pre><code> task.getClientFromActionPlan().getDocumentsFolder();\n</code></pre>\n\n<p>Much more readable and in case you do these \"convenience methods\" right (i.e. for heavy used object chains), much less to type ;-) .</p>\n\n<p>Edith says: These convenience methods I suggest often do contain Nullpointer-checking when I write them. This way you even can throw Nullpointers with good error messages in (i.e. \"ActionPlan was null while trying to retrieve the client from it\").</p>\n" }, { "answer_id": 159652, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 0, "selected": false, "text": "<p>Related discussion:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/154864/function-chaining-how-many-is-too-many\">Function Chaining - How many is too many?</a></p>\n" }, { "answer_id": 159671, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>This question is very close to <a href=\"https://stackoverflow.com/questions/154864/function-chaining-how-many-is-too-many#155407\">https://stackoverflow.com/questions/154864/function-chaining-how-many-is-too-many#155407</a></p>\n\n<p>In general, it seems that people agree that too long chains are not good and you should stick to one or two chained calls at most.</p>\n\n<p>Though I hear that Python fans consider chaining to be a lot of fun. That might be just a rumor...:-)</p>\n" }, { "answer_id": 159680, "author": "volley", "author_id": 13905, "author_profile": "https://Stackoverflow.com/users/13905", "pm_score": 2, "selected": false, "text": "<p>First of all, stacking code like that can make it annoying to analyze NullPointerExceptions and check references while stepping in a debugger.</p>\n\n<p>Apart from that, I think it all boils down to this: <strong>Does the caller need to have all that knowledge?</strong></p>\n\n<p>Perhaps its functionality could be made more generic; the File could then be passed as a parameter instead. Or, perhaps the ActionPlan should not even reveal that its implementation is based on a ClientFile?</p>\n" }, { "answer_id": 159700, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "<p>Depending on your end goal you would probably want to use The Principal of Least Knowledge to avoid heavy coupling and costing you in the end. As head first likes to put it.. \"Only talk to your friends.\"</p>\n" }, { "answer_id": 159706, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 1, "selected": false, "text": "<p>I agree with the poster that mentioned the Law of Demeter. What you're doing is creating unnecessary dependencies on the implementations of a lot of these classes, and on the structure of the hierarchy itself. It wil make it very difficult to test your code in isolation, since you will need to initialize a dozen other objects just to get a working instance of the class you want to test.</p>\n" }, { "answer_id": 159723, "author": "Aaron H.", "author_id": 16258, "author_profile": "https://Stackoverflow.com/users/16258", "pm_score": 0, "selected": false, "text": "<p>Another important byproduct of chaining is performance. </p>\n\n<p>It's not a big deal in most cases, but especially in a loop you can see a reasonable boost in performance by reducing indirection.</p>\n\n<p>Chaining also makes it harder to estimate performance, you can't tell which of those methods may or may not do something complex.</p>\n" }, { "answer_id": 159749, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>the flag is red, and it says two things in <strong>bold</strong>:</p>\n\n<ul>\n<li>to follow the chain it is necessary for the calling code to know the entire tree structure, which is not good encapsulation, and</li>\n<li>if the hierarchy ever changes you will have a lot of code to edit</li>\n</ul>\n\n<p>and one thing in parentheses:</p>\n\n<ul>\n<li>use a property, i.e. task.ActionPlan instead of task.getActionPlan()</li>\n</ul>\n\n<p>a better solution might be - assuming you need to expose all of the parent properties up the tree at the child level - to go ahead and implement direct properties on the children, i.e.</p>\n\n<pre><code>File clientFolder = task.DocumentsFolder;\n</code></pre>\n\n<p>this will at least hide the tree structure from the calling code. Internally the properties may look like:</p>\n\n<pre><code>class Task {\n public File DocumentsFolder {\n get { return ActionPlan.DocumentsFolder; }\n }\n ...\n}\nclass ActionPlan {\n public File DocumentsFolder {\n get { return ClientFile.DocumentsFolder: }\n }\n ...\n}\nclass ClientFile {\n public File DocumentsFolder {\n get { return Client.DocumentsFolder; }\n }\n ...\n}\nclass Client {\n public File DocumentsFolder {\n get { return ...; } //whatever it really is\n }\n ...\n}\n</code></pre>\n\n<p>but if the tree structure changes in the future you will only need to change the accessor functions in the classes involved in the tree, and not every place where you called up the chain.</p>\n\n<p>[plus it will be easier to trap and report nulls properly in the property functions, which was omitted from the example above]</p>\n" }, { "answer_id": 159832, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 1, "selected": false, "text": "<p>How timely. I am going to write a post on my blog tonight about this smell, <a href=\"http://sis36.berkeley.edu/projects/streek/agile/bad-smells-in-code.html#Message+Chains\" rel=\"nofollow noreferrer\">Message Chains</a>, versus its inverse, <a href=\"http://sis36.berkeley.edu/projects/streek/agile/bad-smells-in-code.html#Middle+Man\" rel=\"nofollow noreferrer\">Middle Man</a>.</p>\n\n<p>Anyhow, a deeper question is why you have \"get\" methods on what appears to be a domain object. If you closely follow the contours of the problem, you will either find out that it doesn't make sense to tell a task to get something, or that what you are doing is really a non-business logic concern like preparing for UI display, persistence, object reconstruction, etc. </p>\n\n<p>In the latter case, then the \"get\" methods are ok as long as they're <a href=\"http://moffdub.wordpress.com/restricted-method-access/\" rel=\"nofollow noreferrer\">used by authorized classes</a>. How you enforce that policy is platform -and process-dependent. </p>\n\n<p>So in the case where the \"get\" methods are deemed ok, you still have to face the problem. And unfortunately, I think it depends on the class that is navigating the chain. If it is appropriate for that class to be coupled to the structure (say, a factory), then let it be. Otherwise, you should try to <a href=\"http://www.refactoring.com/catalog/hideDelegate.html\" rel=\"nofollow noreferrer\">Hide Delegate</a>.</p>\n\n<p>Edit: <a href=\"http://moffdub.wordpress.com/2008/10/01/a-hidden-delegation-of-middle-men/\" rel=\"nofollow noreferrer\">click here for my post</a>.</p>\n" }, { "answer_id": 160169, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html\" rel=\"nofollow noreferrer\">Getters and setters are evil</a>. Generally, avoid getting an object to do something with it. Instead delegate the task itself.</p>\n\n<p>Instead of</p>\n\n<pre><code>Object a = b.getA();\ndoSomething(a);\n</code></pre>\n\n<p>do</p>\n\n<pre><code>b.doSomething();\n</code></pre>\n\n<p>As with all design principles, do not follow this blindly. I have never been able to write anything remotely complicated without getters and setters, but it is a nice guideline. If you have a lot of getters and setters, it probably means you are doing it wrong.</p>\n" }, { "answer_id": 160217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'd point to The Law of Demeter, too.</p>\n\n<p>And add an article about <a href=\"http://www.pragmaticprogrammer.com/articles/tell-dont-ask\" rel=\"nofollow noreferrer\">Tell, Don't Ask</a></p>\n" }, { "answer_id": 160246, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 1, "selected": false, "text": "<p>Are you realistically going to ever use each and every one of those functions independently? Why not just make task have a GetDocumentsFolder() method that does all the dirty work of calling all those methods for you? Then you can make that do all the dirty work of null-checking everything without crufting up your code in places where it doesn't need to be crufted up.</p>\n" }, { "answer_id": 162036, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "<p>OK as others point out the code isn't great because you're locking in the code to a specific hierarchy. It can present problems debugging, and it's not nice to read, but the major point is the code that takes a task knows way too much about traversing to get some folder thing. Dollars to donuts, somebody's going to want to insert something in the middle. (all tasks are in a task list, etc)</p>\n\n<p>Going out on a limb, are all of these classes just special names for the same thing? ie are they hierarchical, but each level has maybe a few extra properties?</p>\n\n<p>So, from a different angle, I'm going to simplify to an enum and an interface, where the child classes delegate up the chain if they aren't the requested thing. For the sake of argument, I'm calling them folders.</p>\n\n<pre><code>enum FolderType { ActionPlan, ClientFile, Client, etc }\n\ninterface IFolder\n{\n IFolder FindTypeViaParent( FolderType folderType )\n}\n</code></pre>\n\n<p>and each class that implements IFolder probably just does</p>\n\n<pre><code>IFolder FindTypeViaParent( FolderType folderType )\n{\n if( myFolderType == folderType )\n return this;\n\n if( parent == null )\n return null;\n\n IFolder parentIFolder = (IFolder)parent;\n return parentIFolder.FindTypeViaParent(folderType)\n}\n</code></pre>\n\n<p>A variation is to make the IFolder interface:</p>\n\n<pre><code>interface IFolder\n{\n FolderType FolderType { get; }\n IFolder Parent { get; }\n}\n</code></pre>\n\n<p>This allows you to externalize the traversal code. However this takes control away from the classes (maybe they have multiple parents) and exposes implementation. Good and bad.</p>\n\n<p>[<em>ramblings</em>]</p>\n\n<p>At a glance this appears to be a pretty expensive hierarchy to set up. Do I need to instantiate top-down every time? i.e. if something just needs a task, do you have to instantiate everything bottom-up to ensure all those back-pointers work? Even if it's lazy-load, do I need to walk up the hierarchy just to get the root?</p>\n\n<p>Then again, is the hierarchy really a part of object identity? If it's not, perhaps you could externalize the hierarchy as an n-ary tree.</p>\n\n<p>As a side-note, you may want to consider the DDD (Domain Driven Design) concept of aggregate and determine who the major players are. What is the ultimate owner object that is responsible? e.g. wheels of a car. In a design that models a car, the wheels are also objects, but they are owned by the car.</p>\n\n<p>Maybe it works for you, maybe it doesn't. Like I said, this is just a shot in the dark.</p>\n" }, { "answer_id": 621697, "author": "Pontus Gagge", "author_id": 20402, "author_profile": "https://Stackoverflow.com/users/20402", "pm_score": 0, "selected": false, "text": "<p>On the other hand, the <a href=\"https://stackoverflow.com/questions/67561/do-fluent-interfaces-violate-the-law-of-demeter\">Law of Demeter isn't universally applicable</a>, nor a hard rule (arrr, <a href=\"http://www.logan.ws/quotes/pirates-of-the-caribbean.asp\" rel=\"nofollow noreferrer\">it be more of a guideline</a>!). </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I've organized my code hierarchically and I find myself crawling up the tree using code like the following. ``` File clientFolder = task.getActionPlan().getClientFile().getClient().getDocumentsFolder(); ``` I'm not drilling down into the `task` object; I'm drilling up to its parents, so I don't think I'm losing anything in terms of encapsulation; but a flag is going off in the back of my mind telling me there's something dirty about doing it this way. Is this wrong?
the flag is red, and it says two things in **bold**: * to follow the chain it is necessary for the calling code to know the entire tree structure, which is not good encapsulation, and * if the hierarchy ever changes you will have a lot of code to edit and one thing in parentheses: * use a property, i.e. task.ActionPlan instead of task.getActionPlan() a better solution might be - assuming you need to expose all of the parent properties up the tree at the child level - to go ahead and implement direct properties on the children, i.e. ``` File clientFolder = task.DocumentsFolder; ``` this will at least hide the tree structure from the calling code. Internally the properties may look like: ``` class Task { public File DocumentsFolder { get { return ActionPlan.DocumentsFolder; } } ... } class ActionPlan { public File DocumentsFolder { get { return ClientFile.DocumentsFolder: } } ... } class ClientFile { public File DocumentsFolder { get { return Client.DocumentsFolder; } } ... } class Client { public File DocumentsFolder { get { return ...; } //whatever it really is } ... } ``` but if the tree structure changes in the future you will only need to change the accessor functions in the classes involved in the tree, and not every place where you called up the chain. [plus it will be easier to trap and report nulls properly in the property functions, which was omitted from the example above]
159,598
<p>This snippet works well if I try to write in a user directory but as soon as I try to write in Program Files, it just executes silently and the file has not been copied (no exception). If I try to copy the file in C:\ or in C:\Windows I catch an UnauthorizedAccessException.</p> <p>Do you know another way to get the permissions to write in that directory or to make it work another way?</p> <p>Any help greatly appreciated! Thanks</p> <pre><code>using(FileStream fs=File.Open(source, FileMode.Open)){ } try { FileIOPermission fp = new FileIOPermission(FileIOPermissionAccess.Write, AccessControlActions.Change, "C:\\Program Files\\MyPath"); fp.Demand(); //&lt;-- no exception but file is not copied File.Copy("C:\\Users\\teebot\\Documents\\File.xml","C:\\Program Files\\MyPath\\File.xml",true); } catch(SecurityExceptions) { throw(s); } catch(UnauthorizedAccessException unauthroizedException) { throw unauthroizedException; } </code></pre>
[ { "answer_id": 159605, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p><strong>Don't write in the Program Files folder.</strong></p>\n\n<p>That's a big no-no, and will especially cause problems when the day comes where your code runs in Vista or on a machine at a company where users only get standard security rather than admin rights. Use the Application Data folder instead.</p>\n" }, { "answer_id": 159632, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>Code access security grants or denies permissions to your <em>code</em>.\nIt can't be used to override permissions that are granted/denied to the current user.</p>\n" }, { "answer_id": 159654, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>Are you running on Vista? If so then you may be running into file system virtualization. This is a feature in 32 bit versions of Vista which allows a normal user to write to protected parts of the file system. It's a shim introduced to reduce the pain of the LUA features of Vista. </p>\n\n<p>The short version is that the operating system will create a virtual file system for certain protected roots (such as program files). When a non-admin attempts to write to it, a copy will be created an editted instead of the original. When your user account attempts to look at the file it will see the edit.s Other user accounts will only see the original. </p>\n\n<p>Longer Version: <a href=\"http://thelazyadmin.com/blogs/thelazyadmin/archive/2007/04/26/file-system-virtualization.aspx\" rel=\"nofollow noreferrer\">http://thelazyadmin.com/blogs/thelazyadmin/archive/2007/04/26/file-system-virtualization.aspx</a></p>\n" }, { "answer_id": 159679, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 2, "selected": true, "text": "<p>If you are running under Vista then the system just redirects writes to the program files folder, this is done so old program that keep their configuration in the program directory will continue to work when the user is not an Admin (or UAC is enabled).</p>\n\n<p>All you have to do is add a manifest to your program that specify the required access level, then the system assume your program is Vista-aware and turns off all those compatibility patches.</p>\n\n<p>You can see an example of a manifest file on my blog at:</p>\n\n<p><a href=\"http://www.nbdtech.com/blog/archive/2008/06/16/The-Application-Manifest-Needed-for-XP-and-Vista-Style-File.aspx\" rel=\"nofollow noreferrer\">http://www.nbdtech.com/blog/archive/2008/06/16/The-Application-Manifest-Needed-for-XP-and-Vista-Style-File.aspx</a></p>\n\n<p>(the focus of the post is on getting the right version of the common controls, but the Vista security declarations are also there)</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24291/" ]
This snippet works well if I try to write in a user directory but as soon as I try to write in Program Files, it just executes silently and the file has not been copied (no exception). If I try to copy the file in C:\ or in C:\Windows I catch an UnauthorizedAccessException. Do you know another way to get the permissions to write in that directory or to make it work another way? Any help greatly appreciated! Thanks ``` using(FileStream fs=File.Open(source, FileMode.Open)){ } try { FileIOPermission fp = new FileIOPermission(FileIOPermissionAccess.Write, AccessControlActions.Change, "C:\\Program Files\\MyPath"); fp.Demand(); //<-- no exception but file is not copied File.Copy("C:\\Users\\teebot\\Documents\\File.xml","C:\\Program Files\\MyPath\\File.xml",true); } catch(SecurityExceptions) { throw(s); } catch(UnauthorizedAccessException unauthroizedException) { throw unauthroizedException; } ```
If you are running under Vista then the system just redirects writes to the program files folder, this is done so old program that keep their configuration in the program directory will continue to work when the user is not an Admin (or UAC is enabled). All you have to do is add a manifest to your program that specify the required access level, then the system assume your program is Vista-aware and turns off all those compatibility patches. You can see an example of a manifest file on my blog at: <http://www.nbdtech.com/blog/archive/2008/06/16/The-Application-Manifest-Needed-for-XP-and-Vista-Style-File.aspx> (the focus of the post is on getting the right version of the common controls, but the Vista security declarations are also there)
159,599
<p>I have a .net project that has a web reference to a service. I would like to update that web reference as part of every build. Is that possible?</p>
[ { "answer_id": 159617, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "<p>Also, when you are deploying your webservices on production make sure that they are set as Dynamic and not static. </p>\n" }, { "answer_id": 159629, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>You can use svcutil (<a href=\"http://msdn.microsoft.com/en-us/library/aa347733.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa347733.aspx</a>) tool to generate the web reference for you. The tool will generate the proper client proxy classes and the proper config (and it can even merge it in your application config). Keep in mind that the tool requires .Net 3.0 and will generate WCF-style client proxies and configuration.</p>\n" }, { "answer_id": 159751, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 5, "selected": true, "text": "<p>You can use MSBuild script with a task that calls <a href=\"http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx\" rel=\"noreferrer\">wsdl.exe</a> </p>\n\n<pre><code> &lt;Target Name=\"UpdateWebReference\"&gt;\n &lt;Message Text=\"Updating Web Reference...\"/&gt;\n &lt;Exec Command=\"wsdl.exe /o &amp;quot;$(OutDir)&amp;quot; /n &amp;quot;$(WebServiceNamespace)&amp;quot; &amp;quot$(PathToWebServiceURL)&amp;quot;\"/&gt;\n &lt;/Target&gt;\n</code></pre>\n" }, { "answer_id": 161922, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 1, "selected": false, "text": "<p>You can do it using the methods provided by the other answerers, but you have to know that doing this could cause your build to fail. If the WSDL was changed, the generated code is also going to change and your code may no longer compile.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15903/" ]
I have a .net project that has a web reference to a service. I would like to update that web reference as part of every build. Is that possible?
You can use MSBuild script with a task that calls [wsdl.exe](http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx) ``` <Target Name="UpdateWebReference"> <Message Text="Updating Web Reference..."/> <Exec Command="wsdl.exe /o &quot;$(OutDir)&quot; /n &quot;$(WebServiceNamespace)&quot; &quot$(PathToWebServiceURL)&quot;"/> </Target> ```
159,615
<p>When running command-line queries in MySQL you can optionally use '<strong>\G</strong>' as a statement terminator, and instead of the result set columns being listed horizontally across the screen, it will list each column vertically, which the corresponding data to the right. Is there a way to the same or a similar thing with the DB2 command line utility?</p> <p>Example regular MySQL result</p> <pre><code>mysql&gt; select * from tagmap limit 2; +----+---------+--------+ | id | blog_id | tag_id | +----+---------+--------+ | 16 | 8 | 1 | | 17 | 8 | 4 | +----+---------+--------+ </code></pre> <p>Example Alternate MySQL result:</p> <pre><code>mysql&gt; select * from tagmap limit 2\G *************************** 1. row *************************** id: 16 blog_id: 8 tag_id: 1 *************************** 2. row *************************** id: 17 blog_id: 8 tag_id: 4 2 rows in set (0.00 sec) </code></pre> <p>Obviously, this is much more useful when the columns are large strings, or when there are many columns in a result set, but this demonstrates the formatting better than I can probably explain it.</p>
[ { "answer_id": 161151, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": true, "text": "<p>I don't think such an option is available with the DB2 command line client. See <a href=\"http://www.dbforums.com/showthread.php?t=708079\" rel=\"nofollow noreferrer\">http://www.dbforums.com/showthread.php?t=708079</a> for some suggestions. For a more general set of information about the DB2 command line client you might check out the IBM DeveloperWorks article <a href=\"http://www.ibm.com/developerworks/db2/library/techarticle/adamache/0109adamache.html\" rel=\"nofollow noreferrer\">DB2's Command Line Processor and Scripting</a>.</p>\n" }, { "answer_id": 27618935, "author": "Bimal Jha", "author_id": 4177130, "author_profile": "https://Stackoverflow.com/users/4177130", "pm_score": -1, "selected": false, "text": "<p>DB2 command line utility always displays data in tabular format. i.e. rows horizontally and columns vertically. It does not support any other format like \\G statement terminator do for mysql. But yes, you can store column organized data in DB2 tables when DB2_WORKLOAD=ANALYTICS is set.</p>\n\n<pre><code>db2 =&gt; connect to coldb\n\n Database Connection Information\n\n Database server = DB2/LINUXX8664 10.5.5\n SQL authorization ID = BIMALJHA\n Local database alias = COLDB\n\ndb2 =&gt; create table testtable (c1 int, c2 varchar(10)) organize by column\nDB20000I The SQL command completed successfully.\ndb2 =&gt; insert into testtable values (2, 'bimal'),(3, 'kumar')\nDB20000I The SQL command completed successfully.\ndb2 =&gt; select * from testtable\n\nC1 C2 \n----------- ----------\n 2 bimal \n 3 kumar \n\n 2 record(s) selected.\n\ndb2 =&gt; terminate\nDB20000I The TERMINATE command completed successfully.\n</code></pre>\n" }, { "answer_id": 69814199, "author": "stoeps", "author_id": 4946225, "author_profile": "https://Stackoverflow.com/users/4946225", "pm_score": 0, "selected": false, "text": "<p>Little bit late, but found this post when I searched for an option to retrieve only the selected data.</p>\n<p>So <code>db2 -x &lt;query&gt;</code> gives only the result back. More options can be found here: <a href=\"https://www.ibm.com/docs/en/db2/11.1?topic=clp-options\" rel=\"nofollow noreferrer\">https://www.ibm.com/docs/en/db2/11.1?topic=clp-options</a></p>\n<p>Example:</p>\n<pre><code>[db2inst1@a21c-db2 db2]$ db2 -n select postschemaver from files.product\n\nPOSTSCHEMAVER \n--------------------------------\n147.3 \n\n 1 record(s) selected.\n\n[db2inst1@a21c-db2 db2]$ db2 -x select postschemaver from files.product \n147.3 \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8636/" ]
When running command-line queries in MySQL you can optionally use '**\G**' as a statement terminator, and instead of the result set columns being listed horizontally across the screen, it will list each column vertically, which the corresponding data to the right. Is there a way to the same or a similar thing with the DB2 command line utility? Example regular MySQL result ``` mysql> select * from tagmap limit 2; +----+---------+--------+ | id | blog_id | tag_id | +----+---------+--------+ | 16 | 8 | 1 | | 17 | 8 | 4 | +----+---------+--------+ ``` Example Alternate MySQL result: ``` mysql> select * from tagmap limit 2\G *************************** 1. row *************************** id: 16 blog_id: 8 tag_id: 1 *************************** 2. row *************************** id: 17 blog_id: 8 tag_id: 4 2 rows in set (0.00 sec) ``` Obviously, this is much more useful when the columns are large strings, or when there are many columns in a result set, but this demonstrates the formatting better than I can probably explain it.
I don't think such an option is available with the DB2 command line client. See <http://www.dbforums.com/showthread.php?t=708079> for some suggestions. For a more general set of information about the DB2 command line client you might check out the IBM DeveloperWorks article [DB2's Command Line Processor and Scripting](http://www.ibm.com/developerworks/db2/library/techarticle/adamache/0109adamache.html).
159,704
<p>What options are there for serialization when returning instances of custom classes from a WebService?</p> <p>We have some classes with a number of child collection class properties as well as other properties that may or may not be set depending on usage. These objects are returned from an ASP.NET .asmx WebService decorated with the ScriptService attribute, so are serialized via JSON serialization when returned by the various WebMethods.</p> <p>The problem is that the out of the box serialization returns all public properties, regardless of whether or not they are used, as well as returning class name and other information in a more verbose manner than would be desired if you wanted to limit the amount of traffic.</p> <p>Currently, for the classes being returned we have added custom javascript converters that handle the JSON serializtion, and added them to the web.config as below:</p> <pre><code>&lt;system.web.extensions&gt; &lt;scripting&gt; &lt;webServices&gt; &lt;jsonSerialization&gt; &lt;converters&gt; &lt;add name="CustomClassConverter" type="Namespace.CustomClassConverter" /&gt; &lt;/converters&gt; &lt;/jsonSerialization&gt; &lt;/webServices&gt; &lt;/scripting&gt; &lt;/system.web.extensions&gt; </code></pre> <p>But this requires a custom converter for each class. Is there any other way to change the out of the box JSON serialization, either through extending the service, creating a custom serializer or the like?</p> <p><b>Follow Up</b><br> @marxidad:</p> <p>We are using the DataContractJsonSerializer class in other applications, however I have been unable to figure out how to apply it to these services. Here's an example of how the services are set-up:</p> <pre><code>[ScriptService] public class MyService : System.Web.Services.WebService { [WebMethod] public CustomClass GetCustomClassMethod { return new customClass(); } } </code></pre> <p>The WebMethods are called by javascript and return data serialized in JSON. The only method we have been able to change the serialization is to use the javascript converters as referenced above? </p> <p>Is there a way to tell the WebService to use a custom DataContractJsonSerializer? Whether it be by web.config configuration, decorating the service with attributes, etc.? </p> <p><b>Update</b><br> Well, we couldn't find any way to switch the out of the box JavaScriptSerializer except for creating individual JavaScriptConverters as above.</p> <p>What we did on that end to prevent having to create a separate converter was create a generic JavaScriptConverter. We added an empty interface to the classes we wanted handled and the SupportedTypes which is called on web-service start-up uses reflection to find any types that implement the interface kind of like this:</p> <pre><code>public override IEnumerable&lt;Type&gt; SupportedTypes { get { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { AssemblyBuilder dynamicAssemblyCheck = assembly as AssemblyBuilder; if (dynamicAssemblyCheck == null) { foreach (Type type in assembly.GetExportedTypes()) { if (typeof(ICustomClass).IsAssignableFrom(type)) { yield return type; } } } } } } </code></pre> <p>The actual implementation is a bit different so that the type are cached, and we will likely refactor it to use custom attributes rather than an empty interface.</p> <p>However with this, we ran into a slightly different problem when dealing with custom collections. These typically just extend a generic list, but the custom classes are used instead of the List&lt;> itself because there is generally custom logic, sorting etc. in the collection classes.</p> <p>The problem is that the Serialize method for a JavaScriptConverter returns a dictionary which is serialized into JSON as name value pairs with the associated type, whereas a list is returned as an array. So the collection classes could not be easily serialized using the converter. The solution for this was to just not include those types in the converter's SupportedTypes and they serialize perfectly as lists.</p> <p>So, serialization works, but when you try to pass these objects the other way as a parameter for a web service call, the deserialization breaks, because they can't be the input is treated as a list of string/object dictionaries, which can't be converted to a list of whatever custom class the collection contains. The only way we could find to deal with this is to create a generic class that is a list of string/object dictionaries which then converts the list to the appropriate custom collection class, and then changing any web service parameters to use the generic class instead.</p> <p>I'm sure there are tons of issues and violations of "best practices" here, but it gets the job done for us without creating a ton of custom converter classes.</p>
[ { "answer_id": 159811, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>System.Runtime.Serialization.Json.</code><a href=\"http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx\" rel=\"nofollow noreferrer\"><strong><code>DataContractJsonSerializer</code></strong></a> class in the <code>System.ServiceModel.Web.dll</code> assembly.</p>\n" }, { "answer_id": 159911, "author": "Ty.", "author_id": 8873, "author_profile": "https://Stackoverflow.com/users/8873", "pm_score": 0, "selected": false, "text": "<p>Don't quote me on this working for certain, but I believe this is what you are looking for.</p>\n\n<pre><code>[WebMethod]\n[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\npublic XmlDocument GetXmlDocument()\n{\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.LoadXml(_xmlString);\n return xmlDoc;\n}\n</code></pre>\n" }, { "answer_id": 200138, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 1, "selected": false, "text": "<p>If you're using .NET 3.x (or can), a WCF service is going to be your best bet.</p>\n\n<p>You can selectively control which properties are serialized to the client with the [DataMember] attribute. WCF also allows more fine-grained control over the JSON serialization and deserialization, if you desire it.</p>\n\n<p>This is a good example to get started: <a href=\"http://blogs.msdn.com/kaevans/archive/2007/09/04/using-wcf-json-linq-and-ajax-passing-complex-types-to-wcf-services-with-json-encoding.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/kaevans/archive/2007/09/04/using-wcf-json-linq-and-ajax-passing-complex-types-to-wcf-services-with-json-encoding.aspx</a></p>\n" }, { "answer_id": 802628, "author": "ntcolonel", "author_id": 97730, "author_profile": "https://Stackoverflow.com/users/97730", "pm_score": 2, "selected": false, "text": "<p>If you don't use code-generated classes, you can decorate your properties with the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx\" rel=\"nofollow noreferrer\">ScriptIgnoreAttribute</a> to tell the serializer to ignore certain properties. Xml serialization has a similar attribute.</p>\n\n<p>Of course, you cannot use this approach if you want to return some properties of a class on one service method call and different properties of the same class on a different service method call. If you want to do that, return an anonymous type in the service method.</p>\n\n<pre><code>[WebMethod]\n[ScriptMethod]\npublic object GimmieData()\n{\n var dalEntity = dal.GimmieEntity(); //However yours works...\n\n return new\n {\n id = dalEntity.Id,\n description = dalEntity.Desc\n };\n\n}\n</code></pre>\n\n<p>The serializer could care less about the type of the object you send to it, since it just turns it into text anyway.</p>\n\n<p>I also believe that you could implement <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx\" rel=\"nofollow noreferrer\">ISerializable</a> on your data entity (as a partial class if you have code-gen'd data entities) to gain fine-grained control over the serialization process, but I haven't tried it.</p>\n" }, { "answer_id": 933665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I know this thread has been quiet for a while, but I thought I'd offer that if you override the SupportedTypes property of JavaScriptConverter in you custom converter, you can add the types that should use the converter. This could go into a config file if necessary. That way you wouldn't need a custom converter for each class. </p>\n\n<p>I tried to create a generic converter but couldn't figure out how to identify it in the web.config. Would love to find out if anyone else has managed it.</p>\n\n<p>I got the idea when trying to solve the above issue and stumbled on Nick Berardi's \"Creating a more accurate JSON .NET Serializer\" (google it).</p>\n\n<p>Worked for me:)</p>\n\n<p>Thanks to all.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4299/" ]
What options are there for serialization when returning instances of custom classes from a WebService? We have some classes with a number of child collection class properties as well as other properties that may or may not be set depending on usage. These objects are returned from an ASP.NET .asmx WebService decorated with the ScriptService attribute, so are serialized via JSON serialization when returned by the various WebMethods. The problem is that the out of the box serialization returns all public properties, regardless of whether or not they are used, as well as returning class name and other information in a more verbose manner than would be desired if you wanted to limit the amount of traffic. Currently, for the classes being returned we have added custom javascript converters that handle the JSON serializtion, and added them to the web.config as below: ``` <system.web.extensions> <scripting> <webServices> <jsonSerialization> <converters> <add name="CustomClassConverter" type="Namespace.CustomClassConverter" /> </converters> </jsonSerialization> </webServices> </scripting> </system.web.extensions> ``` But this requires a custom converter for each class. Is there any other way to change the out of the box JSON serialization, either through extending the service, creating a custom serializer or the like? **Follow Up** @marxidad: We are using the DataContractJsonSerializer class in other applications, however I have been unable to figure out how to apply it to these services. Here's an example of how the services are set-up: ``` [ScriptService] public class MyService : System.Web.Services.WebService { [WebMethod] public CustomClass GetCustomClassMethod { return new customClass(); } } ``` The WebMethods are called by javascript and return data serialized in JSON. The only method we have been able to change the serialization is to use the javascript converters as referenced above? Is there a way to tell the WebService to use a custom DataContractJsonSerializer? Whether it be by web.config configuration, decorating the service with attributes, etc.? **Update** Well, we couldn't find any way to switch the out of the box JavaScriptSerializer except for creating individual JavaScriptConverters as above. What we did on that end to prevent having to create a separate converter was create a generic JavaScriptConverter. We added an empty interface to the classes we wanted handled and the SupportedTypes which is called on web-service start-up uses reflection to find any types that implement the interface kind of like this: ``` public override IEnumerable<Type> SupportedTypes { get { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { AssemblyBuilder dynamicAssemblyCheck = assembly as AssemblyBuilder; if (dynamicAssemblyCheck == null) { foreach (Type type in assembly.GetExportedTypes()) { if (typeof(ICustomClass).IsAssignableFrom(type)) { yield return type; } } } } } } ``` The actual implementation is a bit different so that the type are cached, and we will likely refactor it to use custom attributes rather than an empty interface. However with this, we ran into a slightly different problem when dealing with custom collections. These typically just extend a generic list, but the custom classes are used instead of the List<> itself because there is generally custom logic, sorting etc. in the collection classes. The problem is that the Serialize method for a JavaScriptConverter returns a dictionary which is serialized into JSON as name value pairs with the associated type, whereas a list is returned as an array. So the collection classes could not be easily serialized using the converter. The solution for this was to just not include those types in the converter's SupportedTypes and they serialize perfectly as lists. So, serialization works, but when you try to pass these objects the other way as a parameter for a web service call, the deserialization breaks, because they can't be the input is treated as a list of string/object dictionaries, which can't be converted to a list of whatever custom class the collection contains. The only way we could find to deal with this is to create a generic class that is a list of string/object dictionaries which then converts the list to the appropriate custom collection class, and then changing any web service parameters to use the generic class instead. I'm sure there are tons of issues and violations of "best practices" here, but it gets the job done for us without creating a ton of custom converter classes.
If you don't use code-generated classes, you can decorate your properties with the [ScriptIgnoreAttribute](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx) to tell the serializer to ignore certain properties. Xml serialization has a similar attribute. Of course, you cannot use this approach if you want to return some properties of a class on one service method call and different properties of the same class on a different service method call. If you want to do that, return an anonymous type in the service method. ``` [WebMethod] [ScriptMethod] public object GimmieData() { var dalEntity = dal.GimmieEntity(); //However yours works... return new { id = dalEntity.Id, description = dalEntity.Desc }; } ``` The serializer could care less about the type of the object you send to it, since it just turns it into text anyway. I also believe that you could implement [ISerializable](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx) on your data entity (as a partial class if you have code-gen'd data entities) to gain fine-grained control over the serialization process, but I haven't tried it.
159,705
<p>I am checking whether the new name already exists or not.</p> <p>Code 1</p> <pre><code>if(cmbxExistingGroups.Properties.Items.Cast&lt;string&gt;().ToList().Exists(txt =&gt; txt==txtNewGroup.Text.Trim())) { MessageBox.Show("already exists.", "Add new group"); } </code></pre> <p>Otherwise I could have written:</p> <p>Code 2</p> <pre><code>foreach(var str in cmbxExistingGroups.Properties.Items) { if(str==txtNewGroup.Text) { MessageBox.Show("already exists.", "Add new group"); break; } } </code></pre> <p>I wrote these two and thought I was exploiting language features in code 1.</p> <p>...and yes: both of them work for me ... I am wondering about the performance :-/</p>
[ { "answer_id": 159724, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 4, "selected": false, "text": "<p>I appreciate the cleverness of the first sample (assuming it works), but the second one is a lot easier for the next person who has to maintain the code to figure out.</p>\n" }, { "answer_id": 159730, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 1, "selected": false, "text": "<p>Verbosity in coding is not always bad at all. I prefer the second code snippet a lot over the first one. Just imagine you would have to maintain (or even change the functionality of) the first example... um.</p>\n" }, { "answer_id": 159734, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>I would agree, go with the second one because it will be easier to maintain for anybody else who works on it and when you come back to that in 6-12 months, it will be easier to remember what you were doing.</p>\n" }, { "answer_id": 159735, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": false, "text": "<p>I've quoted it before but I'll do it again:</p>\n\n<blockquote>\n <p>Write your code as if the person maintaining it is a homicidal maniac\n who knows where you live.</p>\n</blockquote>\n" }, { "answer_id": 159738, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": -1, "selected": false, "text": "<p>I imagine that on the WTF's per minute scale, the first would be off the chart. Count the dots, any more than two per line is a potential problem</p>\n" }, { "answer_id": 159776, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>would </p>\n\n<pre><code>cmbxExistingGroups.Properties.Items.Contains(text) \n</code></pre>\n\n<p>not work instead?</p>\n" }, { "answer_id": 159790, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>Sometimes just a little indentation makes a world of difference:</p>\n\n<pre><code>if (cmbxExistingGroups.Properties.Items\n .Cast&lt;string&gt;().ToList()\n .Exists\n (\n txt =&gt; txt==txtNewGroup.Text.Trim()\n )) \n{\n MessageBox.Show(\"already exists.\", \"Add new group\");\n}\n</code></pre>\n\n<p>Since your using a List&lt;String&gt;, you might as well just drop the Exists predicate and use Contains...use Exists when comparing complex objects by unique values.</p>\n" }, { "answer_id": 159794, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>There are a few things wrong here:</p>\n\n<p>1) The two bits of code don't do the same thing - the first looks for the trimmed version of txtNewGroup, the second just looks for txtNewGroup</p>\n\n<p>2) There's no point in calling ToList() - that just make things less efficient</p>\n\n<p>3) Using Exists with a predicate is overkill - Contains is all you need here</p>\n\n<p>So, the first could easily come down to:</p>\n\n<pre><code>if (cmbxExistingGroups.Properties.Items.Cast&lt;string&gt;.Contains(txtNewGroup.Text))\n{\n // Stuff\n}\n</code></pre>\n\n<p>I'd probably create a variable to give \"cmbxExistingGroups.Properties.Items.Cast\" a meaningful, simple name - but then I'd say it's easier to understand than the explicit foreach loop.</p>\n" }, { "answer_id": 159796, "author": "gbarry", "author_id": 19512, "author_profile": "https://Stackoverflow.com/users/19512", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>both of them works for me ..i am wonodering about the performance</p>\n</blockquote>\n\n<p>I see no one read the question :) I think I see what you're doing (I don't use this language). The first tries to generate the list and test it in one shot. The second does an explicit iteration and can \"short circuit\" itself (exit early) if it finds the duplicate early on. The question is whether the \"all at once\" is more efficient due to the language implementation.</p>\n" }, { "answer_id": 159814, "author": "mattlant", "author_id": 14642, "author_profile": "https://Stackoverflow.com/users/14642", "pm_score": 0, "selected": false, "text": "<p>The second of the two would perform better, and it would perform the same as other people's samples that use Contains.</p>\n\n<p>The reason why the first one uses an extra trim. plus a conversion to list. so it iterates once for conversion, then starts again to check using exists, and does a trim each time, but will exit iteration if found. The second starts iterating once, has no trim, and will exit if found.</p>\n\n<p>So in short the answer to your question is the second performs much better.</p>\n" }, { "answer_id": 159815, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 1, "selected": false, "text": "<p>Well, if it were me, it would be a variation on 2. Always prefer readability over one-liners. Additionally, always extract a method to make it clearer.</p>\n\n<p>your calling code becomes</p>\n\n<pre><code>if( cmbxExistingGroups.ContainsKey(txtNewGroup.Text) )\n{\n MessageBox.Show(\"Already Exists\");\n}\n</code></pre>\n\n<p>If you define an extension method for Combo Boxes</p>\n\n<pre><code>public static class ComboBoxExtensions\n{\n public static bool ContainsKey(this ComboBox comboBox, string key)\n {\n foreach (string existing in comboBox.Items)\n {\n if (string.Equals(key, existing))\n {\n return true;\n }\n }\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 159868, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>First, they're not equivalent. The 1st sample does a check against txtNewSGroup.Text.Trim(), the 2nd omits trim. Also, the 1st casts everything to a string, whereas the second uses whatever comes out of the iterator. I assume that's an object, or you wouldn't have needed the cast in the 1st place.</p>\n\n<p>So, to be fair, the closest equivalent to the 2nd sample in the LINQ style would be:</p>\n\n<pre><code>if (mbxExistingGroups.Properties.Items.Cast&lt;string&gt;().Contains(txtNewGroup.Text)) {\n ...\n}\n</code></pre>\n\n<p>which isn't too bad. But, since you seem to be working with old style IEnumerable instead of new fangled IEnumerable&lt;T&gt;, why don't we give you another extension method:</p>\n\n<pre><code>public static Contains&lt;T&gt;(this IEnumerable e, T value) {\n return e.Cast&lt;T&gt;().Contains(value);\n}\n</code></pre>\n\n<p>And now we have:</p>\n\n<pre><code>if (mbxExistingGroups.Properties.Items.Contains(txtNewGroup.Text)) {\n ...\n}\n</code></pre>\n\n<p>which is pretty readable IMO.</p>\n" }, { "answer_id": 160131, "author": "Alex Lyman", "author_id": 5897, "author_profile": "https://Stackoverflow.com/users/5897", "pm_score": 2, "selected": false, "text": "<p>The first code bit is fine, except instead of calling <code>Enumerable.ToList()</code> and <code>List&lt;T&gt;.Exists()</code>, you should just call <code>Enumerable.Any()</code> -- it does a lazy evaluation, so it never allocates the memory for the <code>List&lt;T&gt;</code>, and it will stop enumerating <code>cmbxExistingGroups.Properties.Items</code> and casting them to <code>string</code>. Also, calling the trim from inside that predicate means it happens for every item it looks at. It would be best to move it out to the outer scope:</p>\n\n<pre><code>string match = txtNewGroup.Text.Trim();\nif(cmbxExistingGroups.Properties.Items.Cast&lt;string&gt;().Any(txt =&gt; txt==match)) {\n MessageBox.Show(\"already exists.\", \"Add new group\");\n}\n</code></pre>\n" }, { "answer_id": 160563, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>From a performance point of view:</p>\n\n<pre><code>txtNewGroup.Text.Trim()\n</code></pre>\n\n<p>Do your control interaction/string manipulation outside of the loop - one time, instead of n times.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22858/" ]
I am checking whether the new name already exists or not. Code 1 ``` if(cmbxExistingGroups.Properties.Items.Cast<string>().ToList().Exists(txt => txt==txtNewGroup.Text.Trim())) { MessageBox.Show("already exists.", "Add new group"); } ``` Otherwise I could have written: Code 2 ``` foreach(var str in cmbxExistingGroups.Properties.Items) { if(str==txtNewGroup.Text) { MessageBox.Show("already exists.", "Add new group"); break; } } ``` I wrote these two and thought I was exploiting language features in code 1. ...and yes: both of them work for me ... I am wondering about the performance :-/
I appreciate the cleverness of the first sample (assuming it works), but the second one is a lot easier for the next person who has to maintain the code to figure out.
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:</p> <pre class="lang-cs prettyprint-override"><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre class="lang-py prettyprint-override"><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
[ { "answer_id": 159745, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 11, "selected": true, "text": "<p>See Python <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8: Function and Variable Names</a>:</p>\n<blockquote>\n<p>Function names should be <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"noreferrer\">lowercase, with words separated by underscores</a> as necessary to improve readability.</p>\n<p>Variable names follow the same convention as function names.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/MixedCase\" rel=\"noreferrer\">mixedCase</a> is allowed only in contexts where that's already the prevailing style (e.g. <a href=\"https://docs.python.org/library/threading.html\" rel=\"noreferrer\">threading.py</a>), to retain backwards compatibility.</p>\n</blockquote>\n" }, { "answer_id": 159756, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 3, "selected": false, "text": "<p>The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python. </p>\n" }, { "answer_id": 159778, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 5, "selected": false, "text": "<p>There is <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.</p>\n" }, { "answer_id": 159798, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 5, "selected": false, "text": "<p>Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head. </p>\n\n<p>I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have <code>SomeClass.doSomething()</code> than <code>SomeClass.do_something()</code>. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.</p>\n" }, { "answer_id": 160769, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 4, "selected": false, "text": "<p>Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.</p>\n" }, { "answer_id": 160830, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 8, "selected": false, "text": "<p>David Goodger (in \"Code Like a Pythonista\" <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\" rel=\"noreferrer\">here</a>) describes the PEP 8 recommendations as follows:</p>\n\n<ul>\n<li><p><code>joined_lower</code> for functions, methods,\nattributes, variables</p></li>\n<li><p><code>joined_lower</code> or <code>ALL_CAPS</code> for\nconstants</p></li>\n<li><p><code>StudlyCaps</code> for classes</p></li>\n<li><p><code>camelCase</code> only to conform to\npre-existing conventions</p></li>\n</ul>\n" }, { "answer_id": 160833, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 0, "selected": false, "text": "<p>Typically, one follow the conventions used in the language's standard library.</p>\n" }, { "answer_id": 264226, "author": "claytron", "author_id": 34530, "author_profile": "https://Stackoverflow.com/users/34530", "pm_score": 5, "selected": false, "text": "<p>As mentioned, PEP 8 says to use <code>lower_case_with_underscores</code> for variables, methods and functions.</p>\n\n<p>I prefer using <code>lower_case_with_underscores</code> for variables and <code>mixedCase</code> for methods and functions makes the code more explicit and readable. Thus following the <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">Zen of Python's</a> \"explicit is better than implicit\" and \"Readability counts\"</p>\n" }, { "answer_id": 2708015, "author": "Jonik", "author_id": 56285, "author_profile": "https://Stackoverflow.com/users/56285", "pm_score": 6, "selected": false, "text": "<p>As the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> admits,</p>\n\n<blockquote>\n <p>The naming conventions of Python's\n library are a bit of a mess, so we'll\n never get this completely consistent</p>\n</blockquote>\n\n<p>Note that this refers just to Python's <em>standard library</em>. If they can't get <em>that</em> consistent, then there hardly is much hope of having a generally-adhered-to convention for <em>all</em> Python code, is there?</p>\n\n<p>From that, and the discussion here, I would deduce that it's <strong>not</strong> a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, <em>internal consistency</em> matters most.</p>\n\n<p><sup>Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a \"Pythonista\", not yet anyway.</sup></p>\n" }, { "answer_id": 8423697, "author": "John Slade", "author_id": 104446, "author_profile": "https://Stackoverflow.com/users/104446", "pm_score": 10, "selected": false, "text": "<p>The <a href=\"https://google.github.io/styleguide/pyguide.html#316-naming\" rel=\"noreferrer\">Google Python Style Guide</a> has the following convention:</p>\n\n<blockquote>\n <p><code>module_name</code>, <code>package_name</code>, <code>ClassName</code>, <code>method_name</code>, <code>ExceptionName</code>, <code>function_name</code>, <code>GLOBAL_CONSTANT_NAME</code>, <code>global_var_name</code>, <code>instance_var_name</code>, <code>function_parameter_name</code>, <code>local_var_name</code>.</p>\n</blockquote>\n\n<p>A similar naming scheme should be applied to a <code>CLASS_CONSTANT_NAME</code></p>\n" }, { "answer_id": 37120709, "author": "alebian", "author_id": 3323850, "author_profile": "https://Stackoverflow.com/users/3323850", "pm_score": 4, "selected": false, "text": "<p>There is a paper about this: <a href=\"http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf\" rel=\"noreferrer\">http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf</a></p>\n\n<p>TL;DR It says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.</p>\n" }, { "answer_id": 50958547, "author": "Sufiyan Ghori", "author_id": 1149423, "author_profile": "https://Stackoverflow.com/users/1149423", "pm_score": 5, "selected": false, "text": "<p>further to what @JohnTESlade has answered. <a href=\"https://google.github.io/styleguide/pyguide.html?showone=Naming#Naming\" rel=\"noreferrer\">Google's python style guide</a> has some pretty neat recommendations,</p>\n\n<p><strong>Names to Avoid</strong></p>\n\n<ul>\n<li>single character names except for counters or iterators</li>\n<li>dashes (-) in any package/module name</li>\n<li><code>\\__double_leading_and_trailing_underscore__ names</code> (reserved by Python)</li>\n</ul>\n\n<p><strong>Naming Convention</strong></p>\n\n<ul>\n<li>\"Internal\" means internal to a module or protected or private within a class.</li>\n<li>Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).</li>\n<li>Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.</li>\n<li>Use <code>CapWords</code> for class names, but <code>lower_with_under.py</code> for module names. Although there are many existing modules named <code>CapWords.py</code>, this is now discouraged because it's confusing when the module happens to be named after a class. (\"wait -- did I write <code>import StringIO</code> or <code>from StringIO import StringIO</code>?\")</li>\n</ul>\n\n<p><strong>Guidelines derived from Guido's Recommendations</strong>\n<a href=\"https://i.stack.imgur.com/uBr10.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uBr10.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 57601736, "author": "bradylange", "author_id": 10572044, "author_profile": "https://Stackoverflow.com/users/10572044", "pm_score": 2, "selected": false, "text": "<p>I personally use Java's naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn't be the hardest part of my project!</p>\n" }, { "answer_id": 68958842, "author": "vic123", "author_id": 357241, "author_profile": "https://Stackoverflow.com/users/357241", "pm_score": 1, "selected": false, "text": "<p>Lenin has told... I'm from Java/C# world too. And SQL as well.\nScrutinized myself in attempts to find first sight understandable examples of complex constructions like list in the dictionary of lists where everything is an object.\nAs for me - camelCase or their variants should become standard for any language. Underscores should be preserved for complex sentences.</p>\n" }, { "answer_id": 72603424, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 2, "selected": false, "text": "<p><em><strong>Whether or not being in class or out of class</strong></em>:</p>\n<p>A variable and function are <strong>lowercase</strong> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>name = &quot;John&quot;\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>def display(name):\n print(&quot;John&quot;)\n</code></pre>\n<p>And if they're more than one word, they're separated with <strong>underscore &quot;_&quot;</strong> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>first_name = &quot;John&quot;\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>def display_first_name(first_name):\n print(first_name)\n</code></pre>\n<p>And, if a variable is a constant, it's <strong>uppercase</strong> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>FIRST_NAME = &quot;John&quot;\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase: ```cs // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() ``` In Python, I have seen the above but I have also seen underscores being used: ```py # python example this_is_my_variable = 'a' def this_is_my_function(): ``` Is there a more preferable, definitive coding style for Python?
See Python [PEP 8: Function and Variable Names](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names): > > Function names should be [lowercase, with words separated by underscores](https://en.wikipedia.org/wiki/Snake_case) as necessary to improve readability. > > > Variable names follow the same convention as function names. > > > [mixedCase](https://en.wikipedia.org/wiki/MixedCase) is allowed only in contexts where that's already the prevailing style (e.g. [threading.py](https://docs.python.org/library/threading.html)), to retain backwards compatibility. > > >
159,769
<p>I have a complex query with group by and order by clause and I need a sorted row number (1...2...(n-1)...n) returned with every row. Using a ROWNUM (value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation) gives me a non-sorted list (4...567...123...45...). I cannot use application for counting and assigning numbers to each row.</p>
[ { "answer_id": 159779, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 5, "selected": true, "text": "<p>Is there a reason that you can't just do</p>\n\n<pre><code>SELECT rownum, a.* \n FROM (&lt;&lt;your complex query including GROUP BY and ORDER BY&gt;&gt;) a\n</code></pre>\n" }, { "answer_id": 159781, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 2, "selected": false, "text": "<p>You could do it as a subquery, so have:</p>\n\n<pre><code>select q.*, rownum from (select... group by etc..) q\n</code></pre>\n\n<p>That would probably work... don't know if there is anything better than that.</p>\n" }, { "answer_id": 159782, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 0, "selected": false, "text": "<p>Can you use an in-line query? ie</p>\n\n<pre><code>SELECT cols, ROWNUM\nFROM (your query)\n</code></pre>\n" }, { "answer_id": 159787, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 0, "selected": false, "text": "<p>Assuming that you're query is already ordered in the manner you desire and you just want a number to indicate what row in the order it is:</p>\n\n<pre><code>SELECT ROWNUM AS RowOrderNumber, Col1, Col2,Col3...\nFROM (\n [Your Original Query Here]\n)\n</code></pre>\n\n<p>and replace \"Colx\" with the names of the columns in your query.</p>\n" }, { "answer_id": 175885, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 0, "selected": false, "text": "<p>I also sometimes do something like:</p>\n\n<pre><code>SELECT * FROM\n(SELECT X,Y FROM MY_TABLE WHERE Z=16 ORDER BY MY_DATE DESC)\nWHERE ROWNUM=1\n</code></pre>\n" }, { "answer_id": 3344626, "author": "zbonig", "author_id": 203591, "author_profile": "https://Stackoverflow.com/users/203591", "pm_score": 0, "selected": false, "text": "<p>If you want to use ROWNUM to do anything more than limit the total number of rows returned in a query (e.g. AND ROWNUM &lt; 10) you'll need to alias ROWNUM:</p>\n\n<pre><code> select * \n (select rownum rn, a.* from \n (&lt;sorted query&gt;) a))\n where rn between 500 and 1000 \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4235/" ]
I have a complex query with group by and order by clause and I need a sorted row number (1...2...(n-1)...n) returned with every row. Using a ROWNUM (value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation) gives me a non-sorted list (4...567...123...45...). I cannot use application for counting and assigning numbers to each row.
Is there a reason that you can't just do ``` SELECT rownum, a.* FROM (<<your complex query including GROUP BY and ORDER BY>>) a ```
159,821
<p>In an app I'm working on, I have a plain style UITableView that can contain a section containing zero rows. I want to be able to scroll to this section using scrollToRowAtIndexPath:atScrollPosition:animated: but I get an error when I try to scroll to this section due to the lack of child rows.</p> <p>Apple's calendar application is able to do this, if you look at your calendar in list view, and there are no events in your calendar for today, an empty section is inserted for today and you can scroll to it using the Today button in the toolbar at the bottom of the screen. As far as I can tell Apple may be using a customized UITableView, or they're using a private API...</p> <p>The only workaround I can think of is to insert an empty UITableCell in that's 0 pixels high and scroll to that. But it's my understanding that having cells of varying heights is really bad for scrolling performance. Still I'll try it anyway, maybe the performance hit won't be too bad.</p> <p><strong>Update</strong></p> <p>Since there seems to be no solution to this, I've filed a bug report with apple. If this affects you too, file a duplicate of rdar://problem/6263339 (<a href="http://openradar.appspot.com/radar?id=283" rel="noreferrer">Open Radar link)</a> if you want this to get this fixed faster.</p> <p><strong>Update #2</strong></p> <p>I have a decent workaround to this issue, take a look at my answer below.</p>
[ { "answer_id": 159854, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": -1, "selected": false, "text": "<p>I think a blank row is probably the only way to go there. Is it possible to redesign the UI such that the \"empty\" row can display something useful?</p>\n\n<p>I say try it out, and see what the performance is like. They give pretty dire warnings about using transparent sub-views in your list items, and I didn't find that it mattered all that much in my application.</p>\n" }, { "answer_id": 351109, "author": "Mike Akers", "author_id": 17188, "author_profile": "https://Stackoverflow.com/users/17188", "pm_score": 8, "selected": true, "text": "<p>UPDATE: Looks like this bug is fixed in iOS 3.0. You can use the following <code>NSIndexPath</code> to scroll to a section containing 0 rows:</p>\n\n<pre><code>[NSIndexPath indexPathForRow:NSNotFound inSection:section]\n</code></pre>\n\n<p>I'll leave my original workaround here for anyone still maintaining a project using the 2.x SDK.</p>\n\n<hr>\n\n<p>Found a decent workaround:</p>\n\n<pre><code>CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];\n[tableView scrollRectToVisible:sectionRect animated:YES];\n</code></pre>\n\n<p>The code above will scroll the tableview so the desired section is visible but not necessarily at the top or bottom of the visible area. If you want to scroll so the section is at the top do this:</p>\n\n<pre><code>CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo];\nsectionRect.size.height = tableView.frame.size.height;\n[tableView scrollRectToVisible:sectionRect animated:YES];\n</code></pre>\n\n<p>Modify sectionRect as desired to scroll the desired section to the bottom or middle of the visible area.</p>\n" }, { "answer_id": 10782747, "author": "Simon Tillson", "author_id": 1416291, "author_profile": "https://Stackoverflow.com/users/1416291", "pm_score": 2, "selected": false, "text": "<p>This is an old question, but Apple still haven't added anything which helps or fixed the crash bug where the section has no rows.</p>\n\n<p>For me, I really needed to make a new section scroll to the middle when added, so I now use this code:</p>\n\n<pre><code>if (rowCount &gt; 0) {\n [self.tableView scrollToRowAtIndexPath: [NSIndexPath indexPathForRow: 0 inSection: sectionIndexForNewFolder] \n atScrollPosition: UITableViewScrollPositionMiddle\n animated: TRUE];\n} else { \n CGRect sectionRect = [self.tableView rectForSection: sectionIndexForNewFolder];\n // Try to get a full-height rect which is centred on the sectionRect\n // This produces a very similar effect to UITableViewScrollPositionMiddle.\n CGFloat extraHeightToAdd = sectionRect.size.height - self.tableView.frame.size.height;\n sectionRect.origin.y -= extraHeightToAdd * 0.5f;\n sectionRect.size.height += extraHeightToAdd;\n [self.tableView scrollRectToVisible:sectionRect animated:YES];\n}\n</code></pre>\n\n<p>Hope you like it - it's based on Mike Akers' code as you can see, but does the calculation for scrolling to the middle instead of top. Thanks Mike - you're a star.</p>\n" }, { "answer_id": 48180723, "author": "Chaitanya Ramji", "author_id": 4833548, "author_profile": "https://Stackoverflow.com/users/4833548", "pm_score": 2, "selected": false, "text": "<p>A Swift approach to the same:</p>\n\n<pre><code>if rows &gt; 0 {\n let indexPath = IndexPath(row: 0, section: section)\n self.tableView.setContentOffset(CGPoint.zero, animated: true)\n self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)\n}\n\nelse {\n let sectionRect : CGRect = tableView.rect(forSection: section)\n tableView.scrollRectToVisible(sectionRect, animated: true)\n}\n</code></pre>\n" }, { "answer_id": 55843309, "author": "Vladimir Pchelyakov", "author_id": 9917037, "author_profile": "https://Stackoverflow.com/users/9917037", "pm_score": 3, "selected": false, "text": "<p>If your section have not rows use this</p>\n\n<pre><code>let indexPath = IndexPath(row: NSNotFound, section: section)\ntableView.scrollToRow(at: indexPath, at: .middle, animated: true)\n</code></pre>\n" }, { "answer_id": 60375047, "author": "Idan Moshe", "author_id": 1673632, "author_profile": "https://Stackoverflow.com/users/1673632", "pm_score": 2, "selected": false, "text": "<p>Since using:</p>\n\n<pre><code>[NSIndexPath indexPathForRow:NSNotFound inSection:EXAMPLE]\n</code></pre>\n\n<p>Broken for me in Xcode 11.3.1 (iOS simulator - 13.3) I decided to use:</p>\n\n<pre><code>NSUInteger index = [self.sectionTypes indexOfObject:@(EXAMPLE)];\nif (index != NSNotFound) {\n CGRect rect = [self.tableView rectForSection:index];\n [self.tableView scrollRectToVisible:rect animated:YES];\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188/" ]
In an app I'm working on, I have a plain style UITableView that can contain a section containing zero rows. I want to be able to scroll to this section using scrollToRowAtIndexPath:atScrollPosition:animated: but I get an error when I try to scroll to this section due to the lack of child rows. Apple's calendar application is able to do this, if you look at your calendar in list view, and there are no events in your calendar for today, an empty section is inserted for today and you can scroll to it using the Today button in the toolbar at the bottom of the screen. As far as I can tell Apple may be using a customized UITableView, or they're using a private API... The only workaround I can think of is to insert an empty UITableCell in that's 0 pixels high and scroll to that. But it's my understanding that having cells of varying heights is really bad for scrolling performance. Still I'll try it anyway, maybe the performance hit won't be too bad. **Update** Since there seems to be no solution to this, I've filed a bug report with apple. If this affects you too, file a duplicate of rdar://problem/6263339 ([Open Radar link)](http://openradar.appspot.com/radar?id=283) if you want this to get this fixed faster. **Update #2** I have a decent workaround to this issue, take a look at my answer below.
UPDATE: Looks like this bug is fixed in iOS 3.0. You can use the following `NSIndexPath` to scroll to a section containing 0 rows: ``` [NSIndexPath indexPathForRow:NSNotFound inSection:section] ``` I'll leave my original workaround here for anyone still maintaining a project using the 2.x SDK. --- Found a decent workaround: ``` CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo]; [tableView scrollRectToVisible:sectionRect animated:YES]; ``` The code above will scroll the tableview so the desired section is visible but not necessarily at the top or bottom of the visible area. If you want to scroll so the section is at the top do this: ``` CGRect sectionRect = [tableView rectForSection:indexOfSectionToScrollTo]; sectionRect.size.height = tableView.frame.size.height; [tableView scrollRectToVisible:sectionRect animated:YES]; ``` Modify sectionRect as desired to scroll the desired section to the bottom or middle of the visible area.
159,842
<p>Often times when mixing jQuery with asp.net I need to use asp .net angle bracket percent, &lt;% %>, syntax within a jQuery selector.</p> <p>If I would like to separate the JavaScript from markup into different files is there still a way to evaluate my JavaScript file so the angle bracket percents are interpolated before reaching the client browser?</p>
[ { "answer_id": 159865, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>No, you'll need to refactor your JavaScript to accept that information as parameters.</p>\n\n<p>So, instead of </p>\n\n<pre><code>jQuery('#&lt;%=MainPanel.ClientId%&gt;').hide('slow');\n</code></pre>\n\n<p>do something like this:</p>\n\n<pre><code>function hidePanel(panelId) {\n jQuery('#' + panelId).hide('slow');\n}\n</code></pre>\n\n<p>which you can call from your page with</p>\n\n<pre><code>hidePanel('&lt;%=MainPanel.ClientId%&gt;');\n</code></pre>\n" }, { "answer_id": 159871, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>If you want to evaluate <code>&lt;% code blocks %&gt;</code> as ASP.NET code in a JavaScript file, you can just put the JavaScript in an ASPX file and reference it from a SCRIPT element.</p>\n\n<p><code>script.js.aspx</code>:</p>\n\n<pre><code>function hideElements()\n { &lt;% foreach(var elementId in Request.QueryString[\"hide\"].Split(',') { %&gt;\n jQuery('#' + &lt;%= elementId %&gt;).hide('slow');\n &lt;% } %&gt;\n }\n</code></pre>\n\n<p><code>page.aspx</code>:</p>\n\n<pre><code>&lt;script src=\"script.js.aspx?hide=&lt;%= GetElementsIds() %&gt;\"\n type='text/javascript'&gt;&lt;/script&gt;\n</code></pre>\n\n<p><code>page.aspx.cs</code>:</p>\n\n<pre><code>public string GetElementIds() \n {\n return string.Join(\",\", new []{control1.ClientID, control2.ClientID});\n }\n</code></pre>\n" }, { "answer_id": 160086, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "<p>You could also handle .js files as .aspx files; this way you won't lose intellisense and code formatting while you're editing them. Just add this to web.config:</p>\n\n<pre><code>&lt;system.webServer&gt;\n &lt;handlers&gt;\n &lt;add name=\"Dynamic JS\" path=\"*.js\" verb=\"*\" type=\"System.Web.UI.PageHandlerFactory\" resourceType=\"Unspecified\"/&gt;\n</code></pre>\n" }, { "answer_id": 167298, "author": "John Grant", "author_id": 4521, "author_profile": "https://Stackoverflow.com/users/4521", "pm_score": 2, "selected": false, "text": "<p>I made an attempt to separate javascript on the search grid user control from the html in the .ascx file. In the first iteration I used the jQuery(document).onReady function to attach my intialization.</p>\n\n<p>The problem with this is that &lt;%= %> tags used within jQuery selectors were not interpolated correctly and the controls the javascript acted on were not found with the jQuery selectors.</p>\n\n<p>Next, I attempted to create a json object in the Page initialization and write that out using the asp.net method Page.ClientScript.RegisterClientScriptBlock. This worked ok, but with drawbacks: hard wired the json object's name and keys in the asp.net file and javascript file. This is disadvantageous because now there exists \"two points of truth\" to maintain and further more there is the potential for name collision in the final rendered page.</p>\n\n<p>The most elegant solution within the asp .net and utilizing jQuery is to create an ajax script behavior in javascript. Then within the asp codebehind register the script behavior's properties in the GetScriptDescriptors() method of the IScriptControl interface, adding the server side control's ClientID as a property to the script descriptor.</p>\n\n<pre><code>// Ajax Javacsript Code below:\n\nType.registerNamespace('SearchGrid');\n\n// Define the behavior properties\n//\nButtonBehavior = function() {\n ButtonBehavior.initializeBase(this);\n this._lnkSearchID = null;\n}\n\n// Create the prototype for the behavior\n//\n//\nSearchGrid.ButtonBehavior.prototype = {\ninitialize: function() {\n SearchGrid.ButtonBehavior.callBaseMethod(this, 'initialize');\n jQuery('#' + this._lnkSearchID).click(function() { alert('We clicked!'); });\n},\n\ndispose: function() {\n SearchGrid.ButtonBehavior.callBaseMethod(this, 'dispose');\n jQuery('#' + this._lnkSearchID).unbind();\n }\n}\n\n// Register the class as a type that inherits from Sys.Component.\nSearchGrid.ButtonBehavior.registerClass('SearchGrid.ButtonBehavior', Sys.Component);\n\n\nif (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();\n</code></pre>\n\n<hr>\n\n<p>Asp .Net code below:</p>\n\n<pre><code> public partial class SearchGrid : System.Web.UI.UserControl, IScriptControl\n { \n // Initialization \n protected override void OnPreRender(EventArgs e)\n {\n if (!this.DesignMode)\n {\n // Test for ScriptManager and register if it exists\n ScriptManager sm = ScriptManager.GetCurrent(Page); \n if (sm == null)\n throw new ApplicationException(\"A ScriptManager control must exist on the current page.\"); \n sm.RegisterScriptControl(this);\n } \n base.OnPreRender(e);\n }\n protected override void Render(HtmlTextWriter writer)\n {\n if (!this.DesignMode)\n sm.RegisterScriptDescriptors(this);\n\n base.Render(writer);\n }\n\n // IScriptControl Members\n public IEnumerable&lt;ScriptDescriptor&gt; GetScriptDescriptors()\n {\n ScriptBehaviorDescriptor desc = new ScriptBehaviorDescriptor(\"SearchGrid.ButtonBehavior\", this.ClientID); \n desc.AddProperty(\"lnkSearchID\", this.lnkSearch.ClientID);\n yield return desc;\n }\n\n public IEnumerable&lt;ScriptReference&gt; GetScriptReferences()\n {\n ScriptReference reference = new ScriptReference();\n reference.Path = ResolveClientUrl(\"SearchGrid.ButtonBehavior.js\");\n return new ScriptReference[] { reference };\n } \n }\n</code></pre>\n\n<hr>\n\n<p>The advantage here is that you may create stand alone reusable controls with javascript behavior contained in its own separate file (or as a web resource) while passing state and context, which might otherwise would be interpolated with angle,percent, equals syntax, necessary for jQuery to do its work. </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4521/" ]
Often times when mixing jQuery with asp.net I need to use asp .net angle bracket percent, <% %>, syntax within a jQuery selector. If I would like to separate the JavaScript from markup into different files is there still a way to evaluate my JavaScript file so the angle bracket percents are interpolated before reaching the client browser?
If you want to evaluate `<% code blocks %>` as ASP.NET code in a JavaScript file, you can just put the JavaScript in an ASPX file and reference it from a SCRIPT element. `script.js.aspx`: ``` function hideElements() { <% foreach(var elementId in Request.QueryString["hide"].Split(',') { %> jQuery('#' + <%= elementId %>).hide('slow'); <% } %> } ``` `page.aspx`: ``` <script src="script.js.aspx?hide=<%= GetElementsIds() %>" type='text/javascript'></script> ``` `page.aspx.cs`: ``` public string GetElementIds() { return string.Join(",", new []{control1.ClientID, control2.ClientID}); } ```
159,853
<p>I have some local changes to an open source project which uses Subversion as its source control. (I do not have commit access on the original project repository.)</p> <p>My change adds a file, but this file is not included in the output of "svn diff". (It may be worth noting that the new file is a binary, not plain text.)</p> <p>How can I make a <a href="http://en.wikipedia.org/wiki/Patch_(Unix)" rel="nofollow noreferrer">patch</a> which includes the new files?</p> <hr> <pre><code> $ svn st A tests/foo.zip $ svn diff $ </code></pre>
[ { "answer_id": 159866, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 0, "selected": false, "text": "<p>If you're building a patch, you might want to use plain old 'diff' with the --new-file option which treats the missing file as empty.</p>\n\n<p>Note that the syntax for this option may actually vary depending on what version of plain old diff you're using. </p>\n" }, { "answer_id": 160028, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 4, "selected": true, "text": "<p>The fact that your file is binary is exactly why it is not displayed I'm afraid. Subversion's diff command only does textual diffs/patches (even though Subversion internally can handle binary file differences efficiently between versions).</p>\n" }, { "answer_id": 1051396, "author": "Balázs Pozsár", "author_id": 119797, "author_profile": "https://Stackoverflow.com/users/119797", "pm_score": 4, "selected": false, "text": "<p>There is a --force option to the diff command, but it produces an incorrect patch file for binaries on my machine. Using it with the --diff-cmd option works for me though:</p>\n\n<pre><code>svn diff --force --diff-cmd /usr/bin/diff -x -au\n</code></pre>\n\n<p>I think this produces exactly what you wanted.</p>\n" }, { "answer_id": 2255846, "author": "Jason Favors", "author_id": 272196, "author_profile": "https://Stackoverflow.com/users/272196", "pm_score": 5, "selected": false, "text": "<p>I experienced similar behavior to Pozsar. And his answer worked for me better than the normal svn diff --force. However, if running on a DOS machine (e.g. via Cygwin), you may need to modify his answer slightly. The following diff + patch worked for patching my text + binary files in Cygwin using the --binary arg:</p>\n\n<pre><code>svn diff --force --diff-cmd /usr/bin/diff -x \"-au --binary\" OLD-URL NEW-URL &gt; mybinarydiff.diff\n\npatch -p0 --binary -i mybinarydiff.diff\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17732/" ]
I have some local changes to an open source project which uses Subversion as its source control. (I do not have commit access on the original project repository.) My change adds a file, but this file is not included in the output of "svn diff". (It may be worth noting that the new file is a binary, not plain text.) How can I make a [patch](http://en.wikipedia.org/wiki/Patch_(Unix)) which includes the new files? --- ``` $ svn st A tests/foo.zip $ svn diff $ ```
The fact that your file is binary is exactly why it is not displayed I'm afraid. Subversion's diff command only does textual diffs/patches (even though Subversion internally can handle binary file differences efficiently between versions).
159,856
<p>I am running NUnit with the project named AssemblyTest.nunit. The test calls another assembly which uses the log4net assembly. This is using nunit version 2.4.3 with the .net 2.0 framework.</p> <p>In TestFixtureSetup I am calling log4net.Config.XmlConfigurator.Configure( ) and am getting the following error:</p> <pre> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section log4net. (C:\path\to\assembly.dll.config line 7) </pre> <p>Is there a way to fix this without renaming the config file to 'AssemblyTest.config'?</p>
[ { "answer_id": 162689, "author": "gyrolf", "author_id": 23772, "author_profile": "https://Stackoverflow.com/users/23772", "pm_score": 3, "selected": true, "text": "<p>Create a separate config file for log4net with root element log4net.</p>\n\n<p>In TestFixtureSetup create a FileInfo object for this config file and give it as argument to log4net.Config.XmlConfigurator.Configure( ).</p>\n" }, { "answer_id": 9032281, "author": "Christoph Brückmann", "author_id": 909980, "author_profile": "https://Stackoverflow.com/users/909980", "pm_score": 4, "selected": false, "text": "<p>I had the same problem because I forget to add the <em>log4net</em> definition in the <em>configSections</em> element.</p>\n\n<p>So, if you want to put <em>log4net</em>-elements into the app.config, you need to include the <em>configSections</em> element (which tells where <em>log4net</em>-elements are defined) at the top of the config file.</p>\n\n<p>Try it like this:</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" /&gt;\n &lt;/configSections&gt;\n &lt;log4net&gt;\n ...\n &lt;/log4net&gt;\n&lt;/configuration&gt;\n</code></pre>\n" }, { "answer_id": 19672646, "author": "Mubashar", "author_id": 806076, "author_profile": "https://Stackoverflow.com/users/806076", "pm_score": 3, "selected": false, "text": "<p>I don't know why you guys are trapped in config files, for nunit if you like to see logs running in Text Output window in nunit test runner all you need to do is following line of code, </p>\n\n<pre><code>BasicConfigurator.Configure();\n</code></pre>\n\n<p>best point add this line is the constructor of Test class </p>\n\n<p>e.g. </p>\n\n<pre><code>[TestFixture]\n public class MyTest\n {\n log4net.ILog log = log4net.LogManager.GetLogger(typeof(MyTest));\n\n public MyTest()\n {\n BasicConfigurator.Configure();\n }\n\n [SetUp]\n public void SetUp()\n {\n log.Debug(\"&gt;SetUp\"); \n }\n\n [TearDown]\n public void TearDown()\n {\n log.Debug(\"&gt;TearDown\");\n }\n\n [Test]\n public void TestNothing()\n {\n log.Debug(\"&gt;TestNothing\");\n }\n }\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24174/" ]
I am running NUnit with the project named AssemblyTest.nunit. The test calls another assembly which uses the log4net assembly. This is using nunit version 2.4.3 with the .net 2.0 framework. In TestFixtureSetup I am calling log4net.Config.XmlConfigurator.Configure( ) and am getting the following error: ``` System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section log4net. (C:\path\to\assembly.dll.config line 7) ``` Is there a way to fix this without renaming the config file to 'AssemblyTest.config'?
Create a separate config file for log4net with root element log4net. In TestFixtureSetup create a FileInfo object for this config file and give it as argument to log4net.Config.XmlConfigurator.Configure( ).
159,864
<p>I'm working on a control to tie together the view from one ListView to another so that when the master ListView is scrolled, the child ListView view is updated to match. </p> <p>So far I've been able to get the child ListViews to update their view when the master scrollbar buttons are clicked. The problem is that when clicking and dragging the ScrollBar itself, the child ListViews are not updated. I've looked at the messages being sent using Spy++ and the correct messages are getting sent. </p> <p>Here is my current code:</p> <pre><code>public partial class LinkedListViewControl : ListView { [DllImport("User32.dll")] private static extern bool SendMessage(IntPtr hwnd, UInt32 msg, IntPtr wParam, IntPtr lParam); [DllImport("User32.dll")] private static extern bool ShowScrollBar(IntPtr hwnd, int wBar, bool bShow); [DllImport("user32.dll")] private static extern int SetScrollPos(IntPtr hWnd, int wBar, int nPos, bool bRedraw); private const int WM_HSCROLL = 0x114; private const int SB_HORZ = 0; private const int SB_VERT = 1; private const int SB_CTL = 2; private const int SB_BOTH = 3; private const int SB_THUMBPOSITION = 4; private const int SB_THUMBTRACK = 5; private const int SB_ENDSCROLL = 8; public LinkedListViewControl() { InitializeComponent(); } private readonly List&lt;ListView&gt; _linkedListViews = new List&lt;ListView&gt;(); public void AddLinkedView(ListView listView) { if (!_linkedListViews.Contains(listView)) { _linkedListViews.Add(listView); HideScrollBar(listView); } } public bool RemoveLinkedView(ListView listView) { return _linkedListViews.Remove(listView); } private void HideScrollBar(ListView listView) { //Make sure the list view is scrollable listView.Scrollable = true; //Then hide the scroll bar ShowScrollBar(listView.Handle, SB_BOTH, false); } protected override void WndProc(ref Message msg) { if (_linkedListViews.Count &gt; 0) { //Look for WM_HSCROLL messages if (msg.Msg == WM_HSCROLL) { foreach (ListView view in _linkedListViews) { SendMessage(view.Handle, WM_HSCROLL, msg.WParam, IntPtr.Zero); } } } } } </code></pre> <p>Based on <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3111420&amp;SiteID=1" rel="nofollow noreferrer">this post</a> on the MS Tech Forums I tried to capture and process the SB_THUMBTRACK event:</p> <pre><code> protected override void WndProc(ref Message msg) { if (_linkedListViews.Count &gt; 0) { //Look for WM_HSCROLL messages if (msg.Msg == WM_HSCROLL) { Int16 hi = (Int16)((int)msg.WParam &gt;&gt; 16); Int16 lo = (Int16)msg.WParam; foreach (ListView view in _linkedListViews) { if (lo == SB_THUMBTRACK) { SetScrollPos(view.Handle, SB_HORZ, hi, true); int wParam = 4 + 0x10000 * hi; SendMessage(view.Handle, WM_HSCROLL, (IntPtr)(wParam), IntPtr.Zero); } else { SendMessage(view.Handle, WM_HSCROLL, msg.WParam, IntPtr.Zero); } } } } // Pass message to default handler. base.WndProc(ref msg); } </code></pre> <p>This will update the location of the child ListView ScrollBar but does not change the actual view in the child.</p> <p>So my questions are: </p> <ol> <li>Is it possible to update the child ListViews when the master ListView ScrollBar is dragged?</li> <li>If so, how?</li> </ol>
[ { "answer_id": 166063, "author": "Yuval Peled", "author_id": 20257, "author_profile": "https://Stackoverflow.com/users/20257", "pm_score": 0, "selected": false, "text": "<p>A naive solution to your problem can be handling the paint message in the parent list view and checking if the linked list views are displaying the correct data. If they don't, then update them to display the correct data by calling the EnsureVisible method.</p>\n" }, { "answer_id": 167089, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 1, "selected": false, "text": "<p>This is conjecture just to get the mental juices flowing so take it as you will: \nIn the scroll handler for the master list, can you call the scroll handler for the child list (passing the sender and eventargs from the master)? </p>\n\n<p>Add this to your Form load:</p>\n\n<pre><code>masterList.Scroll += new ScrollEventHandler(this.masterList_scroll);\n</code></pre>\n\n<p>Which references this: </p>\n\n<pre><code>private void masterList_scroll(Object sender, System.ScrollEventArgs e)\n{\n childList_scroll(sender, e);\n}\n\nprivate void childList_scroll(Object sender, System.ScrollEventArgs e)\n{\n childList.value = e.NewValue\n}\n</code></pre>\n" }, { "answer_id": 175553, "author": "Jeremy", "author_id": 9266, "author_profile": "https://Stackoverflow.com/users/9266", "pm_score": 1, "selected": false, "text": "<p>I would create my own class, inheriting from ListView to expose the Vertical and Horizontal scroll events.</p>\n\n<p>Then I would do create scroll handlers in my form to synchronize the two controls</p>\n\n<p>This is sample code which should allow a listview to publish scroll events:</p>\n\n<pre><code>public class MyListView : System.Windows.Forms.ListView\n{\n const int WM_HSCROLL = 0x0114;\n const int WM_VSCROLL = 0x0115;\n\n private ScrollEventHandler evtHScroll_m;\n private ScrollEventHandler evtVScroll_m;\n\n public event ScrollEventHandler OnHScroll\n {\n add\n {\n evtHScroll_m += value;\n }\n remove\n {\n evtHScroll_m -= value;\n }\n }\n\n public event ScrollEventHandler OnHVcroll\n {\n add\n {\n evtVScroll_m += value;\n }\n remove\n {\n evtVScroll_m -= value;\n }\n }\n\n protected override void WndProc(ref System.Windows.Forms.Message msg) \n { \n if (msg.Msg == WM_HSCROLL &amp;&amp; evtHScroll_m != null) \n {\n evtHScroll_m(this,new ScrollEventArgs(ScrollEventType.ThumbTrack, msg.WParam.ToInt32()));\n }\n\n if (msg.Msg == WM_VSCROLL &amp;&amp; evtVScroll_m != null) \n {\n evtVScroll_m(this, new ScrollEventArgs(ScrollEventType.ThumbTrack, msg.WParam.ToInt32()));\n }\n base.WndProc(ref msg); \n }\n</code></pre>\n\n<p>Now handle the scroll events in your form:</p>\n\n<p>Set up a PInvoke method to be able to send a windows message to a control:</p>\n\n<pre><code>[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern int SendMessage(IntPtr hWnd, [MarshalAs(UnmanagedType.U4)] int iMsg, int iWParam, int iLParam);\n</code></pre>\n\n<p>Set up your event handlers (lstMaster and lstChild are two listboxes):</p>\n\n<pre><code>lstMaster.OnVScroll += new ScrollEventHandler(this.lstMaster_OnVScroll);\nlstMaster.OnHScroll += new ScrollEventHandler(this.lstMaster_OnHScroll);\n\nconst int WM_HSCROLL = 0x0114; \nconst int WM_VSCROLL = 0x0115; \n\nprivate void lstMaster_OnVScroll(Object sender, System.ScrollEventArgs e)\n{ \n SendMessage(lstChild.Handle,WM_VSCROLL,(IntPtr)e.NewValue, IntPtr.Zero); \n}\n\nprivate void lstMaster_OnHScroll(Object sender, System.ScrollEventArgs e)\n{ \n SendMessage(lstChild.Handle,WM_HSCROLL,(IntPtr)e.NewValue, IntPtr.Zero); \n}\n</code></pre>\n" }, { "answer_id": 275954, "author": "AZDean", "author_id": 12058, "author_profile": "https://Stackoverflow.com/users/12058", "pm_score": 3, "selected": true, "text": "<p>I wanted to do the same thing, and after searching around I found your code here, which helped, but of course didn't solve the problem. But after playing around with it, I have found a solution.</p>\n\n<p>The key came when I realized that since the scroll buttons work, that you can use that to make the slider work. In other words, when the SB_THUMBTRACK event comes in, I issue repeated SB_LINELEFT and SB_LINERIGHT events until my child ListView gets close to where the master is. Yes, this isn't perfect, but it works close enough.</p>\n\n<p>In my case, my master ListView is called \"reportView\", while my child ListView is called \"summaryView\". Here's my pertinent code:</p>\n\n<pre><code>public class MyListView : ListView\n{\n public event ScrollEventHandler HScrollEvent;\n\n protected override void WndProc(ref System.Windows.Forms.Message msg) \n {\n if (msg.Msg==WM_HSCROLL &amp;&amp; HScrollEvent != null)\n HScrollEvent(this,new ScrollEventArgs(ScrollEventType.ThumbTrack, (int)msg.WParam));\n\n base.WndProc(ref msg);\n }\n}\n</code></pre>\n\n<p>And then the event handler itself:</p>\n\n<pre><code>reportView.HScrollEvent += new ScrollEventHandler((sender,e) =&gt; {\n if ((ushort) e.NewValue != SB_THUMBTRACK)\n SendMessage(summaryView.Handle, WM_HSCROLL, (IntPtr) e.NewValue, IntPtr.Zero);\n else {\n int newPos = e.NewValue &gt;&gt; 16;\n int oldPos = GetScrollPos(reportView .Handle, SB_HORZ); \n int pos = GetScrollPos(summaryView.Handle, SB_HORZ);\n int lst;\n\n if (pos != newPos)\n if (pos&lt;newPos &amp;&amp; oldPos&lt;newPos) do { lst=pos; SendMessage(summaryView.Handle,WM_HSCROLL,(IntPtr)SB_LINERIGHT,IntPtr.Zero); } while ((pos=GetScrollPos(summaryView.Handle,SB_HORZ)) &lt; newPos &amp;&amp; pos!=lst);\n else if (pos&gt;newPos &amp;&amp; oldPos&gt;newPos) do { lst=pos; SendMessage(summaryView.Handle,WM_HSCROLL,(IntPtr)SB_LINELEFT, IntPtr.Zero); } while ((pos=GetScrollPos(summaryView.Handle,SB_HORZ)) &gt; newPos &amp;&amp; pos!=lst);\n }\n });\n</code></pre>\n\n<p>Sorry about the odd formatting of the while loops there, but that's how I prefer to code things like that.</p>\n\n<p>The next problem was getting rid of the scroll bars in the child ListView. I noticed you had a method called HideScrollBar. This didn't really work for me. I found a better solution in my case was leaving the scroll bar there, but \"covering\" it up instead. I do this with the column header as well. I just slide my child control up under the master control to cover the column header. And then I stretch the child to fall out of the panel that contains it. And then to provide a bit of a border along the edge of my containing panel, I throw in a control to cover the visible bottom edge of my child ListView. It ends up looking rather nice.</p>\n\n<p>I also added an event handler to sync changing column widths, as in:</p>\n\n<pre><code>reportView.ColumnWidthChanging += new ColumnWidthChangingEventHandler((sender,e) =&gt; {\n summaryView.Columns[e.ColumnIndex].Width = e.NewWidth;\n }); \n</code></pre>\n\n<p>While this all seems a bit of a kludge, it works for me.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1314/" ]
I'm working on a control to tie together the view from one ListView to another so that when the master ListView is scrolled, the child ListView view is updated to match. So far I've been able to get the child ListViews to update their view when the master scrollbar buttons are clicked. The problem is that when clicking and dragging the ScrollBar itself, the child ListViews are not updated. I've looked at the messages being sent using Spy++ and the correct messages are getting sent. Here is my current code: ``` public partial class LinkedListViewControl : ListView { [DllImport("User32.dll")] private static extern bool SendMessage(IntPtr hwnd, UInt32 msg, IntPtr wParam, IntPtr lParam); [DllImport("User32.dll")] private static extern bool ShowScrollBar(IntPtr hwnd, int wBar, bool bShow); [DllImport("user32.dll")] private static extern int SetScrollPos(IntPtr hWnd, int wBar, int nPos, bool bRedraw); private const int WM_HSCROLL = 0x114; private const int SB_HORZ = 0; private const int SB_VERT = 1; private const int SB_CTL = 2; private const int SB_BOTH = 3; private const int SB_THUMBPOSITION = 4; private const int SB_THUMBTRACK = 5; private const int SB_ENDSCROLL = 8; public LinkedListViewControl() { InitializeComponent(); } private readonly List<ListView> _linkedListViews = new List<ListView>(); public void AddLinkedView(ListView listView) { if (!_linkedListViews.Contains(listView)) { _linkedListViews.Add(listView); HideScrollBar(listView); } } public bool RemoveLinkedView(ListView listView) { return _linkedListViews.Remove(listView); } private void HideScrollBar(ListView listView) { //Make sure the list view is scrollable listView.Scrollable = true; //Then hide the scroll bar ShowScrollBar(listView.Handle, SB_BOTH, false); } protected override void WndProc(ref Message msg) { if (_linkedListViews.Count > 0) { //Look for WM_HSCROLL messages if (msg.Msg == WM_HSCROLL) { foreach (ListView view in _linkedListViews) { SendMessage(view.Handle, WM_HSCROLL, msg.WParam, IntPtr.Zero); } } } } } ``` Based on [this post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3111420&SiteID=1) on the MS Tech Forums I tried to capture and process the SB\_THUMBTRACK event: ``` protected override void WndProc(ref Message msg) { if (_linkedListViews.Count > 0) { //Look for WM_HSCROLL messages if (msg.Msg == WM_HSCROLL) { Int16 hi = (Int16)((int)msg.WParam >> 16); Int16 lo = (Int16)msg.WParam; foreach (ListView view in _linkedListViews) { if (lo == SB_THUMBTRACK) { SetScrollPos(view.Handle, SB_HORZ, hi, true); int wParam = 4 + 0x10000 * hi; SendMessage(view.Handle, WM_HSCROLL, (IntPtr)(wParam), IntPtr.Zero); } else { SendMessage(view.Handle, WM_HSCROLL, msg.WParam, IntPtr.Zero); } } } } // Pass message to default handler. base.WndProc(ref msg); } ``` This will update the location of the child ListView ScrollBar but does not change the actual view in the child. So my questions are: 1. Is it possible to update the child ListViews when the master ListView ScrollBar is dragged? 2. If so, how?
I wanted to do the same thing, and after searching around I found your code here, which helped, but of course didn't solve the problem. But after playing around with it, I have found a solution. The key came when I realized that since the scroll buttons work, that you can use that to make the slider work. In other words, when the SB\_THUMBTRACK event comes in, I issue repeated SB\_LINELEFT and SB\_LINERIGHT events until my child ListView gets close to where the master is. Yes, this isn't perfect, but it works close enough. In my case, my master ListView is called "reportView", while my child ListView is called "summaryView". Here's my pertinent code: ``` public class MyListView : ListView { public event ScrollEventHandler HScrollEvent; protected override void WndProc(ref System.Windows.Forms.Message msg) { if (msg.Msg==WM_HSCROLL && HScrollEvent != null) HScrollEvent(this,new ScrollEventArgs(ScrollEventType.ThumbTrack, (int)msg.WParam)); base.WndProc(ref msg); } } ``` And then the event handler itself: ``` reportView.HScrollEvent += new ScrollEventHandler((sender,e) => { if ((ushort) e.NewValue != SB_THUMBTRACK) SendMessage(summaryView.Handle, WM_HSCROLL, (IntPtr) e.NewValue, IntPtr.Zero); else { int newPos = e.NewValue >> 16; int oldPos = GetScrollPos(reportView .Handle, SB_HORZ); int pos = GetScrollPos(summaryView.Handle, SB_HORZ); int lst; if (pos != newPos) if (pos<newPos && oldPos<newPos) do { lst=pos; SendMessage(summaryView.Handle,WM_HSCROLL,(IntPtr)SB_LINERIGHT,IntPtr.Zero); } while ((pos=GetScrollPos(summaryView.Handle,SB_HORZ)) < newPos && pos!=lst); else if (pos>newPos && oldPos>newPos) do { lst=pos; SendMessage(summaryView.Handle,WM_HSCROLL,(IntPtr)SB_LINELEFT, IntPtr.Zero); } while ((pos=GetScrollPos(summaryView.Handle,SB_HORZ)) > newPos && pos!=lst); } }); ``` Sorry about the odd formatting of the while loops there, but that's how I prefer to code things like that. The next problem was getting rid of the scroll bars in the child ListView. I noticed you had a method called HideScrollBar. This didn't really work for me. I found a better solution in my case was leaving the scroll bar there, but "covering" it up instead. I do this with the column header as well. I just slide my child control up under the master control to cover the column header. And then I stretch the child to fall out of the panel that contains it. And then to provide a bit of a border along the edge of my containing panel, I throw in a control to cover the visible bottom edge of my child ListView. It ends up looking rather nice. I also added an event handler to sync changing column widths, as in: ``` reportView.ColumnWidthChanging += new ColumnWidthChangingEventHandler((sender,e) => { summaryView.Columns[e.ColumnIndex].Width = e.NewWidth; }); ``` While this all seems a bit of a kludge, it works for me.
159,886
<p>I've seen this is various codebases, and wanted to know if this generally frowned upon or not.</p> <p>For example:</p> <pre><code>public class MyClass { public int Id; public MyClass() { Id = new Database().GetIdFor(typeof(MyClass)); } } </code></pre>
[ { "answer_id": 159894, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "<p>The only problem I can think of with this approach is that any errors from the DB initialization will be propagated as exceptions from the constructor.</p>\n" }, { "answer_id": 159895, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 4, "selected": false, "text": "<p>Well.. I wouldn't. But then again my approach usually involves the class NOT being responsible for retrieving its own data.</p>\n" }, { "answer_id": 159908, "author": "stu", "author_id": 12386, "author_profile": "https://Stackoverflow.com/users/12386", "pm_score": 2, "selected": false, "text": "<p>Yea, you CAN do it, but it's not the best design, and error handling in constructors isn't as tidy as elsewhere.</p>\n" }, { "answer_id": 159913, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 3, "selected": false, "text": "<p>It will also make it difficult to write unit tests for the class as you won't be able to force the class to use a Mock/Stub version of the db class. See here:\n<a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Dependency_injection</a></p>\n" }, { "answer_id": 159921, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>You can use the <em>disposable</em> pattern if you refer to a DB connection:</p>\n\n<pre><code>public class MyClass : IDisposable\n{\n private Database db;\n private int? _id;\n\n public MyClass()\n {\n db = new Database();\n }\n\n public int Id\n {\n get\n {\n if (_id == null) _id = db.GetIdFor(typeof(MyClass));\n return _id.Value;\n }\n }\n\n public void Dispose()\n {\n db.Close();\n }\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>using (var x = new MyClass()) \n{\n /* ... */\n\n} //closes DB by calling IDisposable.Dispose() when going out of \"using\" scope\n</code></pre>\n" }, { "answer_id": 160138, "author": "user9930", "author_id": 9930, "author_profile": "https://Stackoverflow.com/users/9930", "pm_score": 5, "selected": true, "text": "<p>There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned.</p>\n\n<p>The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that any use of that object outside of it original design requires significant rework. As an example what if you came across an instance where you needed to use that object without any values assigned for instance to persist a new instance of that class? you now either have to overload the constructor and then make sure all of your other logic handles this new case, or inherit and override. </p>\n\n<p>If the object and the data access were decoupled then you could create an instance and then not hydrate it. Or if your have a different project that uses the same entities but uses a different persistence layer then the objects are reusable. </p>\n\n<p>Having said that I have taken the easier path of coupling in projects in the past :)</p>\n" }, { "answer_id": 336794, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Why would anyone want to use a mock object/stub instead of the real thing?\nWould you agree that car manufacturers should use paperboard models\nfor crashtests?</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
I've seen this is various codebases, and wanted to know if this generally frowned upon or not. For example: ``` public class MyClass { public int Id; public MyClass() { Id = new Database().GetIdFor(typeof(MyClass)); } } ```
There are several reasons this is not generally considered good design some of which like causing difficult unit testing and difficulty of handling errors have already been mentioned. The main reason I would choose not to do so is that your object and the data access layer are now very tightly coupled which means that any use of that object outside of it original design requires significant rework. As an example what if you came across an instance where you needed to use that object without any values assigned for instance to persist a new instance of that class? you now either have to overload the constructor and then make sure all of your other logic handles this new case, or inherit and override. If the object and the data access were decoupled then you could create an instance and then not hydrate it. Or if your have a different project that uses the same entities but uses a different persistence layer then the objects are reusable. Having said that I have taken the easier path of coupling in projects in the past :)
159,914
<p>Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML?</p> <p>I have a '<em>User Profile</em>' form where I want to disable part of it for a '<em>Non-Premium</em>' member, but want the user to see what is behind the form and place a '<em>Call to Action</em>' on top of it.</p> <p>Does anybody know an easy way to do this either via CSS or JavaScript?</p> <p>Edit: I will make sure that the form doesn't work on server side so CSS or JavaScript will suffice.</p>
[ { "answer_id": 159962, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 6, "selected": false, "text": "<p>Add this to your HTML:</p>\n\n<pre><code>&lt;div id=\"darkLayer\" class=\"darkClass\" style=\"display:none\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>And this to your CSS:</p>\n\n<pre><code>.darkClass\n{\n background-color: white;\n filter:alpha(opacity=50); /* IE */\n opacity: 0.5; /* Safari, Opera */\n -moz-opacity:0.50; /* FireFox */\n z-index: 20;\n height: 100%;\n width: 100%;\n background-repeat:no-repeat;\n background-position:center;\n position:absolute;\n top: 0px;\n left: 0px;\n}\n</code></pre>\n\n<p>And finally this to turn it off and on with JavaScript:</p>\n\n<pre><code>function dimOff()\n{\n document.getElementById(\"darkLayer\").style.display = \"none\";\n}\nfunction dimOn()\n{\n document.getElementById(\"darkLayer\").style.display = \"\";\n}\n</code></pre>\n\n<p>Change the dimensions of the darkClass to suite your purposes.</p>\n" }, { "answer_id": 159989, "author": "Mike", "author_id": 24316, "author_profile": "https://Stackoverflow.com/users/24316", "pm_score": 6, "selected": true, "text": "<p>You might try the jQuery <a href=\"http://malsup.com/jquery/block/\" rel=\"noreferrer\">BlockUI</a> plugin. It's quite flexible and is very easy to use, if you don't mind the dependency on jQuery. It supports <a href=\"http://malsup.com/jquery/block/#element\" rel=\"noreferrer\">element-level</a> blocking as well an overlay message, which seems to be what you need.</p>\n\n<p>The code to use it is as simple as:</p>\n\n<pre><code>$('div.profileform').block({\n message: '&lt;h1&gt;Premium Users only&lt;/h1&gt;',\n});\n</code></pre>\n\n<p>You should also keep in mind that you may still need some sort of server-side protection to make sure that Non-Premium users can't use your form, since it'll be easy for people to access the form elements if they use something like Firebug.</p>\n" }, { "answer_id": 161804, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": false, "text": "<p>If you rely on CSS or JavaScript to prevent a user from editing part of a form then this can easily by circumvented by disabling CSS or JavaScript.</p>\n\n<p>A better solution might be to present the non-editable information outside of the form for non-premium members, but include the relevant form fields for premium members.</p>\n" }, { "answer_id": 7351362, "author": "Oscar", "author_id": 935286, "author_profile": "https://Stackoverflow.com/users/935286", "pm_score": 2, "selected": false, "text": "<pre><code>With opacity\n\n\n//function to grey out the screen\n$(function() {\n// Create overlay and append to body:\n$('&lt;div id=\"ajax-busy\"/&gt;').css({\n opacity: 0.5, \n position: 'fixed',\n top: 0,\n left: 0,\n width: '100%',\n height: $(window).height() + 'px',\n background: 'white url(../images/loading.gif) no-repeat center'\n }).hide().appendTo('body');\n});\n\n\n$.ajax({\n type: \"POST\",\n url: \"Page\",\n data: JSON.stringify({ parameters: XXXXXXXX }),\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n beforeSend: function() {\n $('#ajax-busy').show();\n },\n success: function(msg) {\n $('#ajax-busy').hide();\n\n },\n error: function() {\n $(document).ajaxError(function(xhr, ajaxOptions, thrownError) {\n alert('status: ' + ajaxOptions.status + '-' + ajaxOptions.statusText + ' \\n' + 'error:\\n' + ajaxOptions.responseText);\n });\n }\n});\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML? I have a '*User Profile*' form where I want to disable part of it for a '*Non-Premium*' member, but want the user to see what is behind the form and place a '*Call to Action*' on top of it. Does anybody know an easy way to do this either via CSS or JavaScript? Edit: I will make sure that the form doesn't work on server side so CSS or JavaScript will suffice.
You might try the jQuery [BlockUI](http://malsup.com/jquery/block/) plugin. It's quite flexible and is very easy to use, if you don't mind the dependency on jQuery. It supports [element-level](http://malsup.com/jquery/block/#element) blocking as well an overlay message, which seems to be what you need. The code to use it is as simple as: ``` $('div.profileform').block({ message: '<h1>Premium Users only</h1>', }); ``` You should also keep in mind that you may still need some sort of server-side protection to make sure that Non-Premium users can't use your form, since it'll be easy for people to access the form elements if they use something like Firebug.
159,924
<p>I'm slowly moving all of my <code>LAMP websites</code> from <code>mysql_</code> functions to <code>PDO</code> functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:</p> <pre><code>foreach ($database-&gt;query("SELECT * FROM widgets") as $results) { echo $results["widget_name"]; } </code></pre> <p>However if I want to do something like this:</p> <pre><code>foreach ($database-&gt;query("SELECT * FROM widgets WHERE something='something else'") as $results) { echo $results["widget_name"]; } </code></pre> <p>Obviously the 'something else' will be dynamic.</p>
[ { "answer_id": 159967, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": false, "text": "<p>According to the <a href=\"http://ca3.php.net/manual/en/pdo.query.php\" rel=\"nofollow noreferrer\">PHP documentation</a> is says you should be able to to do the following:</p>\n<pre><code>$sql = &quot;SELECT * FROM widgets WHERE something='something else'&quot;;\nforeach ($database-&gt;query($sql) as $row) {\n echo $row[&quot;widget_name&quot;];\n}\n</code></pre>\n" }, { "answer_id": 160365, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 7, "selected": true, "text": "<p>Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):</p>\n<pre><code>// connect to PDO\n$pdo = new PDO(&quot;mysql:host=localhost;dbname=test&quot;, &quot;user&quot;, &quot;password&quot;);\n\n// the following tells PDO we want it to throw Exceptions for every error.\n// this is far more useful than the default mode of throwing php errors\n$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n// prepare the statement. the placeholders allow PDO to handle substituting\n// the values, which also prevents SQL injection\n$stmt = $pdo-&gt;prepare(&quot;SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand&quot;);\n\n// bind the parameters\n$stmt-&gt;bindValue(&quot;:productTypeId&quot;, 6);\n$stmt-&gt;bindValue(&quot;:brand&quot;, &quot;Slurm&quot;);\n\n// initialise an array for the results\n$products = array();\n$stmt-&gt;execute();\nwhile ($row = $stmt-&gt;fetch(PDO::FETCH_ASSOC)) {\n $products[] = $row;\n}\n</code></pre>\n" }, { "answer_id": 17102106, "author": "John K", "author_id": 969423, "author_profile": "https://Stackoverflow.com/users/969423", "pm_score": 2, "selected": false, "text": "<p>If you like the foreach syntax, you can use the following class:</p>\n\n<pre><code>// Wrap a PDOStatement to iterate through all result rows. Uses a \n// local cache to allow rewinding.\nclass PDOStatementIterator implements Iterator\n{\n public\n $stmt,\n $cache,\n $next;\n\n public function __construct($stmt)\n {\n $this-&gt;cache = array();\n $this-&gt;stmt = $stmt;\n }\n\n public function rewind()\n {\n reset($this-&gt;cache);\n $this-&gt;next();\n }\n\n public function valid()\n {\n return (FALSE !== $this-&gt;next);\n }\n\n public function current()\n {\n return $this-&gt;next[1];\n }\n\n public function key()\n {\n return $this-&gt;next[0];\n }\n\n public function next()\n {\n // Try to get the next element in our data cache.\n $this-&gt;next = each($this-&gt;cache);\n\n // Past the end of the data cache\n if (FALSE === $this-&gt;next)\n {\n // Fetch the next row of data\n $row = $this-&gt;stmt-&gt;fetch(PDO::FETCH_ASSOC);\n\n // Fetch successful\n if ($row)\n {\n // Add row to data cache\n $this-&gt;cache[] = $row;\n }\n\n $this-&gt;next = each($this-&gt;cache);\n }\n }\n</code></pre>\n\n<p>}</p>\n\n<p>Then to use it:</p>\n\n<pre><code>foreach(new PDOStatementIterator($stmt) as $col =&gt; $val)\n{\n ...\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
I'm slowly moving all of my `LAMP websites` from `mysql_` functions to `PDO` functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following: ``` foreach ($database->query("SELECT * FROM widgets") as $results) { echo $results["widget_name"]; } ``` However if I want to do something like this: ``` foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results) { echo $results["widget_name"]; } ``` Obviously the 'something else' will be dynamic.
Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended): ``` // connect to PDO $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password"); // the following tells PDO we want it to throw Exceptions for every error. // this is far more useful than the default mode of throwing php errors $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // prepare the statement. the placeholders allow PDO to handle substituting // the values, which also prevents SQL injection $stmt = $pdo->prepare("SELECT * FROM product WHERE productTypeId=:productTypeId AND brand=:brand"); // bind the parameters $stmt->bindValue(":productTypeId", 6); $stmt->bindValue(":brand", "Slurm"); // initialise an array for the results $products = array(); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $products[] = $row; } ```
159,934
<p>How would one structure a table for an entity that can have a one to many relationship to itself? Specifically, I'm working on an app to track animal breeding. Each animal has an ID; it's also got a sire ID and a dame ID. So it's possible to have a one to many from the sire or dame to its offspring. I would be inclined to something like this:</p> <pre><code>ID INT NOT NULL PRIMARY KEY SIRE_ID INT DAME_ID INT </code></pre> <p>and record a null value for those animals which were purchased and added to the breeding stock and an ID in the table for the rest. </p> <p>So:</p> <ol> <li>Can someone point me to an article/web page that discusses modeling this sort of relationship?</li> <li>Should the ID be an INT or some sort of String? A NULL in the INT would indicate that the animal has no parents in the database but a String with special flag values could be used to indicate the same thing.</li> <li><p>Would this possibly be best modeled via two tables? I mean one table for the animals and a separate table solely indicating kinship e. g.:</p> <p>Animal</p> <p>ID INT NOT NULL PRIMARY KEY</p> <p>Kinship</p> <p>ID INT NOT NULL PRIMARY KEY FOREIGN KEY</p> <p>SIRE_ID INT PRIMARY KEY FOREIGN KEY</p> <p>DAME_ID INT PRIMARY KEY FOREIGN KEY</p></li> </ol> <p>I apologize for the above: my SQL is rusty. I hope it sort of conveys what I'm thinking about. </p>
[ { "answer_id": 159968, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 4, "selected": true, "text": "<p>Well, this is a \"normal\" one-to-many relationship and the method you suggest is the classical one for solving it.</p>\n\n<p>Note that two tables are denormalized (I can't point out exactly where the superkey-is-not-well-should-be-subset-of-other-key-fsck-I-forgot part is, but I'm pretty sure it's there somewhere); the intuitive reason is that a tuple in the first one matches at most a tuple in the second one, so unless you have lots of animals with null sire and dame IDs, it's not a good solution in any prospect (it worsens performance -- need a join -- and does not reduce storage requirements).</p>\n" }, { "answer_id": 159972, "author": "Lost in Alabama", "author_id": 5285, "author_profile": "https://Stackoverflow.com/users/5285", "pm_score": 1, "selected": false, "text": "<p>INT is the better choice for the ID column and better suited if you should use a sequence to generate the unique IDs.</p>\n\n<p>I don't see any benefit in splitting the design into two tables.</p>\n" }, { "answer_id": 159973, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 2, "selected": false, "text": "<p>I asked a similar question a number of months ago on the MySQL website. I would recommend that you take a look at the response that I received from Peter Brawley regarding this type of relationship: <a href=\"http://forums.mysql.com/read.php?135,187196,187196#msg-187196\" rel=\"nofollow noreferrer\"><a href=\"http://forums.mysql.com/read.php?135,187196,187196#msg-187196\" rel=\"nofollow noreferrer\">http://forums.mysql.com/read.php?135,187196,187196#msg-187196</a></a></p>\n\n<p>If you want to research the topic further then I would recommend that you look into Tree Hierarchies on Wikipedia.</p>\n\n<p>An alternate suggested architecture (that would be fully normalized) would look something like the following:</p>\n\n<p>Table: animal</p>\n\n<p>ID | Name | Breed</p>\n\n<p>Table: pedigree</p>\n\n<p>animal_id | parent_id | parentType (either sire or dame)</p>\n" }, { "answer_id": 159976, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 0, "selected": false, "text": "<p>Use the \"connect by\" clause with SQL to tell it which hierarchy to follow.</p>\n" }, { "answer_id": 159979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's not really a one to many relationship, unless an animal can have many parents.</p>\n\n<p>I would leave it as a single table with the unique key ID for the animal, one int field for each of the parents, and probably a text field to use for general notes about the animal, like where it was purchased if that's the case.</p>\n" }, { "answer_id": 159995, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I think that since it is clear that an animal only has one sire and one dam, that using a single table would make the most sense. My preference is to use int or bigint as the row identifier, with a null value signifying no relationship. I would probably, then, to use some other method to uniquely identify animals so they don't end up in the table twice and create a unique index on that column as well.</p>\n" }, { "answer_id": 159997, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 2, "selected": false, "text": "<p>I think your layout using just one table is fine. You definitely want to keep SIRE_ID and DAME_ID in the same data type as ID. You also want to declare them as FOREIGN KEYs (it is possible to have a foreign key point back to the same table, and a foreign key can also be null).</p>\n\n<pre><code>ID INT NOT NULL PRIMARY KEY\nSIRE_ID INT REFERENCES TABLENAME (ID)\nDAME_ID INT REFERENCES TABLENAME (ID)\n</code></pre>\n\n<p>Using this layout, you can easily look up the parent animals, and you could also build an offspring tree for a given animal (for Oracle there is CONNECT BY)</p>\n" }, { "answer_id": 160004, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 0, "selected": false, "text": "<p>Seems like you want to build something like a tree.</p>\n\n<p>What about something like?:</p>\n\n<pre><code> ID Primary Key,\n Parent_ID Foreing_Key\n ( data )\n</code></pre>\n\n<p>There are some functionality for doing querys in tables with relations to themselves. See the syntax of <strong>Connect By</strong>: <a href=\"http://www.adp-gmbh.ch/ora/sql/connect_by.html\" rel=\"nofollow noreferrer\">http://www.adp-gmbh.ch/ora/sql/connect_by.html</a></p>\n" }, { "answer_id": 160005, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 1, "selected": false, "text": "<p>I don't know about animal breeding, but it sounds like your Sire_ID is the father and Dame_ID is the mother? No problem. One row per animal, null sire_ and dame_ID's for purchased animals, I don't forsee any problems.</p>\n\n<pre><code>[ID],[Sire_ID],[Dame_ID];\n0,null,null (male)\n1,null,null (female)\n2,null,null (female)\n3,0,1 (male)\n4,0,2 (male)\n5,null,null (female)\n6,3,5\n7,4,5\n</code></pre>\n\n<p>and so forth. You would likely populate a TreeView or XmlNodeList in a while loop...</p>\n\n<pre><code>While (myAnimal.HasChildren) {\n Animal[] children = GetChildren(Animal.ID)\n for (int x=0; x&lt;children.length; x++) \n myAnimal.Children.Add(children[x]);\n}\n</code></pre>\n\n<p>In this case, Animal.Children is a Collection of Animals. Therefore, myAnimal.Children[0].Father would return myAnimal. .Parent[] could be a collection of its two parents, which should work as long as [0] is always one parent (father) and [1] is always the other (mother).</p>\n\n<p>Make ID an Autonumber PK and assign Sire_ID and Dame_ID programatically by returning the IDs of its parents. No foreign key relationships should be neccessary though both parent IDs could reference back to ID if you really want to.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2820/" ]
How would one structure a table for an entity that can have a one to many relationship to itself? Specifically, I'm working on an app to track animal breeding. Each animal has an ID; it's also got a sire ID and a dame ID. So it's possible to have a one to many from the sire or dame to its offspring. I would be inclined to something like this: ``` ID INT NOT NULL PRIMARY KEY SIRE_ID INT DAME_ID INT ``` and record a null value for those animals which were purchased and added to the breeding stock and an ID in the table for the rest. So: 1. Can someone point me to an article/web page that discusses modeling this sort of relationship? 2. Should the ID be an INT or some sort of String? A NULL in the INT would indicate that the animal has no parents in the database but a String with special flag values could be used to indicate the same thing. 3. Would this possibly be best modeled via two tables? I mean one table for the animals and a separate table solely indicating kinship e. g.: Animal ID INT NOT NULL PRIMARY KEY Kinship ID INT NOT NULL PRIMARY KEY FOREIGN KEY SIRE\_ID INT PRIMARY KEY FOREIGN KEY DAME\_ID INT PRIMARY KEY FOREIGN KEY I apologize for the above: my SQL is rusty. I hope it sort of conveys what I'm thinking about.
Well, this is a "normal" one-to-many relationship and the method you suggest is the classical one for solving it. Note that two tables are denormalized (I can't point out exactly where the superkey-is-not-well-should-be-subset-of-other-key-fsck-I-forgot part is, but I'm pretty sure it's there somewhere); the intuitive reason is that a tuple in the first one matches at most a tuple in the second one, so unless you have lots of animals with null sire and dame IDs, it's not a good solution in any prospect (it worsens performance -- need a join -- and does not reduce storage requirements).
159,950
<p>How do I change the system-wide short date format in Ubuntu? For example, Thunderbird is showing dates in the DD/MM/YY format, and I would like to change it to MM/DD/YY or YYYY-MM-DD.</p> <p>The best information I can find so far is in this thread:</p> <p><a href="http://ubuntuforums.org/showthread.php?t=193916" rel="noreferrer">http://ubuntuforums.org/showthread.php?t=193916</a></p> <p>Edit: I want to change the system-wide date format, so that all my applications use this new date format.</p>
[ { "answer_id": 160036, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 1, "selected": false, "text": "<p>Thunderbird uses the system's date format, and that format depends on the system's locale settings. You have two options:</p>\n\n<ol>\n<li>modify the system locale, the instructions are in the forum thread you linked above, or</li>\n<li>set <code>LC_TIME</code> to a locale that uses the format you want. The <a href=\"http://kb.mozillazine.org/Date_display_format\" rel=\"nofollow noreferrer\">article</a> linked by <a href=\"https://stackoverflow.com/questions/159950/changing-short-date-format-in-ubuntu#159963\">Craig H</a> suggests <code>en_DK</code>.</li>\n</ol>\n" }, { "answer_id": 42686893, "author": "ScottK", "author_id": 6693299, "author_profile": "https://Stackoverflow.com/users/6693299", "pm_score": 2, "selected": false, "text": "<p>How to do this in 2017 with <a href=\"https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_16.04_LTS_.28Xenial_Xerus.29\" rel=\"nofollow noreferrer\">Ubuntu&nbsp;16.04</a> (Xenial Xerus) is described <a href=\"https://help.ubuntu.com/stable/ubuntu-help/session-formats.html\" rel=\"nofollow noreferrer\">here</a>. Cut/Paste follows below in case that site goes away:</p>\n\n<p><strong>Change date and measurement formats</strong></p>\n\n<p>You can control the formats that are used for dates, times, numbers, currency, and measurement to match the local customs of your region.</p>\n\n<ul>\n<li>Click the icon at the very right of the menu bar and select System Settings.</li>\n<li>Open Language Support and select the Regional Formats tab.</li>\n<li>Select the region that most closely matches the formats you'd like to use. By default, the list only shows regions that use the language set on the Language tab.</li>\n<li>You have to log out and back in for these changes to take effect.\nClick the icon at the very right of the menu bar and select Log Out to log out.</li>\n<li>After you've selected a region, the area below the list shows various examples of how dates and other values are shown. Although not shown in the examples, your region also controls the starting day of the week in calendars.</li>\n</ul>\n" }, { "answer_id": 46157865, "author": "Nishi", "author_id": 211369, "author_profile": "https://Stackoverflow.com/users/211369", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Install and launch \"dconf Editor\", navigate to com -> canonical -> indicator -> datetime.</li>\n<li>Set the value of <code>time-format</code> to <code>custom</code>.</li>\n<li>Customize the Time &amp; Date format by editing the value of <code>custom-time-format</code>, e.g. set it to <code>%Y-%m-%d %H:%M:%S</code> for \"2017-12-31 23:59:59\" format.</li>\n<li>Re-login to see effect of the changes.</li>\n</ul>\n\n<p>You can also do this via a command in terminal:</p>\n\n<pre><code>gsettings set com.canonical.indicator.datetime time-format 'custom'\ngsettings set com.canonical.indicator.datetime custom-time-format '%Y-%m-%d %H:%M:%S'\n</code></pre>\n\n<p>Source: <a href=\"http://ubuntuhandbook.org/index.php/2015/12/time-date-format-ubuntu-panel/\" rel=\"noreferrer\">http://ubuntuhandbook.org/index.php/2015/12/time-date-format-ubuntu-panel/</a></p>\n" }, { "answer_id": 47386424, "author": "Arya", "author_id": 2954429, "author_profile": "https://Stackoverflow.com/users/2954429", "pm_score": 1, "selected": false, "text": "<p>The instructions <a href=\"https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/\" rel=\"nofollow noreferrer\">here</a> worked for me to create a custom locale based on <code>en_US</code>. Then Thunderbird showed the date/time format how I want (I prefer YYYY-MM-DD over MM/DD/YY).</p>\n\n<p>Some time later, the date/time format in Thunderbird changed back to what was set in <code>en_US</code> (MM/DD/YY), because I had inadvertently set $LC_ALL to <code>en_US.UTF-8</code>. So, I <code>sudo gedit /etc/environment</code> and changed <code>LC_ALL=\"en_US.UTF-8\"</code> to <code>LC_ALL=\"custom.UTF-8\"</code>. Finally, Thunderbird is showing the dates how I want them.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24311/" ]
How do I change the system-wide short date format in Ubuntu? For example, Thunderbird is showing dates in the DD/MM/YY format, and I would like to change it to MM/DD/YY or YYYY-MM-DD. The best information I can find so far is in this thread: <http://ubuntuforums.org/showthread.php?t=193916> Edit: I want to change the system-wide date format, so that all my applications use this new date format.
* Install and launch "dconf Editor", navigate to com -> canonical -> indicator -> datetime. * Set the value of `time-format` to `custom`. * Customize the Time & Date format by editing the value of `custom-time-format`, e.g. set it to `%Y-%m-%d %H:%M:%S` for "2017-12-31 23:59:59" format. * Re-login to see effect of the changes. You can also do this via a command in terminal: ``` gsettings set com.canonical.indicator.datetime time-format 'custom' gsettings set com.canonical.indicator.datetime custom-time-format '%Y-%m-%d %H:%M:%S' ``` Source: <http://ubuntuhandbook.org/index.php/2015/12/time-date-format-ubuntu-panel/>
159,978
<p>What are differences between declaring a method in a base type "<code>virtual</code>" and then overriding it in a child type using the "<code>override</code>" keyword as opposed to simply using the "<code>new</code>" keyword when declaring the matching method in the child type? </p>
[ { "answer_id": 159993, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 9, "selected": true, "text": "<p>The \"new\" keyword doesn't override, it signifies a new method that has nothing to do with the base class method. </p>\n\n<pre><code>public class Foo\n{\n public bool DoSomething() { return false; }\n}\n\npublic class Bar : Foo\n{\n public new bool DoSomething() { return true; }\n}\n\npublic class Test\n{\n public static void Main ()\n {\n Foo test = new Bar ();\n Console.WriteLine (test.DoSomething ());\n }\n}\n</code></pre>\n\n<p><strong>This prints false, if you used override it would have printed true.</strong></p>\n\n<p>(Base code taken from Joseph Daigle)</p>\n\n<p>So, if you are doing real polymorphism you <strong>SHOULD ALWAYS OVERRIDE</strong>. The only place where you need to use \"new\" is when the method is not related in any way to the base class version.</p>\n" }, { "answer_id": 159994, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 4, "selected": false, "text": "<p>The <code>new</code> keyword actually creates a completely new member that only exists on that specific type.</p>\n\n<p>For instance</p>\n\n<pre><code>public class Foo\n{\n public bool DoSomething() { return false; }\n}\n\npublic class Bar : Foo\n{\n public new bool DoSomething() { return true; }\n}\n</code></pre>\n\n<p>The method exists on both types. When you use reflection and get the members of type <code>Bar</code>, you will actually find 2 methods called <code>DoSomething()</code> that look exactly the same. By using <code>new</code> you effectively hide the implementation in the base class, so that when classes derive from <code>Bar</code> (in my example) the method call to <code>base.DoSomething()</code> goes to <code>Bar</code> and not <code>Foo</code>.</p>\n" }, { "answer_id": 160000, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "<p>The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.</p>\n\n<p>Check out the folllowing links for more information...</p>\n\n<p><a href=\"http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkversioningtutorial.asp\" rel=\"nofollow noreferrer\">MSDN</a> and <a href=\"http://www.akadia.com/services/dotnet_polymorphism.html\" rel=\"nofollow noreferrer\">Other</a></p>\n" }, { "answer_id": 160011, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 6, "selected": false, "text": "<p>Here's some code to understand the difference in the behavior of virtual and non-virtual methods:</p>\n\n<pre><code>class A\n{\n public void foo()\n {\n Console.WriteLine(\"A::foo()\");\n }\n public virtual void bar()\n {\n Console.WriteLine(\"A::bar()\");\n }\n}\n\nclass B : A\n{\n public new void foo()\n {\n Console.WriteLine(\"B::foo()\");\n }\n public override void bar()\n {\n Console.WriteLine(\"B::bar()\");\n }\n}\n\nclass Program\n{\n static int Main(string[] args)\n {\n B b = new B();\n A a = b;\n a.foo(); // Prints A::foo\n b.foo(); // Prints B::foo\n a.bar(); // Prints B::bar\n b.bar(); // Prints B::bar\n return 0;\n }\n}\n</code></pre>\n" }, { "answer_id": 160029, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<p>Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.</p>\n" }, { "answer_id": 160034, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p><strong>virtual / override</strong> tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.</p>\n\n<pre><code>(new SubClass() as BaseClass).VirtualFoo()\n</code></pre>\n\n<p>Will call the SubClass's overriden VirtualFoo() method.</p>\n\n<p><strong>new</strong> tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.</p>\n\n<pre><code>(new SubClass() as BaseClass).NewBar()\n</code></pre>\n\n<p>Will call the BaseClass's NewBar() method, whereas:</p>\n\n<pre><code>(new SubClass()).NewBar()\n</code></pre>\n\n<p>Will call the SubClass's NewBar() method.</p>\n" }, { "answer_id": 160095, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 8, "selected": false, "text": "<p>I always find things like this more easily understood with pictures:</p>\n\n<p>Again, taking joseph daigle's code,</p>\n\n<pre><code>public class Foo\n{\n public /*virtual*/ bool DoSomething() { return false; }\n}\n\npublic class Bar : Foo\n{\n public /*override or new*/ bool DoSomething() { return true; }\n}\n</code></pre>\n\n<p>If you then call the code like this:</p>\n\n<pre><code>Foo a = new Bar();\na.DoSomething();\n</code></pre>\n\n<p><em>NOTE: The important thing is that our object is actually a <code>Bar</code>, but we are <strong>storing it in a variable of type <code>Foo</code></strong> (this is similar to casting it)</em></p>\n\n<p>Then the result will be as follows, depending on whether you used <code>virtual</code>/<code>override</code> or <code>new</code> when declaring your classes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/4NrQk.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4NrQk.jpg\" alt=\"Virtual/Override explanation image\"></a></p>\n" }, { "answer_id": 6743287, "author": "Chetan", "author_id": 851405, "author_profile": "https://Stackoverflow.com/users/851405", "pm_score": 2, "selected": false, "text": "<ul>\n<li><code>new</code> keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.</li>\n<li><code>override</code> for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.</li>\n</ul>\n" }, { "answer_id": 39343057, "author": "Dror Weiss", "author_id": 1006127, "author_profile": "https://Stackoverflow.com/users/1006127", "pm_score": 2, "selected": false, "text": "<p>My version of explanation comes from using <strong>properties</strong> to help understand the differences.</p>\n\n<p><code>override</code> is simple enough, right ? The underlying type <em>overrides</em> the parent's.</p>\n\n<p><code>new</code> is perhaps the misleading (for me it was). With properties it's easier to understand:</p>\n\n<pre><code>public class Foo\n{\n public bool GetSomething =&gt; false;\n}\n\npublic class Bar : Foo\n{\n public new bool GetSomething =&gt; true;\n}\n\npublic static void Main(string[] args)\n{\n Foo foo = new Bar();\n Console.WriteLine(foo.GetSomething);\n\n Bar bar = new Bar();\n Console.WriteLine(bar.GetSomething);\n}\n</code></pre>\n\n<p>Using a debugger you can notice that <code>Foo foo</code> has <strong>2</strong> <code>GetSomething</code> properties, as it actually has 2 versions of the property, <code>Foo</code>'s and <code>Bar</code>'s, and to know which one to use, c# \"picks\" the property for the current type. </p>\n\n<p>If you wanted to use the Bar's version, you would have used override or use <code>Foo foo</code> instead.</p>\n\n<p><code>Bar bar</code> has only <strong>1</strong>, as it wants completely <strong>new</strong> behavior for <code>GetSomething</code>.</p>\n" }, { "answer_id": 53639866, "author": "Emre Tapcı", "author_id": 8489067, "author_profile": "https://Stackoverflow.com/users/8489067", "pm_score": 1, "selected": false, "text": "<p>Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding). </p>\n\n<p>Marking a method with <code>virtual</code> means: Bind this method using the object's runtime type, not compile time type (dynamic binding). </p>\n\n<p>Marking a base class <code>virtual</code> method with <code>override</code> in derived class means: This is the method to be bound using the object's runtime type (dynamic binding). </p>\n\n<p>Marking a base class <code>virtual</code> method with <code>new</code> in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding). </p>\n\n<p>Not marking a base class <code>virtual</code> method in the derived class means: This method is marked as <code>new</code> (static binding). </p>\n\n<p>Marking a method <code>abstract</code> means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding). </p>\n" }, { "answer_id": 68192875, "author": "Mehdi", "author_id": 12648236, "author_profile": "https://Stackoverflow.com/users/12648236", "pm_score": 1, "selected": false, "text": "<pre><code>using System; \nusing System.Text; \n \nnamespace OverrideAndNew \n{ \n class Program \n { \n static void Main(string[] args) \n { \n BaseClass bc = new BaseClass(); \n DerivedClass dc = new DerivedClass(); \n BaseClass bcdc = new DerivedClass(); \n \n // The following two calls do what you would expect. They call \n // the methods that are defined in BaseClass. \n bc.Method1(); \n bc.Method2(); \n // Output: \n // Base - Method1 \n // Base - Method2 \n \n // The following two calls do what you would expect. They call \n // the methods that are defined in DerivedClass. \n dc.Method1(); \n dc.Method2(); \n // Output: \n // Derived - Method1 \n // Derived - Method2 \n \n // The following two calls produce different results, depending\n // on whether override (Method1) or new (Method2) is used. \n bcdc.Method1(); \n bcdc.Method2(); \n // Output: \n // Derived - Method1 \n // Base - Method2 \n } \n } \n \n class BaseClass \n { \n public virtual void Method1() \n { \n Console.WriteLine(&quot;Base - Method1&quot;); \n } \n \n public virtual void Method2() \n { \n Console.WriteLine(&quot;Base - Method2&quot;); \n } \n } \n \n class DerivedClass : BaseClass \n { \n public override void Method1() \n { \n Console.WriteLine(&quot;Derived - Method1&quot;); \n } \n \n public new void Method2() \n { \n Console.WriteLine(&quot;Derived - Method2&quot;); \n } \n } \n} \n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9898/" ]
What are differences between declaring a method in a base type "`virtual`" and then overriding it in a child type using the "`override`" keyword as opposed to simply using the "`new`" keyword when declaring the matching method in the child type?
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method. ``` public class Foo { public bool DoSomething() { return false; } } public class Bar : Foo { public new bool DoSomething() { return true; } } public class Test { public static void Main () { Foo test = new Bar (); Console.WriteLine (test.DoSomething ()); } } ``` **This prints false, if you used override it would have printed true.** (Base code taken from Joseph Daigle) So, if you are doing real polymorphism you **SHOULD ALWAYS OVERRIDE**. The only place where you need to use "new" is when the method is not related in any way to the base class version.
159,990
<p>I've done some Python but have just now starting to use Ruby<br> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br> Python methods receive self as an explicit argument, whereas Ruby does not.<br> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br> <a href="http://rubylearning.com/satishtalim/ruby_self.html" rel="noreferrer">http://rubylearning.com/satishtalim/ruby_self.html</a><br> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html" rel="noreferrer">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
[ { "answer_id": 160017, "author": "interstar", "author_id": 8482, "author_profile": "https://Stackoverflow.com/users/8482", "pm_score": 3, "selected": false, "text": "<p>Well, I don't know much about Ruby. But the obvious point about Python's \"self\" is that it's not a \"keyword\" ...it's just the name of an argument that's sent to your method.</p>\n\n<p>You can use any name you like for this argument. \"Self\" is just a convention.</p>\n\n<p>For example :</p>\n\n<pre><code>class X :\n def __init__(a,val) :\n a.x = val\n def p(b) :\n print b.x\n\nx = X(6)\nx.p()\n</code></pre>\n\n<p>Prints the number 6 on the terminal. In the constructor the self object is actually called a. But in the p() method, it's called b.</p>\n\n<p>Update : In October 2008, Guido pointed out that having an explicit self was also necessary to allow Python decorators to be general enough to work on pure functions, methods or classmethods : <a href=\"http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html\" rel=\"nofollow noreferrer\">http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html</a></p>\n" }, { "answer_id": 160064, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 3, "selected": false, "text": "<p>self is used only as a convention, you can use spam, bacon or sausage instead of self and get the same result. It's just the first argument passed to bound methods. But stick to using self as it will confuse others and some editors.</p>\n" }, { "answer_id": 160227, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 4, "selected": true, "text": "<p>Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.</p>\n\n<p>Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.</p>\n\n<p>If you're inside an instance method of one of your class, self is a reference to said instance. </p>\n\n<p>If you're in the definition of the class itself (not in a method), self is the class itself:</p>\n\n<pre><code>class C\n puts \"I am a #{self}\"\n def instance_method\n puts 'instance_method'\n end\n def self.class_method\n puts 'class_method'\n end\nend\n</code></pre>\n\n<p>At class definition time, 'I am a C' will be printed.</p>\n\n<p>The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.</p>\n\n<pre><code>c=C.new\n\nc.instance_method\n#=&gt; instance_method\nC.class_method\n#=&gt; class_method\n</code></pre>\n" }, { "answer_id": 165574, "author": "Matthew Trevor", "author_id": 11265, "author_profile": "https://Stackoverflow.com/users/11265", "pm_score": 3, "selected": false, "text": "<p>Despite webmat's claim, Guido <a href=\"http://markmail.org/message/n6fs5pec5233mbfg\" rel=\"noreferrer\">wrote</a> that explicit self is \"not an implementation hack -- it is a semantic device\".</p>\n\n<blockquote>\n <p>The reason for explicit self in method\n definition signatures is semantic\n consistency. If you write</p>\n \n <p>class C: def foo(self, x, y): ...</p>\n \n <p>This really <em>is</em> the same as writing</p>\n \n <p>class C: pass</p>\n \n <p>def foo(self, x, y): ... C.foo = foo</p>\n</blockquote>\n\n<p>This was an intentional design decision, not a result of introducing OO behaviour at a latter date.</p>\n\n<p>Everything in Python -is- an object, including literals.</p>\n\n<p>See also <a href=\"http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm\" rel=\"noreferrer\">Why must 'self' be used explicitly in method definitions and calls?</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/159990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2242/" ]
I've done some Python but have just now starting to use Ruby I could use a good explanation of the difference between "self" in these two languages. **Obvious on first glance:** Self is not a keyword in Python, but there is a "self-like" value no matter what you call it. Python methods receive self as an explicit argument, whereas Ruby does not. Ruby sometimes has methods explicitly defined as part of self using dot notation. **Initial Googling reveals** <http://rubylearning.com/satishtalim/ruby_self.html> <http://www.ibiblio.org/g2swap/byteofpython/read/self.html>
Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly. Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are. If you're inside an instance method of one of your class, self is a reference to said instance. If you're in the definition of the class itself (not in a method), self is the class itself: ``` class C puts "I am a #{self}" def instance_method puts 'instance_method' end def self.class_method puts 'class_method' end end ``` At class definition time, 'I am a C' will be printed. The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method. ``` c=C.new c.instance_method #=> instance_method C.class_method #=> class_method ```
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="noreferrer">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
[ { "answer_id": 160035, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": -1, "selected": false, "text": "<p>Hmmm, I don't fully understand your question. But if you can't do it when you declare the model maybe you can achieve the same thing with overriding methods of the class of objects where you \"send\" the user object, maybe start with the constructor.</p>\n" }, { "answer_id": 160421, "author": "ilvar", "author_id": 1215136, "author_profile": "https://Stackoverflow.com/users/1215136", "pm_score": 2, "selected": false, "text": "<p>Model itself doesn't know anything about current user but you can give this user in a view to the form which operates models objects (and in form reset <code>choices</code> for necessary field). </p>\n\n<p>If you need this on admin site - you can try <code>raw_id_admin</code> along with <code>django-granular-permissions</code> (<a href=\"http://code.google.com/p/django-granular-permissions/\" rel=\"nofollow noreferrer\">http://code.google.com/p/django-granular-permissions/</a> but I couldn't rapidly get it working on my django but it seems to be fresh enough for 1.0 so...). </p>\n\n<p>At last, if you heavily need a selectbox in admin - then you'll need to hack <code>django.contrib.admin</code> itself.</p>\n" }, { "answer_id": 160435, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 0, "selected": false, "text": "<p>I'm not sure that I fully understand exactly what you want to do, but I think that there's a good chance that you'll get at least part the way there using a <a href=\"https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance\" rel=\"nofollow noreferrer\">custom Manager</a>. In particular, don't try to define your models with restrictions to the current user, but create a manager that only returns objects that match the current user.</p>\n" }, { "answer_id": 161615, "author": "Dmitry Shevchenko", "author_id": 7437, "author_profile": "https://Stackoverflow.com/users/7437", "pm_score": -1, "selected": true, "text": "<p>Use threadlocals if you want to get <strong>current</strong> user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware</p>\n\n<pre><code>from threading import local\n\n_thread_locals = local()\ndef get_current_user():\n return getattr(getattr(_thread_locals, 'user', None),'id',None)\n\nclass ThreadLocals(object):\n \"\"\"Middleware that gets various objects from the\n request object and saves them in thread local storage.\"\"\"\n def process_request(self, request):\n _thread_locals.user = getattr(request, 'user', None)\n</code></pre>\n\n<p>Check the documentation on how to use middleware classes. Then anywhere in code you can call</p>\n\n<pre><code>user = threadlocals.get_current_user\n</code></pre>\n" }, { "answer_id": 4656296, "author": "Anentropic", "author_id": 202168, "author_profile": "https://Stackoverflow.com/users/202168", "pm_score": 3, "selected": false, "text": "<p>This limiting of choices to current user is a kind of validation that needs to happen dynamically in the request cycle, not in the static Model definition.</p>\n\n<p>In other words: at the point where you are creating an <em>instance</em> of this model you will be in a View and at that point you will have access to the current user and can limit the choices.</p>\n\n<p>Then you just need a custom ModelForm to pass in the request.user to, see the example here:\n<a href=\"http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/\" rel=\"noreferrer\">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a></p>\n\n<pre><code>from datetime import datetime, timedelta\nfrom django import forms\nfrom mysite.models import Project, TimeWorked\n\nclass TimeWorkedForm(forms.ModelForm):\n def __init__(self, user, *args, **kwargs):\n super(ProjectForm, self).__init__(*args, **kwargs)\n self.fields['project'].queryset = Project.objects.filter(user=user)\n\n class Meta:\n model = TimeWorked\n</code></pre>\n\n<p>then in your view:</p>\n\n<pre><code>def time_worked(request):\n form = TimeWorkedForm(request.user, request.POST or None)\n if form.is_valid():\n obj = form.save()\n # redirect somewhere\n return render_to_response('time_worked.html', {'form': form})\n</code></pre>\n" }, { "answer_id": 55389028, "author": "Stephen G Tuggy", "author_id": 5067822, "author_profile": "https://Stackoverflow.com/users/5067822", "pm_score": 1, "selected": false, "text": "<p>Using class-based generic Views in Django 1.8.x / Python 2.7.x, here is what my colleagues and I came up with:</p>\n\n<p>In models.py:</p>\n\n<pre><code># ...\n\nclass Proposal(models.Model):\n # ...\n\n # Soft foreign key reference to customer\n customer_id = models.PositiveIntegerField()\n\n # ...\n</code></pre>\n\n<p>In forms.py:</p>\n\n<pre><code># -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.forms import ModelForm, ChoiceField, Select\nfrom django import forms\nfrom django.forms.utils import ErrorList\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext as _\nfrom .models import Proposal\nfrom account.models import User\nfrom customers.models import customer\n\n\n\ndef get_customers_by_user(curUser=None):\n customerSet = None\n\n # Users with userType '1' or '2' are superusers; they should be able to see\n # all the customers regardless. Users with userType '3' or '4' are limited\n # users; they should only be able to see the customers associated with them\n # in the customized user admin.\n # \n # (I know, that's probably a terrible system, but it's one that I\n # inherited, and am keeping for now.)\n if curUser and (curUser.userType in ['1', '2']):\n customerSet = customer.objects.all().order_by('company_name')\n elif curUser:\n customerSet = curUser.customers.all().order_by('company_name')\n else:\n customerSet = customer.objects.all().order_by('company_name')\n\n return customerSet\n\n\ndef get_customer_choices(customerSet):\n retVal = []\n\n for customer in customerSet:\n retVal.append((customer.customer_number, '%d: %s' % (customer.customer_number, customer.company_name)))\n\n return tuple(retVal)\n\n\nclass CustomerFilterTestForm(ModelForm):\n\n class Meta:\n model = Proposal\n fields = ['customer_id']\n\n def __init__(self, user=None, *args, **kwargs):\n super(CustomerFilterTestForm, self).__init__(*args, **kwargs)\n self.fields['customer_id'].widget = Select(choices=get_customer_choices(get_customers_by_user(user)))\n\n# ...\n</code></pre>\n\n<p>In views.py:</p>\n\n<pre><code># ...\n\nclass CustomerFilterTestView(generic.UpdateView):\n model = Proposal\n form_class = CustomerFilterTestForm\n template_name = 'proposals/customer_filter_test.html'\n context_object_name = 'my_context'\n success_url = \"/proposals/\"\n\n def get_form_kwargs(self):\n kwargs = super(CustomerFilterTestView, self).get_form_kwargs()\n kwargs.update({\n 'user': self.request.user,\n })\n return kwargs\n</code></pre>\n\n<p>In templates/proposals/customer_filter_test.html:</p>\n\n<pre><code>{% extends \"base/base.html\" %}\n\n{% block title_block %}\n&lt;title&gt;Customer Filter Test&lt;/title&gt;\n{% endblock title_block %}\n\n{% block header_add %}\n&lt;style&gt;\n label {\n min-width: 300px;\n }\n&lt;/style&gt;\n{% endblock header_add %}\n\n{% block content_body %}\n&lt;form action=\"\" method=\"POST\"&gt;\n {% csrf_token %}\n &lt;table&gt;\n {{ form.as_table }}\n &lt;/table&gt;\n &lt;input type=\"submit\" value=\"Save\" class=\"btn btn-default\" /&gt;\n&lt;/form&gt;\n{% endblock content_body %}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16342/" ]
I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example: ``` class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() ``` Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in. Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :( **UPDATE**: The solution is here: <http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/> sending `request.user` to a model.
Use threadlocals if you want to get **current** user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware ``` from threading import local _thread_locals = local() def get_current_user(): return getattr(getattr(_thread_locals, 'user', None),'id',None) class ThreadLocals(object): """Middleware that gets various objects from the request object and saves them in thread local storage.""" def process_request(self, request): _thread_locals.user = getattr(request, 'user', None) ``` Check the documentation on how to use middleware classes. Then anywhere in code you can call ``` user = threadlocals.get_current_user ```
160,022
<p>Is there anyway to determine if a ResourceManager contains a named resource? Currently I am catching the MissingManifestResourceException but I hate having to use Exceptions for non-exceptional situations. There must be some way to enumerate the name value pairs of a ResourceManager through reflection, or something?</p> <p><strong>EDIT</strong>: A little more detail. The resources are not in executing assembly, however the ResourceManager is working just fine. If I try <code>_resourceMan.GetResourceSet(_defaultCuture, false, true)</code> I get null, whereas if I try <code>_resourceMan.GetString("StringExists")</code> I get a string back.</p>
[ { "answer_id": 160054, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "<p>I think you can use something like <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcenames(VS.80).aspx\" rel=\"nofollow noreferrer\">Assembly.GetManifestResourceNames</a> to enumerate the list of resources available in the Assembly's manifest. It isn't pretty and doesn't solve all of the corner cases, but works if required.</p>\n" }, { "answer_id": 162013, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 6, "selected": true, "text": "<p>You can use the ResourceSet to do that, only it loads all the data into memory if you enumerate it. Here y'go:</p>\n\n<pre><code> // At startup.\n ResourceManager mgr = Resources.ResourceManager;\n List&lt;string&gt; keys = new List&lt;string&gt;();\n\n ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true);\n foreach (DictionaryEntry o in set)\n {\n keys.Add((string)o.Key);\n }\n mgr.ReleaseAllResources();\n\n Console.WriteLine(Resources.A);\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ]
Is there anyway to determine if a ResourceManager contains a named resource? Currently I am catching the MissingManifestResourceException but I hate having to use Exceptions for non-exceptional situations. There must be some way to enumerate the name value pairs of a ResourceManager through reflection, or something? **EDIT**: A little more detail. The resources are not in executing assembly, however the ResourceManager is working just fine. If I try `_resourceMan.GetResourceSet(_defaultCuture, false, true)` I get null, whereas if I try `_resourceMan.GetString("StringExists")` I get a string back.
You can use the ResourceSet to do that, only it loads all the data into memory if you enumerate it. Here y'go: ``` // At startup. ResourceManager mgr = Resources.ResourceManager; List<string> keys = new List<string>(); ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true); foreach (DictionaryEntry o in set) { keys.Add((string)o.Key); } mgr.ReleaseAllResources(); Console.WriteLine(Resources.A); ```
160,030
<p>Is there a macro that does it? Which DTE objects to use?</p>
[ { "answer_id": 160039, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>I don't know what DTE functions to use, but you could very simply record a macro that could pretty much do it:</p>\n\n<ol>\n<li>Go to the top of the file</li>\n<li>ctrl - shift - R (start recording)</li>\n<li>ctrl - I (incremental search)</li>\n<li>{ (search for the first { character).</li>\n<li>F9 (set breakpoint)</li>\n<li>ctrl - ] (go to matching } character)</li>\n<li>ctrl - shift - R (stop recording)</li>\n</ol>\n\n<p>Now just run this over and over (ctrl - shift P repeatedly) until you reach the end of the file.</p>\n\n<p>If you have namespaces, then change 4. to:</p>\n\n<ol start=\"4\">\n<li>( (search for \"(\" at the start of the function definition)</li>\n<li>esc (stop incremental search)</li>\n<li>ctrl - I (incremental search again)</li>\n<li>{ (start of function body)</li>\n</ol>\n\n<p>This kind of thing can be infinitely modified to suit your codebase </p>\n" }, { "answer_id": 160839, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": -1, "selected": false, "text": "<p>Put this at the top of the file:</p>\n\n<pre><code>#define WANT_BREAK_IN_EVERY_FUNCTION\n\n#ifdef WANT_BREAK_IN_EVERY_FUNCTION\n#define DEBUG_BREAK DebugBreak();\n#else\n#define DEBUG_BREAK \n#endif\n</code></pre>\n\n<p>then insert DEBUG_BREAK in the beginning of every function, like this: </p>\n\n<pre><code>void function1()\n{\n DEBUG_BREAK\n // the rest of the function\n}\n\nvoid function2()\n{\n DEBUG_BREAK\n // the rest of the function\n}\n</code></pre>\n\n<p>When you no longer want the debug breaks, comment the line </p>\n\n<pre><code>// #define WANT_BREAK_IN_EVERY_FUNCTION\n</code></pre>\n\n<p>at the top of the file.</p>\n" }, { "answer_id": 188829, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<p>Here's how something similar could be achieved in WinDbg:</p>\n\n<pre><code>bm mymodule!CSpam::*\n</code></pre>\n\n<p>This puts breakpoint in every method of class (or namespace) <code>CSpam</code> in module <code>mymodule</code>.</p>\n\n<p>I'm still looking for anything close to this functionality in Visual Studio.</p>\n" }, { "answer_id": 357807, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 3, "selected": false, "text": "<p>Here's a quick implementation of 1800 INFORMATION's idea:</p>\n\n<pre><code>Sub TemporaryMacro()\n DTE.ActiveDocument.Selection.StartOfDocument()\n Dim returnValue As vsIncrementalSearchResult\n While True\n DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.StartForward()\n returnValue = DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.AppendCharAndSearch(AscW(\"{\"))\n DTE.ActiveDocument.ActiveWindow.Object.ActivePane.IncrementalSearch.Exit()\n If Not (returnValue = vsIncrementalSearchResult.vsIncrementalSearchResultFound) Then\n Return\n End If\n DTE.ExecuteCommand(\"Debug.ToggleBreakpoint\")\n DTE.ExecuteCommand(\"Edit.GotoBrace\")\n DTE.ActiveDocument.Selection.CharRight()\n End While\nEnd Sub\n</code></pre>\n" }, { "answer_id": 855320, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 2, "selected": false, "text": "<p>Like Constantin's method... This seems like windbg territory.</p>\n\n<p>Since you have the cpp, (even if you didn't you could script something to get by), it should be no problem to use <a href=\"http://msdn.microsoft.com/en-us/library/cc266308.aspx\" rel=\"nofollow noreferrer\">logger</a> part of the debugging tools for windows... it's a very handy tool, shame so few people use it.</p>\n\n<p>logger debug's C/COM/C++ easily, with rich symbolic info, hooks/profiling/flexible instrumentation;</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/cc266315.aspx\" rel=\"nofollow noreferrer\"><em>One way to activate Logger is to start CDB or WinDbg and attach to a user-mode target application as usual. Then, use the !logexts.logi or !logexts.loge extension command.\nThis will insert code at the current breakpoint that will jump off to a routine that loads and initializes Logexts.dll in the target application process. This is referred to as \"injecting Logger into the target application.\"</em></a></p>\n" }, { "answer_id": 3370624, "author": "RichieHindle", "author_id": 21886, "author_profile": "https://Stackoverflow.com/users/21886", "pm_score": 4, "selected": false, "text": "<p>(This is not quite what you're asking for, but almost:)</p>\n\n<p>You can put a breakpoint on <strong>every member function of a class</strong> in Visual Studio by bringing up the <em>New Breakpoint</em> dialog and entering:</p>\n\n<pre><code>CMyClass::*\n</code></pre>\n\n<p>See <a href=\"http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx</a> for more details.</p>\n" }, { "answer_id": 20211467, "author": "alexkovelsky", "author_id": 2874220, "author_profile": "https://Stackoverflow.com/users/2874220", "pm_score": 0, "selected": false, "text": "<p>There is a macro, but I tested it only with c#.</p>\n\n<pre><code>Sub BreakAtEveryFunction()\nFor Each project In DTE.Solution.Projects\n SetBreakpointOnEveryFunction(project)\nNext project\nEnd Sub\n\n\nSub SetBreakpointOnEveryFunction(ByVal project As Project)\nDim cm = project.CodeModel\n\n' Look for all the namespaces and classes in the \n' project.\nDim list As List(Of CodeFunction)\nlist = New List(Of CodeFunction)\nDim ce As CodeElement\nFor Each ce In cm.CodeElements\n If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then\n ' Determine whether that namespace or class \n ' contains other classes.\n GetClass(ce, list)\n End If\nNext\n\nFor Each cf As CodeFunction In list\n\n DTE.Debugger.Breakpoints.Add(cf.FullName)\nNext\n\nEnd Sub\n\nSub GetClass(ByVal ct As CodeElement, ByRef list As List(Of CodeFunction))\n\n' Determine whether there are nested namespaces or classes that \n' might contain other classes.\nDim aspace As CodeNamespace\nDim ce As CodeElement\nDim cn As CodeNamespace\nDim cc As CodeClass\nDim elements As CodeElements\nIf (TypeOf ct Is CodeNamespace) Then\n cn = CType(ct, CodeNamespace)\n elements = cn.Members\nElse\n cc = CType(ct, CodeClass)\n elements = cc.Members\nEnd If\nTry\n For Each ce In elements\n If (TypeOf ce Is CodeNamespace) Or (TypeOf ce Is CodeClass) Then\n GetClass(ce, list)\n End If\n If (TypeOf ce Is CodeFunction) Then\n list.Add(ce)\n End If\n Next\nCatch\nEnd Try\nEnd Sub\n</code></pre>\n" }, { "answer_id": 37243519, "author": "joshcomley", "author_id": 64519, "author_profile": "https://Stackoverflow.com/users/64519", "pm_score": 0, "selected": false, "text": "<p>Here's one way to do it (I warn you it is hacky):</p>\n\n<pre><code>EnvDTE.TextSelection textSelection = (EnvDTE.TextSelection)dte.ActiveWindow.Selection;\n// I'm sure there's a better way to get the line count than this...\nvar lines = File.ReadAllLines(dte.ActiveDocument.FullName).Length;\nvar methods = new List&lt;CodeElement&gt;();\nvar oldLine = textSelection.AnchorPoint.Line;\nvar oldLineOffset = textSelection.AnchorPoint.LineCharOffset;\nEnvDTE.CodeElement codeElement = null;\nfor (var i = 0; i &lt; lines; i++)\n{\n try\n {\n textSelection.MoveToLineAndOffset(i, 1);\n // I'm sure there's a better way to get a code element by point than this...\n codeElement = textSelection.ActivePoint.CodeElement[vsCMElement.vsCMElementFunction];\n if (codeElement != null)\n {\n if (!methods.Contains(codeElement))\n {\n methods.Add(codeElement);\n }\n }\n }\n catch\n {\n //MessageBox.Show(\"Add error handling here.\");\n }\n}\n\n// Restore cursor position\ntextSelection.MoveToLineAndOffset(oldLine, oldLineOffset);\n\n// This could be in the for-loop above, but it's here instead just for\n// clarity of the two separate jobs; find all methods, then add the\n// breakpoints\nforeach (var method in methods)\n{\n dte.Debugger.Breakpoints.Add(\n Line: method.StartPoint.Line,\n File: dte.ActiveDocument.FullName);\n}\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20310/" ]
Is there a macro that does it? Which DTE objects to use?
(This is not quite what you're asking for, but almost:) You can put a breakpoint on **every member function of a class** in Visual Studio by bringing up the *New Breakpoint* dialog and entering: ``` CMyClass::* ``` See <http://blogs.msdn.com/b/habibh/archive/2009/09/10/class-breakpoint-how-to-set-a-breakpoint-on-a-c-class-in-the-visual-studio-debugger.aspx> for more details.
160,045
<p>Is there a way to place a watch on variable and only have Visual Studio break when that value changes?</p> <p>It would make it so much easier to find tricky state issues.</p> <p>Can this be done?</p> <p>Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.</p>
[ { "answer_id": 160048, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 2, "selected": false, "text": "<p>Right click on the breakpoint works fine for me (though mostly I am using it for conditional breakpoints on specific variable values. Even breaking on expressions involving a thread name works which is very useful if you're trying to spot threading issues).</p>\n" }, { "answer_id": 160049, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>I remember the way you described it using <a href=\"http://en.wikipedia.org/wiki/Visual_Basic#Timeline\" rel=\"nofollow noreferrer\">Visual Basic 6.0</a>. In Visual Studio, the only way I have found so far is by specifying a <a href=\"http://msdn.microsoft.com/en-us/library/7sye83ce.aspx\" rel=\"nofollow noreferrer\">breakpoint condition</a>.</p>\n" }, { "answer_id": 160074, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 8, "selected": true, "text": "<p>In the Visual Studio 2005 menu:</p>\n\n<p><em>Debug</em> -> <em>New Breakpoint</em> -> <em>New Data Breakpoint</em></p>\n\n<p>Enter:</p>\n\n<pre><code>&amp;myVariable\n</code></pre>\n" }, { "answer_id": 160083, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>You can use a memory watchpoint in unmanaged code. Not sure if these are available in managed code though.</p>\n" }, { "answer_id": 160107, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 5, "selected": false, "text": "<p>You can also choose to break explicitly in code:</p>\n\n<pre><code>// Assuming C#\nif (condition)\n{\n System.Diagnostics.Debugger.Break();\n}\n</code></pre>\n\n<p>From MSDN:</p>\n\n<blockquote>\n <p>Debugger.Break:\n If no debugger is attached, users are\n asked if they want to attach a\n debugger. If yes, the debugger is\n started. If a debugger is attached,\n the debugger is signaled with a user\n breakpoint event, and the debugger\n suspends execution of the process just\n as if a debugger breakpoint had been\n hit.</p>\n</blockquote>\n\n<p>This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.</p>\n" }, { "answer_id": 5206696, "author": "momboco", "author_id": 646316, "author_profile": "https://Stackoverflow.com/users/646316", "pm_score": 4, "selected": false, "text": "<p>Imagine you have a class called A with the following declaration.</p>\n\n<pre><code>class A \n{ \n public: \n A();\n\n private:\n int m_value;\n};\n</code></pre>\n\n<p>You want the program to stop when someone modifies the value of \"m_value\".</p>\n\n<p>Go to the class definition and put a breakpoint in the constructor of A.</p>\n\n<pre><code>A::A()\n{\n ... // set breakpoint here\n}\n</code></pre>\n\n<p>Once we stopped the program:</p>\n\n<p>Debug -> New Breakpoint -> New Data Breakpoint ...</p>\n\n<p>Address: &amp;(this->m_value)<br>\nByte Count: 4 (Because int has 4 bytes)</p>\n\n<p>Now, we can resume the program. The debugger will stop when the value is changed.</p>\n\n<p>You can do the same with inherited classes or compound classes.</p>\n\n<pre><code>class B\n{\n private:\n A m_a;\n};\n</code></pre>\n\n<p>Address: &amp;(this->m_a.m_value)</p>\n\n<p>If you don't know the number of bytes of the variable you want to inspect, you can use the sizeof operator.</p>\n\n<p>For example:</p>\n\n<pre><code>// to know the size of the word processor, \n// if you want to inspect a pointer.\nint wordTam = sizeof (void* ); \n</code></pre>\n\n<p>If you look at the \"Call stack\" you can see the function that changed the value of the variable.</p>\n" }, { "answer_id": 6040929, "author": "wip", "author_id": 758666, "author_profile": "https://Stackoverflow.com/users/758666", "pm_score": 1, "selected": false, "text": "<p>You can probably make a clever use of the <a href=\"http://msdn.microsoft.com/en-us/library/ms679297%28v=vs.85%29.aspx\" rel=\"nofollow\">DebugBreak()</a> function.</p>\n" }, { "answer_id": 8171391, "author": "Julien N", "author_id": 28544, "author_profile": "https://Stackoverflow.com/users/28544", "pm_score": 2, "selected": false, "text": "<p>If you are using WPF, there is an awesome tool : <a href=\"http://wpfinspector.codeplex.com/\" rel=\"nofollow\">WPF Inspector</a>.<br>\nIt attaches itself to a WPF app and display the full tree of controls with the all properties, an it allows you (amongst other things) to break on any property change.</p>\n\n<p>But sadly I didn't find any tool that would allow you to do the same with ANY property or variable.</p>\n" }, { "answer_id": 18616729, "author": "Marcello", "author_id": 2531142, "author_profile": "https://Stackoverflow.com/users/2531142", "pm_score": 4, "selected": false, "text": "<p>Change the variable into a property and add a breakpoint in the set method. Example:</p>\n\n<pre><code>private bool m_Var = false;\nprotected bool var\n{\n get { \n return m_var;\n }\n\n set { \n m_var = value;\n }\n}\n</code></pre>\n" }, { "answer_id": 34020681, "author": "PRIME", "author_id": 1875585, "author_profile": "https://Stackoverflow.com/users/1875585", "pm_score": 1, "selected": false, "text": "<p>You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.</p>\n" }, { "answer_id": 37869667, "author": "Craig", "author_id": 525558, "author_profile": "https://Stackoverflow.com/users/525558", "pm_score": 5, "selected": false, "text": "<p>In <strong>Visual Studio 2015</strong>, you can place a breakpoint on the <code>set</code> accessor of an Auto-Implemented Property and the debugger will break when the property is updated</p>\n<pre><code>public bool IsUpdated\n{\n get;\n set; //set breakpoint on this line\n}\n</code></pre>\n<p><strong>Update</strong></p>\n<p>Alternatively; @AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the <code>get;</code> or <code>set;</code> and hit <code>F9</code> and a breakpoint will be placed accordingly. Nice!</p>\n<pre><code>public bool IsUpdated { get; set; }\n</code></pre>\n" }, { "answer_id": 54180293, "author": "R Risack", "author_id": 4559295, "author_profile": "https://Stackoverflow.com/users/4559295", "pm_score": 2, "selected": false, "text": "<p>As Peter Mortensen wrote:</p>\n\n<blockquote>\n <p>In the Visual Studio 2005 menu:</p>\n \n <p>Debug -> New Breakpoint -> New Data Breakpoint</p>\n \n <p>Enter: &amp;myVariable</p>\n</blockquote>\n\n<p>Additional information:</p>\n\n<p>Obviously, the system must know which address in memory to watch. \nSo \n- set a normal breakpoint to the initialisation of <code>myVariable</code> (or <code>myClass.m_Variable</code>)\n- run the system and wait till it stops at that breakpoint.\n- Now the Menu entry is enabled, and you can watch the variable by entering <code>&amp;myVariable</code>,\nor the instance by entering <code>&amp;myClass.m_Variable</code>. Now the addresses are well defined.</p>\n\n<p>Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this. </p>\n" }, { "answer_id": 54657265, "author": "Matt", "author_id": 6016987, "author_profile": "https://Stackoverflow.com/users/6016987", "pm_score": 3, "selected": false, "text": "<p><strong>Update in 2019:</strong></p>\n\n<p>This is now officially supported in Visual Studio 2019 Preview 2 for .Net Core 3.0 or higher. Of course, you may have to put some thoughts in potential risks of using a Preview version of IDE. I imagine in the near future this will be included in the official Visual Studio.</p>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/\" rel=\"noreferrer\">https://blogs.msdn.microsoft.com/visualstudio/2019/02/12/break-when-value-changes-data-breakpoints-for-net-core-in-visual-studio-2019/</a></p>\n\n<blockquote>\n <p>Fortunately, data breakpoints are no longer a C++ exclusive because they are now available for .NET Core (3.0 or higher) in Visual Studio 2019 Preview 2!</p>\n</blockquote>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Is there a way to place a watch on variable and only have Visual Studio break when that value changes? It would make it so much easier to find tricky state issues. Can this be done? Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.
In the Visual Studio 2005 menu: *Debug* -> *New Breakpoint* -> *New Data Breakpoint* Enter: ``` &myVariable ```
160,051
<p>I'm working on a database that needs to represent computers and their users. Each computer can have multiple users and each user can be associated with multiple computers, so it's a classic many-to-many relationship. However, there also needs to be a concept of a "primary" user. I have to be able to join against the primary user to list all computers with their primary users. I'm not sure what the best way structure this in the database:</p> <p>1) As I'm currently doing: linking table with a boolean IsPrimary column. Joining requires something like ON (c.computer_id = l.computer_id AND l.is_primary = 1). It works, but it feels wrong because it's not easy to constrain the data to only have one primary user per computer.</p> <p>2) A field on the computer table that points directly at a user row, all rows in the user table represent non-primary users. This represents the one-primary-per-computer constraint better, but makes getting a list of computer-users harder.</p> <p>3) A field on the computer table linking to a row in the linking table. Feels strange...</p> <p>4) Something else?</p> <p>What is the 'relational' way to describe this relationship?</p> <p>EDIT: @Mark Brackett: The third option seems a lot less strange to me now that you've shown how nice it can look. For some reason I didn't even think of using a compound foreign key, so I was thinking I'd have to add an identity column on the linking table to make it work. Looks great, thanks! </p> <p>@j04t: Cool, I'm glad we agree on #3 now.</p>
[ { "answer_id": 160062, "author": "Sijin", "author_id": 8884, "author_profile": "https://Stackoverflow.com/users/8884", "pm_score": 0, "selected": false, "text": "<p>Since the primary user is a function of the computer and the user I would tend to go with your approach of having the primaryUser being a column on the linking table.</p>\n\n<p>The other alternative that I can think of is to have a primaryUser column directly on the computer table itself.</p>\n" }, { "answer_id": 160073, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<p>I would have made another table PRIMARY_USERS with unique on <code>computer_id</code> and making both <code>computer_id</code> and <code>user_id</code> foreign keys of USERS.</p>\n" }, { "answer_id": 160089, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 0, "selected": false, "text": "<p>Either solution 1 or 2 will work. At this point I would ask myself which one will be easier to work with. I've used both methods in different situations though I would generally go with a flag on the linking table and then force a unique constraint on computer_id and isPrimaryUser, that way you ensure that each computer will only have one primary user.</p>\n" }, { "answer_id": 160099, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 0, "selected": false, "text": "<p>2 feels right to me, but I would test out 1, 2 and 3 for performance on the sorts of queries you normally perform and the sorts of data volumes you have. </p>\n\n<p>As a general rule of thumb I tend to believe that where there is a choice of implementations you should look to your query requirements and design your schema so you get the best performance and resource utilisation in the most common case.</p>\n\n<p>In the rare situation where you have equally common cases which suggest opposite implementations, then use Occam's razor.</p>\n" }, { "answer_id": 160108, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 1, "selected": false, "text": "<p>Edit -- \nI didn't think properly about it the first 3 times through...\nI vote for --\n(Number 3 solution)</p>\n\n<p>Users</p>\n\n<pre><code>user id (pk)\n</code></pre>\n\n<p>Computers</p>\n\n<pre><code>computer id (pk)\nprimary user id (fk -&gt; computer users id)\n</code></pre>\n\n<p>Computer Users</p>\n\n<pre><code>user id (pk) (fk -&gt; user id)\ncomputer id (pk) (fk -&gt; user id)\n</code></pre>\n\n<p>This is the best solution I can think of.</p>\n\n<p>Why I like this design.</p>\n\n<p>1) Since this is a relationship involving computers and users I like the idea of being able to associate a user to multiple computers as the primary user. This may not ever occur where this database is being used though.</p>\n\n<p>2) The reason I don't like having the primary_user on the link table </p>\n\n<pre><code> (computer_users.primary_user_id fk-&gt; users.user_id)\n</code></pre>\n\n<p>is to prevent a computer from ever having multiple primary users.</p>\n\n<p>Given those reasons Number 3 solution looks better since you will never run into some possible problems I see with the other approaches.</p>\n\n<p>Solution 1 problem - Possible to have multiple primary users per computer.</p>\n\n<p>Solution 2 problem - Computer links to a primary user when the computer and user aren't link to each other.</p>\n\n<pre><code>computer.primaryUser = user.user_id\ncomputer_users.user_id != user.user_id\n</code></pre>\n\n<p>Solution 3 problem - It does seem kind of odd doesn't it? Other than that I can't think of anything.</p>\n\n<p>Solution 4 problem - I can't think of any other way of doing it.</p>\n\n<hr>\n\n<p>This is the 4th edit so I hope it makes sense still.</p>\n" }, { "answer_id": 160123, "author": "Mark", "author_id": 5904, "author_profile": "https://Stackoverflow.com/users/5904", "pm_score": 0, "selected": false, "text": "<p>We have a similar situation in the application I work on where we have Accounts that can have many Customers attached but only one should be the Primary customer.</p>\n\n<p>We use a link table (as you have) but have a Sequence value on the link table. The Primary user is the one with Sequence = 1. Then, <strong>we have an Index on that Link table for AccountID and Sequence to ensure that the combination of AccountID</strong> and Sequence is unique (thereby ensuring that no two Customers can be the Primary one on an Account). So you would have:</p>\n\n<pre><code>LEFT JOIN c.computer_id = l.computer_id AND l.sequence = 1\n</code></pre>\n" }, { "answer_id": 160129, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "<p>Option 3, though it may feel strange, is the closest to what you want to model. You'd do something like:</p>\n\n<pre><code>User { \n UserId \n PRIMARY KEY (UserId) \n}\n\nComputer { \n ComputerId, PrimaryUserId\n PRIMARY KEY (UserId) \n FOREIGN KEY (ComputerId, PrimaryUserId) \n REFERENCES Computer_User (ComputerId, UserId) \n}\n\nComputer_User { \n ComputerId, UserId \n PRIMARY KEY (ComputerId, UserId)\n FOREIGN KEY (ComputerId) \n REFERENCES Computer (ComputerId)\n FOREIGN KEY (UserId) \n REFERENCES User (UserId)\n}\n</code></pre>\n\n<p>Which gives you 0 or 1 primary user (the PrimaryUserId can be nullable if you want), that must be in Computer_User. Edit: If a user can only be primary for 1 computer, then a UNIQUE CONSTRAINT on Computer.PrimaryUserId will enforce that. Note that there is no requirement that all users be a primary on some computer (that would be a 1:1 relationship, and would call for them to be in the same table).</p>\n\n<p>Edit: Some queries to show you the simplicity of this design</p>\n\n<pre><code>--All users of a computer\nSELECT User.* \nFROM User \nJOIN Computer_User ON \n User.UserId = Computer_User.UserId \nWHERE \n Computer_User.ComputerId = @computerId\n\n--Primary user of a computer\nSELECT User.* \nFROM User \nJOIN Computer ON \n User.UserId = Computer.PrimaryUserId\nWHERE \n Computer.ComputerId = @computerId\n\n--All computers a user has access to\nSELECT Computer.*\nFROM Computer\nJOIN Computer_User ON\n Computer.ComputerId = Computer_User.ComputerId\nWHERE\n Computer_User.UserId = @userId\n\n--Primary computer for a user\nSELECT Computer.*\nFROM Computer\nWHERE\n PrimaryUserId = @userId\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9617/" ]
I'm working on a database that needs to represent computers and their users. Each computer can have multiple users and each user can be associated with multiple computers, so it's a classic many-to-many relationship. However, there also needs to be a concept of a "primary" user. I have to be able to join against the primary user to list all computers with their primary users. I'm not sure what the best way structure this in the database: 1) As I'm currently doing: linking table with a boolean IsPrimary column. Joining requires something like ON (c.computer\_id = l.computer\_id AND l.is\_primary = 1). It works, but it feels wrong because it's not easy to constrain the data to only have one primary user per computer. 2) A field on the computer table that points directly at a user row, all rows in the user table represent non-primary users. This represents the one-primary-per-computer constraint better, but makes getting a list of computer-users harder. 3) A field on the computer table linking to a row in the linking table. Feels strange... 4) Something else? What is the 'relational' way to describe this relationship? EDIT: @Mark Brackett: The third option seems a lot less strange to me now that you've shown how nice it can look. For some reason I didn't even think of using a compound foreign key, so I was thinking I'd have to add an identity column on the linking table to make it work. Looks great, thanks! @j04t: Cool, I'm glad we agree on #3 now.
Option 3, though it may feel strange, is the closest to what you want to model. You'd do something like: ``` User { UserId PRIMARY KEY (UserId) } Computer { ComputerId, PrimaryUserId PRIMARY KEY (UserId) FOREIGN KEY (ComputerId, PrimaryUserId) REFERENCES Computer_User (ComputerId, UserId) } Computer_User { ComputerId, UserId PRIMARY KEY (ComputerId, UserId) FOREIGN KEY (ComputerId) REFERENCES Computer (ComputerId) FOREIGN KEY (UserId) REFERENCES User (UserId) } ``` Which gives you 0 or 1 primary user (the PrimaryUserId can be nullable if you want), that must be in Computer\_User. Edit: If a user can only be primary for 1 computer, then a UNIQUE CONSTRAINT on Computer.PrimaryUserId will enforce that. Note that there is no requirement that all users be a primary on some computer (that would be a 1:1 relationship, and would call for them to be in the same table). Edit: Some queries to show you the simplicity of this design ``` --All users of a computer SELECT User.* FROM User JOIN Computer_User ON User.UserId = Computer_User.UserId WHERE Computer_User.ComputerId = @computerId --Primary user of a computer SELECT User.* FROM User JOIN Computer ON User.UserId = Computer.PrimaryUserId WHERE Computer.ComputerId = @computerId --All computers a user has access to SELECT Computer.* FROM Computer JOIN Computer_User ON Computer.ComputerId = Computer_User.ComputerId WHERE Computer_User.UserId = @userId --Primary computer for a user SELECT Computer.* FROM Computer WHERE PrimaryUserId = @userId ```
160,104
<p>I've been using this long command:</p> <pre><code>svn st | awk '/\?/ {print $2}' | xargs svn add </code></pre> <p>Similarly, to svn rm files I accidentally deleted with normal rm with :</p> <pre><code>svn st | awk '/\!/ {print $2}' | xargs svn rm --force </code></pre> <p>I guess I can write a bash function to do these two, but I'd prefer an interactive add/rm like the one git has.</p>
[ { "answer_id": 160177, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 3, "selected": false, "text": "<p>I use a generalization of the command line that you run, called <code>svnapply.sh</code>. I did not write it, but I don't remember where I found it. Hopefully, the original author will forgive me for reposting it here:</p>\n\n<pre><code>#!/bin/bash\n#\n# Applies arbitrary commands to any svn status. e.g.\n#\n# Delete all non-svn files (escape the ? from the shell):\n# svnapply \\? rm\n#\n# List all conflicted files:\n# svnapply C ls -l\n\nAPPLY=$1\nshift\n\nsvn st | egrep \"^\\\\${APPLY}[ ]+\" | \\\nsed -e \"s|^\\\\${APPLY}[ ]*||\" | \\\nsed -e \"s|\\\\\\\\|/|g\" | \\\nxargs -i \"$@\" '{}'\n</code></pre>\n\n<p>Per the comments, the script allows you to run arbitrary commands against all files with the same status.</p>\n\n<p>Update: </p>\n\n<p>It would not be too difficult to write a script that takes a file path as an argument and prompts the user for add/delete and then does the appropriate thing for that file. Chaining that together with the above script would get you what you want.</p>\n" }, { "answer_id": 160191, "author": "Colin Jensen", "author_id": 9884, "author_profile": "https://Stackoverflow.com/users/9884", "pm_score": 0, "selected": false, "text": "<p>Use a GUI that can show you all the untracked files, then select all and add. Any decent SVN gui should provide this functionality.</p>\n\n<p>That said, be careful you really want all those files. </p>\n" }, { "answer_id": 162455, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 0, "selected": false, "text": "<p>TortoiseSVN has the option of showing unversioned files in the Commit and Show Changes dialogs. You can right click a file to 'Add' it or to mark it as ignored.</p>\n\n<p>If you are using Visual Studio:\nThe latest stable version of AnkhSVN has a similar command, but in most cases it only shows the files you should add. (The project provides a list of files to version to the SCC provider; other files are ignored automatically)</p>\n" }, { "answer_id": 1515401, "author": "Mark Shust", "author_id": 183810, "author_profile": "https://Stackoverflow.com/users/183810", "pm_score": 3, "selected": false, "text": "<p>there's an easier line...</p>\n\n<pre><code>svn add `svn status | grep ?`\n</code></pre>\n\n<p>then you can set it up as an alias in ~/.bashrc such as</p>\n\n<pre><code>alias svn-addi='svn add `svn status | grep ?`'\n</code></pre>\n" }, { "answer_id": 4605024, "author": "chiborg", "author_id": 130121, "author_profile": "https://Stackoverflow.com/users/130121", "pm_score": 1, "selected": false, "text": "<p>There is a <a href=\"https://stackoverflow.com/questions/1068506/svn-add-interactive\">similar question</a> which contains a <a href=\"https://stackoverflow.com/questions/1068506/svn-add-interactive/1321101#1321101\">nice Ruby script</a> that gives you the option to add, ignore or skip new files. I've tried it and it worked for me. No GUI needed, only Ruby.</p>\n" }, { "answer_id": 18706236, "author": "Johnny Utahh", "author_id": 605356, "author_profile": "https://Stackoverflow.com/users/605356", "pm_score": 3, "selected": false, "text": "<p>This adds all svn-untracked and -unversioned files in the current directory, recursing through all subdirectories:</p>\n\n<pre><code>svn add --force ./*\n</code></pre>\n\n<p>Works for me in MacOS 10.6+ and Ubuntu 10+, with svn 1.6+. This does not provide any per-file, user-interactivity; I don't know how to do that.</p>\n\n<p>This will also add svn-ignored files, for better or worse.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13200/" ]
I've been using this long command: ``` svn st | awk '/\?/ {print $2}' | xargs svn add ``` Similarly, to svn rm files I accidentally deleted with normal rm with : ``` svn st | awk '/\!/ {print $2}' | xargs svn rm --force ``` I guess I can write a bash function to do these two, but I'd prefer an interactive add/rm like the one git has.
I use a generalization of the command line that you run, called `svnapply.sh`. I did not write it, but I don't remember where I found it. Hopefully, the original author will forgive me for reposting it here: ``` #!/bin/bash # # Applies arbitrary commands to any svn status. e.g. # # Delete all non-svn files (escape the ? from the shell): # svnapply \? rm # # List all conflicted files: # svnapply C ls -l APPLY=$1 shift svn st | egrep "^\\${APPLY}[ ]+" | \ sed -e "s|^\\${APPLY}[ ]*||" | \ sed -e "s|\\\\|/|g" | \ xargs -i "$@" '{}' ``` Per the comments, the script allows you to run arbitrary commands against all files with the same status. Update: It would not be too difficult to write a script that takes a file path as an argument and prompts the user for add/delete and then does the appropriate thing for that file. Chaining that together with the above script would get you what you want.
160,141
<p>C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.</p> <pre><code> private void SetProgressBar(string text, int position, int max) { try { int percent = (100 * position) / max; //when max is 0 bug hits string txt = text + String.Format(". {0}%", percent); SetStatus(txt); } catch { } } </code></pre>
[ { "answer_id": 160146, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 4, "selected": false, "text": "<pre><code>int percent = 0\nif (max != 0) percent = (100*position) / max\n</code></pre>\n" }, { "answer_id": 160148, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 2, "selected": false, "text": "<p>Check for zero.</p>\n\n<pre><code>if ( max == 0 ) {\n txt = \"0%\";\n} else {\n // Do the other stuff....\n</code></pre>\n" }, { "answer_id": 160149, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 3, "selected": false, "text": "<p>Well, that entirely depends on the behaviour you want. If the maximum value of your program bar is zero, is it full? Is it empty? This is a design choice, and when you've chosen, just test for max == 0 and deploy your answer.</p>\n" }, { "answer_id": 160150, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 3, "selected": false, "text": "<ul>\n<li>You can throw an exception.</li>\n<li>You can do <code>int percent = ( max &gt; 0 ) ? (100 * position) / max : 0;</code></li>\n<li>You can choose to do nothing instead of assigning a value to percent.</li>\n<li>many, many other things...</li>\n</ul>\n\n<p>Depends on what you want.</p>\n" }, { "answer_id": 160154, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 2, "selected": false, "text": "<p>This is not a C# problem, it's a math problem. Division by zero is undefined. Have an if statement that checks whether max > 0 and only execute your division then.</p>\n" }, { "answer_id": 160156, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 0, "selected": false, "text": "<p>Well, if max is zero, then there is no progress to be made. Try catching the exception where this is called. That is probably the place to decide whether there is a problem or if the progress bar should be set at zero or at 100%.</p>\n" }, { "answer_id": 160157, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<p>I guess the root question is: Does it make sense to even call this function where max is '0'? If yes, then I'd add special handling to it i.e.:</p>\n\n<pre><code>if (max == 0) \n{\n //do special handling here\n}\nelse\n{\n //do normal code here\n}\n</code></pre>\n\n<p>If 0 doesn't make sense, I'd investigate where it's coming from.</p>\n" }, { "answer_id": 160158, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 0, "selected": false, "text": "<p>You would need a guard clause which checks for max == 0. </p>\n\n<pre><code>private void SetProgressBar(string text, int position, int max)\n{\n if(max == 0)\n return;\n int percent = (100 * position) / max; //when max is 0 bug hits\n string txt = text + String.Format(\". {0}%\", percent);\n SetStatus(txt);\n}\n</code></pre>\n\n<p>You could also handle the Divide by Zero exception, as your sample showed, but it is generally more costly to handle exceptions then to set up checks for known bad values.</p>\n" }, { "answer_id": 160160, "author": "Dre", "author_id": 23033, "author_profile": "https://Stackoverflow.com/users/23033", "pm_score": 0, "selected": false, "text": "<p>If you are using this for a download, you'll probably want to show 0% as I assume max would == 0 in this case when you don't KNOW the file size yet.</p>\n\n<pre><code>int percent = 0;\nif (max != 0)\n ...;\n</code></pre>\n\n<p>If you are using this for some other long task, I'd want to assume 100%</p>\n\n<p>But also, since position can never be between 0 and -1, so you'll probably want to drop the 100 * </p>\n" }, { "answer_id": 160161, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>Convert your</p>\n\n<pre><code>int percent = (100 * position) / max;\n</code></pre>\n\n<p>into</p>\n\n<pre><code>int percent;\nif (max != 0)\n percent = (100 * position) / max;\nelse\n percent = 100; // or whatever fits your needs\n</code></pre>\n" }, { "answer_id": 66557189, "author": "Stephen85", "author_id": 11224134, "author_profile": "https://Stackoverflow.com/users/11224134", "pm_score": 0, "selected": false, "text": "<p>You can user a ternary operator.</p>\n<pre><code>int percent = max != 0 ? (100 * position) / max : 0;\n</code></pre>\n<p>This means that when max does not equal zero, to perform the calculation. If it equals 0 then it will set the percent to 0.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int. ``` private void SetProgressBar(string text, int position, int max) { try { int percent = (100 * position) / max; //when max is 0 bug hits string txt = text + String.Format(". {0}%", percent); SetStatus(txt); } catch { } } ```
``` int percent = 0 if (max != 0) percent = (100*position) / max ```
160,144
<p>How can I find the XY coordinates of an HTML element (DIV) from JavaScript if they were not explicitly set?</p>
[ { "answer_id": 160155, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 3, "selected": false, "text": "<p>That can be tricky depending on browser and version. I would suggest using <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a> and the positions plugin.</p>\n" }, { "answer_id": 160180, "author": "wulimaster", "author_id": 21749, "author_profile": "https://Stackoverflow.com/users/21749", "pm_score": -1, "selected": false, "text": "<p>I am not sure what you need it for, and such things are always relative (screen, window, document). But when I needed to figure that out, I found this site helpful:\n<a href=\"http://www.mattkruse.com/javascript/anchorposition/source.html\" rel=\"nofollow noreferrer\">http://www.mattkruse.com/javascript/anchorposition/source.html</a></p>\n\n<p>And I also found that the tooltip plugin someone made for jQuery had all sorts of interesting insight to x,y positioning tricks (look at its viewport class and the underlying support jQuery provides for it).\n<a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/\" rel=\"nofollow noreferrer\">http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/</a></p>\n" }, { "answer_id": 160189, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 3, "selected": false, "text": "<p>You can use a library such as Prototype or jQuery, or you can use <a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"nofollow noreferrer\">this handy function</a>:</p>\n\n<p>It returns an array.</p>\n\n<pre><code>myPos = findPos(document.getElementById('something'))\nx = myPos[0]\ny = myPos[1]\n\nfunction findPos(obj) {\n var curleft = curtop = 0;\n if (obj.offsetParent) {\n curleft = obj.offsetLeft\n curtop = obj.offsetTop\n while (obj = obj.offsetParent) {\n curleft += obj.offsetLeft\n curtop += obj.offsetTop\n }\n }\n return [curleft,curtop];\n}\n</code></pre>\n" }, { "answer_id": 160428, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 5, "selected": false, "text": "<p>Here's how I do it:</p>\n\n<pre><code>// Based on: http://www.quirksmode.org/js/findpos.html\nvar getCumulativeOffset = function (obj) {\n var left, top;\n left = top = 0;\n if (obj.offsetParent) {\n do {\n left += obj.offsetLeft;\n top += obj.offsetTop;\n } while (obj = obj.offsetParent);\n }\n return {\n x : left,\n y : top\n };\n};\n</code></pre>\n" }, { "answer_id": 5004338, "author": "jjthrash", "author_id": 218026, "author_profile": "https://Stackoverflow.com/users/218026", "pm_score": 2, "selected": false, "text": "<p>For what it's worth, here's a recursive version:</p>\n\n<pre><code>function findPos(element) {\n if (element) {\n var parentPos = findPos(element.offsetParent);\n return [\n parentPos.X + element.offsetLeft,\n parentPos.Y + element.offsetTop\n ];\n } else {\n return [0,0];\n }\n}\n</code></pre>\n" }, { "answer_id": 8861193, "author": "ThinkingStiff", "author_id": 918414, "author_profile": "https://Stackoverflow.com/users/918414", "pm_score": 2, "selected": false, "text": "<p>You can add two properties to the <code>Element.prototype</code> to get top/left of any element.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {\n get: function () { return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 ); }\n} );\n\nwindow.Object.defineProperty( Element.prototype, 'documentOffsetLeft', {\n get: function () { return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 ); }\n} );\n</code></pre>\n\n<p>Here's a demo comparing the results to jQuery's <code>offset().top</code> and <code>.left</code>: <a href=\"http://jsfiddle.net/ThinkingStiff/3G7EZ/\" rel=\"nofollow\">http://jsfiddle.net/ThinkingStiff/3G7EZ/</a></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I find the XY coordinates of an HTML element (DIV) from JavaScript if they were not explicitly set?
Here's how I do it: ``` // Based on: http://www.quirksmode.org/js/findpos.html var getCumulativeOffset = function (obj) { var left, top; left = top = 0; if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; } while (obj = obj.offsetParent); } return { x : left, y : top }; }; ```
160,147
<p>Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:</p> <pre><code>class A { public: A(const B&amp; b): mB(b) { }; private: B mB; }; </code></pre> <p>Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?</p>
[ { "answer_id": 160163, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 0, "selected": false, "text": "<p>I don't see how you'd do that with initializer-list syntax, but I'm also a bit sceptical that you'll be able to do anything useful by catching the exception in your constructor. It depends on the design of the classes, obviously, but in what case are you going to fail to create \"mB\", and still have a useful \"A\" object? </p>\n\n<p>You might as well let the exception percolate up, and handle it wherever the constructor for A is being called.</p>\n" }, { "answer_id": 160164, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 8, "selected": true, "text": "<p>Have a read of <a href=\"http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/\" rel=\"noreferrer\">http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/</a>)</p>\n\n<p>Edit: After more digging, these are called \"Function try blocks\".</p>\n\n<p>I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)</p>\n\n<p>To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:</p>\n\n<pre><code>C::C()\ntry : init1(), ..., initn()\n{\n // Constructor\n}\ncatch(...)\n{\n // Handle exception\n}\n</code></pre>\n" }, { "answer_id": 160171, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 4, "selected": false, "text": "<p>It's not particularly pretty:</p>\n\n<pre><code>A::A(const B&amp; b) try : mB(b) \n{ \n // constructor stuff\n}\ncatch (/* exception type */) \n{\n // handle the exception\n}\n</code></pre>\n" }, { "answer_id": 6676341, "author": "Mikhail Semenov", "author_id": 653772, "author_profile": "https://Stackoverflow.com/users/653772", "pm_score": 2, "selected": false, "text": "<p>I know it has been awhile since this discussion started. But that try-and-catch construct mentioned by Adam is part of the C++ standard and is supported by Microsoft VC++ and GNU C++.\nHere is the program that works. By the way the the catch generates automatically another exception to signal about the constructor failure.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;exception&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nclass my_exception: public exception\n{\n string message;\npublic:\n my_exception(const char* message1)\n {\n message = message1;\n }\n\n virtual const char* what() const throw()\n {\n cout &lt;&lt; message &lt;&lt; endl;\n return message.c_str();\n }\n\n virtual ~my_exception() throw() {};\n};\n\nclass E\n{\npublic:\n E(const char* message) { throw my_exception(message);}\n};\n\nclass A\n{\n E p;\npublic:\n A()\n try :p(\"E failure\")\n {\n cout &lt;&lt; \"A constructor\" &lt;&lt; endl;\n }\n catch (const exception&amp; ex)\n {\n cout &lt;&lt; \"Inside A. Constructor failure: \" &lt;&lt; ex.what() &lt;&lt; endl;\n }\n};\n\n\nint main()\n{\n try\n {\n A z;\n }\n catch (const exception&amp; ex)\n {\n cout &lt;&lt; \"In main. Constructor failure: \" &lt;&lt; ex.what() &lt;&lt; endl;\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 35265504, "author": "IceFire", "author_id": 2573127, "author_profile": "https://Stackoverflow.com/users/2573127", "pm_score": 1, "selected": false, "text": "<p>You could work with lazy initialization, though, that is hold a unique_ptr to Reader in MyClass and create it with new. That way, you do not even need the flag has_reader but you can just see if your unique_ptr is initial or not.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;memory&gt;\nusing namespace std;\n\nclass MyOtherClass\n{\npublic:\n MyOtherClass()\n {\n throw std::runtime_error(\"not working\");\n }\n};\n\nclass MyClass\n{\npublic:\n typedef std::unique_ptr&lt;MyOtherClass&gt; MyOtherClassPtr;\n\n MyClass()\n {\n try\n {\n other = std::make_unique&lt;MyOtherClass&gt;();\n }\n catch(...)\n {\n cout &lt;&lt; \"initialization failed.\" &lt;&lt; endl;\n }\n\n cout &lt;&lt; \"other is initialized: \" &lt;&lt; (other ? \"yes\" : \"no\");\n }\n\nprivate:\n std::unique_ptr&lt;MyOtherClass&gt; other;\n};\n\nint main()\n{\n MyClass c;\n\n return 0;\n}\n</code></pre>\n\n<p>Of course, there are also solutions without using exceptions at all but I assumed that this is a prerequisite in your setting.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so: ``` class A { public: A(const B& b): mB(b) { }; private: B mB; }; ``` Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?
Have a read of <http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/>) Edit: After more digging, these are called "Function try blocks". I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :) To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be: ``` C::C() try : init1(), ..., initn() { // Constructor } catch(...) { // Handle exception } ```
160,162
<p>I'm trying to commit to an SVN server hosted on my school's network. I have installed SVN 1.5.2 with binaries downloaded from CollabNet <a href="http://www.collab.net/downloads/community/" rel="nofollow noreferrer">here</a>. The error reported is:</p> <pre><code>svn: Commit failed (details follow): svn: MKACTIVITY of '/opensvn/cs598r/!svn/act/defe271c-f33b-4851-a706-b2906301fed0': authorization failed (http://dna.cs.byu.edu) </code></pre> <p>That's the complete error message - nowhere does it say 403 Forbidden. I have tried deleting my working copy and checking it out again to no avail. I have checked and double-checked that my password and permissions are correct on the server. I have checked that the URL is correct. I can successfully commit from a remote machine, but not from mine. Other members of my team are able to commit from their computers, but when they try from mine, they get the same error. One of the other members of my team is using 1.5.1 CollabNet binaries with no trouble. What about my client is broken?</p>
[ { "answer_id": 160366, "author": "Zed", "author_id": 19202, "author_profile": "https://Stackoverflow.com/users/19202", "pm_score": 0, "selected": false, "text": "<p>Not all forms of accessing a repository allow all forms of access. If you checked out your code via a read-only method, you won't be able to commit. As an example, it isn't uncommon for a WebDav repository to allow only anonymous checkout on http://... and allow authentication and commits only on https://...</p>\n\n<p>Check that the repository you are checking out from is letter-for-letter identical to the repositories that the other members of your team are checking out from.</p>\n" }, { "answer_id": 160630, "author": "olore", "author_id": 1691, "author_profile": "https://Stackoverflow.com/users/1691", "pm_score": 0, "selected": false, "text": "<p>Make sure you're using the <a href=\"http://www.alagad.com/go/blog-entry/subversion-mkactivity-and-403-forbidden-headaches\" rel=\"nofollow noreferrer\">proper CAPS for the entire svn url</a></p>\n" }, { "answer_id": 163310, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": true, "text": "<p>Since you can commit from other machines, and your team members can commit but not from your machine, I'd say it's probably an issue with your subversion client. I'd suggest you uninstall the client you have, then install the version that's being run on the server just to be safe.</p>\n" }, { "answer_id": 2886024, "author": "Sarah Elkins", "author_id": 347525, "author_profile": "https://Stackoverflow.com/users/347525", "pm_score": 0, "selected": false, "text": "<p>I think the problem is within the parentheses (<a href=\"http://dna.cs.byu.edu\" rel=\"nofollow noreferrer\">http://dna.cs.byu.edu</a>). You can often checkout with the http path, but commits usually want https. </p>\n" }, { "answer_id": 8133642, "author": "me_an", "author_id": 1013810, "author_profile": "https://Stackoverflow.com/users/1013810", "pm_score": 1, "selected": false, "text": "<p>I think <strong>authorization</strong> is required for you to commit your local copy...</p>\n\n<p>or</p>\n\n<p>Maybe you can commit, but the server is not auto updating? ...try updating the server after committing your work through <strong>SSH</strong> and <strong>SVN update</strong> </p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10140/" ]
I'm trying to commit to an SVN server hosted on my school's network. I have installed SVN 1.5.2 with binaries downloaded from CollabNet [here](http://www.collab.net/downloads/community/). The error reported is: ``` svn: Commit failed (details follow): svn: MKACTIVITY of '/opensvn/cs598r/!svn/act/defe271c-f33b-4851-a706-b2906301fed0': authorization failed (http://dna.cs.byu.edu) ``` That's the complete error message - nowhere does it say 403 Forbidden. I have tried deleting my working copy and checking it out again to no avail. I have checked and double-checked that my password and permissions are correct on the server. I have checked that the URL is correct. I can successfully commit from a remote machine, but not from mine. Other members of my team are able to commit from their computers, but when they try from mine, they get the same error. One of the other members of my team is using 1.5.1 CollabNet binaries with no trouble. What about my client is broken?
Since you can commit from other machines, and your team members can commit but not from your machine, I'd say it's probably an issue with your subversion client. I'd suggest you uninstall the client you have, then install the version that's being run on the server just to be safe.
160,175
<p>If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it. In other words, if we have $f->{$x}{$y}, I want something like</p> <pre><code>foreach ($x, $y) (deep_keys %{$f}) { } </code></pre> <p>instead of </p> <pre><code>foreach $x (keys %f) { foreach $y (keys %{$f-&gt;{$x}) { } } </code></pre>
[ { "answer_id": 160210, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "<p>It's easy enough if all you want to do is operate on values, but if you want to operate on keys, you need specifications of how levels will be recoverable.</p>\n\n<p>a. For instance, you could specify keys as <code>\"$level1_key.$level2_key.$level3_key\"</code>--or any separator, representing the levels.</p>\n\n<p>b. Or you could have a list of keys. </p>\n\n<p>I recommend the latter. </p>\n\n<ul>\n<li><p>Level can be understood by <code>@$key_stack</code></p></li>\n<li><p>and the most local key is <code>$key_stack-&gt;[-1]</code>.</p></li>\n<li><p>The path can be reconstructed by: <code>join( '.', @$key\\_stack )</code></p></li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>use constant EMPTY_ARRAY =&gt; [];\nuse strict; \nuse Scalar::Util qw&lt;reftype&gt;;\n\nsub deep_keys (\\%) { \n sub deeper_keys { \n my ( $key_ref, $hash_ref ) = @_;\n return [ $key_ref, $hash_ref ] if reftype( $hash_ref ) ne 'HASH';\n my @results;\n\n while ( my ( $key, $value ) = each %$hash_ref ) { \n my $k = [ @{ $key_ref || EMPTY_ARRAY }, $key ];\n push @results, deeper_keys( $k, $value );\n }\n return @results;\n }\n\n return deeper_keys( undef, shift );\n}\n\nforeach my $kv_pair ( deep_keys %$f ) { \n my ( $key_stack, $value ) = @_;\n ...\n}\n</code></pre>\n\n<p>This has been tested in Perl 5.10. </p>\n" }, { "answer_id": 160270, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>Keep in mind that Perl lists and hashes do not <strong>have</strong> dimensions and so cannot be multidimensional. What you <strong>can</strong> have is a hash item that is set to reference another hash or list. This can be used to create fake multidimensional structures.</p>\n\n<p>Once you realize this, things become easy. For example:</p>\n\n<pre><code>sub f($) {\n my $x = shift;\n if( ref $x eq 'HASH' ) {\n foreach( values %$x ) {\n f($_);\n }\n } elsif( ref $x eq 'ARRAY' ) {\n foreach( @$x ) {\n f($_);\n }\n }\n}\n</code></pre>\n\n<p>Add whatever else needs to be done besides traversing the structure, of course.</p>\n\n<p>One nifty way to do what you need is to pass a code reference to be called from inside f. By using sub prototyping you could even make the calls look like Perl's grep and map functions.</p>\n" }, { "answer_id": 160321, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 5, "selected": true, "text": "<p>Here's an option. This works for arbitrarily deep hashes:</p>\n\n<pre><code>sub deep_keys_foreach\n{\n my ($hashref, $code, $args) = @_;\n\n while (my ($k, $v) = each(%$hashref)) {\n my @newargs = defined($args) ? @$args : ();\n push(@newargs, $k);\n if (ref($v) eq 'HASH') {\n deep_keys_foreach($v, $code, \\@newargs);\n }\n else {\n $code-&gt;(@newargs);\n }\n }\n}\n\ndeep_keys_foreach($f, sub {\n my ($k1, $k2) = @_;\n print \"inside deep_keys, k1=$k1, k2=$k2\\n\";\n});\n</code></pre>\n" }, { "answer_id": 160323, "author": "Zed", "author_id": 19202, "author_profile": "https://Stackoverflow.com/users/19202", "pm_score": 1, "selected": false, "text": "<p>If you are working with tree data going more than two levels deep, and you find yourself wanting to walk that tree, you should first consider that you are going to make a lot of extra work for yourself if you plan on reimplementing everything you need to do manually on hashes of hashes of hashes when there are a lot of good alternatives available (<a href=\"http://search.cpan.org/search?query=tree&amp;mode=all\" rel=\"nofollow noreferrer\">search CPAN for \"Tree\"</a>).</p>\n\n<p>Not knowing what your data requirements actually are, I'm going to blindly point you at a <a href=\"http://www.perlmonks.org/?node_id=153259\" rel=\"nofollow noreferrer\">tutorial for Tree::DAG_Node</a> to get you started.</p>\n\n<p>That said, Axeman is correct, a hashwalk is most easily done with recursion. Here's an example to get you started if you feel you absolutely must solve your problem with hashes of hashes of hashes:</p>\n\n<pre>\n#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy %hash = (\n \"toplevel-1\" => \n { \n \"sublevel1a\" => \"value-1a\",\n \"sublevel1b\" => \"value-1b\"\n },\n \"toplevel-2\" =>\n {\n \"sublevel1c\" => \n {\n \"value-1c.1\" => \"replacement-1c.1\",\n \"value-1c.2\" => \"replacement-1c.2\"\n },\n \"sublevel1d\" => \"value-1d\"\n }\n);\n\nhashwalk( \\%hash );\n\nsub hashwalk\n{\n my ($element) = @_;\n if( ref($element) =~ /HASH/ )\n {\n foreach my $key (keys %$element)\n {\n print $key,\" => \\n\";\n hashwalk($$element{$key});\n }\n }\n else\n {\n print $element,\"\\n\";\n }\n}\n</pre>\n\n<p>It will output:</p>\n\n<pre>\ntoplevel-2 => \nsublevel1d => \nvalue-1d\nsublevel1c => \nvalue-1c.2 => \nreplacement-1c.2\nvalue-1c.1 => \nreplacement-1c.1\ntoplevel-1 => \nsublevel1a => \nvalue-1a\nsublevel1b => \nvalue-1b\n</pre>\n\n<p>Note that you CAN NOT predict in what order the hash elements will be traversed unless you tie the hash via Tie::IxHash or similar — again, if you're going to go through that much work, I recommend a tree module.</p>\n" }, { "answer_id": 160513, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "<p>There's no way to get the semantics you describe because <code>foreach</code> iterates over a list one element at a time. You'd have to have <code>deep_keys</code> return a LoL (list of lists) instead. Even that doesn't work in the general case of an arbitrary data structure. There could be varying levels of sub-hashes, some of the levels could be ARRAY refs, etc.</p>\n\n<p>The Perlish way of doing this would be to write a function that can walk an arbitrary data structure and apply a callback at each \"leaf\" (that is, non-reference value). <a href=\"https://stackoverflow.com/questions/160175/traversing-a-multi-dimensional-hash-in-perl#160321\">bmdhacks' answer</a> is a starting point. The exact function would vary depending one what you wanted to do at each level. It's pretty straightforward if all you care about is the leaf values. Things get more complicated if you care about the keys, indices, etc. that got you to the leaf.</p>\n" }, { "answer_id": 160886, "author": "Greg Cottman", "author_id": 10496, "author_profile": "https://Stackoverflow.com/users/10496", "pm_score": 2, "selected": false, "text": "<p>You can also fudge multi-dimensional arrays if you always have all of the key values, or you just don't need to access the individual levels as separate arrays:</p>\n\n<pre><code>$arr{\"foo\",1} = \"one\";\n$arr{\"bar\",2} = \"two\";\n\nwhile(($key, $value) = each(%arr))\n{\n @keyValues = split($;, $key);\n print \"key = [\", join(\",\", @keyValues), \"] : value = [\", $value, \"]\\n\";\n}\n</code></pre>\n\n<p>This uses the subscript separator \"$;\" as the separator for multiple values in the key.</p>\n" }, { "answer_id": 161370, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 4, "selected": false, "text": "<p>Stage one: don't reinvent the wheel :)</p>\n\n<p>A quick <a href=\"http://search.cpan.org/search?query=walk&amp;mode=all\" rel=\"nofollow noreferrer\">search on CPAN</a> throws up the incredibly useful <a href=\"http://search.cpan.org/dist/Data-Walk/\" rel=\"nofollow noreferrer\">Data::Walk</a>. Define a subroutine to process each node, and you're sorted</p>\n\n<pre><code>use Data::Walk;\n\nmy $data = { # some complex hash/array mess };\n\nsub process {\n print \"current node $_\\n\";\n}\n\nwalk \\&amp;process, $data;\n</code></pre>\n\n<p>And Bob's your uncle. Note that if you want to pass it a hash to walk, you'll need to pass a reference to it (see <a href=\"http://perldoc.perl.org/perlref.html\" rel=\"nofollow noreferrer\">perldoc perlref</a>), as follows (otherwise it'll try and process your hash keys as well!):</p>\n\n<pre><code>walk \\&amp;process, \\%hash;\n</code></pre>\n\n<p>For a more comprehensive solution (but harder to find at first glance in CPAN), use <a href=\"http://search.cpan.org/dist/Data-Visitor/lib/Data/Visitor/Callback.pm\" rel=\"nofollow noreferrer\">Data::Visitor::Callback</a> or its parent module - this has the advantage of giving you finer control of what you do, and (just for extra street cred) is written using Moose.</p>\n" }, { "answer_id": 161386, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 3, "selected": false, "text": "<p>This sounds to me as if <a href=\"http://search.cpan.org/perldoc?Data::Diver\" rel=\"nofollow noreferrer\">Data::Diver</a> or <a href=\"http://search.cpan.org/perldoc?Data::Visitor\" rel=\"nofollow noreferrer\">Data::Visitor</a> are good approaches for you.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14167/" ]
If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it. In other words, if we have $f->{$x}{$y}, I want something like ``` foreach ($x, $y) (deep_keys %{$f}) { } ``` instead of ``` foreach $x (keys %f) { foreach $y (keys %{$f->{$x}) { } } ```
Here's an option. This works for arbitrarily deep hashes: ``` sub deep_keys_foreach { my ($hashref, $code, $args) = @_; while (my ($k, $v) = each(%$hashref)) { my @newargs = defined($args) ? @$args : (); push(@newargs, $k); if (ref($v) eq 'HASH') { deep_keys_foreach($v, $code, \@newargs); } else { $code->(@newargs); } } } deep_keys_foreach($f, sub { my ($k1, $k2) = @_; print "inside deep_keys, k1=$k1, k2=$k2\n"; }); ```
160,204
<p>I'm a Linux guy and I'm used to copying directory trees with <code>cp -a</code>. OS X doesn't have <code>-a</code> option on <code>cp</code>... but it does have the <code>ditto</code> command. I'm reading the man on <code>ditto</code> now, but is there anything I should specifically be looking out for?</p>
[ { "answer_id": 160242, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "<p>As j04t pointed out that should be <code>cp -pR</code></p>\n\n<p><strike>On OS X, you would do</p>\n\n<pre><code>cp -dRL src target\n</code></pre>\n\n<p></strike>\ncp preserves resources in newer version of OS X (was it 10.3 when that happened?)</p>\n\n<p>Hey d is kinda like an upsidedown p, right ;)</p>\n" }, { "answer_id": 160254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>From Linux cp(1):</p>\n\n<blockquote>\n <p>-a, --archive same as -dpR</p>\n</blockquote>\n\n<p>which is confusing, since -d appears to be equivalent to -p. Anyway, OSX has -p and -R so you could just use that.</p>\n" }, { "answer_id": 160260, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": false, "text": "<p>Personally I use <code>rsync -a</code> (or whatever <code>rsync</code> params are called for). My two reasons are: I already know how to do this, and I need my scripts to be portable across Linux/BSD/Solaris. There are also some filesystems where <code>rsync</code> is more efficient than <code>cp</code>.</p>\n\n<p>Sorry that's not a direct answer, I have used <code>ditto</code> on BSDs but don't have any gotchas for you that aren't in the man page.</p>\n" }, { "answer_id": 160268, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 4, "selected": true, "text": "<p>According to the <strong>cp</strong> man page <strong>cp -a</strong> is the same as <strong>cp -dpR</strong> which is</p>\n\n<pre><code>-p = preserve mode,ownership,timestamps\n-R = recursive\n-d = no dereference and preserve links\n</code></pre>\n\n<p>The OS X equivalent would be</p>\n\n<p><strong>cp -pPR</strong></p>\n\n<pre><code>-p = preserve\n-R = recursive\n-P = no symbolic links are followed -- can be added but this is the default behavior\n</code></pre>\n\n<p>The only thing missing is <strong>-d</strong> which I think is the default behavior but I'm not positive.</p>\n\n<p>I've never messed with <strong>ditto</strong></p>\n\n<p>Edit -- @SoloBold</p>\n\n<p><strong>-L</strong> follows symbolic links. <strong>-p</strong> does NOT follow symbolic links.\nOS X (10.4 at least) has no <strong>-d</strong> option.</p>\n\n<p>that is a huge difference.</p>\n" }, { "answer_id": 1515379, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>there is a difference between ditto and cp which is that when source is a directory, cp creates a directory with that name on the destination, but ditto just copies the contents. Beware!</p>\n" }, { "answer_id": 18368741, "author": "Liyan Chang", "author_id": 664345, "author_profile": "https://Stackoverflow.com/users/664345", "pm_score": 2, "selected": false, "text": "<p>If you're using ditto, you should be aware that it moves the contents a bit differently from <code>cp -a</code> when it comes to folders:</p>\n\n<pre><code>ditto foo bar\n</code></pre>\n\n<p>will move the contents of foo into bar (resulting in bar/file1, bar/file2 .. )</p>\n\n<pre><code>cp -a foo bar\n</code></pre>\n\n<p>will move foo/ into bar/ (resulting in bar/foo/file1, bar/foo/file2, .. )</p>\n\n<p>Also: OSX cp now support <code>cp -a</code>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601671/" ]
I'm a Linux guy and I'm used to copying directory trees with `cp -a`. OS X doesn't have `-a` option on `cp`... but it does have the `ditto` command. I'm reading the man on `ditto` now, but is there anything I should specifically be looking out for?
According to the **cp** man page **cp -a** is the same as **cp -dpR** which is ``` -p = preserve mode,ownership,timestamps -R = recursive -d = no dereference and preserve links ``` The OS X equivalent would be **cp -pPR** ``` -p = preserve -R = recursive -P = no symbolic links are followed -- can be added but this is the default behavior ``` The only thing missing is **-d** which I think is the default behavior but I'm not positive. I've never messed with **ditto** Edit -- @SoloBold **-L** follows symbolic links. **-p** does NOT follow symbolic links. OS X (10.4 at least) has no **-d** option. that is a huge difference.
160,214
<p>I am trying to get the value of some ListViewSubItems, but I have no idea what values it uses for its keys. I have some simple code:</p> <pre><code> protected override void OnItemDrag(ItemDragEventArgs e) { base.OnItemDrag(e); ListViewItem item = e.Item as ListViewItem; string val = item.SubItems[???].ToString(); } </code></pre> <p>The ??? part is where I am having a problem. I cannot figure out what the keys are. I have tried the column names of the ListView with no luck. I would like to use this method instead of using numeric indices. </p>
[ { "answer_id": 160235, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p>Subitems are only ordered by column index unluckily. So you'd have to access them like:</p>\n\n<pre><code>protected override void OnItemDrag(ItemDragEventArgs e)\n{\n base.OnItemDrag(e); \n ListViewItem item = e.Item as ListViewItem;\n string val = item.SubItems[0].ToString(); \n}\n</code></pre>\n" }, { "answer_id": 160243, "author": "Dan Walker", "author_id": 752, "author_profile": "https://Stackoverflow.com/users/752", "pm_score": 1, "selected": false, "text": "<p>You can only use the column index to add subitems, but you can make it easier to read by making an enumeration containing the index of each of your columns.</p>\n" }, { "answer_id": 160344, "author": "Matt Nelson", "author_id": 788, "author_profile": "https://Stackoverflow.com/users/788", "pm_score": 2, "selected": true, "text": "<p>The key of the <code>ListViewSubItem</code> is the <code>Name</code> property as described <a href=\"http://msdn.microsoft.com/en-us/library/1x4396ba.aspx\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>Setting the Name equal to the column name, would allow you to index into the SubItems by the name of the column.</p>\n\n<p>And some code as an example</p>\n\n<p><code>\nListViewItem myListViewItem = new ListViewItem();<br>\nListViewItem.ListViewSubItem myListViewSubItem = new ListViewItem.ListViewSubItem();<br>\nmyListViewSubItem.Text = \"This will be displayed\";<br>\nmyListViewSubItem.Name = \"my key\";<br>\nmyListViewItem.SubItems.Add(myListViewSubItem);<br>\nListViewItem.ListViewSubItem subItem = myListViewItem.SubItems[\"my key\"];<br>\n</code></p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053/" ]
I am trying to get the value of some ListViewSubItems, but I have no idea what values it uses for its keys. I have some simple code: ``` protected override void OnItemDrag(ItemDragEventArgs e) { base.OnItemDrag(e); ListViewItem item = e.Item as ListViewItem; string val = item.SubItems[???].ToString(); } ``` The ??? part is where I am having a problem. I cannot figure out what the keys are. I have tried the column names of the ListView with no luck. I would like to use this method instead of using numeric indices.
The key of the `ListViewSubItem` is the `Name` property as described [here](http://msdn.microsoft.com/en-us/library/1x4396ba.aspx). Setting the Name equal to the column name, would allow you to index into the SubItems by the name of the column. And some code as an example `ListViewItem myListViewItem = new ListViewItem(); ListViewItem.ListViewSubItem myListViewSubItem = new ListViewItem.ListViewSubItem(); myListViewSubItem.Text = "This will be displayed"; myListViewSubItem.Name = "my key"; myListViewItem.SubItems.Add(myListViewSubItem); ListViewItem.ListViewSubItem subItem = myListViewItem.SubItems["my key"];`
160,216
<p>I'd like something like this:</p> <pre><code>each[i_, {1,2,3}, Print[i] ] </code></pre> <p>Or, more generally, to destructure arbitrary stuff in the list you're looping over, like:</p> <pre><code>each[{i_, j_}, {{1,10}, {2,20}, {3,30}}, Print[i*j] ] </code></pre> <p>Usually you want to use <code>Map</code> or other purely functional constructs and eschew a non-functional programming style where you use side effects. But here's an example where I think a for-each construct is supremely useful: </p> <p>Say I have a list of options (rules) that pair symbols with expressions, like</p> <pre><code>attrVals = {a -&gt; 7, b -&gt; 8, c -&gt; 9} </code></pre> <p>Now I want to make a hash table where I do the obvious mapping of those symbols to those numbers. I don't think there's a cleaner way to do that than</p> <pre><code>each[a_ -&gt; v_, attrVals, h[a] = v] </code></pre> <h2>Additional test cases</h2> <p>In this example, we transform a list of variables:</p> <pre><code>a = 1; b = 2; c = 3; each[i_, {a,b,c}, i = f[i]] </code></pre> <p>After the above, <code>{a,b,c}</code> should evaluate to <code>{f[1],f[2],f[3]}</code>. Note that that means the second argument to <code>each</code> should be held unevaluated if it's a list.</p> <p>If the unevaluated form is not a list, it should evaluate the second argument. For example:</p> <pre><code>each[i_, Rest[{a,b,c}], Print[i]] </code></pre> <p>That should print the values of <code>b</code> and <code>c</code>.</p> <p><strong>Addendum</strong>: To do for-each properly, it should support <code>Break[]</code> and <code>Continue[]</code>. I'm not sure how to implement that. Perhaps it will need to somehow be implemented in terms of For, While, or Do since those are the only loop constructs that support <code>Break[]</code> and <code>Continue[]</code>.</p> <p>And another problem with the answers so far: they eat <code>Return[]</code>s. That is, if you are using a ForEach loop in a function and want to return from the function from within the loop, you can't. Issuing Return inside the ForEach loop seems to work like <code>Continue[]</code>. This just (wait for it) threw me for a loop.</p>
[ { "answer_id": 160219, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": false, "text": "<p>The built-in <code>Scan</code> basically does this, though it's uglier:</p>\n\n<pre>\n Scan[Print[#]&, {1,2,3}]\n</pre>\n\n<p>It's especially ugly when you want to destructure the elements:</p>\n\n<pre>\n Scan[Print[#[[1]] * #[[2]]]&, {{1,10}, {2,20}, {3,30}}]\n</pre>\n\n<p>The following function avoids the ugliness by converting <code>pattern</code> to <code>body</code> for each element of <code>list</code>.</p>\n\n<pre>\nSetAttributes[ForEach, HoldAll];\nForEach[pat_, lst_, bod_] := Scan[Replace[#, pat:>bod]&, Evaluate@lst]\n</pre>\n\n<p>which can be used as in the example in the question.</p>\n\n<p>PS: The accepted answer induced me to switch to this, which is what I've been using ever since and it seems to work great (except for the caveat I appended to the question):</p>\n\n<pre><code>SetAttributes[ForEach, HoldAll]; (* ForEach[pattern, list, body] *)\nForEach[pat_, lst_, bod_] := ReleaseHold[ (* converts pattern to body for *)\n Hold[Cases[Evaluate@lst, pat:&gt;bod];]]; (* each element of list. *)\n</code></pre>\n" }, { "answer_id": 311929, "author": "kchoose2", "author_id": 39870, "author_profile": "https://Stackoverflow.com/users/39870", "pm_score": 2, "selected": false, "text": "<p>The built-in Map function does exactly what you want. It can be used in long form:</p>\n\n<p>Map[Print, {1,2,3}]</p>\n\n<p>or short-hand</p>\n\n<p>Print /@ {1,2,3}</p>\n\n<p>In your second case, you'd use \"Print[Times@@#]&amp;/@{{1,10}, {2,20}, {3,30}}\"</p>\n\n<p>I'd recommend reading the Mathematica help on Map, MapThread, Apply, and Function. They can take bit of getting used to, but once you are, you'll never want to go back!</p>\n" }, { "answer_id": 1260797, "author": "Pillsy", "author_id": 85467, "author_profile": "https://Stackoverflow.com/users/85467", "pm_score": 3, "selected": false, "text": "<p>Newer versions of Mathematica (6.0+) have generalized versions of Do[] and Table[] that do almost precisely what you want, by taking an alternate form of iterator argument. For instance,</p>\n\n<pre><code>Do[\n Print[i],\n {i, {1, 2, 3}}]\n</code></pre>\n\n<p>is exactly like your </p>\n\n<pre><code>ForEach[i_, {1, 2, 3,},\n Print[i]]\n</code></pre>\n\n<p>Alterntatively, if you really like the specific ForEach syntax, you can make a HoldAll function that implements it, like so:</p>\n\n<pre><code>Attributes[ForEach] = {HoldAll};\n\nForEach[var_Symbol, list_, expr_] :=\n ReleaseHold[\n Hold[\n Scan[\n Block[{var = #},\n expr] &amp;,\n list]]];\n\nForEach[vars : {__Symbol}, list_, expr_] :=\n ReleaseHold[\n Hold[\n Scan[\n Block[vars,\n vars = #;\n expr] &amp;,\n list]]];\n</code></pre>\n\n<p>This uses symbols as variable names, not patterns, but that's how the various built-in control structures like Do[] and For[] work. </p>\n\n<p>HoldAll[] functions allow you to put together a pretty wide variety of custom control structures. ReleaseHold[Hold[...]] is usually the easiest way to assemble a bunch of Mathematica code to be evaluated later, and Block[{x = #}, ...]&amp; allows variables in your expression body to be bound to whatever values you want.</p>\n\n<p>In response to dreeves' question below, you can modify this approach to allow for more arbitrary destructuring using the DownValues of a unique symbol.</p>\n\n<pre><code>ForEach[patt_, list_, expr_] := \n ReleaseHold[Hold[\n Module[{f}, \n f[patt] := expr; \n Scan[f, list]]]]\n</code></pre>\n\n<p>At this point, though, I think you may be better off building something on top of Cases.</p>\n\n<pre><code>ForEach[patt_, list_, expr_] :=\n With[{bound = list},\n ReleaseHold[Hold[\n Cases[bound,\n patt :&gt; expr]; \n Null]]]\n</code></pre>\n\n<p>I like making Null explicit when I'm suppressing the return value of a function. <strong>EDIT</strong>: I fixed the bug pointed out be dreeves below; I always like using <code>With</code> to interpolate evaluated expressions into <code>Hold*</code> forms.</p>\n" }, { "answer_id": 1323505, "author": "Per Alexandersson", "author_id": 152109, "author_profile": "https://Stackoverflow.com/users/152109", "pm_score": 1, "selected": false, "text": "<p>Mathematica have map functions, so lets say you have a function <code>Func</code>taking one argument. Then just write</p>\n\n<pre><code>Func /@ list\n\nPrint /@ {1, 2, 3, 4, 5}\n</code></pre>\n\n<p>The return value is a list of the function applied to each element in the in-list.</p>\n\n<pre><code>PrimeQ /@ {10, 2, 123, 555}\n</code></pre>\n\n<p>will return <code>{False,True,False,False}</code></p>\n" }, { "answer_id": 2390686, "author": "Michael Pilat", "author_id": 272923, "author_profile": "https://Stackoverflow.com/users/272923", "pm_score": 4, "selected": false, "text": "<p>I'm years late to the party here, and this is perhaps more an answer to the \"meta-question\", but something many people initially have a hard time with when programming in Mathematica (or other functional languages) is approaching a problem from a functional rather than structural viewpoint. The Mathematica language has structural constructs, but it's functional at its core.</p>\n\n<p>Consider your first example:</p>\n\n<pre><code>ForEach[i_, {1,2,3},\n Print[i]\n]\n</code></pre>\n\n<p>As several people pointed out, this can be expressed functionally as <code>Scan[Print, {1,2,3}]</code> or <code>Print /@ {1,2,3}</code> (although you should favor <code>Scan</code> over <code>Map</code> when possible, as previously explained, but that can be annoying at times since there is no infix operator for <code>Scan</code>).</p>\n\n<p>In Mathematica, there's usually a dozen ways to do everything, which is sometimes beautiful and sometimes frustrating. With that in mind, consider your second example:</p>\n\n<pre><code>ForEach[{i_, j_}, {{1,10}, {2,20}, {3,30}},\n Print[i*j]\n]\n</code></pre>\n\n<p>... which is more interesting from a functional point of view.</p>\n\n<p>One possible functional solution is to instead use list replacement, e.g.:</p>\n\n<pre><code>In[1]:= {{1,10},{2,20},{3,30}}/.{i_,j_}:&gt;i*j\nOut[1]= {10,40,90}\n</code></pre>\n\n<p>...but if the list was very large, this would be unnecessarily slow since we are doing so-called \"pattern matching\" (e.g., looking for instances of {a, b} in the list and assigning them to <code>i</code> and <code>j</code>) unnecessarily. </p>\n\n<p>Given a large array of 100,000 pairs, <code>array = RandomInteger[{1, 100}, {10^6, 2}]</code>, we can look at some timings:</p>\n\n<p>Rule-replacement is pretty quick:</p>\n\n<pre><code>In[3]:= First[Timing[array /. {i_, j_} :&gt; i*j;]]\nOut[3]= 1.13844\n</code></pre>\n\n<p>... but we can do a little better if we take advantage of the expression structure where each pair is really <code>List[i,j]</code> and apply <code>Times</code> as the head of each pair, turning each <code>{i,j}</code> into <code>Times[i,j]</code>:</p>\n\n<pre><code>In[4]:= (* f@@@list is the infix operator form of Apply[f, list, 1] *)\n First[Timing[Times @@@ array;]]\nOut[4]= 0.861267\n</code></pre>\n\n<p>As used in the implementation of <code>ForEach[...]</code> above, <code>Cases</code> is decidedly suboptimal:</p>\n\n<pre><code>In[5]:= First[Timing[Cases[array, {i_, j_} :&gt; i*j];]]\nOut[5]= 2.40212\n</code></pre>\n\n<p>... since <code>Cases</code> does more work than just the rule replacement, having to build an output of matching elements one-by-one. It turns out we can do a <em>lot</em> better by decomposing the problem differently, and take advantage of the fact that <code>Times</code> is <code>Listable</code>, and supports vectorized operation. </p>\n\n<p>The <code>Listable</code> attribute means that a function <code>f</code> will automatically thread over any list arguments:</p>\n\n<pre><code>In[16]:= SetAttributes[f,Listable]\nIn[17]:= f[{1,2,3},{4,5,6}]\nOut[17]= {f[1,4],f[2,5],f[3,6]}\n</code></pre>\n\n<p>So, since <code>Times</code> is <code>Listable</code>, if we instead had the pairs of numbers as two separate arrays:</p>\n\n<pre><code>In[6]:= a1 = RandomInteger[{1, 100}, 10^6];\n a2 = RandomInteger[{1, 100}, 10^6];\n\nIn[7]:= First[Timing[a1*a2;]]\nOut[7]= 0.012661\n</code></pre>\n\n<p><em>Wow</em>, quite a bit faster! Even if the input wasn't provided as two separate arrays (or you have more than two elements in each pair,) we can still do something optimal:</p>\n\n<pre><code>In[8]:= First[Timing[Times@@Transpose[array];]]\nOut[8]= 0.020391\n</code></pre>\n\n<p>The moral of this epic is not that <code>ForEach</code> isn't a valuable construct in general, or even in Mathematica, but that you can often obtain the same results more efficiently and more elegantly when you work in a functional mindset, rather than a structural one. </p>\n" }, { "answer_id": 4700704, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": true, "text": "<p>Thanks to <a href=\"https://stackoverflow.com/users/85467/pillsy\">Pillsy</a> and <a href=\"https://stackoverflow.com/users/565518/leonid-shifrin\">Leonid Shifrin</a>, here's what I'm now using:</p>\n\n<pre><code>SetAttributes[each, HoldAll]; (* each[pattern, list, body] *)\neach[pat_, lst_List, bod_] := (* converts pattern to body for *)\n (Cases[Unevaluated@lst, pat:&gt;bod]; Null); (* each element of list. *)\neach[p_, l_, b_] := (Cases[l, p:&gt;b]; Null); (* (Break/Continue not supported) *)\n</code></pre>\n" }, { "answer_id": 7259824, "author": "faysou", "author_id": 884752, "author_profile": "https://Stackoverflow.com/users/884752", "pm_score": 2, "selected": false, "text": "<p>Here is a slight improvement based on the last answer of dreeves that allows to specify the pattern without Blank (making the syntax similar to other functions like Table or Do) and that uses the level argument of Cases</p>\n\n<pre><code>SetAttributes[ForEach,HoldAll];\nForEach[patt_/; FreeQ[patt, Pattern],list_,expr_,level_:1] :=\n Module[{pattWithBlanks,pattern},\n pattWithBlanks = patt/.(x_Symbol/;!MemberQ[{\"System`\"},Context[x]] :&gt; pattern[x,Blank[]]);\n pattWithBlanks = pattWithBlanks/.pattern-&gt;Pattern;\n\n Cases[Unevaluated@list, pattWithBlanks :&gt; expr, {level}];\n Null\n ];\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>ForEach[{i, j}, {{1, 10}, {2, 20}, {3, 30}}, Print[i*j]]\nForEach[i, {{1, 10}, {2, 20}, {3, 30}}, Print[i], 2]\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
I'd like something like this: ``` each[i_, {1,2,3}, Print[i] ] ``` Or, more generally, to destructure arbitrary stuff in the list you're looping over, like: ``` each[{i_, j_}, {{1,10}, {2,20}, {3,30}}, Print[i*j] ] ``` Usually you want to use `Map` or other purely functional constructs and eschew a non-functional programming style where you use side effects. But here's an example where I think a for-each construct is supremely useful: Say I have a list of options (rules) that pair symbols with expressions, like ``` attrVals = {a -> 7, b -> 8, c -> 9} ``` Now I want to make a hash table where I do the obvious mapping of those symbols to those numbers. I don't think there's a cleaner way to do that than ``` each[a_ -> v_, attrVals, h[a] = v] ``` Additional test cases --------------------- In this example, we transform a list of variables: ``` a = 1; b = 2; c = 3; each[i_, {a,b,c}, i = f[i]] ``` After the above, `{a,b,c}` should evaluate to `{f[1],f[2],f[3]}`. Note that that means the second argument to `each` should be held unevaluated if it's a list. If the unevaluated form is not a list, it should evaluate the second argument. For example: ``` each[i_, Rest[{a,b,c}], Print[i]] ``` That should print the values of `b` and `c`. **Addendum**: To do for-each properly, it should support `Break[]` and `Continue[]`. I'm not sure how to implement that. Perhaps it will need to somehow be implemented in terms of For, While, or Do since those are the only loop constructs that support `Break[]` and `Continue[]`. And another problem with the answers so far: they eat `Return[]`s. That is, if you are using a ForEach loop in a function and want to return from the function from within the loop, you can't. Issuing Return inside the ForEach loop seems to work like `Continue[]`. This just (wait for it) threw me for a loop.
Thanks to [Pillsy](https://stackoverflow.com/users/85467/pillsy) and [Leonid Shifrin](https://stackoverflow.com/users/565518/leonid-shifrin), here's what I'm now using: ``` SetAttributes[each, HoldAll]; (* each[pattern, list, body] *) each[pat_, lst_List, bod_] := (* converts pattern to body for *) (Cases[Unevaluated@lst, pat:>bod]; Null); (* each element of list. *) each[p_, l_, b_] := (Cases[l, p:>b]; Null); (* (Break/Continue not supported) *) ```
160,218
<p>I'm personally an advocate of the <a href="https://en.wikipedia.org/wiki/%3F:" rel="nofollow noreferrer">ternary operator</a>: <code>() ? : </code></p> <p>I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.</p> <p>What are your feelings on it? What interesting code have you seen using it?</p>
[ { "answer_id": 160221, "author": "John Mulder", "author_id": 2242, "author_profile": "https://Stackoverflow.com/users/2242", "pm_score": 4, "selected": false, "text": "<p>In my mind, it only makes sense to use the ternary operator in cases where an expression is needed.</p>\n\n<p>In other cases, it seems like the ternary operator decreases clarity.</p>\n" }, { "answer_id": 160226, "author": "Marcin", "author_id": 21640, "author_profile": "https://Stackoverflow.com/users/21640", "pm_score": 2, "selected": false, "text": "<p>Well, the syntax for it is horrid. I find functional <em>ifs</em> very useful, and they often makes code more readable.</p>\n<p>I would suggest making a macro to make it more readable, but I'm sure someone can come up with a horrible edge case (as there always is with C++).</p>\n" }, { "answer_id": 160231, "author": "Erik Forbes", "author_id": 16942, "author_profile": "https://Stackoverflow.com/users/16942", "pm_score": 3, "selected": false, "text": "<p>I use it quite often in places where I'm constrained to work in a constructor - for example, the new .NET 3.5 LINQ to XML constructs - to define default values when an optional parameter is null.</p>\n\n<p>Contrived example:</p>\n\n<pre><code>var e = new XElement(\"Something\",\n param == null ? new XElement(\"Value\", \"Default\")\n : new XElement(\"Value\", param.ToString())\n);\n</code></pre>\n\n<p>or (thanks asterite)</p>\n\n<pre><code>var e = new XElement(\"Something\",\n new XElement(\"Value\",\n param == null ? \"Default\"\n : param.ToString()\n )\n);\n</code></pre>\n\n<p>No matter whether you use the ternary operator or not, making sure your code is readable is the important thing. Any construct can be made unreadable.</p>\n" }, { "answer_id": 160236, "author": "Dan Walker", "author_id": 752, "author_profile": "https://Stackoverflow.com/users/752", "pm_score": 2, "selected": false, "text": "<p>I treat ternary operators a lot like GOTO. They have their place, but they are something which you should usually avoid to make the code easier to understand.</p>\n" }, { "answer_id": 160238, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 7, "selected": false, "text": "<p>It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.</p>\n" }, { "answer_id": 160240, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>I agree with jmulder: it shouldn't be used in place of a <code>if</code>, but it has its place for return expression or inside an expression:</p>\n<pre><code>echo &quot;Result: &quot; + n + &quot; meter&quot; + (n != 1 ? &quot;s&quot; : &quot;&quot;);\nreturn a == null ? &quot;null&quot; : a;\n</code></pre>\n<p>The former is just an example, and better <a href=\"https://en.wikipedia.org/wiki/Internationalization_and_localization\" rel=\"nofollow noreferrer\">internationalisation and localisation</a> support of plural should be used!</p>\n" }, { "answer_id": 160248, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 4, "selected": false, "text": "<p>I use the ternary operator wherever I can, unless it makes the code extremely hard to read, but then that's usually just an indication that my code could use a little refactoring.</p>\n<p>It always puzzles me how some people think the ternary operator is a &quot;hidden&quot; feature or is somewhat mysterious. It's one of the first things I learnt when I start programming in C, and I don't think it decreases readability at all. It's a natural part of the language.</p>\n" }, { "answer_id": 160253, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 3, "selected": false, "text": "<p>I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:</p>\n\n<pre><code>return (a&gt;0)?a:0;\n</code></pre>\n\n<p>Compared to:</p>\n\n<pre><code>if(a&gt;0) return a;\nelse return 0;\n</code></pre>\n\n<p>You also have the case where the solution is between the ternary operator and creating a function. For example in Python:</p>\n\n<pre><code>l = [ i if i &gt; 0 else 0 for i in lst ]\n</code></pre>\n\n<p>The alternative is:</p>\n\n<pre><code>def cap(value):\n if value &gt; 0:\n return value\n return 0\nl = [ cap(i) for i in lst ]\n</code></pre>\n\n<p>It is needed enough that in Python (as an example), such an idiom could be seen regularly:</p>\n\n<pre><code>l = [ ((i&gt;0 and [i]) or [0])[0] for i in lst ]\n</code></pre>\n\n<p>this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.</p>\n" }, { "answer_id": 160275, "author": "Keith Williams", "author_id": 20376, "author_profile": "https://Stackoverflow.com/users/20376", "pm_score": 5, "selected": false, "text": "<p>It's a question of style, really; the subconscious rules I tend to follow are:</p>\n\n<ul>\n<li>Only evaluate 1 expression - so <code>foo = (bar &gt; baz) ? true : false</code>, but NOT <code>foo = (bar &gt; baz &amp;&amp; lotto &amp;&amp; someArray.Contains(someValue)) ? true : false</code></li>\n<li>If I'm using it for display logic, e.g. <code>&lt;%= (foo) ? \"Yes\" : \"No\" %&gt;</code></li>\n<li><del>Only really use it for assignment; never flow logic (so never <code>(foo) ? FooIsTrue(foo) : FooIsALie(foo)</code> )</del> Flow logic in ternary is itself a lie, ignore that last point.</li>\n</ul>\n\n<p>I like it because it's concise and elegant for simple assignment operations.</p>\n" }, { "answer_id": 160280, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>I almost never use the ternary operator, because whenever I <em>do</em> use it, it always makes me think a lot more than I have to later when I try to maintain it.</p>\n<p>I like to avoid verbosity, but when it makes the code a lot easier to pick up, I will go for the verbosity.</p>\n<p>Consider:</p>\n<pre><code>String name = firstName;\n\nif (middleName != null) {\n name += &quot; &quot; + middleName;\n}\n\nname += &quot; &quot; + lastName;\n</code></pre>\n<p>Now, that is a bit verbose, but I find it a lot more readable than:</p>\n<pre><code>String name = firstName + (middleName == null ? &quot;&quot; : &quot; &quot; + middleName)\n + &quot; &quot; + lastName;\n</code></pre>\n<p>Or:</p>\n<pre><code>String name = firstName;\nname += (middleName == null ? &quot;&quot; : &quot; &quot; + middleName);\nname += &quot; &quot; + lastName;\n</code></pre>\n<p>It just seems to compress too much information into too little space, without making it clear what's going on. Every time I saw the ternary operator used, I have always found an alternative that seemed much easier to read... then again, that is an extremely subjective opinion, so if you and your colleagues find ternary very readable, go for it.</p>\n" }, { "answer_id": 160291, "author": "indiv", "author_id": 19719, "author_profile": "https://Stackoverflow.com/users/19719", "pm_score": 2, "selected": false, "text": "<p>I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.</p>\n\n<pre><code>int result = do_something();\nif( result != 0 )\n{\n debug_printf(\"Error while doing something, code %x (%s)\\n\", result,\n result == 7 ? \"ERROR_YES\" :\n result == 8 ? \"ERROR_NO\" :\n result == 9 ? \"ERROR_FILE_NOT_FOUND\" :\n \"Unknown\");\n}\n</code></pre>\n" }, { "answer_id": 160293, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "<p>I'm a big fan of it ... when appropriate.</p>\n<p>Stuff like this is great, and, personally, I don't find it too hard to read/understand:</p>\n<pre><code>$y = ($x == &quot;a&quot; ? &quot;apple&quot;\n : ($x == &quot;b&quot; ? &quot;banana&quot;\n : ($x == &quot;c&quot; ? &quot;carrot&quot;\n : &quot;default&quot;)));\n</code></pre>\n<p>I know that probably makes a lot of people cringe, though.</p>\n<p>One thing to keep in mind when using it in PHP is how it works with a function that returns a reference.</p>\n<pre><code>class Foo {\n var $bar;\n\n function Foo() {\n $this-&gt;bar = &quot;original value&quot;;\n }\n\n function &amp;tern() {\n return true ? $this-&gt;bar : false;\n }\n\n function &amp;notTern() {\n if (true) return $this-&gt;bar;\n else return false;\n }\n}\n\n$f = new Foo();\n$b =&amp; $f-&gt;notTern();\n$b = &quot;changed&quot;;\necho $f-&gt;bar; // &quot;changed&quot;\n\n$f2 = new Foo();\n$b2 =&amp; $f-&gt;tern();\n$b2 = &quot;changed&quot;;\necho $f2-&gt;bar; // &quot;original value&quot;\n</code></pre>\n" }, { "answer_id": 160295, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 9, "selected": true, "text": "<p>Use it for <strong>simple expressions only</strong>:</p>\n<pre><code>int a = (b &gt; 10) ? c : d;\n</code></pre>\n<p><strong>Don't chain or nest</strong> ternary operators as it hard to read and confusing:</p>\n<pre><code>int a = b &gt; 10 ? c &lt; 20 ? 50 : 80 : e == 2 ? 4 : 8;\n</code></pre>\n<p>Moreover, when using ternary operator, consider formatting the code in a way that improves readability:</p>\n<pre><code>int a = (b &gt; 10) ? some_value \n : another_value;\n</code></pre>\n" }, { "answer_id": 160337, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 2, "selected": false, "text": "<p>I recently saw a variation on ternary operators (well, sort of) that make the standard &quot;() ? :&quot; variant seem to be a paragon of clarity:</p>\n<pre><code>var Result = [CaseIfFalse, CaseIfTrue][(boolean expression)]\n</code></pre>\n<p>or, to give a more tangible example:</p>\n<pre><code>var Name = ['Jane', 'John'][Gender == 'm'];\n</code></pre>\n<p>Mind you, this is JavaScript, so things like that might not be possible in other languages (thankfully).</p>\n" }, { "answer_id": 160415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Only when:</p>\n<pre><code>$var = (simple &gt; test ? simple_result_1 : simple_result_2);\n</code></pre>\n<p><a href=\"https://en.wikipedia.org/wiki/KISS_principle#In_software_development\" rel=\"nofollow noreferrer\">KISS</a>.</p>\n" }, { "answer_id": 160424, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": -1, "selected": false, "text": "<p>How would anyone win an obfuscated code contest without the ternary operator?!</p>\n<p>I'm personally for using it, when appropriate, but I don't think I'd ever nest it. It's very useful, but it has a couple knocks against it in that it makes code harder to read and is in use in some other languages in other operations (like <a href=\"https://en.wikipedia.org/wiki/Groovy_%28programming_language%29\" rel=\"nofollow noreferrer\">Groovy</a>'s null-check).</p>\n" }, { "answer_id": 160460, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 5, "selected": false, "text": "<p>The <em>ternary</em> <code>?:</code> operator is merely a functional equivalent of the procedural <code>if</code> construct. So as long as you are not using nested <code>?:</code> expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).</p>\n<p>But there are plenty of situations where conservative use of the <code>?:</code> operator can result in code that is actually <em>easier</em> to read than otherwise. For example:</p>\n<pre><code>int compareTo(Object object) {\n if((isLessThan(object) &amp;&amp; reverseOrder) || (isGreaterThan(object) &amp;&amp; !reverseOrder)) {\n return 1;\n if((isLessThan(object) &amp;&amp; !reverseOrder) || (isGreaterThan(object) &amp;&amp; reverseOrder)) {\n return -1;\n else\n return 0;\n}\n</code></pre>\n<p>Now compare that with this:</p>\n<pre><code>int compareTo(Object object) {\n if(isLessThan(object))\n return reverseOrder ? 1 : -1;\n else(isGreaterThan(object))\n return reverseOrder ? -1 : 1;\n else\n return 0;\n}\n</code></pre>\n<p>As the code is more compact, there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the <em>reverseOrder</em> property) the end result isn't particularly terse.</p>\n" }, { "answer_id": 160468, "author": "Rodrigo Gómez", "author_id": 16772, "author_profile": "https://Stackoverflow.com/users/16772", "pm_score": 2, "selected": false, "text": "<p>For simple if cases, I like to use it. Actually it's much easier to read/code for instance as parameters for functions or things like that. Also to avoid the new line I like to keep with all my if/else.</p>\n<p>Nesting it would be a big <em>no-no</em> in my book.</p>\n<p>So, resuming, for a single if/else I'll use the ternary operator. For other cases, a regular if/else if/else (or switch).</p>\n" }, { "answer_id": 160492, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 0, "selected": false, "text": "<p>Interesting anecdote: I have seen the optimizer weigh the ternary operator as less &quot;heavy&quot; for the purposes of inlining than the equivalent <em>if</em>. I noticed this with Microsoft compilers, but it could be more widespread.</p>\n<p>In particular functions like this would inline:</p>\n<pre><code>int getSomething()\n{\n return m_t ? m_t-&gt;v : 0;\n}\n</code></pre>\n<p>But this wouldn't:</p>\n<pre><code>int getSomething()\n{\n if( m_t )\n return m_t-&gt;v;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 160744, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 2, "selected": false, "text": "<p>I typically use it in things like this:</p>\n<pre><code>before:\n\nif(isheader)\n drawtext(x, y, WHITE, string);\nelse\n drawtext(x, y, BLUE, string);\n\nafter:\n\n drawtext(x, y, isheader == true ? WHITE : BLUE, string);\n</code></pre>\n" }, { "answer_id": 160780, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I like it a lot. When I use it, I write it like an <em>if-then-else</em>: one line each for condition, true action, and false action. That way, I can nest them easily.</p>\n<p>Example:</p>\n<pre>\nx = (a == b\n ? (sqrt(a) - 2)\n : (a*a + b*b)\n );\n\nx = (a == b\n ? (sqrt(a) - 2)\n : (a*a + b*b)\n );\nx = (a == b\n ? (c > d\n ? (sqrt(a) - 2)\n : (c + cos(d))\n )\n : (a*a + b*b)\n );\n</pre>\n<p>To me, this is reasonably easy to read. It also makes it easy to add subcases or change existing cases.</p>\n" }, { "answer_id": 160887, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 6, "selected": false, "text": "<p>Chained I'm fine with - nested, not so much.</p>\n<p>I tend to use them more in C simply because they're an <em>if</em> statement that has value, so it cuts down on unnecessary repetition or variables:</p>\n<pre><code>x = (y &lt; 100) ? &quot;dog&quot; :\n (y &lt; 150) ? &quot;cat&quot; :\n (y &lt; 300) ? &quot;bar&quot; : &quot;baz&quot;;\n</code></pre>\n<p>rather than</p>\n<pre><code> if (y &lt; 100) { x = &quot;dog&quot;; }\nelse if (y &lt; 150) { x = &quot;cat&quot;; }\nelse if (y &lt; 300) { x = &quot;bar&quot;; }\nelse { x = &quot;baz&quot;; }\n</code></pre>\n<p>In assignments like this, I find it's less to refactor, and clearer.</p>\n<p>When I'm working in ruby on the other hand, I'm more likely to use <code>if...else...end</code> because it's an expression too.</p>\n<pre><code>x = if (y &lt; 100) then &quot;dog&quot;\n elif (y &lt; 150) then &quot;cat&quot;\n elif (y &lt; 300) then &quot;bar&quot;\n else &quot;baz&quot;\n end\n</code></pre>\n<p>(Although, admittedly, for something this simple, I might just use the ternary operator anyway.)</p>\n" }, { "answer_id": 161172, "author": "mar10", "author_id": 19166, "author_profile": "https://Stackoverflow.com/users/19166", "pm_score": 0, "selected": false, "text": "<p>I use and recommend ternaries to avoid code lines in situations where the logic is trivial.</p>\n\n<pre><code>int i;\nif( piVal ) {\n i = *piVal;\n} else {\n i = *piDefVal;\n}\n</code></pre>\n\n<p>In the above case I would choose a ternary, because it has less noise:</p>\n\n<pre><code>int i = ( piVal ) ? *piVal : *piDefVal;\n</code></pre>\n\n<p>Likewise conditional return values are good candidates:</p>\n\n<pre><code>return ( piVal ) ? *piVal : *piDefVal;\n</code></pre>\n\n<p>I think compactness can improve readability which in turn helps to improve the code quality.</p>\n\n<p>But <em>readability</em> always depends on the code's audience.</p>\n\n<p>The readers must be able to understand the <code>a ? b : c</code> pattern without any mental effort.\nIf you can not presume this, go for the long version.</p>\n" }, { "answer_id": 162525, "author": "Steve Losh", "author_id": 13498, "author_profile": "https://Stackoverflow.com/users/13498", "pm_score": 2, "selected": false, "text": "<p>I like Groovy's special case of the ternary operator, called the Elvis operator: ?:</p>\n\n<pre><code>expr ?: default\n</code></pre>\n\n<p>This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.</p>\n" }, { "answer_id": 168412, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 0, "selected": false, "text": "<p>If your ternary operator ends up taking the whole screen width, then I wouldn't use it. I keep it to just checking one simple condition and returning single values:</p>\n<pre><code>int x = something == somethingElse ? 0 : -1;\n</code></pre>\n<p>We actually have some nasty code like this in production...not good:</p>\n<pre><code>int x = something == (someValue == someOtherVal ? string.Empty : &quot;Blah blah&quot;) ? (a == b ? 1 : 2 ): (c == d ? 3 : 4);\n</code></pre>\n" }, { "answer_id": 422478, "author": "Julien Chastang", "author_id": 32174, "author_profile": "https://Stackoverflow.com/users/32174", "pm_score": 0, "selected": false, "text": "<p>The ternary operator is extremely useful for concisely producing comma separated lists. Here is a Java example:</p>\n<pre><code> int[] iArr = {1, 2, 3};\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; iArr.length; i++) {\n sb.append(i == 0 ? iArr[i] : &quot;, &quot; + iArr[i]);\n }\n System.out.println(sb.toString());\n</code></pre>\n<p>It produces: &quot;1, 2, 3&quot;</p>\n<p>Otherwise, special casing for the last comma becomes annoying.</p>\n" }, { "answer_id": 422499, "author": "Jobo", "author_id": 51915, "author_profile": "https://Stackoverflow.com/users/51915", "pm_score": 0, "selected": false, "text": "<p>If you are trying to reduce the amount of lines in your code or are refactoring code, then go for it.</p>\n<p>If you care about the next programmer that has to take that extra 0.1 millisecond to understand the expression, then go for it anyway.</p>\n" }, { "answer_id": 535096, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 6, "selected": false, "text": "<p>I love them, especially in type-safe languages.</p>\n<p>I don't see how this:</p>\n<pre><code>int count = (condition) ? 1 : 0;\n</code></pre>\n<p>is any harder than this:</p>\n<pre><code>int count;\n\nif (condition)\n{\n count = 1;\n}\nelse\n{\n count = 0;\n}\n</code></pre>\n<p>I'd argue that ternary operators make everything less complex and more neat than the alternative.</p>\n" }, { "answer_id": 535100, "author": "Svet", "author_id": 8934, "author_profile": "https://Stackoverflow.com/users/8934", "pm_score": 2, "selected": false, "text": "<p>For simple tasks, like assigning a different value depending on a condition, they're great. I wouldn't use them when there are longer expressions depending on the condition though.</p>\n" }, { "answer_id": 535103, "author": "Alex", "author_id": 42707, "author_profile": "https://Stackoverflow.com/users/42707", "pm_score": 2, "selected": false, "text": "<p>If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.</p>\n<p>The only time I think ternary operators make code harder to understand is when you have more than three or foyr in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.</p>\n" }, { "answer_id": 535106, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 0, "selected": false, "text": "<p>No, ternary operators <em>do not</em> increase complexity. Unfortunately, some developers are so oriented to an imperative programming style that they reject (or won't learn) anything else. I do not believe that, for example:</p>\n\n<pre><code>int c = a &lt; b ? a : b;\n</code></pre>\n\n<p>is \"more complex\" than the equivalent (but more verbose):</p>\n\n<pre><code>int c;\nif (a &lt; b) {\n c = a;\n} else {\n c = b;\n}\n</code></pre>\n\n<p>or the even more awkward (which I've seen):</p>\n\n<pre><code>int c = a;\nif (!a &lt; b) {\n c = b;\n}\n</code></pre>\n\n<p>That said, look carefully at your alternatives on a case-by-case basis. Assuming a propoerly-educated developer, ask which most succinctly expresses the intent of your code and go with that one.</p>\n" }, { "answer_id": 535107, "author": "Sean Bright", "author_id": 21926, "author_profile": "https://Stackoverflow.com/users/21926", "pm_score": 4, "selected": false, "text": "<p>Like so many opinion questions, the answer is inevitably: <em>it depends</em></p>\n\n<p>For something like:</p>\n\n<pre><code>return x ? \"Yes\" : \"No\";\n</code></pre>\n\n<p>I think that is <strong>much</strong> more concise (and quicker for me to parse) than:</p>\n\n<pre><code>if (x) {\n return \"Yes\";\n} else {\n return \"No\";\n}\n</code></pre>\n\n<p>Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:</p>\n\n<pre><code>x &amp;&amp; y &amp;&amp; z &gt;= 10 &amp;&amp; s.Length == 0 || !foo\n</code></pre>\n\n<p>is not a good candidate for the ternary operator.</p>\n\n<p>As an aside, if you are a C programmer, GCC actually has <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Conditionals.html#Conditionals\" rel=\"noreferrer\">an extension</a> that allows you to exclude the if-true portion of the ternary, like this:</p>\n\n<pre><code>/* 'y' is a char * */\nconst char *x = y ? : \"Not set\";\n</code></pre>\n\n<p>Which will set <code>x</code> to <code>y</code> assuming <code>y</code> is not <code>NULL</code>. Good stuff.</p>\n" }, { "answer_id": 535109, "author": "Joe Basirico", "author_id": 20795, "author_profile": "https://Stackoverflow.com/users/20795", "pm_score": 0, "selected": false, "text": "<p>I used to be in the “ternary operators make a line un-readable” camp, but in the last few years I’ve grown to like them when used in moderation. Single line ternary operators can increase readability if everybody on your team understands what’s going on. It’s a concise way of doing something without the overhead of lots of curly braces for the sake of curly braces. </p>\n\n<p>The two cases where I don’t like them: if they go too far beyond the 120 column mark or if they are embedded in other ternary operators. If you can’t quickly, easily and readably express what you’re doing in a ternary operator. Then use the if/else equivalent.</p>\n" }, { "answer_id": 535113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It depends :)</p>\n<p>They are useful when dealing with possibly null references (BTW: Java really needs a way to easily compare two possibly null strings).</p>\n<p>The problem begins, when you are nesting many ternary operators in one expression.</p>\n" }, { "answer_id": 535114, "author": "Denis Hennessy", "author_id": 35958, "author_profile": "https://Stackoverflow.com/users/35958", "pm_score": 0, "selected": false, "text": "<p>No (unless they're misused). Where the expression is part of a larger expression, the use of a ternary operator is often much clearer.</p>\n" }, { "answer_id": 535122, "author": "JimDaniel", "author_id": 63, "author_profile": "https://Stackoverflow.com/users/63", "pm_score": 2, "selected": false, "text": "<p>I like them. I don't know why, but I feel very cool when I use the ternary expression.</p>\n" }, { "answer_id": 535124, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):</p>\n\n<pre><code>isLeapYear =\n ((yyyy % 400) == 0)\n ? 1\n : ((yyyy % 100) == 0)\n ? 0\n : ((yyyy % 4) == 0)\n ? 1\n : 0;\n</code></pre>\n\n<p>where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).</p>\n\n<p>I don't mind it for small things like:</p>\n\n<pre><code>reportedAge = (isFemale &amp;&amp; (Age &gt;= 21)) ? 21 + (Age - 21) / 3 : Age;\n</code></pre>\n\n<p>or even slightly tricky things like:</p>\n\n<pre><code>printf (\"Deleted %d file%s\\n\", n, (n == 1) ? \"\" : \"s\");\n</code></pre>\n" }, { "answer_id": 535142, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>By the measure of <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a>, the use of <code>if</code> statements or the ternary operator are equivalent. So by that measure, the answer is <strong>no</strong>, the complexity would be exactly the same as before.</p>\n<p>By other measures such as readability, maintainability, and <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> (don't repeat yourself), either choice may prove better than the other.</p>\n" }, { "answer_id": 535191, "author": "Onion-Knight", "author_id": 64708, "author_profile": "https://Stackoverflow.com/users/64708", "pm_score": 0, "selected": false, "text": "<p>I think it really depends on the context they are used in.</p>\n\n<p>Something like this would be a really confusing, albeit effective, way to use them:</p>\n\n<pre><code> __CRT_INLINE int __cdecl getchar (void)\n{\n return (--stdin-&gt;_cnt &gt;= 0)\n ? (int) (unsigned char) *stdin-&gt;_ptr++\n : _filbuf (stdin);\n}\n</code></pre>\n\n<p>However, this:</p>\n\n<pre><code>c = a &gt; b ? a : b;\n</code></pre>\n\n<p>is perfectly reasonable.</p>\n\n<p>I personally think they should be used when they cut down on overly verbose IF statements. The problem is people are either petrified of them, or like them so much they get used almost exclusively instead of IF statements.</p>\n" }, { "answer_id": 535193, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p>If you're using the ternary operator for a simple conditional assignment I think it's fine. I've seen it (ab)used to control program flow without even making an assignment, and I think that should be avoided. Use an if statement in these cases.</p>\n" }, { "answer_id": 535195, "author": "maccullt", "author_id": 4945, "author_profile": "https://Stackoverflow.com/users/4945", "pm_score": 2, "selected": false, "text": "<p>As others have pointed out they are nice for short simple conditions. I especially like them for defaults (kind of like the <strong>||</strong> and <strong>or</strong> usage in JavaScript and Python), e.g.</p>\n<pre><code>int repCount = pRepCountIn ? *pRepCountIn : defaultRepCount;\n</code></pre>\n<p>Another common use is to initialize a reference in C++. Since references have to be declared and initialized in the same statement you can't use an <em>if</em> statement.</p>\n<pre><code>SomeType&amp; ref = pInput ? *pInput : somethingElse;\n</code></pre>\n" }, { "answer_id": 535226, "author": "Genericrich", "author_id": 39932, "author_profile": "https://Stackoverflow.com/users/39932", "pm_score": 1, "selected": false, "text": "<p>No. They are hard to read. If/Else is much easier to read.</p>\n<p>This is my opinion. <a href=\"https://en.wiktionary.org/wiki/your_mileage_may_vary#Phrase\" rel=\"nofollow noreferrer\">Your mileage may vary</a>.</p>\n" }, { "answer_id": 535231, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "<p>As so many answers have said, <em>it depends</em>. I find that if the ternary comparison is not visible in a quick scan down the code, then it should not be used.</p>\n<p>As a side issue, I might also note that its very existence is actually a bit of an anomaly due to the fact that in C, comparison testing is a statement. In <a href=\"https://en.wikipedia.org/wiki/Icon_(programming_language)\" rel=\"nofollow noreferrer\">Icon</a>, the <code>if</code> construct (like most of Icon) is actually an expression. So you can do things like:</p>\n<pre><code>x[if y &gt; 5 then 5 else y] := &quot;Y&quot;\n</code></pre>\n<p>... which I find much more readable than a ternary comparison operator. :-)</p>\n<p>There was a discussion recently about the possibility of adding the <code>?:</code> operator to Icon, but several people correctly pointed out that there was absolutely no need because of the way <code>if</code> works.</p>\n<p>Which means that if you could do that in C (or any of the other languages that have the ternary operator), then you wouldn't, in fact, need the ternary operator at all.</p>\n" }, { "answer_id": 535413, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>string someSay = bCanReadThis ? \"No\" : \"Yes\";</p>\n" }, { "answer_id": 535490, "author": "Adam Hawes", "author_id": 54415, "author_profile": "https://Stackoverflow.com/users/54415", "pm_score": 0, "selected": false, "text": "<p>In small doses they can reduce the number of lines and make code more readable; particularly if the outcome is something like setting a char string to &quot;Yes&quot; or &quot;No&quot; based on the result of a calculation.</p>\n<p>Example:</p>\n<pre><code>char* c = NULL;\nif(x) {\n c = &quot;true&quot;;\n}else {\n c = &quot;false&quot;;\n}\n</code></pre>\n<p>compared with:</p>\n<pre><code>char* c = x ? &quot;Yes&quot; : &quot;No&quot;;\n</code></pre>\n<p>The only bug that can occur in simple tests like that is assigning an incorrect value, but since the conditional is usually simple it's less likely the programmer will get it wrong. Having your program print the wrong output isn't the end of the world, and should be caught in all of code review, bench testing and production testing phases.</p>\n<p>I'll counter my own argument with now it's more difficult to use code coverage metrics to assist in knowing how good your test cases are. In the first example you can test for coverage on both the assignment lines; if one is not covered then your tests are not exercising all possible code flows.</p>\n<p>In the second example the line will show as being executed regardless of the value of X, so you can't be certain you've tested the alternate path (<a href=\"https://en.wiktionary.org/wiki/YMMV\" rel=\"nofollow noreferrer\">YMMV</a> depending on the ability of your coverage tools).</p>\n<p>This matters more with the increasing complexity of the tests.</p>\n" }, { "answer_id": 1507461, "author": "Travis", "author_id": 4284, "author_profile": "https://Stackoverflow.com/users/4284", "pm_score": 1, "selected": false, "text": "<p>My recently formulated rule of thumb for determining whether you should use the ternary operator is:</p>\n\n<ul>\n<li>if your code is choosing between two different values, go ahead and use the ternary operator.</li>\n<li>if your code choosing between two different code paths, stick to an if statement.</li>\n</ul>\n\n<p>And be kind to readers of your code. If you are nesting ternary operators, format the code to make that nesting obvious.</p>\n" }, { "answer_id": 1697086, "author": "dsimcha", "author_id": 23903, "author_profile": "https://Stackoverflow.com/users/23903", "pm_score": 0, "selected": false, "text": "<p>One reason no one seems to mention for using the ternary operator, at least in languages, like <a href=\"https://en.wikipedia.org/wiki/D_(programming_language)\" rel=\"nofollow noreferrer\">D</a>, that support type inference is to allow type inference to work for amazingly complicated template types.</p>\n<pre><code>auto myVariable = fun();\n// typeof(myVariable) == Foo!(Bar, Baz, Waldo!(Stuff, OtherStuff)).\n\n// Now I want to declare a variable and assign a value depending on some\n// conditional to it.\nauto myOtherVariable = (someCondition) ? fun() : gun();\n\n// If I didn't use the ternary I'd have to do:\nFoo!(Bar, Baz, Waldo!(Stuff, OtherStuff)) myLastVariable; // Ugly.\nif(someCondition) {\n myLastVariable = fun();\n} else {\n myLastVariable = gun():\n}\n</code></pre>\n" }, { "answer_id": 2389733, "author": "Tim", "author_id": 280564, "author_profile": "https://Stackoverflow.com/users/280564", "pm_score": 0, "selected": false, "text": "<p>I like the operator in some situations, but I think some people tend to overuse it and that it can make the code harder to read.</p>\n<p>I recently stumbled across this line in some open source code I am working to modify.</p>\n<p>Where</p>\n<pre><code> (active == null ? true :\n ((bool)active ? p.active : !p.active)) &amp;&amp;...\n</code></pre>\n<p>Instead of</p>\n<pre><code>where ( active == null || p.active == active) &amp;&amp;...\n</code></pre>\n<p>I wonder if the ternary use adds extra overhead to the <a href=\"https://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"nofollow noreferrer\">LINQ</a> statement in this case.</p>\n" }, { "answer_id": 2389942, "author": "bta", "author_id": 79566, "author_profile": "https://Stackoverflow.com/users/79566", "pm_score": 0, "selected": false, "text": "<p>I agree with the sentiments of many of the posters here. The ternary operator is perfectly valid as long as it is used correctly and does not introduce ambiguity (to be fair, you can say that about any operator/construct).</p>\n\n<p>I use the ternary operator often in embedded code to clarify what my code is doing. Take the following (oversimplified for clarity) code samples:</p>\n\n<p>Snippet 1:</p>\n\n<pre><code>int direction = read_or_write(io_command);\n\n// Send an I/O\nio_command.size = (direction==WRITE) ? (32 * 1024) : (128 * 1024);\nio_command.data = &amp;buffer;\ndispatch_request(io_command);\n</code></pre>\n\n<p>Snippet 2:</p>\n\n<pre><code>int direction = read_or_write(io_command);\n\n// Send an I/O\nif (direction == WRITE) {\n io_command.size = (32 * 1024);\n io_command.data = &amp;buffer;\n dispatch_request(io_command);\n} else {\n io_command.size = (128 * 1024);\n io_command.data = &amp;buffer;\n dispatch_request(io_command);\n}\n</code></pre>\n\n<p>Here, I am dispatching an input or output request. The process is the same whether the request is a read or a write, only the default I/O size changes. In the first sample, I use the ternary operator to make it clear that the procedure is the same and that the <code>size</code> field gets a different value depending on the I/O direction. In the second example, it is not as immediately clear that the algorithm for the two cases is the same (especially as the code grows much longer than three lines). The second example would be more difficult to keep the common code in sync. Here, the ternary operator does a better job of expressing the largely parallel nature of the code.</p>\n\n<p>The ternary operator has another advantage (albeit one that is normally only an issue with embedded software). Some compilers can only perform certain optimizations if the code is not \"nested\" past a certain depth (meaning inside a function, you increase the nesting depth by 1 every time you enter an if, loop, or switch statement and decrease it by 1 when you leave it). On occasion, using the ternary operator can minimize the amount of code that needs to be inside a conditional (sometimes to the point where the compiler can optimize away the conditional) and can reduce the nesting depth of your code. In some instances, I was able to re-structure some logic using the ternary operator (as in my example above) and reduce the nested depth of the function enough that the compiler could perform additional optimization steps on it. Admittedly this is a rather narrow use case, but I figured it was worth mentioning anyway.</p>\n" }, { "answer_id": 2473019, "author": "jeremysawesome", "author_id": 296889, "author_profile": "https://Stackoverflow.com/users/296889", "pm_score": 1, "selected": false, "text": "<p>The ternary operator hands down. They aren't complex if you format properly. Take the leap year example <a href=\"https://stackoverflow.com/questions/160218/to-ternary-or-not-to-ternary/535124#535124\">from paxdiablo</a>:</p>\n<pre><code>$isLeapYear =\n (($year % 400) == 0)\n ? 1\n : ((($year % 100) == 0)\n ? 0\n : ((($year % 4) == 0)\n ? 1\n : 0));\n</code></pre>\n<p>This can be written more concise and be made much more readable with this formatting:</p>\n<pre><code>//--------------Test expression-----Result\n$isLeapYear = (($year % 400) == 0) ? 1 :\n ((($year % 100) == 0)? 0 :\n ((($year % 4) == 0) ? 1 :\n 0)); // Default result\n</code></pre>\n" }, { "answer_id": 3946860, "author": "John John", "author_id": 477577, "author_profile": "https://Stackoverflow.com/users/477577", "pm_score": 3, "selected": false, "text": "<p>(Hack of the day)</p>\n\n<pre><code>#define IF(x) x ?\n#define ELSE :\n</code></pre>\n\n<p>Then you can do if-then-else as expression:</p>\n\n<pre><code>int b = IF(condition1) res1\n ELSE IF(condition2) res2\n ELSE IF(conditions3) res3\n ELSE res4;\n</code></pre>\n" }, { "answer_id": 5275297, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "<p>I would say that the number of <em>conditions</em> in a logic expression make it harder to read. This is true of an if statement and this is true of a ternary <em>operator</em>. In a perfect world, there should be <em>one</em> summarizable reason for taking a branch as opposed to others. Chances are that it really is more of a &quot;business rule&quot; if your explanation is &quot;only when this cluster of states occur&quot;.</p>\n<p>However, in the <em>real</em> world, we don't add intermediate steps to fold states into one expressible state simply to obey the ideal case. We have made inferences about multiple states and have to make a decision on how to handle them.</p>\n<p>I <em>like</em> ternaries because it's possible to do <em>anything</em> with an if statement.</p>\n<pre><code>if( object.testSomeCondition()) {\n System.exec( &quot;format c:&quot; );\n}\nelse {\n a++;\n}\n</code></pre>\n<p>On the other hand:</p>\n<pre><code>a += ( object.testSomeCondition() ? 0 : 1 );\n</code></pre>\n<p>makes it <em>clear</em> that the goal is to find a value for <code>a</code>. Of course, in line with that, there probably <em>shouldn't</em> be more than reasonable side effects.</p>\n<ul>\n<li><p>I use an <code>if</code> for long or complex conditions after I've decided whether I have the time to rework conditions upstream so that I'm answering an easier question. But when I use an if, I <em>still</em> try to do <em>parallel</em> processing, just under a different condition.</p>\n<pre><code> if ( user.hasRepeatedlyPressedOKWithoutAnswer()\n &amp;&amp; me.gettingTowardMyLunchtime( time )\n ) {\n ...\n }\n</code></pre>\n</li>\n<li><p>Also my goal is <em>near</em>-single-stream processing. So I often try <em>not</em> to do an <code>else</code> and an <code>if</code> is simply a step off the common path. When you do a lot of single-stream processing, it's much harder for bugs to hide in your code waiting for that one condition that will jump out and break things.</p>\n</li>\n<li><p>As I said above, if you use a ternary to set <em>one</em> thing, or you have a small number of cases you want to test in order to set it to a value, then I just <em>like</em> the <em>readability</em> of a ternary.</p>\n</li>\n<li><p>With one caveat--&gt; <em>NO COMPLEX true CLAUSES</em></p>\n<pre><code> a = b == c ? ( c == d ? ( c == e ? f : g ) : h ) : i;\n</code></pre>\n</li>\n</ul>\n<p>Of course that can be decomposed into:</p>\n<pre><code>a = b != c ? i\n : c != d ? h\n : c == e ? f\n : g\n ;\n</code></pre>\n<p>And it looks like a (<em>compressed</em>) truth table.</p>\n<p>Remember that there are <em>more important</em> factors for readability. One of them is block length and another is indentation level. Doing simple things in ternaries doesn't create an impetus to further and further levels of indentation.</p>\n" }, { "answer_id": 5509999, "author": "SoSo", "author_id": 667105, "author_profile": "https://Stackoverflow.com/users/667105", "pm_score": 0, "selected": false, "text": "<p>Making code smaller doesn't always mean it's easier to parse. It differs from language to language.</p>\n<p>In <a href=\"https://en.wikipedia.org/wiki/PHP\" rel=\"nofollow noreferrer\">PHP</a> for example, whitespace and line-breaks are encouraged since PHP's lexer first breaks the code up in bits starting with line-breaks and then whitespace. So I do not see a performance issue, unless less whitespace is used.</p>\n<p>Bad:</p>\n<pre><code>($var)?1:0;\n</code></pre>\n<p>Good:</p>\n<pre><code>($var) ? 1 : 0;\n</code></pre>\n<p>It doesn't seem like a big issue, but with lexing code in PHP, whitespace is essential. Plus, it also reads a bit better this way.</p>\n" }, { "answer_id": 5970245, "author": "gion_13", "author_id": 491075, "author_profile": "https://Stackoverflow.com/users/491075", "pm_score": 1, "selected": false, "text": "<p>Use it to:</p>\n<ul>\n<li><p>access object (array) properties:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var status = statuses[error == null ? 'working' : 'stopped'];\n</code></pre>\n</li>\n<li><p>return statements:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function getFullName(){\n return this.isMale() ? &quot;Mr. &quot; : &quot;Ms. &quot; + this.name;\n}\n</code></pre>\n</li>\n<li><p>initialize variables:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var formMethod = DEBUG_FLAG == true ? &quot;GET&quot; : &quot;POST&quot;;\n</code></pre>\n</li>\n<li><p>validate arguments:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function(object){\n var prop1 = typeof object.property == 'undefined'\n ? &quot;default prop&quot;\n : object.property;\n //...\n}\n</code></pre>\n</li>\n</ul>\n<p>Code examples are in <a href=\"https://en.wikipedia.org/wiki/JavaScript\" rel=\"nofollow noreferrer\">JavaScript</a>.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21804/" ]
I'm personally an advocate of the [ternary operator](https://en.wikipedia.org/wiki/%3F:): `() ? :` I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often. What are your feelings on it? What interesting code have you seen using it?
Use it for **simple expressions only**: ``` int a = (b > 10) ? c : d; ``` **Don't chain or nest** ternary operators as it hard to read and confusing: ``` int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8; ``` Moreover, when using ternary operator, consider formatting the code in a way that improves readability: ``` int a = (b > 10) ? some_value : another_value; ```
160,233
<p>I tried this in mysql:</p> <pre><code>mysql&gt; alter table region drop column country_id; </code></pre> <p>And got this:</p> <pre><code>ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to './product/region' (errno: 150) </code></pre> <p>Any ideas? Foreign key stuff?</p>
[ { "answer_id": 160261, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 0, "selected": false, "text": "<p>I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?</p>\n\n<p>I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.</p>\n\n<p>I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.</p>\n" }, { "answer_id": 179501, "author": "Harrison Fisk", "author_id": 16111, "author_profile": "https://Stackoverflow.com/users/16111", "pm_score": 7, "selected": false, "text": "<p>It is indeed a foreign key error, you can find out using perror:</p>\n\n<pre><code>shell$ perror 150\nMySQL error code 150: Foreign key constraint is incorrectly formed\n</code></pre>\n\n<p>To find out more details about what failed, you can use <code>SHOW ENGINE INNODB STATUS</code> and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong. </p>\n\n<p>In your case, it is most likely cause something is referencing the country_id column.</p>\n" }, { "answer_id": 1605819, "author": "Jeroen", "author_id": 194409, "author_profile": "https://Stackoverflow.com/users/194409", "pm_score": 4, "selected": false, "text": "<p>You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.</p>\n\n<p>If the foreign key does exist, and you are still getting this error try the following:</p>\n\n<pre><code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;\nSET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;\nSET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';\n</code></pre>\n\n<p>// Drop the foreign key here!</p>\n\n<pre><code>SET SQL_MODE=@OLD_SQL_MODE;\nSET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;\nSET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;\n</code></pre>\n\n<p>This always does the trick for me :)</p>\n" }, { "answer_id": 2456269, "author": "marabol", "author_id": 169533, "author_profile": "https://Stackoverflow.com/users/169533", "pm_score": 1, "selected": false, "text": "<p>Take a look in error file for your mysql database. According to <a href=\"http://bugs.mysql.com/bug.php?id=26305\" rel=\"nofollow noreferrer\">Bug #26305</a> my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)</p>\n" }, { "answer_id": 5615783, "author": "Jeshurun", "author_id": 473637, "author_profile": "https://Stackoverflow.com/users/473637", "pm_score": 9, "selected": true, "text": "<p>You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.</p>\n\n<p>But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:</p>\n\n<blockquote>\n <p>SHOW CREATE TABLE region;</p>\n</blockquote>\n\n<p>This should show you the name of the index, something like this:</p>\n\n<blockquote>\n <p>CONSTRAINT <code>region_ibfk_1</code> FOREIGN\n KEY (<code>country_id</code>) REFERENCES\n <code>country</code> (<code>id</code>) ON DELETE NO\n ACTION ON UPDATE NO ACTION</p>\n</blockquote>\n\n<p>Now simply issue an:</p>\n\n<blockquote>\n <p>alter table region drop foreign key\n <code>region_ibfk_1</code>;</p>\n</blockquote>\n\n<p>And finally an:</p>\n\n<blockquote>\n <p>alter table region drop column\n country_id;</p>\n</blockquote>\n\n<p>And you are good to go!</p>\n" }, { "answer_id": 14223419, "author": "iltaf khalid", "author_id": 1209409, "author_profile": "https://Stackoverflow.com/users/1209409", "pm_score": 1, "selected": false, "text": "<p>If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.</p>\n\n<p>Then you can run the query like this:</p>\n\n<pre><code>alter table table_name drop foreign_key_col_name;\n</code></pre>\n" }, { "answer_id": 14997309, "author": "Muhammad Sohail", "author_id": 1006905, "author_profile": "https://Stackoverflow.com/users/1006905", "pm_score": 3, "selected": false, "text": "<p>Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.</p>\n\n<pre><code>ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;\n</code></pre>\n\n<p>here in <code>DROP KEY</code> instead of <code>DROP FOREIGN KEY</code>,</p>\n\n<p>hope it will help.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 34722679, "author": "youngdero", "author_id": 5543469, "author_profile": "https://Stackoverflow.com/users/5543469", "pm_score": 1, "selected": false, "text": "<p>There is probably another table with a foreign key referencing the primary key you are trying to change.</p>\n\n<p>To find out which table caused the error you can run <code>SHOW ENGINE INNODB</code> <code>STATUS</code> and then look at the <code>LATEST FOREIGN KEY ERROR</code> section</p>\n\n<p>Use SHOW CREATE TABLE categories to show the name of constraint.</p>\n\n<p>Most probably it will be categories_ibfk_1</p>\n\n<p>Use the name to drop the foreign key first and the column then:</p>\n\n<pre><code>ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;\nALTER TABLE categories DROP COLUMN assets_id;\n</code></pre>\n" }, { "answer_id": 34736306, "author": "Joomler", "author_id": 3114661, "author_profile": "https://Stackoverflow.com/users/3114661", "pm_score": 2, "selected": false, "text": "<p>I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.</p>\n\n<p>You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.</p>\n" }, { "answer_id": 35621320, "author": "chepaiytrath", "author_id": 4571486, "author_profile": "https://Stackoverflow.com/users/4571486", "pm_score": 0, "selected": false, "text": "<p>In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:</p>\n\n<ol>\n<li><p>Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.</p></li>\n<li><p>Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.</p></li>\n<li><p>Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;</p></li>\n<li><p>Now you can execute the drop statement which shall execute successfully.</p></li>\n</ol>\n" }, { "answer_id": 41543786, "author": "Baccata", "author_id": 5627467, "author_profile": "https://Stackoverflow.com/users/5627467", "pm_score": 2, "selected": false, "text": "<p>I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.</p>\n\n<p>However, there is an easy \"hack\" for fixing this issue:</p>\n\n<p>Before you execute your command(s) you first have to disable the foreign key constraints check using this command:</p>\n\n<pre><code>SET FOREIGN_KEY_CHECKS = 0;\n</code></pre>\n\n<p>Then you are able to execute your command(s).</p>\n\n<p>After you are done, don't forget to enable the foreign key constraints check again, using this command:</p>\n\n<pre><code>SET FOREIGN_KEY_CHECKS = 1;\n</code></pre>\n\n<p>Good luck with your endeavor.</p>\n" }, { "answer_id": 41652252, "author": "Jan Tchärmän", "author_id": 3018891, "author_profile": "https://Stackoverflow.com/users/3018891", "pm_score": 0, "selected": false, "text": "<p>Doing</p>\n\n<pre><code>SET FOREIGN_KEY_CHECKS=0;\n</code></pre>\n\n<p>before the Operation can also do the trick.</p>\n" }, { "answer_id": 54046313, "author": "Chris Millard", "author_id": 10869430, "author_profile": "https://Stackoverflow.com/users/10869430", "pm_score": 1, "selected": false, "text": "<p>I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN. </p>\n\n<p>The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the \"temporary\" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.</p>\n\n<p>In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.</p>\n\n<p>My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread. </p>\n" }, { "answer_id": 60970389, "author": "Naman Dhameja", "author_id": 11379485, "author_profile": "https://Stackoverflow.com/users/11379485", "pm_score": -1, "selected": false, "text": "<p>averageRatings= FOREACH groupedRatings <strong>GENERATE group AS</strong> movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;</p>\n\n<p>If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601671/" ]
I tried this in mysql: ``` mysql> alter table region drop column country_id; ``` And got this: ``` ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to './product/region' (errno: 150) ``` Any ideas? Foreign key stuff?
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column. But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select: > > SHOW CREATE TABLE region; > > > This should show you the name of the index, something like this: > > CONSTRAINT `region_ibfk_1` FOREIGN > KEY (`country_id`) REFERENCES > `country` (`id`) ON DELETE NO > ACTION ON UPDATE NO ACTION > > > Now simply issue an: > > alter table region drop foreign key > `region_ibfk_1`; > > > And finally an: > > alter table region drop column > country\_id; > > > And you are good to go!
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
[ { "answer_id": 160271, "author": "jmissao", "author_id": 20883, "author_profile": "https://Stackoverflow.com/users/20883", "pm_score": 0, "selected": false, "text": "<p>It works if you use os instead of commands:</p>\n\n<pre><code>import os\nprint os.system(\"ps -u 0\")\n</code></pre>\n" }, { "answer_id": 160284, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 3, "selected": false, "text": "<p>The cross-platform replacement for <code>commands</code> is <code>subprocess</code>. See the <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"noreferrer\">subprocess module documentation</a>. The 'Replacing older modules' section includes <a href=\"http://docs.python.org/lib/node534.html\" rel=\"noreferrer\">how to get output from a command</a>.</p>\n\n<p>Of course, you still have to pass the right arguments to 'ps' for the platform you're on. Python can't help you with that, and though I've seen occasional mention of third-party libraries that try to do this, they usually only work on a few systems (like strictly SysV style, strictly BSD style, or just systems with /proc.)</p>\n" }, { "answer_id": 160316, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 1, "selected": false, "text": "<p>I've tried in on OS X (10.5.5) and seems to work just fine:</p>\n\n<pre><code>print commands.getoutput(\"ps -u 0\")\n\nUID PID TTY TIME CMD\n0 1 ?? 0:01.62 /sbin/launchd\n0 10 ?? 0:00.57 /usr/libexec/kextd\n</code></pre>\n\n<p>etc.</p>\n\n<p>Python 2.5.1</p>\n" }, { "answer_id": 160375, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "<p>This works on Mac OS X 10.5.5. Note the capital <strong>-U</strong> option. Perhaps that's been your problem.</p>\n\n<pre><code>import subprocess\nps = subprocess.Popen(\"ps -U 0\", shell=True, stdout=subprocess.PIPE)\nprint ps.stdout.read()\nps.stdout.close()\nps.wait()\n</code></pre>\n\n<p>Here's the Python version</p>\n\n<pre><code>Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) \n[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin\n</code></pre>\n" }, { "answer_id": 3710903, "author": "Bill", "author_id": 447565, "author_profile": "https://Stackoverflow.com/users/447565", "pm_score": 1, "selected": false, "text": "<p>any of the above python calls - but try 'pgrep \n" }, { "answer_id": 6265416, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 3, "selected": false, "text": "<p>If the OS support the /proc fs you can do:</p>\n\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]\n&gt;&gt;&gt; pids\n[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]\n&gt;&gt;&gt;\n</code></pre>\n\n<p>A cross-platform solution (linux, freebsd, osx, windows) is by using <a href=\"http://code.google.com/p/psutil/\" rel=\"nofollow noreferrer\">psutil</a>:</p>\n\n<pre><code>&gt;&gt;&gt; import psutil\n&gt;&gt;&gt; psutil.pids()\n[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444] \n&gt;&gt;&gt;\n</code></pre>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
I'm trying: ``` import commands print commands.getoutput("ps -u 0") ``` But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND nothing more
This works on Mac OS X 10.5.5. Note the capital **-U** option. Perhaps that's been your problem. ``` import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() ``` Here's the Python version ``` Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin ```
160,250
<p>Just that, if you embed an icon:</p> <pre><code>[Embed(source='icons/checkmark.png')] private static var CheckMark:Class; </code></pre> <p>You end up with a dynamic class. You can pretty easily assign the icon to a button at runtime by calling the setStyle method:</p> <pre><code>var btn:Button = new Button(); btn.setStyle("icon", CheckMark); </code></pre> <p>But what if you wanted to alter the icon at runtime, like changing it's alpha value or even redrawing pixels, before assigning it to the button?</p> <p>So far I can't find a satisfactory answer...</p>
[ { "answer_id": 160952, "author": "Buns of Aluminum", "author_id": 24246, "author_profile": "https://Stackoverflow.com/users/24246", "pm_score": 3, "selected": true, "text": "<p>This is the only answer I could find that seemed close: <a href=\"http://blog.xsive.co.nz/archives/234\" rel=\"nofollow noreferrer\">Dynamic Icons</a> <a href=\"http://blog.xsive.co.nz/flex_source/button_icon_drawing/ButtonTest.html\" rel=\"nofollow noreferrer\">(example with View Source)</a></p>\n\n<p>His solution involves a custom \"DynamicIcon\" class which is used in the button's icon setting, and a custom Button class which adds one method to the Button class to draw dynamic icons.</p>\n\n<p>The end result is that you are able to send BitmapData to the DynamicIcon class, which will show up in the button. So, embed your image, instantiate your asset class, get the bitmapasset and modify it however you need to and send the bitmapData to the icon.</p>\n\n<p>It's an interesting problem and it seems like there should be an easier solution, but this works without a lot of hassle.</p>\n" }, { "answer_id": 163586, "author": "Aaron", "author_id": 23965, "author_profile": "https://Stackoverflow.com/users/23965", "pm_score": 0, "selected": false, "text": "<p>The way I'd solve this is to implement a programmatic skin class that draws the icon itself manually. There's probably more work you'll have to do to ensure the button calculates the correct size as if it has an icon even though it doesn't. You may have to poke through the Button source code to look at how the reference to the icon is stored.</p>\n\n<p>I love just creating programmatic skins that do exactly what I want and then using interesting CSS declarations to modify states - for instance:</p>\n\n<pre><code>button.setStyle(\"customIconAlpha\", .4);\n</code></pre>\n\n<p>and then of course the skin or the custom button class would have:</p>\n\n<pre><code>var alpha:Number = getStyle(\"customIconAlpha\") as Number;\n</code></pre>\n\n<p>(not sure if you have to typecast that one)</p>\n" }, { "answer_id": 710426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The big problem I found with programmatic skins is that the button refuses to measure the width/height. I easily got around this by overriding the get methods for each:</p>\n\n<p>override public function get width():Number { return WIDTH; }\noverride public function get height():Number { return HEIGHT; }</p>\n\n<p>In my case I needed to modify buttons in a TabNavigator, hence no easy way to subclass the button. Thankfully, the parent of each skin is the button, so using static methods within your skin, you can identify the instance of the Button to which the icon skins belong.</p>\n\n<p>If you're using the cover-all \"icon\" style, a new skin object will be created for each state. So you'll need to keep this in mind when changing the state of the icons.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16258/" ]
Just that, if you embed an icon: ``` [Embed(source='icons/checkmark.png')] private static var CheckMark:Class; ``` You end up with a dynamic class. You can pretty easily assign the icon to a button at runtime by calling the setStyle method: ``` var btn:Button = new Button(); btn.setStyle("icon", CheckMark); ``` But what if you wanted to alter the icon at runtime, like changing it's alpha value or even redrawing pixels, before assigning it to the button? So far I can't find a satisfactory answer...
This is the only answer I could find that seemed close: [Dynamic Icons](http://blog.xsive.co.nz/archives/234) [(example with View Source)](http://blog.xsive.co.nz/flex_source/button_icon_drawing/ButtonTest.html) His solution involves a custom "DynamicIcon" class which is used in the button's icon setting, and a custom Button class which adds one method to the Button class to draw dynamic icons. The end result is that you are able to send BitmapData to the DynamicIcon class, which will show up in the button. So, embed your image, instantiate your asset class, get the bitmapasset and modify it however you need to and send the bitmapData to the icon. It's an interesting problem and it seems like there should be an easier solution, but this works without a lot of hassle.
160,298
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p> <p>Suppose you're given two Django Model-derived classes:</p> <pre><code>from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative) </code></pre> <p>and</p> <pre><code>from django.db import models class Mods(models.Model): ... </code></pre> <p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p> <p>I.e. I want to get a class likeso:</p> <pre><code>Cars_by_common_mods = [ { mods: { 'a' }, cars: { 'W1', 'W2' } }, { mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, }, { mods: { 'b' }, cars: { 'Y1', 'Y2' } }, { mods: { 'a', 'b', 'c' }, cars: { 'Z1' } }, ] </code></pre> <p>I've been thinking of something like:</p> <pre><code>def cars_by_common_mods(): cars = Cars.objects.all() mod_list = [] for car in cars: mod_list.append( { 'car': car, 'mods': list(car.mods.all()) } ret = [] for key, mods_group in groupby(list(mods), lambda x: set(x.mods)): ret.append(mods_group) return ret </code></pre> <p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p> <p><em>Cheers &amp; thanks!</em></p>
[ { "answer_id": 160552, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>check <a href=\"http://docs.djangoproject.com/en/dev//ref/templates/builtins/#regroup\" rel=\"nofollow noreferrer\">regroup</a>. it's only for templates, but i guess this kind of classification belongs to the presentation layer anyway.</p>\n" }, { "answer_id": 161082, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "<p>Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.</p>\n\n<pre><code>import itertools\n\ncars = [\n {'car': 'X2', 'mods': [1,2]},\n {'car': 'Y2', 'mods': [2]},\n {'car': 'W2', 'mods': [1]},\n {'car': 'X1', 'mods': [1,2]},\n {'car': 'W1', 'mods': [1]},\n {'car': 'Y1', 'mods': [2]},\n {'car': 'Z1', 'mods': [1,2,3]},\n {'car': 'X3', 'mods': [1,2]},\n]\n\ncars.sort(key=lambda car: car['mods'])\n\ncars_by_common_mods = {}\nfor k, g in itertools.groupby(cars, lambda car: car['mods']):\n cars_by_common_mods[frozenset(k)] = [car['car'] for car in g]\n\nprint cars_by_common_mods\n</code></pre>\n\n<p>Now, about those queries:</p>\n\n<pre><code>import collections\nimport itertools\nfrom operator import itemgetter\n\nfrom django.db import connection\n\ncursor = connection.cursor()\ncursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2')\ncars = collections.defaultdict(list)\nfor row in cursor.fetchall():\n cars[row[0]].append(row[1])\n\n# Here's one I prepared earlier, which emulates the sample data we've been working\n# with so far, but using the car id instead of the previous string.\ncars = {\n 1: [1,2],\n 2: [2],\n 3: [1],\n 4: [1,2],\n 5: [1],\n 6: [2],\n 7: [1,2,3],\n 8: [1,2],\n}\n\nsorted_cars = sorted(cars.iteritems(), key=itemgetter(1))\ncars_by_common_mods = []\nfor k, g in itertools.groupby(sorted_cars, key=itemgetter(1)):\n cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)})\n\nprint cars_by_common_mods\n\n# Which, for the sample data gives me (reformatted by hand for clarity)\n[{'cars': [3, 5], 'mods': [1]},\n {'cars': [1, 4, 8], 'mods': [1, 2]},\n {'cars': [7], 'mods': [1, 2, 3]},\n {'cars': [2, 6], 'mods': [2]}]\n</code></pre>\n\n<p>Now that you've got your lists of car ids and mod ids, if you need the complete objects to work with, you could do a single query for each to get a complete list for each model and create a lookup <code>dict</code> for those, keyed by their ids - then, I believe, Bob is your proverbial father's brother.</p>\n" }, { "answer_id": 161227, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 1, "selected": false, "text": "<p>You have a few problems here.</p>\n\n<p>You didn't sort your list before calling groupby, and this is required. From <a href=\"http://www.python.org/doc/2.5/lib/itertools-functions.html\" rel=\"nofollow noreferrer\">itertools documentation</a>:</p>\n\n<blockquote>\n <p>Generally, the iterable needs to already be sorted on the same key function.</p>\n</blockquote>\n\n<p>Then, you don't duplicate the list returned by groupby. Again, documentation states:</p>\n\n<blockquote>\n <p>The returned group is itself an iterator that shares the underlying iterable with\n groupby(). Because the source is shared, when the groupby object is advanced, the\n previous group is no longer visible. So, if that data is needed later, it should \n be stored as a list:</p>\n\n<pre><code>groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n</code></pre>\n</blockquote>\n\n<p>And final mistake is using sets as keys. They don't work here. A quick fix is to cast them to sorted tuples (there could be a better solution, but I cannot think of it now).</p>\n\n<p>So, in your example, the last part should look like this:</p>\n\n<pre><code>sortMethod = lambda x: tuple(sorted(set(x.mods)))\nsortedMods = sorted(list(mods), key=sortMethod)\nfor key, mods_group in groupby(sortedMods, sortMethod):\n ret.append(list(mods_group))\n</code></pre>\n" }, { "answer_id": 173592, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 1, "selected": false, "text": "<p>If performance is a concern (i.e. lots of cars on a page, or a high-traffic site), <a href=\"http://groups.google.com/group/django-developers/browse_thread/thread/9a672d5bbbe67562\" rel=\"nofollow noreferrer\">denormalization</a> makes sense, and simplifies your problem as a side effect.</p>\n\n<p>Be aware that denormalizing many-to-many relations might be a bit tricky though. I haven't run into any such code examples yet.</p>\n" }, { "answer_id": 178657, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 0, "selected": false, "text": "<p>Thank you all for the helpful replies. I've been plugging away at this problem. A 'best' solution still eludes me, but I've some thoughts.</p>\n\n<p>I should mention that the statistics of the data-set I'm working with. In 75% of the cases there will be one Mod. In 24% of the cases, two. In 1% of the cases there will be zero, or three or more. For every Mod, there is at least one unique Car, though a Mod may be applied to numerous Cars.</p>\n\n<p>Having said that, I've considered (but not implemented) something like-so:</p>\n\n<pre><code>class ModSet(models.Model):\n mods = models.ManyToManyField(Mod)\n</code></pre>\n\n<p>and change cars to </p>\n\n<pre><code>class Car(models.Model):\n modset = models.ForeignKey(ModSet)\n</code></pre>\n\n<p>It's trivial to group by Car.modset: I can use regroup, as suggested by Javier, for example. It seems a simpler and reasonably elegant solution; thoughts would be much appreciated.</p>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/160298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that. In Python, it's worth mentioning that the problem is somewhat related to [how-do-i-use-pythons-itertoolsgroupby](https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby). Suppose you're given two Django Model-derived classes: ``` from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative) ``` and ``` from django.db import models class Mods(models.Model): ... ``` How does one get a list of Cars, grouped by Cars with a common set of Mods? I.e. I want to get a class likeso: ``` Cars_by_common_mods = [ { mods: { 'a' }, cars: { 'W1', 'W2' } }, { mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, }, { mods: { 'b' }, cars: { 'Y1', 'Y2' } }, { mods: { 'a', 'b', 'c' }, cars: { 'Z1' } }, ] ``` I've been thinking of something like: ``` def cars_by_common_mods(): cars = Cars.objects.all() mod_list = [] for car in cars: mod_list.append( { 'car': car, 'mods': list(car.mods.all()) } ret = [] for key, mods_group in groupby(list(mods), lambda x: set(x.mods)): ret.append(mods_group) return ret ``` However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod\_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating. *Cheers & thanks!*
Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits. ``` import itertools cars = [ {'car': 'X2', 'mods': [1,2]}, {'car': 'Y2', 'mods': [2]}, {'car': 'W2', 'mods': [1]}, {'car': 'X1', 'mods': [1,2]}, {'car': 'W1', 'mods': [1]}, {'car': 'Y1', 'mods': [2]}, {'car': 'Z1', 'mods': [1,2,3]}, {'car': 'X3', 'mods': [1,2]}, ] cars.sort(key=lambda car: car['mods']) cars_by_common_mods = {} for k, g in itertools.groupby(cars, lambda car: car['mods']): cars_by_common_mods[frozenset(k)] = [car['car'] for car in g] print cars_by_common_mods ``` Now, about those queries: ``` import collections import itertools from operator import itemgetter from django.db import connection cursor = connection.cursor() cursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2') cars = collections.defaultdict(list) for row in cursor.fetchall(): cars[row[0]].append(row[1]) # Here's one I prepared earlier, which emulates the sample data we've been working # with so far, but using the car id instead of the previous string. cars = { 1: [1,2], 2: [2], 3: [1], 4: [1,2], 5: [1], 6: [2], 7: [1,2,3], 8: [1,2], } sorted_cars = sorted(cars.iteritems(), key=itemgetter(1)) cars_by_common_mods = [] for k, g in itertools.groupby(sorted_cars, key=itemgetter(1)): cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)}) print cars_by_common_mods # Which, for the sample data gives me (reformatted by hand for clarity) [{'cars': [3, 5], 'mods': [1]}, {'cars': [1, 4, 8], 'mods': [1, 2]}, {'cars': [7], 'mods': [1, 2, 3]}, {'cars': [2, 6], 'mods': [2]}] ``` Now that you've got your lists of car ids and mod ids, if you need the complete objects to work with, you could do a single query for each to get a complete list for each model and create a lookup `dict` for those, keyed by their ids - then, I believe, Bob is your proverbial father's brother.
160,304
<p>I am using sybase database to query the daily transaction report. I had subquery within my script. </p> <p>Here as it goes:</p> <pre><code>SELECT orders.accountid ,items.x,etc (SELECT charges.mistotal FROM charges where items.id = charges.id) FROM items,orders WHERE date = '2008-10-02' </code></pre> <p>Here I am getting the error message as:</p> <blockquote> <p><em>Subquery cannot return more than one values</em></p> </blockquote> <p>My values are 7.50, 25.00</p> <p>I want to return the 25.00, but when I use </p> <pre><code>(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id) </code></pre> <p>My result is 7.50 but I want to return 25.00</p> <p>Does anyone has any better suggestion?</p>
[ { "answer_id": 160322, "author": "Manuel Ferreria", "author_id": 4749, "author_profile": "https://Stackoverflow.com/users/4749", "pm_score": 2, "selected": false, "text": "<p>Under what criteria you choose to select the 25.00 instead of the 7.5?</p>\n\n<p>If its related to the maximum value, you can try using the <strong>MAX()</strong> function on that field.</p>\n\n<p>If its related to the chronologically last row added, try using the <strong>MAX()</strong> on the datetime field, if you have details on the hours and minutes it was added.</p>\n" }, { "answer_id": 160327, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<p>You could try this:</p>\n\n<pre><code>SELECT MAX(charges.mistotal) FROM charges WHERE items.id = charges.id\n</code></pre>\n" }, { "answer_id": 160338, "author": "senfo", "author_id": 10792, "author_profile": "https://Stackoverflow.com/users/10792", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT TOP 1 * \nFROM dbo.YourTable \nORDER BY Col DESC\n</code></pre>\n\n<p>In your case, I guess that would be</p>\n\n<pre><code>SELECT TOP 1 charges.mistotal \nFROM charges where items.id = charges.id \nORDER BY charges.mistotal DESC\n</code></pre>\n" }, { "answer_id": 160339, "author": "CodeRedick", "author_id": 17145, "author_profile": "https://Stackoverflow.com/users/17145", "pm_score": 0, "selected": false, "text": "<p>SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id \nORDER BY charges.id DESC</p>\n\n<p>The order by clause will make sure it comes back in the order of the id, and the DESC means descending so it will give you the largest (newest) value first. TOP 1 of course makes sure you just get that one.</p>\n" }, { "answer_id": 160343, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 0, "selected": false, "text": "<p>Sort your subquery. If you want the \"last\" value, you need to define how you determine which item comes last (remember, SQL result sets are unordered by default).</p>\n\n<p>For example:</p>\n\n<pre><code>(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id \n ORDER BY charges.mistotal DESC)\n</code></pre>\n\n<p>This would return 25.00 instead of 7.50 (from your data examples above), but I'm assuming that you want this value to be \"last\" because it's bigger. There may be some other field that it makes more sense for you to sort on; maybe you have a timestamp column, for example, and you could sort on that to get the most recent value instead of the largest value. The key is just defining what you mean by \"last\".</p>\n" }, { "answer_id": 160355, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "<p>So, can you use inverse order:</p>\n\n<pre><code>(SELECT TOP 1 charges.mistotal\n FROM charges\n WHERE items.id = charges.id\n ORDER BY charges.mistotal DESC\n)\n</code></pre>\n\n<p>Actually, since you didn't give an explicit order, the sequence of the returned results is undefined, and you are just lucky that it gave you the answer you didn't want; it could have given you the answer you wanted, and then you might not have noticed that it was not always correct until after it went into production.</p>\n\n<p>Or, can you use:</p>\n\n<pre><code>(SELECT MAX(charges.mistotal)\n FROM charges\n WHERE charges.id = items.id\n)\n</code></pre>\n\n<p>Or did you really want a SUM?</p>\n" }, { "answer_id": 160437, "author": "Zote", "author_id": 20683, "author_profile": "https://Stackoverflow.com/users/20683", "pm_score": 1, "selected": false, "text": "<p>To get first you use select top 1 | first * from table <strong><em>order ascending</em></strong> to get last, just invert your order.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I am using sybase database to query the daily transaction report. I had subquery within my script. Here as it goes: ``` SELECT orders.accountid ,items.x,etc (SELECT charges.mistotal FROM charges where items.id = charges.id) FROM items,orders WHERE date = '2008-10-02' ``` Here I am getting the error message as: > > *Subquery cannot return more than one values* > > > My values are 7.50, 25.00 I want to return the 25.00, but when I use ``` (SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id) ``` My result is 7.50 but I want to return 25.00 Does anyone has any better suggestion?
``` SELECT TOP 1 * FROM dbo.YourTable ORDER BY Col DESC ``` In your case, I guess that would be ``` SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id ORDER BY charges.mistotal DESC ```
160,315
<p>I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup.</p> <p>Unfortunately, there is no obvious way to ask java whether a given key is <strong>currently being pressed</strong>. You can only register to be informed of new key presses via a KeyListener, but that doesn't help if the keypress starts before the app launches.</p>
[ { "answer_id": 160346, "author": "Rodrick Chapman", "author_id": 3927, "author_profile": "https://Stackoverflow.com/users/3927", "pm_score": 0, "selected": false, "text": "<p>I don't know much about Java (mostly code in C#) but what about having a small loader program written in C or something that then launches your Java app with some parameters (like whether or not a certain key is down)?</p>\n" }, { "answer_id": 160806, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": false, "text": "<pre><code>import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.JFrame;\n\npublic class LockingKeyDemo {\n static Toolkit kit = Toolkit.getDefaultToolkit();\n\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n\n frame.addWindowListener(new WindowAdapter() {\n public void windowActivated(WindowEvent e) {\n System.out.println(\"caps lock1 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n\n try {\n Robot robot = new Robot();\n robot.keyPress(KeyEvent.VK_CONTROL);\n robot.keyRelease(KeyEvent.VK_CONTROL);\n } catch (Exception e2) {\n System.out.println(e2);\n }\n\n System.out.println(\"caps lock2 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n }\n });\n\n frame.addKeyListener(new KeyAdapter() {\n public void keyReleased(KeyEvent e) {\n System.out.println(\"caps lock3 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n }\n });\n\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(200, 200);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n}\n</code></pre>\n" }, { "answer_id": 160851, "author": "Karan", "author_id": 11110, "author_profile": "https://Stackoverflow.com/users/11110", "pm_score": 2, "selected": false, "text": "<p>Well there are two types of key press detection: event based, and polling. If you poll the keyboard for <code>KEY_PRESSED</code> on startup (through a loop with a <code>sleep.thread(timeInMs)</code> constantly checking if your key is down), then you can detect if it's already pressed on startup.</p>\n" }, { "answer_id": 160861, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 2, "selected": true, "text": "<pre><code>public class LockingKeyDemo {\n static Toolkit kit = Toolkit.getDefaultToolkit();\n\n public static void main(String[] args) {\n System.out.println(\"caps lock2 = \"\n + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));\n}\n}\n</code></pre>\n" }, { "answer_id": 166155, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 0, "selected": false, "text": "<p>So it appears that you can do this, but only for caps lock et al. Hence, I've switched to using caps lock for this purpose. Not perfect, but OK.</p>\n" }, { "answer_id": 11713934, "author": "AlexV", "author_id": 206494, "author_profile": "https://Stackoverflow.com/users/206494", "pm_score": 2, "selected": false, "text": "<p>The original question seems to be not answered. The proposed method determines the locking key state like CapsLock, ScrollLock, etc. So it would not work for <strong>Alt</strong> pressed state.</p>\n\n<p>Consider the following code:</p>\n\n<p><code>com.sun.jna.platform.KeyboardUtils.isPressed(java.awt.event.KeyEvent.VK_ALT);</code></p>\n\n<p>The only problem is that this class is an internal Sun's JDK class and not likely to be available in any other JVM. Depend on your project it may or may not be acceptable.</p>\n\n<p>Internally it calls into User32.DLL on Windows:</p>\n\n<p><code>User32.INSTANCE.GetAsyncKeyState(...)</code></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15255/" ]
I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup. Unfortunately, there is no obvious way to ask java whether a given key is **currently being pressed**. You can only register to be informed of new key presses via a KeyListener, but that doesn't help if the keypress starts before the app launches.
``` public class LockingKeyDemo { static Toolkit kit = Toolkit.getDefaultToolkit(); public static void main(String[] args) { System.out.println("caps lock2 = " + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK)); } } ```
160,318
<p>The kind of simulation game that I have in mind is the kind where you have things to build in various locations and workers/transporters that connect such locations.</p> <p>Something more like the Settlers series.</p> <p>Let's assume I don't want any graphics at the moment, <strong>that</strong> I think I can manage.</p> <p>So my doubts are the following:</p> <ol> <li>Should every entity be a class and each one have a thread?</li> <li>Should entities be grouped in lists inside classes and each one have a thread?</li> </ol> <p>If one takes implementation 1, it's going to be very hard to run on low spec machines and does not scale well for large numbers.</p> <p>If one takes implementation 2, it's going to be better in terms of resources but then...</p> <p>How should I group the entities?</p> <ol> <li>Have a class for houses in general and have an Interface List to manage that?</li> <li>Have a class for specific groups of houses and have an Object List to manage that?</li> </ol> <p>and what about threads?</p> <ol> <li>Should I have the simplistic main game loop?</li> <li>Should I have a thread for each class group?</li> <li>How do workers/transporters fit in the picture?</li> </ol>
[ { "answer_id": 160349, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 2, "selected": false, "text": "<p>I'm fairly certain you only want to have one thread executing the game logic. Having multiple threads won't speed up anything, and will only make the code confusing. Having a main game loop is perfectly fine, though things get somewhat trickier if the game has multiplayer.</p>\n\n<p>I'm a bit confused about the part of your question relating to classes. If I understand your question correctly, my suggestion would be to have a class for each type of house (pig farm, windmill, etc) deriving from a common abstract base class <code>House</code>. You'd then store all the houses in the game world in a list of Houses.</p>\n" }, { "answer_id": 160356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>The normal approach does not use threading at all, but rather implements entities as state-machines. Then your mainloop looks like this:</p>\n\n<pre><code> while( 1 )\n{\n foreach( entity in entlist )\n {\n entity-&gt;update();\n }\n\n render();\n}\n</code></pre>\n" }, { "answer_id": 160380, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 0, "selected": false, "text": "<p>I would avoid making a separate class for each entity because then you'll have situations where you're either repeating code for shared capabilities, or you'll have a funky inheritance tree.</p>\n\n<p>I'd argue that what you want is a single class and objects with functionality composed onto it. I saw an article on a blog talking about this very concept in an RTS...wait, I think it was a tour of <a href=\"http://blog.cumps.be/design-patterns-decorator-pattern/\" rel=\"nofollow noreferrer\">design patterns that someone was writing</a>.</p>\n\n<p>Use the Visitor pattern spawning a thread on each object's DoEvents (for lack of a better word) method to tell each object to do what it's going to do during this given loop. Sync the threads at the end of your loop because you don't want to have some objects with complex logic still doing its thing from ten loops back when in reality it was destroyed five loops ago.</p>\n" }, { "answer_id": 160389, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 2, "selected": false, "text": "<p>The MMORPG Eve Online uses stackless python and the actor model to emulate a thread-per-entity system without the resource hit. </p>\n\n<p>Check out this link for more information:\n<a href=\"http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/\" rel=\"nofollow noreferrer\">http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/</a></p>\n" }, { "answer_id": 165407, "author": "ZeissS", "author_id": 23760, "author_profile": "https://Stackoverflow.com/users/23760", "pm_score": 1, "selected": false, "text": "<p>Think about using Erlang. With Erlang you can spawn a lot more processes (= lightweight threads) than a normal system thread. Further its distributed, meaning if your system isnt good enough, add another node.</p>\n\n<p>Another alternative would be stackless python (or the current python alternative), as it also support some kind of lightweightthread, which is very cool for game engines. Eve Online uses it for its servers. But it isn't distributed, but that can be easily achieved manually.</p>\n" }, { "answer_id": 12781435, "author": "Deer Hunter", "author_id": 1651408, "author_profile": "https://Stackoverflow.com/users/1651408", "pm_score": 1, "selected": false, "text": "<p>While the answer by @Mike F is mostly correct, you have to bear in mind that iteration over the entities in a <code>foreach</code> cycle makes the order of evaluation significantly deterministic, which has undesirable side-effects. On the other hand, introducing threads opens up potential for <em>heisenbugs</em> and concurrency issues, so the best way I have seen and used relies on combining two cycles: the first one collects actions from agents/workers based on previous state, the second cycle composes the results of the actions and updates the state of the simulation. To avoid possible bias, at each cycle the order of evaluation is randomized. This BTW scales to massively parallel evaluation, subject to a synchronization at the end of each cycle.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ]
The kind of simulation game that I have in mind is the kind where you have things to build in various locations and workers/transporters that connect such locations. Something more like the Settlers series. Let's assume I don't want any graphics at the moment, **that** I think I can manage. So my doubts are the following: 1. Should every entity be a class and each one have a thread? 2. Should entities be grouped in lists inside classes and each one have a thread? If one takes implementation 1, it's going to be very hard to run on low spec machines and does not scale well for large numbers. If one takes implementation 2, it's going to be better in terms of resources but then... How should I group the entities? 1. Have a class for houses in general and have an Interface List to manage that? 2. Have a class for specific groups of houses and have an Object List to manage that? and what about threads? 1. Should I have the simplistic main game loop? 2. Should I have a thread for each class group? 3. How do workers/transporters fit in the picture?
The normal approach does not use threading at all, but rather implements entities as state-machines. Then your mainloop looks like this: ``` while( 1 ) { foreach( entity in entlist ) { entity->update(); } render(); } ```
160,370
<p>In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch.</p> <p>How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".</p>
[ { "answer_id": 160395, "author": "andy", "author_id": 21482, "author_profile": "https://Stackoverflow.com/users/21482", "pm_score": 7, "selected": true, "text": "<p>This will do it I think:</p>\n\n<pre><code>svn diff -r 22334:HEAD --summarize &lt;url of the branch&gt;\n</code></pre>\n" }, { "answer_id": 5207017, "author": "Robert Duchnik", "author_id": 590026, "author_profile": "https://Stackoverflow.com/users/590026", "pm_score": 6, "selected": false, "text": "<p>You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option</p>\n\n<pre><code>svn status -u\n</code></pre>\n\n<p>This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.</p>\n\n<p>There is a good tutorial on svn command here that explains a lot of these common scenarios: <a href=\"http://web.archive.org/web/20110316170621/http://www.duchnik.com/tutorials/vc/svn-command-reference\" rel=\"noreferrer\">SVN Command Reference</a></p>\n" }, { "answer_id": 9901966, "author": "Binny Jeshan", "author_id": 1297285, "author_profile": "https://Stackoverflow.com/users/1297285", "pm_score": 1, "selected": false, "text": "<p>-u option will display including object files if they are added during compilation.</p>\n\n<p>So, to overcome that additionally you may use like this.</p>\n\n<pre><code>svn status -u | grep -v '\\?' \n</code></pre>\n" }, { "answer_id": 11132492, "author": "hunter", "author_id": 1471184, "author_profile": "https://Stackoverflow.com/users/1471184", "pm_score": 4, "selected": false, "text": "<p>This will list only modified files:</p>\n\n<pre><code>svn status -u | grep M\n</code></pre>\n" }, { "answer_id": 11885510, "author": "Hasski", "author_id": 1587846, "author_profile": "https://Stackoverflow.com/users/1587846", "pm_score": 2, "selected": false, "text": "<pre><code>echo You must invoke st from within branch directory\nSvnUrl=`svn info | grep URL | sed 's/URL: //'`\nSvnVer=`svn info | grep Revision | sed 's/Revision: //'`\nsvn diff -r $SvnVer --summarize $SvnUrl\n</code></pre>\n" }, { "answer_id": 46920533, "author": "maskarih", "author_id": 3292365, "author_profile": "https://Stackoverflow.com/users/3292365", "pm_score": 5, "selected": false, "text": "<p>You can use the following command:</p>\n\n<pre><code>svn status -q\n</code></pre>\n\n<p>According to <a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.status.html\" rel=\"noreferrer\">svnbook</a>:</p>\n\n<p><code>With --quiet (-q), it prints only summary information about locally modified items.</code></p>\n\n<p>WARNING: The output of this command only shows your modification. So I suggest to do a <code>svn up</code> to get latest version of the file and then use <code>svn status -q</code> to get the files you have modified. </p>\n" }, { "answer_id": 57669761, "author": "Sweavo", "author_id": 11982419, "author_profile": "https://Stackoverflow.com/users/11982419", "pm_score": 1, "selected": false, "text": "<p><code>svn log -q -v</code> shows paths and hides comments. All the paths are indented so you can search for lines starting with whitespace. Then pipe to <code>cut</code> and <code>sort</code> to tidy up:</p>\n\n<p><code>svn log --stop-on-copy -q -v | grep '^[[:space:]]'| cut -c6- | sort -u</code></p>\n\n<p>This gets all the paths mentioned on the branch since its branch point. Note it will list deleted and added, as well as modified files. I just used this to get the stuff I should worry about reviewing on a slightly messy branch from a new dev.</p>\n" }, { "answer_id": 68303597, "author": "KawaiiGuyNH", "author_id": 11836321, "author_profile": "https://Stackoverflow.com/users/11836321", "pm_score": 1, "selected": false, "text": "<p>I do this as a two-step process. First, I find the version that was the origin of the branch. From within the checkout of the branch:</p>\n<p><code>svn log --stop-on-copy |tail -4</code></p>\n<p><code>--stop-on-copy</code> tells SVN to only operate on entries after the branch. <code>tail</code> gets you the last log entry, which is the one that contains the branch information. The number that begins with an 'r' is the revision at which you branched. Then, use <code>svn diff</code> to find changes since that version:</p>\n<p><code>svn diff -r &lt;revision at which you branched&gt;:head --summarize</code></p>\n<p>the --summarize option shows a file list only, without the actual diff contents, similar to the 'svn status' output. If you want to see the actual diff, just remove the <code>--summarize</code> option.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601671/" ]
In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch. How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".
This will do it I think: ``` svn diff -r 22334:HEAD --summarize <url of the branch> ```
160,373
<pre><code>Function FillAdminAccount() As Boolean FillAdminAccount = True Try SQLconn.ConnectionString = "connect timeout=9999999;" &amp; _ "data source=" &amp; DefaultIserver &amp; ";" &amp; _ "initial catalog=" &amp; DefaultIdBase &amp; "; " &amp; _ "user id=userid;" &amp; _ "password=userpass;" &amp; _ "persist security info=True; " &amp; _ "packet size=4096" SQLconn.Open() SQLcmd.CommandType = CommandType.Text SQLcmd.CommandText = "Select distinct username, cast(convert(varchar,userpassword) as varchar) as 'userpassword' from " &amp; tblUsersList &amp; " where usertype='MainAdmin'" SQLcmd.Connection = SQLconn SQLreader = SQLcmd.ExecuteReader While SQLreader.Read = True CurrentAdminUser = SQLreader("username").ToString CurrentAdminPass = SQLreader("userpassword").ToString 'PROBLEM' End While Catch ex As Exception ErrorMessage(ex) Finally If SQLconn.State = ConnectionState.Open Then SQLconn.Close() If SQLreader.IsClosed = False Then SQLreader.Close() End Try End Function 'FillAdminAccount </code></pre> <p>Please see the line with the comment PROBLEM. On this code, the output is equal to <em>"userpassword</em>. As you can see, there is no quotation mark on the right and <strong>I wonder why</strong>. By the way, the data type of the userpassword in the database is BINARY. Wish you could help me on this. Thank you..x_x</p>
[ { "answer_id": 160396, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "<p>Could it be </p>\n\n<pre><code>as varchar) as 'userpassword'\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>...as varchar) as [userpassword] ..\n</code></pre>\n\n<p>or</p>\n\n<pre><code>...as varchar) as userpassword ..\n</code></pre>\n" }, { "answer_id": 160443, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<p>NEVER store actual passwords in the db. Now it looks like your passwords <em>might</em> not quite be plain text because of the convert/cast operations, but you still have a problem. At very least any encryption used is easily reversible, and if your sql server ever ends up on a different machine from the application then passwords will be traveling over the wire in plain text.</p>\n\n<p>If you MUST do this (perhaps because of a legacy system or mandate from above) then <em>at least</em> do the matching <em>at the server</em> so that the password never comes back to the application.</p>\n\n<p>What you <em>should</em> be doing is using something like SQL Server 2005's HashBytes() function to only store a hash of the actual password. When someone tries to login, hash their attempted password and match up the hashes.</p>\n\n<p>As to your specific question, my guess is the cast or convert operation failed resulting in a NULL value coming back to the application. And do you have <em>both</em> a CAST() <em>and</em> a CONVERT() to the same type? It's redundant.</p>\n" }, { "answer_id": 160457, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "<p>@Oglester is right, it's the single quotes around 'userpassword'.</p>\n\n<p>This is not a bug, but it's just dumb: </p>\n\n<pre><code> cast(convert(varchar,userpassword) as varchar\n</code></pre>\n\n<p>You can use cast or convert but there's no point in using both. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21963/" ]
``` Function FillAdminAccount() As Boolean FillAdminAccount = True Try SQLconn.ConnectionString = "connect timeout=9999999;" & _ "data source=" & DefaultIserver & ";" & _ "initial catalog=" & DefaultIdBase & "; " & _ "user id=userid;" & _ "password=userpass;" & _ "persist security info=True; " & _ "packet size=4096" SQLconn.Open() SQLcmd.CommandType = CommandType.Text SQLcmd.CommandText = "Select distinct username, cast(convert(varchar,userpassword) as varchar) as 'userpassword' from " & tblUsersList & " where usertype='MainAdmin'" SQLcmd.Connection = SQLconn SQLreader = SQLcmd.ExecuteReader While SQLreader.Read = True CurrentAdminUser = SQLreader("username").ToString CurrentAdminPass = SQLreader("userpassword").ToString 'PROBLEM' End While Catch ex As Exception ErrorMessage(ex) Finally If SQLconn.State = ConnectionState.Open Then SQLconn.Close() If SQLreader.IsClosed = False Then SQLreader.Close() End Try End Function 'FillAdminAccount ``` Please see the line with the comment PROBLEM. On this code, the output is equal to *"userpassword*. As you can see, there is no quotation mark on the right and **I wonder why**. By the way, the data type of the userpassword in the database is BINARY. Wish you could help me on this. Thank you..x\_x
NEVER store actual passwords in the db. Now it looks like your passwords *might* not quite be plain text because of the convert/cast operations, but you still have a problem. At very least any encryption used is easily reversible, and if your sql server ever ends up on a different machine from the application then passwords will be traveling over the wire in plain text. If you MUST do this (perhaps because of a legacy system or mandate from above) then *at least* do the matching *at the server* so that the password never comes back to the application. What you *should* be doing is using something like SQL Server 2005's HashBytes() function to only store a hash of the actual password. When someone tries to login, hash their attempted password and match up the hashes. As to your specific question, my guess is the cast or convert operation failed resulting in a NULL value coming back to the application. And do you have *both* a CAST() *and* a CONVERT() to the same type? It's redundant.
160,382
<p>I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant.<br> For exemple:</p> <pre><code>Label l = new Label("Cat"); </code></pre> <p>Would become:</p> <pre><code>Label l = new Label(Constants.CAT); </code></pre> <p>And in <code>Constants.java</code> I would have:</p> <pre><code>public final static String CAT = "Cat"; </code></pre> <p><strong>I do not want the strings to be externalized in a property text file.</strong><br> One reason is for consistency and code readability.<br> The other is that our client code uses <code>GWT</code>, which does not support Java property text file mechanism.</p> <p>I could write some sort of parser (using ant replace task maybe)?<br> But I wondered if an <code>IDE</code> already does this sort of thing automatically.</p>
[ { "answer_id": 160407, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "<p>Eclipse does do this automatically. Right-click the file, choose \"Source\", then \"Externalize strings\"</p>\n\n<p>This doesn't do exactly what you requested (having the strings in a Constants.java file as Strings) but the method used is very powerful indeed. It moves them into a properties file which can be loaded dynamically depending on your locale. Having them in a separate Java source file as you suggest means you'll either have ALL languages in your application at once or you'll ship different applications depending on locale.</p>\n\n<p>We use it for our applications where even the basic stuff has to ship in English and Japanese - our more complicated applications ship with 12 languages - we're not a small software development company by any means :-).</p>\n\n<p>If you <em>do</em> want them in a Java file, despite the shortcomings already mentioned, it's a lot easier to write a program to morph the properties file into a Java source file than it is to try and extract the strings from free-form Java source.</p>\n\n<p>All you then need to do is modify the Accessor class to use the in-built strings (in the separate class) rather than loading them at run time.</p>\n" }, { "answer_id": 160621, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 1, "selected": false, "text": "<p>There are some good reasons why you wouldn't want to do this. Aside from the fact that any such generated file (I didn't know about the eclipse function)is not going to distinguish between strings that you're setting, for example, as constructor args in test classes and things you actually want to have as constants, the bigger issue is that all of your public static finals are going to be compiled into your classes, and if you want to alter the classes behaviour you'll need to alter not only the class holding the constants but everything that references it. </p>\n" }, { "answer_id": 160967, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 1, "selected": false, "text": "<p>I fully acknowledge what Pax Diablo said. We're using that function too.</p>\n\n<p>When applied to a class file the function \"Externalize strings\" will create two files, a class Messages.class and a properties file messages.properties. Then it will redirect all direct usages of string literals to a call to Messages.get(String key) and using the key you entered for the string in the \"Ext. String\" wizard. </p>\n\n<p>BTW: What's so bad about property files? As he said, you can just change the properties file and don't have to change the class if you need to change the text.</p>\n\n<p>Another advantage is this one: The way of extracting the string literals into a property file leaves you free to translate the source language in any language you want <strong>without modifying any code</strong>. The properties file loader loads the target language file automatically by using the corresponding file with the language iso code. So you don't have to worry about the platform your code runs on, it will select the appropriate language (nearly) automatically. See documentation of class <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/ResourceBundle.html\" rel=\"nofollow noreferrer\">ResourceBundle</a> for how this works in detail.</p>\n" }, { "answer_id": 161002, "author": "Peter Kelley", "author_id": 14893, "author_profile": "https://Stackoverflow.com/users/14893", "pm_score": 0, "selected": false, "text": "<p>You may want to check out the <a href=\"http://jackpot.netbeans.org/\" rel=\"nofollow noreferrer\">Jackpot source transformation engine</a> in NetBeans which would allow you to script your source transformations. </p>\n" }, { "answer_id": 161145, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>To complete Peter Kelley answer, you might consider for eclipse IDE the <strong>AST</strong> solution.</p>\n\n<p>You might then write an AST program which parse your source code and does what you want.</p>\n\n<p>A full example is available in this <a href=\"http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html\" rel=\"nofollow noreferrer\">eclipse corner article</a>, also more details in the <a href=\"http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html\" rel=\"nofollow noreferrer\">eclipse help</a>.<br>\nAnd you can find some examples in <a href=\"http://www.eclipse.org/articles/Article-AutomatingDSLEmbeddings/#implementation_in_place\" rel=\"nofollow noreferrer\">Listing 5 of the section \"Implementation of in-place translation\" of <strong>Automating the embedding of Domain Specific Languages in Eclipse JDT</strong></a>, alongside <a href=\"https://github.com/search?q=%22org.eclipse.jdt.core.dom.ASTVisitor%22&amp;ref=cmdform&amp;type=Code\" rel=\"nofollow noreferrer\">multiple examples in GitHub projects</a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406/" ]
I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant. For exemple: ``` Label l = new Label("Cat"); ``` Would become: ``` Label l = new Label(Constants.CAT); ``` And in `Constants.java` I would have: ``` public final static String CAT = "Cat"; ``` **I do not want the strings to be externalized in a property text file.** One reason is for consistency and code readability. The other is that our client code uses `GWT`, which does not support Java property text file mechanism. I could write some sort of parser (using ant replace task maybe)? But I wondered if an `IDE` already does this sort of thing automatically.
To complete Peter Kelley answer, you might consider for eclipse IDE the **AST** solution. You might then write an AST program which parse your source code and does what you want. A full example is available in this [eclipse corner article](http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html), also more details in the [eclipse help](http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html). And you can find some examples in [Listing 5 of the section "Implementation of in-place translation" of **Automating the embedding of Domain Specific Languages in Eclipse JDT**](http://www.eclipse.org/articles/Article-AutomatingDSLEmbeddings/#implementation_in_place), alongside [multiple examples in GitHub projects](https://github.com/search?q=%22org.eclipse.jdt.core.dom.ASTVisitor%22&ref=cmdform&type=Code).
160,391
<p>I've got a ListBox control and I'm presenting a fixed number of ListBoxItem objects in a grid layout. So I've set my ItemsPanelTemplate to be a Grid.</p> <p>I'm accessing the Grid from code behind to configure the RowDefinitions and ColumnDefinitions.</p> <p>So far it's all working as I expect. I've got some custom IValueConverter implementations for returning the Grid.Row and Grid.Column that each ListBoxItem should appear in.</p> <p>However I get weird binding errors sometimes, and I can't figure out exactly why they're happening, or even if they're in my code.</p> <p>Here's the error I get:</p> <blockquote> <p><code>System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')</code></p> </blockquote> <p>Can anybody explain what's going on?</p> <p>Oh, and, here's my XAML:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;!-- Value Converters --&gt; &lt;v:GridRowConverter x:Key="GridRowConverter" /&gt; &lt;v:GridColumnConverter x:Key="GridColumnConverter" /&gt; &lt;v:DevicePositionConverter x:Key="DevicePositionConverter" /&gt; &lt;v:DeviceBackgroundConverter x:Key="DeviceBackgroundConverter" /&gt; &lt;Style x:Key="DeviceContainerStyle" TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="FocusVisualStyle" Value="{x:Null}" /&gt; &lt;Setter Property="Background" Value="Transparent" /&gt; &lt;Setter Property="Grid.Row" Value="{Binding Path=DeviceId, Converter={StaticResource GridRowConverter}}" /&gt; &lt;Setter Property="Grid.Column" Value="{Binding Path=DeviceId, Converter={StaticResource GridColumnConverter}}" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;Border CornerRadius="2" BorderThickness="1" BorderBrush="White" Margin="2" Name="Bd" Background="{Binding Converter={StaticResource DeviceBackgroundConverter}}"&gt; &lt;TextBlock FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=DeviceId, Converter={StaticResource DevicePositionConverter}}" &gt; &lt;TextBlock.LayoutTransform&gt; &lt;RotateTransform Angle="270" /&gt; &lt;/TextBlock.LayoutTransform&gt; &lt;/TextBlock&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsSelected" Value="true"&gt; &lt;Setter TargetName="Bd" Property="BorderThickness" Value="2" /&gt; &lt;Setter TargetName="Bd" Property="Margin" Value="1" /&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/UserControl.Resources&gt; &lt;Border CornerRadius="3" BorderThickness="3" Background="#FF333333" BorderBrush="#FF333333" &gt; &lt;Grid ShowGridLines="False"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="15" /&gt; &lt;RowDefinition Height="*" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;StackPanel Grid.Row="0" Orientation="Horizontal"&gt; &lt;Image Margin="20,3,3,3" Source="Barcode.GIF" Width="60" Stretch="Fill" /&gt; &lt;/StackPanel&gt; &lt;ListBox ItemsSource="{Binding}" x:Name="lstDevices" Grid.Row="1" ItemContainerStyle="{StaticResource DeviceContainerStyle}" Background="#FF333333" SelectedItem="{Binding SelectedDeviceResult, ElementName=root, Mode=TwoWay}" &gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;Grid&gt; &lt;Grid.LayoutTransform&gt; &lt;RotateTransform Angle="90" /&gt; &lt;/Grid.LayoutTransform&gt; &lt;/Grid&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;/ListBox&gt; &lt;/Grid&gt; &lt;/Border&gt; </code></pre> <p></p>
[ { "answer_id": 163728, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 1, "selected": false, "text": "<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/ms742521.aspx\" rel=\"nofollow noreferrer\">Data Templating Overview</a> on MSDN, <code>DataTemplates</code> should be used as the <code>ItemTemplate</code> to define how the data is presented, while a <code>Style</code> would be used as the <code>ItemContainerStyle</code> to style just the generated container, such as <code>ListBoxItem</code>.</p>\n\n<p>However, it appears that you are trying to use the latter to do the job of the former. I can't recreate your situation without much more code, but I suspect that doing databinding in the container style could be throwing a wrench in the assumed visual/logical tree.</p>\n\n<p>I also can't help but think that a custom layout of items based on the item's information calls for creating a custom <code>Panel</code>. It's probably better for the custom <code>Panel</code> to layout the items than for the items to lay themselves out with a Rube Goldberg assortment of <code>IValueConverters</code>.</p>\n" }, { "answer_id": 176410, "author": "ligaz", "author_id": 6409, "author_profile": "https://Stackoverflow.com/users/6409", "pm_score": 5, "selected": false, "text": "<p>The binding problem comes from the default style for ListBoxItem. By default when applying styles to elements WPF looks for the default styles and applies each property that is not specifically set in the custom style from the default style. Refer to <a href=\"http://www.interact-sw.co.uk/iangblog/2007/02/14/wpfdefaulttemplate\" rel=\"noreferrer\">this great blog post</a> By Ian Griffiths for more details on this behavior.</p>\n\n<p>Back to our problem. Here is the default style for ListBoxItem:</p>\n\n<pre><code>&lt;Style\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:s=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n TargetType=\"{x:Type ListBoxItem}\"&gt;\n &lt;Style.Resources&gt;\n &lt;ResourceDictionary/&gt;\n &lt;/Style.Resources&gt;\n &lt;Setter Property=\"Panel.Background\"&gt;\n &lt;Setter.Value&gt;\n &lt;SolidColorBrush&gt;\n #00FFFFFF\n &lt;/SolidColorBrush&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.HorizontalContentAlignment\"&gt;\n &lt;Setter.Value&gt;\n &lt;Binding Path=\"HorizontalContentAlignment\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}\"/&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.VerticalContentAlignment\"&gt;\n &lt;Setter.Value&gt;\n &lt;Binding Path=\"VerticalContentAlignment\" RelativeSource=\"{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}\"/&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.Padding\"&gt;\n &lt;Setter.Value&gt;\n &lt;Thickness&gt;\n 2,0,0,0\n &lt;/Thickness&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"Control.Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type ListBoxItem}\"&gt;\n ...\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;/Style&gt;\n</code></pre>\n\n<p>Note that I have removed the ControlTemplate to make it compact (I have used <a href=\"https://github.com/drewnoakes/style-snooper\" rel=\"noreferrer\">StyleSnooper</a> - to retrieve the style). You can see that there is a binding with a relative source set to ancestor with type ItemsControl. So in your case the ListBoxItems that are created when binding did not find their ItemsControl. Can you provide more info with what is the ItemsSource for your ListBox?</p>\n\n<p>P.S.: One way to remove the errors is to create new setters for HorizontalContentAlignment and VerticalContentAlignment in your custom Style.</p>\n" }, { "answer_id": 218400, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "<p>This is a <a href=\"https://stackoverflow.com/questions/165424/how-does-itemcontainergeneratorcontainerfromitem-work-with-a-grouped-list\">common problem</a> with <code>ListBoxItem</code>s and other ephemeral <code>*Item</code> containers. They are created asynchronously/on the fly, while the <code>ItemsControl</code> is loaded/rendered. You have to attach to <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemcontainergenerator.aspx\" rel=\"nofollow noreferrer\"><code>ListBox.ItemContainerGenerator</code></a>'s <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcontainergenerator.statuschanged.aspx\" rel=\"nofollow noreferrer\"><code>StatusChanged</code></a> event and wait for the Status to become <code>ItemsGenerated</code> before trying to access them.</p>\n" }, { "answer_id": 636862, "author": "JTango18", "author_id": 76954, "author_profile": "https://Stackoverflow.com/users/76954", "pm_score": 5, "selected": false, "text": "<p>Setting <code>OverridesDefaultStyle</code> to <code>True</code> in your <code>ItemContainerStyle</code> will also fix these problems.</p>\n\n<pre><code>&lt;Style TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"OverridesDefaultStyle\" Value=\"True\"/&gt;\n &lt;!-- set the rest of your setters, including Template, here --&gt;\n&lt;/Style&gt;\n</code></pre>\n" }, { "answer_id": 1578969, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 1, "selected": false, "text": "<p>If you want to completely replace the <code>ListBoxItem</code> template such that no selection is visible (perhaps you want the look of <code>ItemsControl</code> with the grouping/etc behaviour of <code>ListBox</code>) then you can use this style:</p>\n\n<pre><code>&lt;Style TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"Margin\" Value=\"2\" /&gt;\n &lt;Setter Property=\"FocusVisualStyle\" Value=\"{x:Null}\" /&gt;\n &lt;Setter Property=\"OverridesDefaultStyle\" Value=\"True\" /&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"{x:Type ListBoxItem}\"&gt;\n &lt;ContentPresenter Content=\"{TemplateBinding ContentControl.Content}\" \n HorizontalAlignment=\"Stretch\" \n VerticalAlignment=\"{TemplateBinding Control.VerticalContentAlignment}\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" /&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n\n<p>This template also excludes the standard <code>Border</code> wrapper. If you need that, you can use replace the template with this:</p>\n\n<pre><code>&lt;Border BorderThickness=\"{TemplateBinding Border.BorderThickness}\" \n Padding=\"{TemplateBinding Control.Padding}\" \n BorderBrush=\"{TemplateBinding Border.BorderBrush}\" \n Background=\"{TemplateBinding Panel.Background}\" \n SnapsToDevicePixels=\"True\"&gt;\n &lt;ContentPresenter Content=\"{TemplateBinding ContentControl.Content}\" \n ContentTemplate=\"{TemplateBinding ContentControl.ContentTemplate}\" \n HorizontalAlignment=\"{TemplateBinding Control.HorizontalContentAlignment}\" \n VerticalAlignment=\"{TemplateBinding Control.VerticalContentAlignment}\" \n SnapsToDevicePixels=\"{TemplateBinding UIElement.SnapsToDevicePixels}\" /&gt;\n&lt;/Border&gt;\n</code></pre>\n\n<p>If you don't need all these <code>TemplateBinding</code> values then you can remove some for performance.</p>\n" }, { "answer_id": 7078679, "author": "SteffenSH", "author_id": 833384, "author_profile": "https://Stackoverflow.com/users/833384", "pm_score": 2, "selected": false, "text": "<p>I just encountered the same type of error:</p>\n\n<blockquote>\n <p>System.Windows.Data Error: 4 : \n Cannot find source for binding with reference \n 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''.\n BindingExpression:Path=HorizontalContentAlignment;\n DataItem=null; target element is 'ListBoxItem' (Name='');\n target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')</p>\n</blockquote>\n\n<p>This happened while doing a binding like this:</p>\n\n<pre><code>&lt;ListBox ItemsSource=\"{Binding Path=MyListProperty}\" /&gt;\n</code></pre>\n\n<p>To this property on my data context object:</p>\n\n<pre><code>public IList&lt;ListBoxItem&gt; MyListProperty{ get; set;}\n</code></pre>\n\n<p>After some experimenting I discovered that the error was only triggered when the number of items exceeded the visible height of my ListBox (e.g. when vertical scrollbars appear).\nSo I immediately thought about virtualization and tried this:</p>\n\n<pre><code>&lt;ListBox ItemsSource=\"{Binding Path=MyListProperty}\" VirtualizingStackPanel.IsVirtualizing=\"False\" /&gt;\n</code></pre>\n\n<p>This solved the problem for me.\nAlthough I would prefer to keep virtualization turned on I did not use any more time to dive into it.\nMy application is a bit on the complex side with mulitiple levels of grids, dock panels etc. and some asynch method calls.\nI was not able to reproduce the problem in a simpler application.</p>\n" }, { "answer_id": 8326034, "author": "akjoshi", "author_id": 45382, "author_profile": "https://Stackoverflow.com/users/45382", "pm_score": 1, "selected": false, "text": "<p>Another workaround/solution that worked for me was to suppress these errors (actually, it seems more appropriate to call them warnings) by setting the data binding source switch level as critical in constructor of the class or a top level window -</p>\n\n<pre><code>#if DEBUG \n System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level =\n System.Diagnostics.SourceLevels.Critical;\n#endif\n</code></pre>\n\n<p>Ref.: <a href=\"http://www.codeproject.com/Tips/124556/How-to-suppress-the-System-Windows-Data-Error-warn\" rel=\"nofollow noreferrer\">How to suppress the System.Windows.Data Error warning message</a></p>\n" }, { "answer_id": 9286069, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 2, "selected": false, "text": "<p>This worked for me. Put this in your Application.xaml file.</p>\n\n<pre><code>&lt;Application.Resources&gt;\n &lt;Style TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" /&gt;\n &lt;Setter Property=\"VerticalContentAlignment\" Value=\"Center\" /&gt;\n &lt;/Style&gt;\n&lt;/Application.Resources&gt;\n</code></pre>\n\n<p>from...</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/42cd1554-de7a\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/42cd1554-de7a</a></p>\n" }, { "answer_id": 9381431, "author": "Alain", "author_id": 529618, "author_profile": "https://Stackoverflow.com/users/529618", "pm_score": 0, "selected": false, "text": "<p>Simply creating a default style for the type \"ComboBoxItem\" doesn't work, because it it overwritten by the ComboBox's default \"ItemContainerStyle\". To really get rid of this, you need to change the default \"ItemContainerStyle\" for ComboBoxes, like this:</p>\n\n<pre><code>&lt;Style TargetType=\"ComboBox\"&gt;\n &lt;Setter Property=\"ItemContainerStyle\"&gt;\n &lt;Setter.Value&gt; \n &lt;Style TargetType=\"ComboBoxItem\"&gt;\n &lt;Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" /&gt;\n &lt;Setter Property=\"VerticalContentAlignment\" Value=\"Center\" /&gt;\n &lt;/Style&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n" }, { "answer_id": 23455790, "author": "Chris", "author_id": 991762, "author_profile": "https://Stackoverflow.com/users/991762", "pm_score": 3, "selected": false, "text": "<p>This is an amalgam of the other answers here, but for me, I had to apply the <code>Setter</code> in two places to solve the error, although this was when using a custom <code>VirtualizingWrapPanel</code></p>\n\n<p>If I remove either one of the below <code>Setter</code> declarations, my errors reappear.</p>\n\n<pre><code> &lt;ListView&gt;\n &lt;ListView.Resources&gt;\n &lt;Style TargetType=\"ListViewItem\"&gt;\n &lt;Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" /&gt;\n &lt;Setter Property=\"VerticalContentAlignment\" Value=\"Top\" /&gt;\n &lt;/Style&gt;\n &lt;/ListView.Resources&gt;\n &lt;ListView.ItemContainerStyle&gt;\n &lt;Style TargetType=\"ListViewItem\"&gt;\n &lt;Setter Property=\"HorizontalContentAlignment\" Value=\"Left\" /&gt;\n &lt;Setter Property=\"VerticalContentAlignment\" Value=\"Top\" /&gt;\n &lt;/Style&gt;\n &lt;/ListView.ItemContainerStyle&gt;\n &lt;ListView.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;controls:VirtualizingWrapPanel /&gt;\n &lt;/ItemsPanelTemplate&gt;\n &lt;/ListView.ItemsPanel&gt;\n &lt;/ListView&gt;\n</code></pre>\n\n<p>I don't really have the time to investigate further at the moment, but I suspect it's related to the default style that JTango mentions in his answer - I'm not really customising my template to a huge degree.</p>\n\n<p>I think there's more mileage to be had out of the other answers, but I thought I'd post this on the off chance it helps someone in the same boat.</p>\n\n<p>David Schmitt's answer looks like it might describe the root cause.</p>\n" }, { "answer_id": 24561281, "author": "Kevin Sherrill", "author_id": 2221707, "author_profile": "https://Stackoverflow.com/users/2221707", "pm_score": 0, "selected": false, "text": "<p>I started running into this problem, even though my ListBox had both a Style and an ItemContainerStyle set - and these named styles had already defined HorizontalContentAlignment. I was using CheckBox controls to turn on/off live filtering on my ListBox and this seemed to be causing the items to pull instead from the default style instead of my assigned styles. Most errors would occur the first time the live filtering kicked in, but thereafter it would continue to throw 2 errors on each change. I find it interesting that exactly 2 records in my collection were empty and thus had nothing to display in the item. So this seems to have contibuted. I plan to create default data to be displayed when a record is empty.</p>\n\n<p>Carter's suggestion worked for me. Adding a separate \"default\" style with no key and a TargetType=\"ListBoxItem\" that defined the HorizontalContentAlignment property solved the problem. I didn't even need to set the OverridesDefaultStyle property for it.</p>\n" }, { "answer_id": 24970497, "author": "RedQueen87", "author_id": 3625735, "author_profile": "https://Stackoverflow.com/users/3625735", "pm_score": 2, "selected": false, "text": "<p>I had the same problem as you and I just wanted to share what was my solution.\nI have tried all options from this post but the last one was the best for me - thx Chris.</p>\n\n<p>So my code:</p>\n\n<p></p>\n\n<pre><code>&lt;ListBox.Resources&gt;\n &lt;Style x:Key=\"listBoxItemStyle\" TargetType=\"ListBoxItem\"&gt;\n &lt;Setter Property=\"HorizontalContentAlignment\" Value=\"Center\" /&gt;\n &lt;Setter Property=\"VerticalContentAlignment\" Value=\"Center\" /&gt;\n &lt;Setter Property=\"MinWidth\" Value=\"24\"/&gt;\n &lt;Setter Property=\"IsEnabled\" Value=\"{Binding IsEnabled}\"/&gt;\n &lt;/Style&gt;\n\n &lt;Style TargetType=\"ListBoxItem\" BasedOn=\"{StaticResource listBoxItemStyle}\"/&gt;\n&lt;/ListBox.Resources&gt;\n\n&lt;ListBox.ItemContainerStyle&gt;\n &lt;Binding Source=\"{StaticResource listBoxItemStyle}\"/&gt;\n&lt;/ListBox.ItemContainerStyle&gt;\n\n&lt;ListBox.ItemsPanel&gt;\n &lt;ItemsPanelTemplate&gt;\n &lt;WrapPanel Orientation=\"Horizontal\" IsItemsHost=\"True\" MaxWidth=\"170\"/&gt;\n &lt;/ItemsPanelTemplate&gt;\n&lt;/ListBox.ItemsPanel&gt;\n</code></pre>\n\n<p></p>\n\n<p>I have also discovered that this bug do not appear when custom <code>ItemsPanelTemplate</code> do not exists.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14537/" ]
I've got a ListBox control and I'm presenting a fixed number of ListBoxItem objects in a grid layout. So I've set my ItemsPanelTemplate to be a Grid. I'm accessing the Grid from code behind to configure the RowDefinitions and ColumnDefinitions. So far it's all working as I expect. I've got some custom IValueConverter implementations for returning the Grid.Row and Grid.Column that each ListBoxItem should appear in. However I get weird binding errors sometimes, and I can't figure out exactly why they're happening, or even if they're in my code. Here's the error I get: > > `System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')` > > > Can anybody explain what's going on? Oh, and, here's my XAML: ``` <UserControl.Resources> <!-- Value Converters --> <v:GridRowConverter x:Key="GridRowConverter" /> <v:GridColumnConverter x:Key="GridColumnConverter" /> <v:DevicePositionConverter x:Key="DevicePositionConverter" /> <v:DeviceBackgroundConverter x:Key="DeviceBackgroundConverter" /> <Style x:Key="DeviceContainerStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="Background" Value="Transparent" /> <Setter Property="Grid.Row" Value="{Binding Path=DeviceId, Converter={StaticResource GridRowConverter}}" /> <Setter Property="Grid.Column" Value="{Binding Path=DeviceId, Converter={StaticResource GridColumnConverter}}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border CornerRadius="2" BorderThickness="1" BorderBrush="White" Margin="2" Name="Bd" Background="{Binding Converter={StaticResource DeviceBackgroundConverter}}"> <TextBlock FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=DeviceId, Converter={StaticResource DevicePositionConverter}}" > <TextBlock.LayoutTransform> <RotateTransform Angle="270" /> </TextBlock.LayoutTransform> </TextBlock> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Bd" Property="BorderThickness" Value="2" /> <Setter TargetName="Bd" Property="Margin" Value="1" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Border CornerRadius="3" BorderThickness="3" Background="#FF333333" BorderBrush="#FF333333" > <Grid ShowGridLines="False"> <Grid.RowDefinitions> <RowDefinition Height="15" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal"> <Image Margin="20,3,3,3" Source="Barcode.GIF" Width="60" Stretch="Fill" /> </StackPanel> <ListBox ItemsSource="{Binding}" x:Name="lstDevices" Grid.Row="1" ItemContainerStyle="{StaticResource DeviceContainerStyle}" Background="#FF333333" SelectedItem="{Binding SelectedDeviceResult, ElementName=root, Mode=TwoWay}" > <ListBox.ItemsPanel> <ItemsPanelTemplate> <Grid> <Grid.LayoutTransform> <RotateTransform Angle="90" /> </Grid.LayoutTransform> </Grid> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> </Grid> </Border> ```
The binding problem comes from the default style for ListBoxItem. By default when applying styles to elements WPF looks for the default styles and applies each property that is not specifically set in the custom style from the default style. Refer to [this great blog post](http://www.interact-sw.co.uk/iangblog/2007/02/14/wpfdefaulttemplate) By Ian Griffiths for more details on this behavior. Back to our problem. Here is the default style for ListBoxItem: ``` <Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" TargetType="{x:Type ListBoxItem}"> <Style.Resources> <ResourceDictionary/> </Style.Resources> <Setter Property="Panel.Background"> <Setter.Value> <SolidColorBrush> #00FFFFFF </SolidColorBrush> </Setter.Value> </Setter> <Setter Property="Control.HorizontalContentAlignment"> <Setter.Value> <Binding Path="HorizontalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}"/> </Setter.Value> </Setter> <Setter Property="Control.VerticalContentAlignment"> <Setter.Value> <Binding Path="VerticalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}"/> </Setter.Value> </Setter> <Setter Property="Control.Padding"> <Setter.Value> <Thickness> 2,0,0,0 </Thickness> </Setter.Value> </Setter> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> ... </ControlTemplate> </Setter.Value> </Setter> </Style> ``` Note that I have removed the ControlTemplate to make it compact (I have used [StyleSnooper](https://github.com/drewnoakes/style-snooper) - to retrieve the style). You can see that there is a binding with a relative source set to ancestor with type ItemsControl. So in your case the ListBoxItems that are created when binding did not find their ItemsControl. Can you provide more info with what is the ItemsSource for your ListBox? P.S.: One way to remove the errors is to create new setters for HorizontalContentAlignment and VerticalContentAlignment in your custom Style.
160,453
<p>I have two tables: <code>foos</code> and <code>bars</code>, and there is a many-to-one relationship between them: each <code>foo</code> can have many <code>bars</code>. I also have a view <code>foobars</code>, which joins these two tables (its query is like <code>select foo.*, bar.id from foos, bars where bar.foo_id=foo.id</code>).</p> <p>EDIT: You would not be wrong if you said that there's a many-to-many relationship between <code>foo</code>s and <code>bar</code>s. A <code>bar</code>, however, is just a tag (in fact, it is a size), and consists just of its name. The table <code>bars</code> has the same role as a link table would have.</p> <p>I have a rule on inserting to <code>foobars</code> such that the “foo” part is inserted to <code>foos</code> as a new row, and “bar” part, which consists of a couple of bar-id's separated by commas is split, and for each such part a link between it and the appropriate <code>foo</code> is created (I use a procedure to do that).</p> <p>This works great for inserts. I have a problem, however, when it comes to updating the whole thing. The <code>foo</code> part of the rule is easy. However, I don't know how to deal with the multiple <code>bar</code>s part. When I try to do something like <code>DELETE FROM bars WHERE foo_id=new.foo_id</code> in the rule, I end deleting everything from the table <code>bars</code>.</p> <p>What am I doing wrong? Is there a way of achieving what I need? Finally, is my approach to the whole thing sensible?</p> <p>(I do this overcomplicated thing with the view because the data I get is in the form of “<code>foo</code> and all its <code>bar</code>s”, but the user must see just <code>foobars</code>.)</p>
[ { "answer_id": 160598, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 0, "selected": false, "text": "<p>I don't think new.foo_id is correct in the context of a delete.</p>\n\n<p>Shouldn't it be DELETE FROM bars WHERE foo_id=old.foo_id?</p>\n" }, { "answer_id": 160616, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "<p>Rysiek, if I understood correctly, you have text column in <code>foos</code> table that is parsed to extract foreign keys pointing to <code>bars</code> table. This approach to building relations may be justified in some cases, however almost every guide/tutorial to database programming would discourage doing so. Why not use standard foreign key in <code>bars</code> that would point to foo in <code>foos</code>? Unless there is a requirement for bars to be assigned to more than one foo. If so, this identifies your relation as many-to-many rather one-to-many. In either situation using standard foreign key based solution seems much more natural for database.</p>\n\n<p>Example db schema for one-to-many relation:</p>\n\n<pre><code>CREATE TABLE foos (\n id SERIAL PRIMARY KEY,\n ....\n);\nCREATE TABLE bars (\n id SERIAL PRIMARY KEY,\n foo_id INT REFERENCES bars (id) ON DELETE CASCADE,\n ...\n);\n</code></pre>\n\n<p>And the same for many-to-many relation:</p>\n\n<pre><code>CREATE TABLE foos (\n id SERIAL PRIMARY KEY,\n ....\n);\nCREATE TABLE bars (\n id SERIAL PRIMARY KEY,\n ...\n);\nCREATE TABLE foostobars (\n foo_id INT REFERENCES foos (id) ON DELETE CASCADE,\n bar_id INT REFERENCES bars (id) ON DELETE CASCADE\n);\n</code></pre>\n\n<p>I would also recommend using INNER JOIN instead of table multiplication (SELECT FROM foos, bars).</p>\n\n<pre><code>CREATE VIEW foobars AS\nSELECT\n foos.id AS foo_id, foos.something,\n bars.id AS bar_id, bars.somethingelse\nFROM foos\nINNER JOIN bars ON bars.foo_id = foo.id;\n</code></pre>\n\n<p>The same for many-to-many INNER JOINS</p>\n\n<pre><code>CREATE VIEW foobars AS\nSELECT\n foos.id AS foo_id, foos.something,\n bars.id AS bar_id, bars.somethingelse\nFROM foos\nINNER JOIN foostobars AS ftb ON ftb.foo_id = foo.id\nINNER JOIN bars ON bars.id = ftb.bar_id;\n</code></pre>\n" }, { "answer_id": 164275, "author": "Ryszard Szopa", "author_id": 19922, "author_profile": "https://Stackoverflow.com/users/19922", "pm_score": 0, "selected": false, "text": "<p>This is how I have actually dealt with it: when I get a unique constraint violation, instead of updating I simply delete the <code>foo</code> and let the cascade take care of the <code>bars</code>. Then I simply try to insert once again. I have to use more than one SQL statement to do it, but it seems to work.</p>\n" }, { "answer_id": 169206, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "<p>The deletion problem is that you are deleting on a predicate that is not based on the table you are deleting from. You need to delete based on a join predicate. This would look something line:</p>\n\n<pre><code>delete b\n from foo f\n join foobar fb\n on f.FooID = fb.FooID\n join bar b\n on b.BarId = fb.BarID\n where f.FooID = 123\n</code></pre>\n\n<p>This lets you jave a table of Foo's, a table of Bar's and a join table that records what Bar's the Foo has. You don't need to compose lists and split them apart. This is a bad thing because the query optimiser can't use an index to identify the relevant records - in fact this violates the 1NF 'No repeating groups' rule.. The correct schema would look something like:</p>\n\n<pre><code>Create table Foo (\n FooID int\n ,[Other Foo attributes]\n)\n\nCreate table Bar (\n BarID int\n ,[Other Bar attributes]\n)\n\nCreate table FooBar (\n FooID int\n ,BarID int\n)\n</code></pre>\n\n<p>With appropriate indexes, the M:M relationship can be stored in FooBar and the DBMS can store and manipulate this efficiently in its native data structures.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19922/" ]
I have two tables: `foos` and `bars`, and there is a many-to-one relationship between them: each `foo` can have many `bars`. I also have a view `foobars`, which joins these two tables (its query is like `select foo.*, bar.id from foos, bars where bar.foo_id=foo.id`). EDIT: You would not be wrong if you said that there's a many-to-many relationship between `foo`s and `bar`s. A `bar`, however, is just a tag (in fact, it is a size), and consists just of its name. The table `bars` has the same role as a link table would have. I have a rule on inserting to `foobars` such that the “foo” part is inserted to `foos` as a new row, and “bar” part, which consists of a couple of bar-id's separated by commas is split, and for each such part a link between it and the appropriate `foo` is created (I use a procedure to do that). This works great for inserts. I have a problem, however, when it comes to updating the whole thing. The `foo` part of the rule is easy. However, I don't know how to deal with the multiple `bar`s part. When I try to do something like `DELETE FROM bars WHERE foo_id=new.foo_id` in the rule, I end deleting everything from the table `bars`. What am I doing wrong? Is there a way of achieving what I need? Finally, is my approach to the whole thing sensible? (I do this overcomplicated thing with the view because the data I get is in the form of “`foo` and all its `bar`s”, but the user must see just `foobars`.)
Rysiek, if I understood correctly, you have text column in `foos` table that is parsed to extract foreign keys pointing to `bars` table. This approach to building relations may be justified in some cases, however almost every guide/tutorial to database programming would discourage doing so. Why not use standard foreign key in `bars` that would point to foo in `foos`? Unless there is a requirement for bars to be assigned to more than one foo. If so, this identifies your relation as many-to-many rather one-to-many. In either situation using standard foreign key based solution seems much more natural for database. Example db schema for one-to-many relation: ``` CREATE TABLE foos ( id SERIAL PRIMARY KEY, .... ); CREATE TABLE bars ( id SERIAL PRIMARY KEY, foo_id INT REFERENCES bars (id) ON DELETE CASCADE, ... ); ``` And the same for many-to-many relation: ``` CREATE TABLE foos ( id SERIAL PRIMARY KEY, .... ); CREATE TABLE bars ( id SERIAL PRIMARY KEY, ... ); CREATE TABLE foostobars ( foo_id INT REFERENCES foos (id) ON DELETE CASCADE, bar_id INT REFERENCES bars (id) ON DELETE CASCADE ); ``` I would also recommend using INNER JOIN instead of table multiplication (SELECT FROM foos, bars). ``` CREATE VIEW foobars AS SELECT foos.id AS foo_id, foos.something, bars.id AS bar_id, bars.somethingelse FROM foos INNER JOIN bars ON bars.foo_id = foo.id; ``` The same for many-to-many INNER JOINS ``` CREATE VIEW foobars AS SELECT foos.id AS foo_id, foos.something, bars.id AS bar_id, bars.somethingelse FROM foos INNER JOIN foostobars AS ftb ON ftb.foo_id = foo.id INNER JOIN bars ON bars.id = ftb.bar_id; ```
160,467
<p>I need to create an ODBC link from an Access 2003 (Jet) database to a SQL Server hosted view which contains aliased field names containing periods such as:</p> <pre><code>Seq.Group </code></pre> <p>In the SQL source behind the view, the field names are encased in square brackets...</p> <pre><code>SELECT Table._Group AS [Seq.Group] </code></pre> <p>...so SQL Server doesn't complain about creating the view, but when I try to create an ODBC link to it from the Jet DB (either programmatically or via the Access 2003 UI) I receive the error message:</p> <blockquote> <p>'Seq.Group' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.</p> </blockquote> <p>Unfortunately, I cannot modify the structure of the view because it's part of another product, so I am stuck with the field names the way that they are. I <em>could</em> add my own view with punctuation-free field names, but I'd really rather not modify the SQL Server at all because then that becomes another point of maintenance every time there's an upgrade, hotfix, etc. Does anyone know a better workaround?</p>
[ { "answer_id": 160487, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 1, "selected": false, "text": "<p>Just guessing here: did you try escaping the dot? Something like \"[Seq\\.Group]\"?</p>\n" }, { "answer_id": 160785, "author": "Tim Lara", "author_id": 3469, "author_profile": "https://Stackoverflow.com/users/3469", "pm_score": 3, "selected": true, "text": "<p>Although I didn't technically end up escaping the dot, your suggestion actually <em>did</em> make me realize another alternative. While wondering how I would \"pass\" the escape code to the \"SQL\" server, it dawned on me: Why not use a \"SQL Pass-Through Query\" instead of an ODBC linked table? Since I only need read access to the SQL Server data, it works fine! Thanks!</p>\n" }, { "answer_id": 161015, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "<p>Another proposal would be to add a new view on your sql server, not modifying the existing one. Even if your initial view is part of a \"solution\", nothing forbids you of adding new views:</p>\n\n<pre><code>SELECT Table._Group AS [Seq_Group]\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3469/" ]
I need to create an ODBC link from an Access 2003 (Jet) database to a SQL Server hosted view which contains aliased field names containing periods such as: ``` Seq.Group ``` In the SQL source behind the view, the field names are encased in square brackets... ``` SELECT Table._Group AS [Seq.Group] ``` ...so SQL Server doesn't complain about creating the view, but when I try to create an ODBC link to it from the Jet DB (either programmatically or via the Access 2003 UI) I receive the error message: > > 'Seq.Group' is not a valid name. Make > sure that it does not include invalid > characters or punctuation and that it > is not too long. > > > Unfortunately, I cannot modify the structure of the view because it's part of another product, so I am stuck with the field names the way that they are. I *could* add my own view with punctuation-free field names, but I'd really rather not modify the SQL Server at all because then that becomes another point of maintenance every time there's an upgrade, hotfix, etc. Does anyone know a better workaround?
Although I didn't technically end up escaping the dot, your suggestion actually *did* make me realize another alternative. While wondering how I would "pass" the escape code to the "SQL" server, it dawned on me: Why not use a "SQL Pass-Through Query" instead of an ODBC linked table? Since I only need read access to the SQL Server data, it works fine! Thanks!
160,494
<pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCount { class Program { static int Count1&lt;T&gt;(T a) where T : IEnumerable&lt;T&gt; { return a.Count(); } static void Main(string[] args) { List&lt;string&gt; mystring = new List&lt;string&gt;() { "rob","tx" }; int count = Count1&lt;List&lt;string&gt;&gt;(mystring);****** Console.WriteLine(count.ToString()); } } } </code></pre> <p>What do I have to change in the above indicated line of code to make it work. I am just trying to pass either List or array in order to get the count. </p>
[ { "answer_id": 160516, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "<p>Your generic constraint is wrong. You cannot enforce it to implement IEnumerabl&lt;T&gt;</p>\n" }, { "answer_id": 160517, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 0, "selected": false, "text": "<p>You have \"where T : IEnumerable&lt;T&gt;\", which is not what you want. Change it to e.g. \"IEnumerable&lt;string&gt;\" and it will compile. In this case, \"T\" is List&lt;string&gt;, which is an IEnumerable&lt;string&gt;.</p>\n" }, { "answer_id": 160570, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": true, "text": "<p>You want this</p>\n\n<pre><code>static int Count1&lt;T&gt;(IEnumerable&lt;T&gt; a)\n{\n return a.Count();\n}\n</code></pre>\n" }, { "answer_id": 160584, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 0, "selected": false, "text": "<p>Your count method is expecting a type of IEnumerable and then you have set T to be List which means the method will expect IEnumerable> which is not what you are passing in. </p>\n\n<p>Instead you should restrict the parameter type to IEnumerable and you can leave T unconstrained.</p>\n\n<pre><code>namespace GenericCount\n{\n class Program\n {\n static int Count1&lt;T&gt;(IEnumerable&lt;T&gt; a)\n {\n return a.Count();\n }\n\n static void Main(string[] args)\n {\n List&lt;string&gt; mystring = new List&lt;string&gt;()\n {\n \"rob\",\"tx\"\n };\n\n int count = Count1(mystring);\n Console.WriteLine(count.ToString());\n\n }\n }\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCount { class Program { static int Count1<T>(T a) where T : IEnumerable<T> { return a.Count(); } static void Main(string[] args) { List<string> mystring = new List<string>() { "rob","tx" }; int count = Count1<List<string>>(mystring);****** Console.WriteLine(count.ToString()); } } } ``` What do I have to change in the above indicated line of code to make it work. I am just trying to pass either List or array in order to get the count.
You want this ``` static int Count1<T>(IEnumerable<T> a) { return a.Count(); } ```
160,519
<p>Can this be done w/ linqtosql?</p> <pre><code>SELECT City, SUM(DATEDIFF(minute,StartDate,Completed)) AS Downtime FROM Incidents GROUP BY City </code></pre>
[ { "answer_id": 160524, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "<p>LINQ to SQL makes good use of partial classes to extend designer generated code. I think you will typically find this pattern of partial classes being used by designer-created code.</p>\n" }, { "answer_id": 160529, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Where I'm at we have a program that handles incoming files from clients. It's set up so that each client's code is in it's own class library project, which knows how to handle whatever format that client chooses to use. </p>\n\n<p>The main code uses the libraries by defining a fairly extensive interface that a class in the library must implement (probably should be a few distinct interfaces, but it's too late to change it now). Sometimes that involves a lot more code in the same class than we'd normally think prudent. Partial classes allow us to break them up somewhat.</p>\n" }, { "answer_id": 160530, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 5, "selected": true, "text": "<p>It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code.</p>\n\n<p>There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable.</p>\n" }, { "answer_id": 160533, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 3, "selected": false, "text": "<p>I use partial classes as a means of separating out the different sub elements of custom controls that I write. Also, when used with entity creation software, it allows products like LLBLGen to create generated versions of classes, as well as a custom, user edited version, that won't get replaced if the entities need to be regenerated.</p>\n" }, { "answer_id": 160542, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>I find partial classes to be extremely helpful. Usually they are used to be able to extend autogenerated classes. I used them in one project with heavy unit tests. My UT classes had complex dependencies and it was not very practical to separate code across multiple classes.Of course it is better to use inheritance\\composition but in some cases partial classes can be rally helpful. </p>\n" }, { "answer_id": 160545, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 1, "selected": false, "text": "<p>On UserControls which are relatively complicated, I put the event handling stuff in one file and the painting and properties in another file. Partial classes work great for this, Usually these parts of the class are relatively independent and it's nice to be able to edit painting and event handling side by side.</p>\n" }, { "answer_id": 160559, "author": "Ali Shafai", "author_id": 24351, "author_profile": "https://Stackoverflow.com/users/24351", "pm_score": 0, "selected": false, "text": "<p>Correction, as Matt pointed out, both sides of the partial need to be in the same assembly.\nmy bad.</p>\n" }, { "answer_id": 160562, "author": "Tobias", "author_id": 14027, "author_profile": "https://Stackoverflow.com/users/14027", "pm_score": 0, "selected": false, "text": "<p>I use it in a data access layer. The generated classes like the mapper and queries a partial. If I need to add a mapper method for example to do a fancy load that's not generated I add it to the custom class.</p>\n\n<p>At the end the programmer that uses the data layer in the business layer only sees one class with all the functionality he or she needs. And if the data source changes the generic parts can easily be generated without overwriting custom stuff.</p>\n" }, { "answer_id": 160576, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 0, "selected": false, "text": "<p>I just found a use for partial classes. I have a [DataContract] class that I use to pass data to the client. I wanted the client to be able to display the class in a specific way (text output). so I created a partial class and overrode the ToString method. </p>\n" }, { "answer_id": 160601, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": false, "text": "<p>I often use partial classes to give each nested class its own file. There have been some architectures I've worked on where most of the implementation was only required by one class and so we nested those classes in that one class. It made sense to keep the files easier to maintain by using the partial class ability and splitting each one into its own file.</p>\n\n<p>We've also used them for grouping stock overrides or the hiding of a stock set of properties. Things like that. It's a handy way of mixing in a stock change (just copy the file and change the partial class name to the target class - as long as the target class is made partial too, of course).</p>\n" }, { "answer_id": 160638, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 3, "selected": false, "text": "<p>Code generation was the driving force behind partial classes. The need comes from having a code-generated class that is constantly changing, but allow developers to supply custom code as part of the class that will not be overridden everytime changes are made that force the class to be regenerated.</p>\n\n<p>Take WinForms or Typed-DataSets for example (or any designer for that matter). Everytime you make a change to the designer it serializes the corresponding code to a file. Let's say you need to provide a few additional methods that the generator doesn't know anything about. If you added it to the generated file your changes would be lost the next time it was generated.</p>\n\n<p>A project that I'm currently working on uses code-generation for all the DAL, BLL, and business entities. However, the generator only get's us 75% of the information. The remaining portion has to be hand coded (custom business logic for instance). I can assume that every BLL class has a SelectAll method, so that's easy to generate. However My customer BLL also needs to have a SelectAllByLocation method. I can't put this in my generator because it's not generic to all BLL classes. Therefore I generate all of my classes as partial classes, and then in a separate file I define my custom methods. Now down the road when my structure changes, or I need to regenerate my BLL for some reason, my custom code won't get wiped out.</p>\n" }, { "answer_id": 160670, "author": "nyxtom", "author_id": 19753, "author_profile": "https://Stackoverflow.com/users/19753", "pm_score": 0, "selected": false, "text": "<p>Sometimes you might find terribly old code at work that may make it close to impossible to refactor out into distinct elements without breaking existing code.</p>\n\n<p>When you aren't given the option or the time to create a more genuine architecture, partial classes make it incredibly easy to separate logic where its needed. This allows existing code to continue using the same architecture while you gain a step closer to a more concrete architecture.</p>\n" }, { "answer_id": 160815, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 1, "selected": false, "text": "<p>I worked on a project a couple years ago where we had a typed DataSet class that had a ton of code in it: Methods in the DataTables, methods in the TableAdapters, declarations of TableAdapter instances, you name it. It was a massive central point of the project that everyone had to work on often, and there was a lot of source-control contention over the partial class code file.</p>\n\n<p>So I split the code file into fix or six partial class files, grouped by function, so that we could work on smaller pieces and not have to lock the whole file every time we had to change some little thing.</p>\n\n<p>(Of course, we could also have solved the problem by not using an exclusively-locking source-control system, but that's another issue.)</p>\n" }, { "answer_id": 160825, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>Anywhere you'd have used <code>#region</code> sections before probably makes more sense as separate files in partial classes.</p>\n\n<p>I personally use partial classes for large classes where static members go in one file and instance members go in the other one.</p>\n" }, { "answer_id": 160856, "author": "flukus", "author_id": 407256, "author_profile": "https://Stackoverflow.com/users/407256", "pm_score": 1, "selected": false, "text": "<p>Generally, I consider it a code smell. </p>\n\n<p>If your class is that complicated then it can probably be broken up into smaller reusable components.</p>\n\n<p>Or it means that theres no inheritance hierarchy where there should be one.</p>\n\n<p>For code generation scenarios it's good but I think code generation is another code smell.</p>\n" }, { "answer_id": 161713, "author": "Luis Filipe", "author_id": 20335, "author_profile": "https://Stackoverflow.com/users/20335", "pm_score": 0, "selected": false, "text": "<p>EDIT: DSL Tools for Visual Studio uses partial classes.</p>\n\n<p>Thus, it's a feature that many automatic generated code uses.\nInstead of using #region the automatic generated code goes to one file and the user code (also called custom code) goes to another and even in different directories so that the developer does not get confused with so many meaningless files.</p>\n\n<p>It's good to have this choice which you can combine - but not forced to use -with inheritance</p>\n\n<p>Also, it can be handy to separate the logic of some classes among several directories. Of course, for machines, it's the same, but it enhances the user readability experience.</p>\n" }, { "answer_id": 161750, "author": "Hibri", "author_id": 15946, "author_profile": "https://Stackoverflow.com/users/15946", "pm_score": 2, "selected": false, "text": "<p>As mentioned earlier, I too think this is a code smell.</p>\n\n<p>If a class is so big that it needs to be split into more files, means that it is breaking the single responsibility principle and doing too many things. \nThe large class could be broken down into smaller classes that cooperate together.</p>\n\n<p>If you have to use partial classes or regions to organize code, consider if they should be in their own classes. It increases readability and you'd get more code reuse.</p>\n" }, { "answer_id": 228442, "author": "David Boike", "author_id": 10039, "author_profile": "https://Stackoverflow.com/users/10039", "pm_score": 2, "selected": false, "text": "<p>Another possible use for partial classes would be to take advantage of partial methods to make methods selectively disappear using conditional compilation - this would be great for debug-mode diagnostic code or specialized unit testing scenarios.</p>\n\n<p>You can declare a partial method kind of like an abstract method, then in the other partial class, when you type the keyword \"partial\" you can take advantage of the Intellisense to create the implementation of that method.</p>\n\n<p>If you surround one part with conditional build statements, then you can easily cut off the debug-only or testing code. In the example below, in DEBUG mode, the LogSomethingDebugOnly method is called, but in the release build, it's like the method doesn't exist at all - a good way to keep diagnostic code away from the production code without a bunch of branching or multiple conditional compilation blocks.</p>\n\n<pre><code>// Main Part\npublic partial class Class1\n{\n private partial void LogSomethingDebugOnly();\n\n public void SomeMethod()\n {\n LogSomethingDebugOnly();\n // do the real work\n }\n}\n\n// Debug Part - probably in a different file\npublic partial class Class1\n{\n\n #if DEBUG\n\n private partial void LogSomethingDebugOnly()\n {\n // Do the logging or diagnostic work\n }\n\n #endif\n}\n</code></pre>\n" }, { "answer_id": 5164388, "author": "Anand Patel", "author_id": 155755, "author_profile": "https://Stackoverflow.com/users/155755", "pm_score": 1, "selected": false, "text": "<p>I am late in the game... but just my 2 cents...</p>\n\n<p>One use could be to refactor an existing god class in an existing legacy code base to multiple partial classes. It could improve the discoverability of code - if proper naming convention is being followed for the file names containing the partial classes. This could also reduce the source code repository - resolve and merge to an extent.</p>\n\n<p>Ideally, a god class should be broken down into multiple small classes - each having single responsibility. Sometimes it is disruptive to perform medium to large refactorings. In such cases partial classes could provide a temporary relief.</p>\n" }, { "answer_id": 6713568, "author": "siamak", "author_id": 422627, "author_profile": "https://Stackoverflow.com/users/422627", "pm_score": 2, "selected": false, "text": "<p>maybe its too late but please let me to add my 2 cents too:</p>\n\n<p>*.When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.</p>\n\n<p>*.You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396/" ]
Can this be done w/ linqtosql? ``` SELECT City, SUM(DATEDIFF(minute,StartDate,Completed)) AS Downtime FROM Incidents GROUP BY City ```
It is in part to support scenarios (WebForms, WinForms, LINQ-to-SQL, etc) mixing generated code with programmer code. There are more reasons to use it. For example, if you have big classes in large, unwieldy files, but the classes have groups of logically related methods, partial classes may be an option to make your file sizes more manageable.
160,532
<p>I want to export the contents of several tables from MSAccess2003. The tables contain unicode Japanese characters. I want to store them as tilde delimited text files.</p> <p>I can do this manually using File/Export and, in the 'Advanced' dialog selecting tilde as Field Delimiter and the Unicode as the Code Page.</p> <p>I can store this as an Export Specification, but this seems to be table specific.</p> <p>I want to export many tables using VBA Code.</p> <p>So far I have tried:</p> <p>Sub ExportTables()</p> <pre><code>Dim lTbl As Long Dim dBase As Database Dim TableName As String Set dBase = CurrentDb For lTbl = 0 To dBase.TableDefs.Count 'If the table name is a temporary or system table then ignore it If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _ Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then '~ indicates a temporary table 'MSYS indicates a system level table Else TableName = dBase.TableDefs(lTbl).Name DoCmd.TransferText acExportDelim, "UnicodeTilde", TableName, "c:\" + TableName + ".txt", True End If Next lTbl Set dBase = Nothing </code></pre> <p>End Sub</p> <p>When I run this I get an exception:</p> <p>Run-time error '3011': The Microsoft Jet database engine could not find the object "Allowance1#txt'. Make sure the object exists and that you spell its name and the path name correctly.</p> <p>If I debug at this point, TableName is 'Allowance1', as expected.</p> <p>I guess my UnicodeTilde export specification is table specific, so I can't use it for multiple tables.</p> <p>What is the solution? Should I use something else, other than TransferText, or perhaps create the export specification programatically?</p> <p>Any help appreciated.</p>
[ { "answer_id": 161017, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 0, "selected": false, "text": "<p>I've got part of the answer:</p>\n\n<p>I'm writing a schema.ini file with VBA, then doing my TransferText. This is creating an export format on the fly. The only problem is, although my schema.ini contains:</p>\n\n<pre><code>ColNameHeader = True\nCharacterSet = Unicode\nFormat = Delimited(~)\n</code></pre>\n\n<p>Only the header row is coming out in unicode with tilde delimiters. The rest of the rows are ANSI with commas.</p>\n" }, { "answer_id": 169704, "author": "Tim Lara", "author_id": 3469, "author_profile": "https://Stackoverflow.com/users/3469", "pm_score": 0, "selected": false, "text": "<p>I've got two suggestions for you:</p>\n\n<ol>\n<li><p>Make sure you're putting each setting in your [schema.ini] file on a new line. (You've listed it here all on one line, so I thought I'd make sure.)</p></li>\n<li><p>Don't forget to supply the CodePage argument (last one) when you call your TransferText. Here's a list of supported values if you need it:</p></li>\n</ol>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa288104.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa288104.aspx</a></p>\n\n<p>Other than that, it looks like your approach should work.</p>\n" }, { "answer_id": 172881, "author": "Richard A", "author_id": 24355, "author_profile": "https://Stackoverflow.com/users/24355", "pm_score": 3, "selected": true, "text": "<p>I have eventually solved this. (I am now using Access 2007 but had the same problems as with Access 2003.)</p>\n\n<p>First, what didn't work:</p>\n\n<p>TransferText would only make the Header Row unicode and tilde delimited, even with a correctly formatted schema.ini. (No, I didn't put it all on one line, that was just a formatting issue with the html on stackoverflow.)</p>\n\n<pre><code>[MyTable.txt]\nCharacterSet = Unicode\nFormat = Delimited(~)\nColNameHeader = True\nNumberDigits = 10\nCol1= \"Col1\" Char Width 10\nCol2= \"Col2\" Integer\nCol3= \"Col3\" Char Width 2\n</code></pre>\n\n<p>Just using a select statement:</p>\n\n<pre><code>SELECT * INTO [Text;DATABASE=c:\\export\\;FMT=Delimited(~)].[MyTable.txt] FROM [MyTable]\n</code></pre>\n\n<p>Totally ignored the FMT. I found it very hard to find documentation on the format of the parameters. Whatever I typed in the FMT parameter, the only things I could get to work was Fixed. Everything else was treated as CSVDelimited. I could chech this as the select statement created a schema.ini file like this:</p>\n\n<pre><code>[MyTable.txt]\nColNameHeader=True\nCharacterSet=1252\nFormat=CSVDelimited\nCol1=Col1 Char Width 10\nCol2=Col2 Integer\nCol3=Col3 Char Width 2\n</code></pre>\n\n<p>My eventual solution was to create my own schema.ini then use the select statement. My Module code looks something like this:</p>\n\n<pre><code>Option Compare Database\nOption Explicit\n\n Public Function CreateSchemaFile(bIncFldNames As Boolean, _\n sPath As String, _\n sSectionName As String, _\n sTblQryName As String) As Boolean\n\n\n Dim Msg As String\n On Local Error GoTo CreateSchemaFile_Err\n Dim ws As Workspace, db As Database\n Dim tblDef As TableDef, fldDef As Field\n Dim i As Integer, Handle As Integer\n Dim fldName As String, fldDataInfo As String\n ' -----------------------------------------------\n ' Set DAO objects.\n ' -----------------------------------------------\n Set db = CurrentDb()\n ' -----------------------------------------------\n ' Open schema file for append.\n ' -----------------------------------------------\n Handle = FreeFile\n Open sPath &amp; \"schema.ini\" For Output Access Write As #Handle\n ' -----------------------------------------------\n ' Write schema header.\n ' -----------------------------------------------\n Print #Handle, \"[\" &amp; sSectionName &amp; \"]\"\n Print #Handle, \"CharacterSet = Unicode\"\n Print #Handle, \"Format = Delimited(~)\"\n Print #Handle, \"ColNameHeader = \" &amp; _\n IIf(bIncFldNames, \"True\", \"False\")\n Print #Handle, \"NumberDigits = 10\"\n ' -----------------------------------------------\n ' Get data concerning schema file.\n ' -----------------------------------------------\n Set tblDef = db.TableDefs(sTblQryName)\n With tblDef\n For i = 0 To .Fields.Count - 1\n Set fldDef = .Fields(i)\n With fldDef\n fldName = .Name\n Select Case .Type\n Case dbBoolean\n fldDataInfo = \"Bit\"\n Case dbByte\n fldDataInfo = \"Byte\"\n Case dbInteger\n fldDataInfo = \"Short\"\n Case dbLong\n fldDataInfo = \"Integer\"\n Case dbCurrency\n fldDataInfo = \"Currency\"\n Case dbSingle\n fldDataInfo = \"Single\"\n Case dbDouble\n fldDataInfo = \"Double\"\n Case dbDate\n fldDataInfo = \"Date\"\n Case dbText\n fldDataInfo = \"Char Width \" &amp; Format$(.Size)\n Case dbLongBinary\n fldDataInfo = \"OLE\"\n Case dbMemo\n fldDataInfo = \"LongChar\"\n Case dbGUID\n fldDataInfo = \"Char Width 16\"\n End Select\n Print #Handle, \"Col\" &amp; Format$(i + 1) _\n &amp; \"= \"\"\" &amp; fldName &amp; \"\"\"\" &amp; Space$(1); \"\" _\n &amp; fldDataInfo\n End With\n Next i\n End With\n CreateSchemaFile = True\nCreateSchemaFile_End:\n Close Handle\n Exit Function\nCreateSchemaFile_Err:\n Msg = \"Error #: \" &amp; Format$(Err.Number) &amp; vbCrLf\n Msg = Msg &amp; Err.Description\n MsgBox Msg\n Resume CreateSchemaFile_End\n End Function\n\nPublic Function ExportATable(TableName As String)\nDim ThePath As String\nDim FileName As String\nDim TheQuery As String\nDim Exporter As QueryDef\nThePath = \"c:\\export\\\"\nFileName = TableName + \".txt\"\nCreateSchemaFile True, ThePath, FileName, TableName\nOn Error GoTo IgnoreDeleteFileErrors\nFileSystem.Kill ThePath + FileName\nIgnoreDeleteFileErrors:\nTheQuery = \"SELECT * INTO [Text;DATABASE=\" + ThePath + \"].[\" + FileName + \"] FROM [\" + TableName + \"]\"\nSet Exporter = CurrentDb.CreateQueryDef(\"\", TheQuery)\nExporter.Execute\nEnd Function\n\n\nSub ExportTables()\n\n Dim lTbl As Long\n Dim dBase As Database\n Dim TableName As String\n\n Set dBase = CurrentDb\n\n For lTbl = 0 To dBase.TableDefs.Count - 1\n 'If the table name is a temporary or system table then ignore it\n If Left(dBase.TableDefs(lTbl).Name, 1) = \"~\" Or _\n Left(dBase.TableDefs(lTbl).Name, 4) = \"MSYS\" Then\n '~ indicates a temporary table\n 'MSYS indicates a system level table\n Else\n TableName = dBase.TableDefs(lTbl).Name\n ExportATable (TableName)\n End If\n Next lTbl\n Set dBase = Nothing\nEnd Sub\n</code></pre>\n\n<p>I make no claims that this is elegant, but it works. Also note that the stackoverflow code formatter doesn't like my \\\", so it doesn't pretty print my code very nicely.</p>\n" }, { "answer_id": 6111949, "author": "Matt Donnan", "author_id": 767913, "author_profile": "https://Stackoverflow.com/users/767913", "pm_score": 1, "selected": false, "text": "<p>In relation to this thread I have stumbled across an incredibly simple solution for being able to use one specification across all table exports whereas normally you would have to create a separate one for each; or use the sub routine provided by Richard A.</p>\n\n<p>The process is as follows:</p>\n\n<p>Create a specification e.g Pipe <code>|</code> delimited with any table, then open a dynaset query in access using SQL <code>SELECT * FROM MSysIMEXColumns</code> and then simply delete all resulting rows. Now this spec will not give error 3011 when you attempt to use a different table to that which you used to create the original spec and is essentially a universal Pipe export spec for any table/query you wish.</p>\n\n<p>This has been discovered/tested in access 2003 so I assume will work for later versions also.</p>\n\n<p>Kind Regards,</p>\n\n<p>Matt Donnan</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24355/" ]
I want to export the contents of several tables from MSAccess2003. The tables contain unicode Japanese characters. I want to store them as tilde delimited text files. I can do this manually using File/Export and, in the 'Advanced' dialog selecting tilde as Field Delimiter and the Unicode as the Code Page. I can store this as an Export Specification, but this seems to be table specific. I want to export many tables using VBA Code. So far I have tried: Sub ExportTables() ``` Dim lTbl As Long Dim dBase As Database Dim TableName As String Set dBase = CurrentDb For lTbl = 0 To dBase.TableDefs.Count 'If the table name is a temporary or system table then ignore it If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _ Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then '~ indicates a temporary table 'MSYS indicates a system level table Else TableName = dBase.TableDefs(lTbl).Name DoCmd.TransferText acExportDelim, "UnicodeTilde", TableName, "c:\" + TableName + ".txt", True End If Next lTbl Set dBase = Nothing ``` End Sub When I run this I get an exception: Run-time error '3011': The Microsoft Jet database engine could not find the object "Allowance1#txt'. Make sure the object exists and that you spell its name and the path name correctly. If I debug at this point, TableName is 'Allowance1', as expected. I guess my UnicodeTilde export specification is table specific, so I can't use it for multiple tables. What is the solution? Should I use something else, other than TransferText, or perhaps create the export specification programatically? Any help appreciated.
I have eventually solved this. (I am now using Access 2007 but had the same problems as with Access 2003.) First, what didn't work: TransferText would only make the Header Row unicode and tilde delimited, even with a correctly formatted schema.ini. (No, I didn't put it all on one line, that was just a formatting issue with the html on stackoverflow.) ``` [MyTable.txt] CharacterSet = Unicode Format = Delimited(~) ColNameHeader = True NumberDigits = 10 Col1= "Col1" Char Width 10 Col2= "Col2" Integer Col3= "Col3" Char Width 2 ``` Just using a select statement: ``` SELECT * INTO [Text;DATABASE=c:\export\;FMT=Delimited(~)].[MyTable.txt] FROM [MyTable] ``` Totally ignored the FMT. I found it very hard to find documentation on the format of the parameters. Whatever I typed in the FMT parameter, the only things I could get to work was Fixed. Everything else was treated as CSVDelimited. I could chech this as the select statement created a schema.ini file like this: ``` [MyTable.txt] ColNameHeader=True CharacterSet=1252 Format=CSVDelimited Col1=Col1 Char Width 10 Col2=Col2 Integer Col3=Col3 Char Width 2 ``` My eventual solution was to create my own schema.ini then use the select statement. My Module code looks something like this: ``` Option Compare Database Option Explicit Public Function CreateSchemaFile(bIncFldNames As Boolean, _ sPath As String, _ sSectionName As String, _ sTblQryName As String) As Boolean Dim Msg As String On Local Error GoTo CreateSchemaFile_Err Dim ws As Workspace, db As Database Dim tblDef As TableDef, fldDef As Field Dim i As Integer, Handle As Integer Dim fldName As String, fldDataInfo As String ' ----------------------------------------------- ' Set DAO objects. ' ----------------------------------------------- Set db = CurrentDb() ' ----------------------------------------------- ' Open schema file for append. ' ----------------------------------------------- Handle = FreeFile Open sPath & "schema.ini" For Output Access Write As #Handle ' ----------------------------------------------- ' Write schema header. ' ----------------------------------------------- Print #Handle, "[" & sSectionName & "]" Print #Handle, "CharacterSet = Unicode" Print #Handle, "Format = Delimited(~)" Print #Handle, "ColNameHeader = " & _ IIf(bIncFldNames, "True", "False") Print #Handle, "NumberDigits = 10" ' ----------------------------------------------- ' Get data concerning schema file. ' ----------------------------------------------- Set tblDef = db.TableDefs(sTblQryName) With tblDef For i = 0 To .Fields.Count - 1 Set fldDef = .Fields(i) With fldDef fldName = .Name Select Case .Type Case dbBoolean fldDataInfo = "Bit" Case dbByte fldDataInfo = "Byte" Case dbInteger fldDataInfo = "Short" Case dbLong fldDataInfo = "Integer" Case dbCurrency fldDataInfo = "Currency" Case dbSingle fldDataInfo = "Single" Case dbDouble fldDataInfo = "Double" Case dbDate fldDataInfo = "Date" Case dbText fldDataInfo = "Char Width " & Format$(.Size) Case dbLongBinary fldDataInfo = "OLE" Case dbMemo fldDataInfo = "LongChar" Case dbGUID fldDataInfo = "Char Width 16" End Select Print #Handle, "Col" & Format$(i + 1) _ & "= """ & fldName & """" & Space$(1); "" _ & fldDataInfo End With Next i End With CreateSchemaFile = True CreateSchemaFile_End: Close Handle Exit Function CreateSchemaFile_Err: Msg = "Error #: " & Format$(Err.Number) & vbCrLf Msg = Msg & Err.Description MsgBox Msg Resume CreateSchemaFile_End End Function Public Function ExportATable(TableName As String) Dim ThePath As String Dim FileName As String Dim TheQuery As String Dim Exporter As QueryDef ThePath = "c:\export\" FileName = TableName + ".txt" CreateSchemaFile True, ThePath, FileName, TableName On Error GoTo IgnoreDeleteFileErrors FileSystem.Kill ThePath + FileName IgnoreDeleteFileErrors: TheQuery = "SELECT * INTO [Text;DATABASE=" + ThePath + "].[" + FileName + "] FROM [" + TableName + "]" Set Exporter = CurrentDb.CreateQueryDef("", TheQuery) Exporter.Execute End Function Sub ExportTables() Dim lTbl As Long Dim dBase As Database Dim TableName As String Set dBase = CurrentDb For lTbl = 0 To dBase.TableDefs.Count - 1 'If the table name is a temporary or system table then ignore it If Left(dBase.TableDefs(lTbl).Name, 1) = "~" Or _ Left(dBase.TableDefs(lTbl).Name, 4) = "MSYS" Then '~ indicates a temporary table 'MSYS indicates a system level table Else TableName = dBase.TableDefs(lTbl).Name ExportATable (TableName) End If Next lTbl Set dBase = Nothing End Sub ``` I make no claims that this is elegant, but it works. Also note that the stackoverflow code formatter doesn't like my \", so it doesn't pretty print my code very nicely.
160,534
<p>I need to get the "td" element of a table. I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY.</p> <p>I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table.</p> <p>Thats what I need, maybe someone can help me out? </p>
[ { "answer_id": 160547, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 6, "selected": true, "text": "<pre><code>$(function() {\n $(\"table#mytable td\").mouseover(function() {\n //The onmouseover code\n }).click(function() {\n //The onclick code\n });\n});\n</code></pre>\n" }, { "answer_id": 160556, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 1, "selected": false, "text": "<p>Work off of the following code to get you started. It should do just what you need. </p>\n\n<pre><code>$(\"td\").hover(function(){\n $(this).css(\"background\",\"#0000ff\");\n},\nfunction(){\n $(this).css(\"background\",\"#ffffff\");\n});\n</code></pre>\n\n<p>You can use <a href=\"http://www.ibm.com/developerworks/web/library/wa-jquery2/\" rel=\"nofollow noreferrer\">this as a reference, which is where I pulled that code</a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
I need to get the "td" element of a table. I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY. I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table. Thats what I need, maybe someone can help me out?
``` $(function() { $("table#mytable td").mouseover(function() { //The onmouseover code }).click(function() { //The onclick code }); }); ```
160,550
<p>I thought people would be working on little code projects together, but I don't see them, so here's an easy one:</p> <p>Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.</p> <p>I wrote a little bit about zip codes in a side project on my wiki/blog:</p> <p><a href="https://benc.fogbugz.com/default.asp?W24" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W24</a></p> <p>There is also a new, weird type of zip code. </p> <p><a href="https://benc.fogbugz.com/default.asp?W42" rel="nofollow noreferrer">https://benc.fogbugz.com/default.asp?W42</a></p> <p>I can do the javascript code, but it would be interesting to see how many languages we can get here.</p>
[ { "answer_id": 160583, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 7, "selected": true, "text": "<p><strong>Javascript Regex Literal</strong>:</p>\n\n<p>US Zip Codes: <code>/(^\\d{5}$)|(^\\d{5}-\\d{4}$)/</code></p>\n\n<pre><code>var isValidZip = /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/.test(\"90210\");\n</code></pre>\n\n<p>Some countries use <a href=\"http://en.wikipedia.org/wiki/Postal_code\" rel=\"noreferrer\">Postal Codes</a>, which would fail this pattern.</p>\n" }, { "answer_id": 160628, "author": "Saif Khan", "author_id": 23667, "author_profile": "https://Stackoverflow.com/users/23667", "pm_score": -1, "selected": false, "text": "<p>Are you referring to address validation? Like the previous answer by Mike, you need to cater for the othe 95%.</p>\n\n<p>What you can do is when the user select's their country, then enable validation. Address validation and zipcode validation are 2 different things. Validating the ZIP is just making sure its integer. Address validation is validating the actual address for accuracy, preferably for mailing.</p>\n" }, { "answer_id": 160880, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 3, "selected": false, "text": "<p>Here's a JavaScript function which validates a ZIP/postal code based on a country code. It allows somewhat liberal formatting. You could add cases for other countries as well. Note that the default case allows empty postal codes since not all countries use them.</p>\n\n<pre><code>function isValidPostalCode(postalCode, countryCode) {\n switch (countryCode) {\n case \"US\":\n postalCodeRegex = /^([0-9]{5})(?:[-\\s]*([0-9]{4}))?$/;\n break;\n case \"CA\":\n postalCodeRegex = /^([A-Z][0-9][A-Z])\\s*([0-9][A-Z][0-9])$/;\n break;\n default:\n postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/;\n }\n return postalCodeRegex.test(postalCode);\n}\n</code></pre>\n\n<p>FYI The second link referring to vanity ZIP codes appears to have been an April Fool's joke.</p>\n" }, { "answer_id": 546280, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>To allow a user to enter a Canadian Postal code with lower case letters as well, the regex would need to look like this:</p>\n\n<p>/^([a-zA-Z][0-9][a-zA-Z])\\s*([0-9][a-zA-Z][0-9])$/</p>\n" }, { "answer_id": 546304, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 5, "selected": false, "text": "<pre><code>function isValidUSZip(sZip) {\n return /^\\d{5}(-\\d{4})?$/.test(sZip);\n}\n</code></pre>\n" }, { "answer_id": 7446316, "author": "Samer", "author_id": 439392, "author_profile": "https://Stackoverflow.com/users/439392", "pm_score": 3, "selected": false, "text": "<p>If you're doing for Canada remember that not all letters are valid</p>\n\n<p>These letters are invalid: D, F, I, O, Q, or U\nAnd the letters W and Z are not used as the first letter.\nAlso some people use an optional space after the 3rd character.</p>\n\n<p>Here is a regular expression for Canadian postal code:</p>\n\n<p><code>new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)</code></p>\n\n<p>The last <em>i</em> makes it case insensitive.</p>\n" }, { "answer_id": 7948939, "author": "TorchLakeDave", "author_id": 1021237, "author_profile": "https://Stackoverflow.com/users/1021237", "pm_score": 1, "selected": false, "text": "<p>This is a good JavaScript solution to the validation issue you have:</p>\n\n<pre><code>/\\b\\d{5}-\\d{4}\\b/\n</code></pre>\n" }, { "answer_id": 14956096, "author": "Irfan", "author_id": 902161, "author_profile": "https://Stackoverflow.com/users/902161", "pm_score": 0, "selected": false, "text": "<p>One way to check valid Canada postal code is-</p>\n\n<pre><code>function isValidCAPostal(pcVal) {\n return ^[A-Za-z][0-9][A-Za-z]\\s{0,1}[0-9][A-Za-z][0-9]$/.test(pcVal);\n}\n</code></pre>\n\n<p>Hope this will help someone.</p>\n" }, { "answer_id": 14987926, "author": "Shogo Yahagi", "author_id": 2092674, "author_profile": "https://Stackoverflow.com/users/2092674", "pm_score": 2, "selected": false, "text": "<p>Here's one from jQuery Validate plugin's <code>additional-methods.js</code> file...</p>\n\n<pre><code>jQuery.validator.addMethod(\"zipUS\", function(value, element) {\n return /(^\\d{5}$)|(^\\d{5}-\\d{4}$)/.test(value);\n}, \"Please specify a valid US zip code.\");\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong>: Since the above code is part of the jQuery Validate plugin, it depends on the <code>.addMethod()</code> method.</p>\n\n<p>Remove dependency on plugins and make it more generic....</p>\n\n<pre><code>function checkZip(value) {\n return (/(^\\d{5}$)|(^\\d{5}-\\d{4}$)/).test(value);\n};\n</code></pre>\n\n<p><strong>Example Usage: <a href=\"http://jsfiddle.net/5PNcJ/\" rel=\"nofollow\">http://jsfiddle.net/5PNcJ/</a></strong></p>\n" }, { "answer_id": 19482039, "author": "user2832940", "author_id": 2832940, "author_profile": "https://Stackoverflow.com/users/2832940", "pm_score": 1, "selected": false, "text": "<p>As I work in the mailing industry for 17 years I've seen all kinds of data entry in this area I find it interesting how many people do not know their address as it is defined by the USPS. I still see addresses like this:</p>\n\n<p>XYZ College<br>\nIT Department<br>\nCity, St ZIP</p>\n\n<p>The worst part is the mail 99% of the time is delivered, the other 1%, well that is returned for an incomplete address as it should. </p>\n\n<p>In an earlier post someone mentioned USPS CASS, that software is not free.</p>\n\n<p>To regex a zip code tester is nice, I'm using expressions to determine if US, CA, UK, or AU zip code. I've seen expressions for Japan and others which only add challenges in choosing the correct country that a zip belongs to.</p>\n\n<p>By far the best answer is to use Drop Down Lists for State, and Country. Then use tables to further validate if needed. Just to give you an idea there are 84052 acceptable US City St Zip combinations on just the first 5 digits. There are 249 valid countries as per the ISO and there are 65 US State/Territories.</p>\n\n<p>There are Military, PO Box only, and Unique zip code classes as well. KISS applies here.</p>\n" }, { "answer_id": 19482185, "author": "user2832940", "author_id": 2832940, "author_profile": "https://Stackoverflow.com/users/2832940", "pm_score": 0, "selected": false, "text": "<p>To further my answer, UPS and FedEx can not deliver to a PO BOX not without using the USPS as final handler. Most shipping software out there will not allow a PO Box zip for their standard services. Examples of PO Box zips are 00604 - RAMEY, PR and 06141 - HARTFORD, CT. </p>\n\n<p>The the whole need to validate zip codes can really be a question of how far do you go, what is the budget, what is the time line.</p>\n\n<p>Like anything with expressions test, test, test, and test again. I had an expression for State validation and found that YORK passed when it should fail. The one time in thousands someone entered New York, New York 10279, ugh.</p>\n\n<p>Also keep in mind, USPS does not like punctuation such as N. Market St. and also has very specific acceptable abbreviations for things like Lane, Place, North, Corporation and the like.</p>\n" }, { "answer_id": 23892577, "author": "pal4life", "author_id": 805923, "author_profile": "https://Stackoverflow.com/users/805923", "pm_score": 0, "selected": false, "text": "<p>Drupal 7 also has an easy solution here, this will allow you to validate against multiple countries.</p>\n\n<p><a href=\"https://drupal.org/project/postal_code_validation\" rel=\"nofollow\">https://drupal.org/project/postal_code_validation</a></p>\n\n<p>You will need this module as well <br/>\n<a href=\"https://drupal.org/project/postal_code\" rel=\"nofollow\">https://drupal.org/project/postal_code</a></p>\n\n<p>Test it in <a href=\"http://simplytest.me/\" rel=\"nofollow\">http://simplytest.me/</a></p>\n" }, { "answer_id": 25455577, "author": "Carl", "author_id": 1639609, "author_profile": "https://Stackoverflow.com/users/1639609", "pm_score": 1, "selected": false, "text": "<p>Suggest you have a look at the USPS Address Information APIs. You can validate a zip and obtain standard formatted addresses. <a href=\"https://www.usps.com/business/web-tools-apis/address-information.htm\" rel=\"nofollow\">https://www.usps.com/business/web-tools-apis/address-information.htm</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2910/" ]
I thought people would be working on little code projects together, but I don't see them, so here's an easy one: Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation. I wrote a little bit about zip codes in a side project on my wiki/blog: <https://benc.fogbugz.com/default.asp?W24> There is also a new, weird type of zip code. <https://benc.fogbugz.com/default.asp?W42> I can do the javascript code, but it would be interesting to see how many languages we can get here.
**Javascript Regex Literal**: US Zip Codes: `/(^\d{5}$)|(^\d{5}-\d{4}$)/` ``` var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210"); ``` Some countries use [Postal Codes](http://en.wikipedia.org/wiki/Postal_code), which would fail this pattern.
160,555
<p>Here's the situation: I'm developing a simple application with the following structure:</p> <ul> <li>FormMain (startup point)</li> <li>FormNotification</li> <li>CompleFunctions</li> </ul> <p>Right?</p> <p>Well, in <strong>FormMain</strong> I have the following function:</p> <pre><code>private void DoItInNewThread(ParameterizedThreadStart pParameterizedThreadStart, object pParameters, ThreadPriority pThreadPriority) { Thread oThread = new Thread(pParameterizedThreadStart); oThread.CurrentUICulture = Settings.Instance.Language; oThread.IsBackground = true; oThread.Priority = pThreadPriority; oThread.Name = "μRemote: Background operation"; oThread.Start(pParameters); } </code></pre> <p>So, everytime that I need to call a time consuming method located on <strong>ComplexFunctions</strong> I do the following:</p> <pre><code>// This is FormMain.cs string strSomeParameter = "lala"; DoItInNewThread(new ParameterizedThreadStart(ComplexFunctions.DoSomething), strSomeParameter, ThreadPriority.Normal); </code></pre> <p>The other class, FormNotification, its a Form that display some information of the process to the user. This FormNotification could be called from FormMain or ComplexFunctions. Example:</p> <pre><code>// This is ComplexFunctions.cs public void DoSomething(string pSomeParameter) { // Imagine some time consuming task FormNotification formNotif = new FormNotification(); formNotif.Notify(); } </code></pre> <p>FormNotify has a timer, so, after 10 seconds closes the form. I'm not using formNotif.ShowDialog because I don't want to give focus to this Form. You could check <a href="https://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c">this link</a> to see what I'm doing in Notify.</p> <p>Ok, here's the problem: When I call <strong>FormNotify</strong> from <strong>ComplexFunction</strong> which is called from another Thread in <strong>FormMain</strong> ... this <strong>FormNotify</strong> disappears after a few milliseconds. It's the same effect that when you do something like this:</p> <pre><code>using(FormSomething formSomething = new FormSomething) { formSomething.Show(); } </code></pre> <p><strong>How can avoid this?</strong></p> <p>These are possible solutions that I don't want to use:</p> <ul> <li>Using Thread.Sleep(10000) in FormNotify</li> <li>Using FormNotif.ShowDialog()</li> </ul> <p>This is a simplified scenario (FormNotify does some other fancy stuff that just stay for 10 seconds, but they are irrelevant to see the problem).</p> <p>Thanks for your time!!! And please, sorry my english.</p>
[ { "answer_id": 160564, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>You aren't allowed to make WinForms calls from other threads. Look at BeginInvoke in the form -- you can call a delegate to show the form from the UI thread.</p>\n\n<p>Edit: From the comments (do not set CheckForIllegalCrossThreadCalls to false).</p>\n\n<p><strong>More Info</strong>\nAlmost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.</p>\n" }, { "answer_id": 160629, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>Use the <strong>SetWindowPos</strong> API call to ensure that your notify form is the topmost window. This post explains how:</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html\" rel=\"nofollow noreferrer\">http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html</a></p>\n" }, { "answer_id": 160663, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "<p>There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread.</p>\n\n<p>Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify.</p>\n\n<p>Fire the event from the worker thread when you want to show the notification. </p>\n" }, { "answer_id": 163609, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 4, "selected": true, "text": "<p>Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.</p>\n\n<p>There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread.</p>\n\n<p>Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify.</p>\n\n<p>Fire the event from the worker thread when you want to show the notification. </p>\n\n<p>When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily while debugging. Note that illegal cross-thread calls will always raise an exception when an application is started outside the debugger.</p>\n\n<p>Note: setting CheckForIllegalCrossThreadCalls to ture should only be done in DEBUGGIN SITUATIONS ONLY. Unpredicatable results will occur and you will wind up trying to chase bugs that you will have a difficuly tome finding.</p>\n" }, { "answer_id": 3712806, "author": "Andranik", "author_id": 447778, "author_profile": "https://Stackoverflow.com/users/447778", "pm_score": 0, "selected": false, "text": "<p>Assuming you have button in the form and want to open another form <code>Form1</code> when user clicks that button</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n Thread t = new Thread(new ThreadStart(this.ShowForm1));\n t.Start();\n}\n</code></pre>\n\n<p>All you need to do is check <code>InvokeRequired</code> property and if yes call Invoke method of your form passing <code>ShowForm1</code> delegate, which will end up in recursive call where <code>InvokeRequired</code> will be false</p>\n\n<pre><code>delegate void Func();\nprivate void ShowForm1()\n{ \n if (this.InvokeRequired)\n {\n Func f = new Func(ShowForm1);\n this.Invoke(f);\n }\n else\n {\n Form1 form1 = new Form1();\n form1.Show();\n } \n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
Here's the situation: I'm developing a simple application with the following structure: * FormMain (startup point) * FormNotification * CompleFunctions Right? Well, in **FormMain** I have the following function: ``` private void DoItInNewThread(ParameterizedThreadStart pParameterizedThreadStart, object pParameters, ThreadPriority pThreadPriority) { Thread oThread = new Thread(pParameterizedThreadStart); oThread.CurrentUICulture = Settings.Instance.Language; oThread.IsBackground = true; oThread.Priority = pThreadPriority; oThread.Name = "μRemote: Background operation"; oThread.Start(pParameters); } ``` So, everytime that I need to call a time consuming method located on **ComplexFunctions** I do the following: ``` // This is FormMain.cs string strSomeParameter = "lala"; DoItInNewThread(new ParameterizedThreadStart(ComplexFunctions.DoSomething), strSomeParameter, ThreadPriority.Normal); ``` The other class, FormNotification, its a Form that display some information of the process to the user. This FormNotification could be called from FormMain or ComplexFunctions. Example: ``` // This is ComplexFunctions.cs public void DoSomething(string pSomeParameter) { // Imagine some time consuming task FormNotification formNotif = new FormNotification(); formNotif.Notify(); } ``` FormNotify has a timer, so, after 10 seconds closes the form. I'm not using formNotif.ShowDialog because I don't want to give focus to this Form. You could check [this link](https://stackoverflow.com/questions/156046/show-a-form-without-stealing-focus-in-c) to see what I'm doing in Notify. Ok, here's the problem: When I call **FormNotify** from **ComplexFunction** which is called from another Thread in **FormMain** ... this **FormNotify** disappears after a few milliseconds. It's the same effect that when you do something like this: ``` using(FormSomething formSomething = new FormSomething) { formSomething.Show(); } ``` **How can avoid this?** These are possible solutions that I don't want to use: * Using Thread.Sleep(10000) in FormNotify * Using FormNotif.ShowDialog() This is a simplified scenario (FormNotify does some other fancy stuff that just stay for 10 seconds, but they are irrelevant to see the problem). Thanks for your time!!! And please, sorry my english.
Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library. There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread. Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify. Fire the event from the worker thread when you want to show the notification. When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily while debugging. Note that illegal cross-thread calls will always raise an exception when an application is started outside the debugger. Note: setting CheckForIllegalCrossThreadCalls to ture should only be done in DEBUGGIN SITUATIONS ONLY. Unpredicatable results will occur and you will wind up trying to chase bugs that you will have a difficuly tome finding.
160,557
<p>I have a Selenium test case that enters dates into a date selector made up of three pulldowns (year, month, and day). </p> <pre><code>select validity_Y label=2008 select validity_M label=08 select validity_D label=08 </code></pre> <p>This part gets repeated a lot throughout the test case. I'd like to reduce it by defining my custom action "selectValidity", so that I can have less redundancy, something like</p> <pre><code>selectValidity 2008,08,08 </code></pre> <p>What is the best (easiest, cleanest) way to add macros or subroutines to a test case?</p>
[ { "answer_id": 160564, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>You aren't allowed to make WinForms calls from other threads. Look at BeginInvoke in the form -- you can call a delegate to show the form from the UI thread.</p>\n\n<p>Edit: From the comments (do not set CheckForIllegalCrossThreadCalls to false).</p>\n\n<p><strong>More Info</strong>\nAlmost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.</p>\n" }, { "answer_id": 160629, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>Use the <strong>SetWindowPos</strong> API call to ensure that your notify form is the topmost window. This post explains how:</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html\" rel=\"nofollow noreferrer\">http://www.pinvoke.net/default.aspx/user32/SetWindowPos.html</a></p>\n" }, { "answer_id": 160663, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "<p>There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread.</p>\n\n<p>Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify.</p>\n\n<p>Fire the event from the worker thread when you want to show the notification. </p>\n" }, { "answer_id": 163609, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 4, "selected": true, "text": "<p>Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.</p>\n\n<p>There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread.</p>\n\n<p>Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify.</p>\n\n<p>Fire the event from the worker thread when you want to show the notification. </p>\n\n<p>When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily while debugging. Note that illegal cross-thread calls will always raise an exception when an application is started outside the debugger.</p>\n\n<p>Note: setting CheckForIllegalCrossThreadCalls to ture should only be done in DEBUGGIN SITUATIONS ONLY. Unpredicatable results will occur and you will wind up trying to chase bugs that you will have a difficuly tome finding.</p>\n" }, { "answer_id": 3712806, "author": "Andranik", "author_id": 447778, "author_profile": "https://Stackoverflow.com/users/447778", "pm_score": 0, "selected": false, "text": "<p>Assuming you have button in the form and want to open another form <code>Form1</code> when user clicks that button</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n Thread t = new Thread(new ThreadStart(this.ShowForm1));\n t.Start();\n}\n</code></pre>\n\n<p>All you need to do is check <code>InvokeRequired</code> property and if yes call Invoke method of your form passing <code>ShowForm1</code> delegate, which will end up in recursive call where <code>InvokeRequired</code> will be false</p>\n\n<pre><code>delegate void Func();\nprivate void ShowForm1()\n{ \n if (this.InvokeRequired)\n {\n Func f = new Func(ShowForm1);\n this.Invoke(f);\n }\n else\n {\n Form1 form1 = new Form1();\n form1.Show();\n } \n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
I have a Selenium test case that enters dates into a date selector made up of three pulldowns (year, month, and day). ``` select validity_Y label=2008 select validity_M label=08 select validity_D label=08 ``` This part gets repeated a lot throughout the test case. I'd like to reduce it by defining my custom action "selectValidity", so that I can have less redundancy, something like ``` selectValidity 2008,08,08 ``` What is the best (easiest, cleanest) way to add macros or subroutines to a test case?
Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library. There is something called thread affinity. There are two threads in a WinForm Application, one for rendering and one for managing user interface. You deal only with user interface thread. The rendering thread remains hidden - runs in the background. The only objects created on UI thread can manipulate the UI - i.e the objects have thread affinity with the UI thread. Since, you are trying to update UI (show a notification) from a different thread than the UI thread. So in your worker thread define a delegate and make FormMain listen to this event. In the event handler (define in FormMain) write code to show the FormNotify. Fire the event from the worker thread when you want to show the notification. When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily while debugging. Note that illegal cross-thread calls will always raise an exception when an application is started outside the debugger. Note: setting CheckForIllegalCrossThreadCalls to ture should only be done in DEBUGGIN SITUATIONS ONLY. Unpredicatable results will occur and you will wind up trying to chase bugs that you will have a difficuly tome finding.
160,587
<p>I'm using <code>Console.WriteLine()</code> from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here?</p> <p>I can reproduce it by creating a WPF application in VS 2008, and simply adding <code>Console.WriteLine(&quot;text&quot;)</code> anywhere where it gets executed. Any ideas?</p> <p>All I need for right now is something as simple as <code>Console.WriteLine()</code>. I realize I could use log4net or somet other logging solution, but I really don't need that much functionality for this application.</p> <p><strong>Edit:</strong> I should have remembered that <code>Console.WriteLine()</code> is for console applications. Oh well, no stupid questions, right? :-) I'll just use <code>System.Diagnostics.Trace.WriteLine()</code> and DebugView for now.</p>
[ { "answer_id": 160597, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 7, "selected": false, "text": "<p>Right click on the project, \"Properties\", \"Application\" tab, change \"Output Type\" to \"Console Application\", and then it will also have a console.</p>\n" }, { "answer_id": 160606, "author": "Phobis", "author_id": 19854, "author_profile": "https://Stackoverflow.com/users/19854", "pm_score": 8, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>Trace.WriteLine(\"text\");\n</code></pre>\n\n<p>This will output to the \"Output\" window in Visual Studio (when debugging).</p>\n\n<p>make sure to have the Diagnostics assembly included:</p>\n\n<pre><code>using System.Diagnostics;\n</code></pre>\n" }, { "answer_id": 161031, "author": "erodewald", "author_id": 24399, "author_profile": "https://Stackoverflow.com/users/24399", "pm_score": 2, "selected": false, "text": "<p>I use Console.WriteLine() for use in the Output window...</p>\n" }, { "answer_id": 718505, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 8, "selected": true, "text": "<p>You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).</p>\n\n<p>Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type.</p>\n\n<p>With the following class, you just need to write <code>ConsoleManager.Show()</code> somewhere before any call to <code>Console.Write</code>...</p>\n\n<pre><code>[SuppressUnmanagedCodeSecurity]\npublic static class ConsoleManager\n{\n private const string Kernel32_DllName = \"kernel32.dll\";\n\n [DllImport(Kernel32_DllName)]\n private static extern bool AllocConsole();\n\n [DllImport(Kernel32_DllName)]\n private static extern bool FreeConsole();\n\n [DllImport(Kernel32_DllName)]\n private static extern IntPtr GetConsoleWindow();\n\n [DllImport(Kernel32_DllName)]\n private static extern int GetConsoleOutputCP();\n\n public static bool HasConsole\n {\n get { return GetConsoleWindow() != IntPtr.Zero; }\n }\n\n /// &lt;summary&gt;\n /// Creates a new console instance if the process is not attached to a console already.\n /// &lt;/summary&gt;\n public static void Show()\n {\n //#if DEBUG\n if (!HasConsole)\n {\n AllocConsole();\n InvalidateOutAndError();\n }\n //#endif\n }\n\n /// &lt;summary&gt;\n /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.\n /// &lt;/summary&gt;\n public static void Hide()\n {\n //#if DEBUG\n if (HasConsole)\n {\n SetOutAndErrorNull();\n FreeConsole();\n }\n //#endif\n }\n\n public static void Toggle()\n {\n if (HasConsole)\n {\n Hide();\n }\n else\n {\n Show();\n }\n }\n\n static void InvalidateOutAndError()\n {\n Type type = typeof(System.Console);\n\n System.Reflection.FieldInfo _out = type.GetField(\"_out\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n System.Reflection.FieldInfo _error = type.GetField(\"_error\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod(\"InitializeStdOutError\",\n System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);\n\n Debug.Assert(_out != null);\n Debug.Assert(_error != null);\n\n Debug.Assert(_InitializeStdOutError != null);\n\n _out.SetValue(null, null);\n _error.SetValue(null, null);\n\n _InitializeStdOutError.Invoke(null, new object[] { true });\n }\n\n static void SetOutAndErrorNull()\n {\n Console.SetOut(TextWriter.Null);\n Console.SetError(TextWriter.Null);\n }\n} \n</code></pre>\n" }, { "answer_id": 793170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Although John Leidegren keeps shooting down the idea, Brian is correct. I've just got it working in Visual Studio.</p>\n\n<p>To be clear a WPF application does not create a Console window by default.</p>\n\n<p>You have to create a WPF Application and then change the OutputType to \"Console Application\". When you run the project you will see a console window with your WPF window in front of it.</p>\n\n<p>It doesn't look very pretty, but I found it helpful as I wanted my app to be run from the command line with feedback in there, and then for certain command options I would display the WPF window.</p>\n" }, { "answer_id": 23957803, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 4, "selected": false, "text": "<p>It's possible to see output intended for console by using <a href=\"http://technet.microsoft.com/en-us/library/bb490982.aspx\" rel=\"noreferrer\">command line redirection</a>.</p>\n\n<p>For example:</p>\n\n<pre><code>C:\\src\\bin\\Debug\\Example.exe &gt; output.txt\n</code></pre>\n\n<p>will write all the content to <code>output.txt</code> file.</p>\n" }, { "answer_id": 25255546, "author": "Sam Wright", "author_id": 2341345, "author_profile": "https://Stackoverflow.com/users/2341345", "pm_score": 0, "selected": false, "text": "<p>Check out this post, was very helpful for myself. Download the code sample:</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/335909/Embedding-a-Console-in-a-C-Application\" rel=\"nofollow\">http://www.codeproject.com/Articles/335909/Embedding-a-Console-in-a-C-Application</a></p>\n" }, { "answer_id": 41732584, "author": "Smitty", "author_id": 5842023, "author_profile": "https://Stackoverflow.com/users/5842023", "pm_score": 5, "selected": false, "text": "<p>Old post, but I ran into this so if you're trying to output something to Output in a WPF project in Visual Studio, the contemporary method is:</p>\n\n<p>Include this:</p>\n\n<pre><code>using System.Diagnostics;\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>Debug.WriteLine(\"something\");\n</code></pre>\n" }, { "answer_id": 51701886, "author": "Emelias Alvarez", "author_id": 8303606, "author_profile": "https://Stackoverflow.com/users/8303606", "pm_score": 2, "selected": false, "text": "<p>I've create a solution, mixed the information of varius post.</p>\n\n<p>Its a form, that contains a label and one textbox. The console output is redirected to the textbox.</p>\n\n<p>There are too a class called ConsoleView that implements three publics methods: Show(), Close(), and Release(). The last one is for leave open the console and activate the Close button for view results.</p>\n\n<p>The forms is called FrmConsole. Here are the XAML and the c# code.</p>\n\n<p>The use is very simple:</p>\n\n<pre><code>ConsoleView.Show(\"Title of the Console\");\n</code></pre>\n\n<p>For open the console. Use:</p>\n\n<pre><code>System.Console.WriteLine(\"The debug message\");\n</code></pre>\n\n<p>For output text to the console.</p>\n\n<p>Use:</p>\n\n<pre><code>ConsoleView.Close();\n</code></pre>\n\n<p>For Close the console.</p>\n\n<pre><code>ConsoleView.Release();\n</code></pre>\n\n<p>Leaves open the console and enables the Close button</p>\n\n<p>XAML</p>\n\n<pre><code>&lt;Window x:Class=\"CustomControls.FrmConsole\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:CustomControls\"\n mc:Ignorable=\"d\"\n Height=\"500\" Width=\"600\" WindowStyle=\"None\" ResizeMode=\"NoResize\" WindowStartupLocation=\"CenterScreen\" Topmost=\"True\" Icon=\"Images/icoConsole.png\"&gt;\n&lt;Grid&gt;\n &lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition Height=\"40\"/&gt;\n &lt;RowDefinition Height=\"*\"/&gt;\n &lt;RowDefinition Height=\"40\"/&gt;\n &lt;/Grid.RowDefinitions&gt;\n &lt;Label Grid.Row=\"0\" Name=\"lblTitulo\" HorizontalAlignment=\"Center\" HorizontalContentAlignment=\"Center\" VerticalAlignment=\"Center\" VerticalContentAlignment=\"Center\" FontFamily=\"Arial\" FontSize=\"14\" FontWeight=\"Bold\" Content=\"Titulo\"/&gt;\n &lt;Grid Grid.Row=\"1\"&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"10\"/&gt;\n &lt;ColumnDefinition Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"10\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;TextBox Grid.Column=\"1\" Name=\"txtInner\" FontFamily=\"Arial\" FontSize=\"10\" ScrollViewer.CanContentScroll=\"True\" VerticalScrollBarVisibility=\"Visible\" HorizontalScrollBarVisibility=\"Visible\" TextWrapping=\"Wrap\"/&gt;\n &lt;/Grid&gt;\n &lt;Button Name=\"btnCerrar\" Grid.Row=\"2\" Content=\"Cerrar\" Width=\"100\" Height=\"30\" HorizontalAlignment=\"Center\" HorizontalContentAlignment=\"Center\" VerticalAlignment=\"Center\" VerticalContentAlignment=\"Center\"/&gt;\n&lt;/Grid&gt;\n</code></pre>\n\n<p></p>\n\n<p>The code of the Window:</p>\n\n<pre><code>partial class FrmConsole : Window\n{\n private class ControlWriter : TextWriter\n {\n private TextBox textbox;\n public ControlWriter(TextBox textbox)\n {\n this.textbox = textbox;\n }\n\n public override void WriteLine(char value)\n {\n textbox.Dispatcher.Invoke(new Action(() =&gt;\n {\n textbox.AppendText(value.ToString());\n textbox.AppendText(Environment.NewLine);\n textbox.ScrollToEnd();\n }));\n }\n\n public override void WriteLine(string value)\n {\n textbox.Dispatcher.Invoke(new Action(() =&gt;\n {\n textbox.AppendText(value);\n textbox.AppendText(Environment.NewLine);\n textbox.ScrollToEnd();\n }));\n }\n\n public override void Write(char value)\n {\n textbox.Dispatcher.Invoke(new Action(() =&gt;\n {\n textbox.AppendText(value.ToString());\n textbox.ScrollToEnd();\n }));\n }\n\n public override void Write(string value)\n {\n textbox.Dispatcher.Invoke(new Action(() =&gt;\n {\n textbox.AppendText(value);\n textbox.ScrollToEnd();\n }));\n }\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n\n }\n }\n\n //DEFINICIONES DE LA CLASE\n #region DEFINICIONES DE LA CLASE\n\n #endregion\n\n\n //CONSTRUCTORES DE LA CLASE\n #region CONSTRUCTORES DE LA CLASE\n\n public FrmConsole(string titulo)\n {\n InitializeComponent();\n lblTitulo.Content = titulo;\n Clear();\n btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);\n Console.SetOut(new ControlWriter(txtInner));\n DesactivarCerrar();\n }\n\n #endregion\n\n\n //PROPIEDADES\n #region PROPIEDADES\n\n #endregion\n\n\n //DELEGADOS\n #region DELEGADOS\n\n private void BtnCerrar_Click(object sender, RoutedEventArgs e)\n {\n Close();\n }\n\n #endregion\n\n\n //METODOS Y FUNCIONES\n #region METODOS Y FUNCIONES\n\n public void ActivarCerrar()\n {\n btnCerrar.IsEnabled = true;\n }\n\n public void Clear()\n {\n txtInner.Clear();\n }\n\n public void DesactivarCerrar()\n {\n btnCerrar.IsEnabled = false;\n }\n\n #endregion \n}\n</code></pre>\n\n<p>the code of ConsoleView class</p>\n\n<pre><code>static public class ConsoleView\n{\n //DEFINICIONES DE LA CLASE\n #region DEFINICIONES DE LA CLASE\n static FrmConsole console;\n static Thread StatusThread;\n static bool isActive = false;\n #endregion\n\n //CONSTRUCTORES DE LA CLASE\n #region CONSTRUCTORES DE LA CLASE\n\n #endregion\n\n //PROPIEDADES\n #region PROPIEDADES\n\n #endregion\n\n //DELEGADOS\n #region DELEGADOS\n\n #endregion\n\n //METODOS Y FUNCIONES\n #region METODOS Y FUNCIONES\n\n public static void Show(string label)\n {\n if (isActive)\n {\n return;\n }\n\n isActive = true;\n //create the thread with its ThreadStart method\n StatusThread = new Thread(() =&gt;\n {\n try\n {\n console = new FrmConsole(label);\n console.ShowDialog();\n //this call is needed so the thread remains open until the dispatcher is closed\n Dispatcher.Run();\n }\n catch (Exception)\n {\n }\n });\n\n //run the thread in STA mode to make it work correctly\n StatusThread.SetApartmentState(ApartmentState.STA);\n StatusThread.Priority = ThreadPriority.Normal;\n StatusThread.Start();\n\n }\n\n public static void Close()\n {\n isActive = false;\n if (console != null)\n {\n //need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread\n console.Dispatcher.InvokeShutdown();\n console = null;\n StatusThread = null;\n }\n\n console = null;\n }\n\n public static void Release()\n {\n isActive = false;\n if (console != null)\n {\n console.Dispatcher.Invoke(console.ActivarCerrar);\n }\n\n }\n #endregion\n}\n</code></pre>\n\n<p>I hope this result usefull.</p>\n" }, { "answer_id": 73971822, "author": "Bip901", "author_id": 7812339, "author_profile": "https://Stackoverflow.com/users/7812339", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/160597/7812339\">Brian's solution</a> is to <strong>always</strong> open a console when your WPF application starts. If you want to <strong>dynamically</strong> enable console output (for example, only when launched with certain commandline arguments) call <code>AttachConsole</code>:</p>\n<pre><code>[DllImport(&quot;kernel32.dll&quot;)]\nstatic extern bool AttachConsole(uint dwProcessId);\n\nconst uint ATTACH_PARENT_PROCESS = 0x0ffffffff;\n</code></pre>\n<p>Then, when you want to start writing to the console:</p>\n<pre><code>AttachConsole(ATTACH_PARENT_PROCESS);\nConsole.WriteLine(&quot;Hello world!&quot;);\nConsole.WriteLine(&quot;Writing to the hosting console!&quot;);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18505/" ]
I'm using `Console.WriteLine()` from a very simple WPF test application, but when I execute the application from the command line, I'm seeing nothing being written to the console. Does anyone know what might be going on here? I can reproduce it by creating a WPF application in VS 2008, and simply adding `Console.WriteLine("text")` anywhere where it gets executed. Any ideas? All I need for right now is something as simple as `Console.WriteLine()`. I realize I could use log4net or somet other logging solution, but I really don't need that much functionality for this application. **Edit:** I should have remembered that `Console.WriteLine()` is for console applications. Oh well, no stupid questions, right? :-) I'll just use `System.Diagnostics.Trace.WriteLine()` and DebugView for now.
You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work). Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type. With the following class, you just need to write `ConsoleManager.Show()` somewhere before any call to `Console.Write`... ``` [SuppressUnmanagedCodeSecurity] public static class ConsoleManager { private const string Kernel32_DllName = "kernel32.dll"; [DllImport(Kernel32_DllName)] private static extern bool AllocConsole(); [DllImport(Kernel32_DllName)] private static extern bool FreeConsole(); [DllImport(Kernel32_DllName)] private static extern IntPtr GetConsoleWindow(); [DllImport(Kernel32_DllName)] private static extern int GetConsoleOutputCP(); public static bool HasConsole { get { return GetConsoleWindow() != IntPtr.Zero; } } /// <summary> /// Creates a new console instance if the process is not attached to a console already. /// </summary> public static void Show() { //#if DEBUG if (!HasConsole) { AllocConsole(); InvalidateOutAndError(); } //#endif } /// <summary> /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown. /// </summary> public static void Hide() { //#if DEBUG if (HasConsole) { SetOutAndErrorNull(); FreeConsole(); } //#endif } public static void Toggle() { if (HasConsole) { Hide(); } else { Show(); } } static void InvalidateOutAndError() { Type type = typeof(System.Console); System.Reflection.FieldInfo _out = type.GetField("_out", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.FieldInfo _error = type.GetField("_error", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Debug.Assert(_out != null); Debug.Assert(_error != null); Debug.Assert(_InitializeStdOutError != null); _out.SetValue(null, null); _error.SetValue(null, null); _InitializeStdOutError.Invoke(null, new object[] { true }); } static void SetOutAndErrorNull() { Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); } } ```
160,604
<p>I'm trying to combine a list of functions like so.</p> <p>I have this:</p> <pre><code>Func&lt;int, bool&gt;[] criteria = new Func&lt;int, bool&gt;[3]; criteria[0] = i =&gt; i % 2 == 0; criteria[1] = i =&gt; i % 3 == 0; criteria[2] = i =&gt; i % 5 == 0; </code></pre> <p>And I want this:</p> <pre><code>Func&lt;int, bool&gt;[] predicates = new Func&lt;int, bool&gt;[3]; predicates[0] = i =&gt; i % 2 == 0; predicates[1] = i =&gt; i % 2 == 0 &amp;&amp; i % 3 == 0; predicates[2] = i =&gt; i % 2 == 0 &amp;&amp; i % 3 == 0 &amp;&amp; i % 5 == 0; </code></pre> <p>So far I've got the following code:</p> <pre><code>Expression&lt;Func&lt;int, bool&gt;&gt;[] results = new Expression&lt;Func&lt;int, bool&gt;&gt;[criteria.Length]; for (int i = 0; i &lt; criteria.Length; i++) { results[i] = f =&gt; true; for (int j = 0; j &lt;= i; j++) { Expression&lt;Func&lt;int, bool&gt;&gt; expr = b =&gt; criteria[j](b); var invokedExpr = Expression.Invoke( expr, results[i].Parameters.Cast&lt;Expression&gt;()); results[i] = Expression.Lambda&lt;Func&lt;int, bool&gt;&gt;( Expression.And(results[i].Body, invokedExpr), results[i].Parameters); } } var predicates = results.Select(e =&gt; e.Compile()).ToArray(); Console.WriteLine(predicates[0](6)); // Returns true Console.WriteLine(predicates[1](6)); // Returns false Console.WriteLine(predicates[2](6)); // Throws an IndexOutOfRangeException </code></pre> <p>Does anyone know what I'm doing wrong?</p>
[ { "answer_id": 160661, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 3, "selected": true, "text": "<p>This was a guess, as I know little about this stuff, but this seems to fix it:</p>\n\n<pre><code>Func&lt;int, bool&gt;[] criteria = new Func&lt;int, bool&gt;[3]; \ncriteria[0] = i =&gt; i % 2 == 0; \ncriteria[1] = i =&gt; i % 3 == 0; \ncriteria[2] = i =&gt; i % 5 == 0;\nExpression&lt;Func&lt;int, bool&gt;&gt;[] results = new Expression&lt;Func&lt;int, bool&gt;&gt;[criteria.Length];\nfor (int i = 0; i &lt; criteria.Length; i++)\n{\n results[i] = f =&gt; true; \n for (int j = 0; j &lt;= i; j++)\n {\n int ii = i;\n int jj = j;\n Expression&lt;Func&lt;int, bool&gt;&gt; expr = b =&gt; criteria[jj](b); \n var invokedExpr = Expression.Invoke(expr, results[ii].Parameters.Cast&lt;Expression&gt;()); \n results[ii] = Expression.Lambda&lt;Func&lt;int, bool&gt;&gt;(Expression.And(results[ii].Body, invokedExpr), results[ii].Parameters);\n }\n} \nvar predicates = results.Select(e =&gt; e.Compile()).ToArray(); \n</code></pre>\n\n<p>The key is the introduction of 'ii' and 'jj' (maybe only one matters, I didn't try). I think you are capturing a mutable variable inside a lambda, and thus when you finally reference it, you're seeing the later-mutated value rather than the original value.</p>\n" }, { "answer_id": 161932, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>No need to pull in Expressions...</p>\n\n<pre><code> Func&lt;int, bool&gt;[] criteria = new Func&lt;int, bool&gt;[3];\n criteria[0] = i =&gt; i % 2 == 0;\n criteria[1] = i =&gt; i % 3 == 0;\n criteria[2] = i =&gt; i % 5 == 0;\n\n Func&lt;int, bool&gt;[] predicates = new Func&lt;int, bool&gt;[3];\n\n predicates[0] = criteria[0];\n for (int i = 1; i &lt; criteria.Length; i++)\n {\n //need j to be an unchanging int, one for each loop execution.\n int j = i;\n\n predicates[j] = x =&gt; predicates[j - 1](x) &amp;&amp; criteria[j](x);\n }\n\n Console.WriteLine(predicates[0](6)); //True\n Console.WriteLine(predicates[1](6)); //True\n Console.WriteLine(predicates[2](6)); //False\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820/" ]
I'm trying to combine a list of functions like so. I have this: ``` Func<int, bool>[] criteria = new Func<int, bool>[3]; criteria[0] = i => i % 2 == 0; criteria[1] = i => i % 3 == 0; criteria[2] = i => i % 5 == 0; ``` And I want this: ``` Func<int, bool>[] predicates = new Func<int, bool>[3]; predicates[0] = i => i % 2 == 0; predicates[1] = i => i % 2 == 0 && i % 3 == 0; predicates[2] = i => i % 2 == 0 && i % 3 == 0 && i % 5 == 0; ``` So far I've got the following code: ``` Expression<Func<int, bool>>[] results = new Expression<Func<int, bool>>[criteria.Length]; for (int i = 0; i < criteria.Length; i++) { results[i] = f => true; for (int j = 0; j <= i; j++) { Expression<Func<int, bool>> expr = b => criteria[j](b); var invokedExpr = Expression.Invoke( expr, results[i].Parameters.Cast<Expression>()); results[i] = Expression.Lambda<Func<int, bool>>( Expression.And(results[i].Body, invokedExpr), results[i].Parameters); } } var predicates = results.Select(e => e.Compile()).ToArray(); Console.WriteLine(predicates[0](6)); // Returns true Console.WriteLine(predicates[1](6)); // Returns false Console.WriteLine(predicates[2](6)); // Throws an IndexOutOfRangeException ``` Does anyone know what I'm doing wrong?
This was a guess, as I know little about this stuff, but this seems to fix it: ``` Func<int, bool>[] criteria = new Func<int, bool>[3]; criteria[0] = i => i % 2 == 0; criteria[1] = i => i % 3 == 0; criteria[2] = i => i % 5 == 0; Expression<Func<int, bool>>[] results = new Expression<Func<int, bool>>[criteria.Length]; for (int i = 0; i < criteria.Length; i++) { results[i] = f => true; for (int j = 0; j <= i; j++) { int ii = i; int jj = j; Expression<Func<int, bool>> expr = b => criteria[jj](b); var invokedExpr = Expression.Invoke(expr, results[ii].Parameters.Cast<Expression>()); results[ii] = Expression.Lambda<Func<int, bool>>(Expression.And(results[ii].Body, invokedExpr), results[ii].Parameters); } } var predicates = results.Select(e => e.Compile()).ToArray(); ``` The key is the introduction of 'ii' and 'jj' (maybe only one matters, I didn't try). I think you are capturing a mutable variable inside a lambda, and thus when you finally reference it, you're seeing the later-mutated value rather than the original value.
160,608
<p>I've been wondering whether there is a good &quot;git export&quot; solution that creates a copy of a tree without the <code>.git</code> repository directory. There are at least three methods I know of:</p> <ol> <li><code>git clone</code> followed by removing the <code>.git</code> repository directory.</li> <li><a href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html" rel="noreferrer"><code>git checkout-index</code></a> alludes to this functionality but starts with &quot;Just read the desired tree into the index...&quot; which I'm not entirely sure how to do.</li> <li><a href="http://code.google.com/p/git-export/" rel="noreferrer"><code>git-export</code></a> is a third-party script that essentially does a <code>git clone</code> into a temporary location followed by <code>rsync --exclude='.git'</code> into the final destination.</li> </ol> <p>None of these solutions really strike me as being satisfactory. The closest one to <code>svn export</code> might be option 1, because both require the target directory to be empty first. But option 2 seems even better, assuming I can figure out what it means to read a tree into the index.</p>
[ { "answer_id": 160620, "author": "jperras", "author_id": 5570, "author_profile": "https://Stackoverflow.com/users/5570", "pm_score": 5, "selected": false, "text": "<p>From the <a href=\"http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html\" rel=\"noreferrer\" title=\"Git Manual\">Git Manual</a>:</p>\n\n<p>Using git-checkout-index to \"export an entire tree\"</p>\n\n<p>The prefix ability basically makes it trivial to use git-checkout-index as an \"export as tree\" function. Just read the desired tree into the index, and do:</p>\n\n<p><code>$ git checkout-index --prefix=git-export-dir/ -a</code></p>\n" }, { "answer_id": 160719, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": false, "text": "<p>I found out what option 2 means. From a repository, you can do:</p>\n\n<pre><code>git checkout-index -a -f --prefix=/destination/path/\n</code></pre>\n\n<p>The slash at the end of the path is important, otherwise it will result in the files being in /destination with a prefix of 'path'.</p>\n\n<p>Since in a normal situation the index contains the contents of the repository, there is nothing special to do to \"read the desired tree into the index\". It's already there.</p>\n\n<p>The <code>-a</code> flag is required to check out all files in the index (I'm not sure what it means to omit this flag in this situation, since it doesn't do what I want). The <code>-f</code> flag forces overwriting any existing files in the output, which this command doesn't normally do.</p>\n\n<p>This appears to be the sort of \"git export\" I was looking for.</p>\n" }, { "answer_id": 162901, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 3, "selected": false, "text": "<p>My preference would actually be to have a <strong>dist</strong> target in your Makefile (or other build system) that exports a distributable archive of your code (.tar.bz2, .zip, .jar, or whatever is appropriate). If you happen to be using GNU autotools or Perl's MakeMaker systems, I think this exists for you automatically. If not, I highly recommend adding it.</p>\n\n<p>ETA (2012-09-06): Wow, harsh downvotes. I still believe it is better to build your distributions with your build tools rather than your source code control tool. I believe in building artifacts with build tools. In my current job, our main product is built with an ant target. We are in the midst of switching source code control systems, and the presence of this ant target means one less hassle in migration.</p>\n" }, { "answer_id": 163769, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 12, "selected": true, "text": "<p>Probably the simplest way to achieve this is with <a href=\"https://git-scm.com/docs/git-archive\" rel=\"noreferrer\"><code>git archive</code></a>. If you really need just the expanded tree you can do something like this.</p>\n\n<pre><code>git archive master | tar -x -C /somewhere/else\n</code></pre>\n\n<p>Most of the time that I need to 'export' something from git, I want a compressed archive in any case so I do something like this.</p>\n\n<pre><code>git archive master | bzip2 &gt;source-tree.tar.bz2\n</code></pre>\n\n<p>ZIP archive:</p>\n\n<pre><code>git archive --format zip --output /full/path/to/zipfile.zip master \n</code></pre>\n\n<p><a href=\"https://git-scm.com/docs/git-archive\" rel=\"noreferrer\"><code>git help archive</code></a> for more details, it's quite flexible.</p>\n\n<hr>\n\n<p>Be aware that even though the archive will not contain the .git directory, it will, however, contain other hidden git-specific files like .gitignore, .gitattributes, etc. If you don't want them in the archive, make sure you use the export-ignore attribute in a .gitattributes file and commit this before doing your archive. <a href=\"http://feeding.cloud.geek.nz/2010/02/excluding-files-from-git-archive.html\" rel=\"noreferrer\">Read more...</a></p>\n\n<hr>\n\n<p>Note: If you are interested in exporting the index, the command is</p>\n\n<pre><code>git checkout-index -a -f --prefix=/destination/path/\n</code></pre>\n\n<p>(See <a href=\"https://stackoverflow.com/a/160719/413020\" title=\"Greg&#39;s answer\">Greg's answer</a> for more details)</p>\n" }, { "answer_id": 209489, "author": "Daniel Schierbeck", "author_id": 20321, "author_profile": "https://Stackoverflow.com/users/20321", "pm_score": 5, "selected": false, "text": "<p>I've written a simple wrapper around <code>git-checkout-index</code> that you can use like this:</p>\n\n<pre><code>git export ~/the/destination/dir\n</code></pre>\n\n<p>If the destination directory already exists, you'll need to add <code>-f</code> or <code>--force</code>.</p>\n\n<p>Installation is simple; just drop the script somewhere in your <code>PATH</code>, and make sure it's executable.</p>\n\n<p><a href=\"http://github.com/dasch/git-export/tree/master\" rel=\"noreferrer\">The github repository for <code>git-export</code></a> </p>\n" }, { "answer_id": 353830, "author": "Alexander Somov", "author_id": 44710, "author_profile": "https://Stackoverflow.com/users/44710", "pm_score": 8, "selected": false, "text": "<p><code>git archive</code> also works with remote repository.</p>\n\n<pre><code>git archive --format=tar \\\n--remote=ssh://remote_server/remote_repository master | tar -xf -\n</code></pre>\n\n<p>To export particular path inside the repo add as many paths as you wish as last argument to git, e.g.:</p>\n\n<pre><code>git archive --format=tar \\\n--remote=ssh://remote_server/remote_repository master path1/ path2/ | tar -xv\n</code></pre>\n" }, { "answer_id": 851113, "author": "kostmo", "author_id": 105137, "author_profile": "https://Stackoverflow.com/users/105137", "pm_score": 5, "selected": false, "text": "<p>It appears that this is less of an issue with Git than SVN. Git only puts a .git folder in the repository root, whereas SVN puts a .svn folder in every subdirectory. So \"svn export\" avoids recursive command-line magic, whereas with Git recursion is not necessary.</p>\n" }, { "answer_id": 1142416, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 2, "selected": false, "text": "<p>I needed this for a deploy script and I couldn't use any of the above mentioned approaches. Instead I figured out a different solution:</p>\n\n<pre><code>#!/bin/sh\n[ $# -eq 2 ] || echo \"USAGE $0 REPOSITORY DESTINATION\" &amp;&amp; exit 1\nREPOSITORY=$1\nDESTINATION=$2\nTMPNAME=\"/tmp/$(basename $REPOSITORY).$$\"\ngit clone $REPOSITORY $TMPNAME\nrm -rf $TMPNAME/.git\nmkdir -p $DESTINATION\ncp -r $TMPNAME/* $DESTINATION\nrm -rf $TMPNAME\n</code></pre>\n" }, { "answer_id": 2478811, "author": "RkG", "author_id": 297518, "author_profile": "https://Stackoverflow.com/users/297518", "pm_score": 2, "selected": false, "text": "<p>Doing it the easy way, this is a function for .bash_profile, it directly unzips the archive on current location, configure first your usual [url:path]. NOTE: With this function you avoid the clone operation, it gets directly from the remote repo.</p>\n\n<pre><code>gitss() {\n URL=[url:path]\n\n TMPFILE=\"`/bin/tempfile`\"\n if [ \"$1\" = \"\" ]; then\n echo -e \"Use: gitss repo [tree/commit]\\n\"\n return\n fi\n if [ \"$2\" = \"\" ]; then\n TREEISH=\"HEAD\"\n else\n TREEISH=\"$2\"\n fi\n echo \"Getting $1/$TREEISH...\"\n git archive --format=zip --remote=$URL/$1 $TREEISH &gt; $TMPFILE &amp;&amp; unzip $TMPFILE &amp;&amp; echo -e \"\\nDone\\n\"\n rm $TMPFILE\n}\n</code></pre>\n\n<p>Alias for .gitconfig, same configuration required (TAKE CARE executing the command inside .git projects, it ALWAYS jumps to the base dir previously <a href=\"http://www.kerneltrap.com/mailarchive/git/2008/12/3/4301934/thread\" rel=\"noreferrer\">as said here</a>, until this is fixed I personally prefer the function</p>\n\n<pre><code>ss = !env GIT_TMPFILE=\"`/bin/tempfile`\" sh -c 'git archive --format=zip --remote=[url:path]/$1 $2 \\ &gt; $GIT_TMPFILE &amp;&amp; unzip $GIT_TMPFILE &amp;&amp; rm $GIT_TMPFILE' -\n</code></pre>\n" }, { "answer_id": 4052484, "author": "dkinzer", "author_id": 256854, "author_profile": "https://Stackoverflow.com/users/256854", "pm_score": 3, "selected": false, "text": "<p>I just want to point out that in the case that you are</p>\n\n<ol>\n<li>exporting a sub folder of the repository (that's how I used to use SVN export feature)</li>\n<li>are OK with copying everything from that folder to the deployment destination</li>\n<li>and since you already have a copy of the entire repository in place.</li>\n</ol>\n\n<p>Then you can just use <code>cp foo [destination]</code> instead of the mentioned <code>git-archive master foo | -x -C [destination]</code>.</p>\n" }, { "answer_id": 4411489, "author": "Harmon", "author_id": 142249, "author_profile": "https://Stackoverflow.com/users/142249", "pm_score": 4, "selected": false, "text": "<p>This will copy all contents, minus the .dot files. I use this to export git cloned projects into my web app's git repo without the .git stuff.</p>\n\n<blockquote>\n <p>cp -R ./path-to-git-repo /path/to/destination/</p>\n</blockquote>\n\n<p>Plain old bash works just great :)</p>\n" }, { "answer_id": 7397656, "author": "slatvick", "author_id": 72766, "author_profile": "https://Stackoverflow.com/users/72766", "pm_score": 5, "selected": false, "text": "<p>I use git-submodules extensively.\nThis one works for me:</p>\n\n<pre><code>rsync -a ./FROM/ ./TO --exclude='.*'\n</code></pre>\n" }, { "answer_id": 7971071, "author": "tocororo", "author_id": 998663, "author_profile": "https://Stackoverflow.com/users/998663", "pm_score": 3, "selected": false, "text": "<p>Bash-implementation of git-export.</p>\n\n<p>I have segmented the .empty file creation and removal processes on their own function, with the purpose of re-using them in the 'git-archive' implementation (will be posted later on).</p>\n\n<p>I have also added the '.gitattributes' file to the process in order to remove un-wanted files from the target export folder.\nIncluded verbosity to the process while making the 'git-export' function more efficient.</p>\n\n<p>EMPTY_FILE=\".empty\";</p>\n\n<pre><code>function create_empty () {\n## Processing path (target-dir):\n TRG_PATH=\"${1}\";\n## Component(s):\n EXCLUDE_DIR=\".git\";\necho -en \"\\nAdding '${EMPTY_FILE}' files to empty folder(s): ...\";\n find ${TRG_PATH} -not -path \"*/${EXCLUDE_DIR}/*\" -type d -empty -exec touch {}/${EMPTY_FILE} \\;\n#echo \"done.\";\n## Purging SRC/TRG_DIRs variable(s):\n unset TRG_PATH EMPTY_FILE EXCLUDE_DIR;\n return 0;\n }\n\ndeclare -a GIT_EXCLUDE;\nfunction load_exclude () {\n SRC_PATH=\"${1}\";\n ITEMS=0; while read LINE; do\n# echo -e \"Line [${ITEMS}]: '${LINE%%\\ *}'\";\n GIT_EXCLUDE[((ITEMS++))]=${LINE%%\\ *};\n done &lt; ${SRC_PATH}/.gitattributes;\n GIT_EXCLUDE[${ITEMS}]=\"${EMPTY_FILE}\";\n## Purging variable(s):\n unset SRC_PATH ITEMS;\n return 0;\n }\n\nfunction purge_empty () {\n## Processing path (Source/Target-dir):\n SRC_PATH=\"${1}\";\n TRG_PATH=\"${2}\";\necho -e \"\\nPurging Git-Specific component(s): ... \";\n find ${SRC_PATH} -type f -name ${EMPTY_FILE} -exec /bin/rm '{}' \\;\n for xRULE in ${GIT_EXCLUDE[@]}; do\necho -en \" '${TRG_PATH}/{${xRULE}}' files ... \";\n find ${TRG_PATH} -type f -name \"${xRULE}\" -exec /bin/rm -rf '{}' \\;\necho \"done.'\";\n done;\necho -e \"done.\\n\"\n## Purging SRC/TRG_PATHs variable(s):\n unset SRC_PATH; unset TRG_PATH;\n return 0;\n }\n\nfunction git-export () {\n TRG_DIR=\"${1}\"; SRC_DIR=\"${2}\";\n if [ -z \"${SRC_DIR}\" ]; then SRC_DIR=\"${PWD}\"; fi\n load_exclude \"${SRC_DIR}\";\n## Dynamically added '.empty' files to the Git-Structure:\n create_empty \"${SRC_DIR}\";\n GIT_COMMIT=\"Including '${EMPTY_FILE}' files into Git-Index container.\"; #echo -e \"\\n${GIT_COMMIT}\";\n git add .; git commit --quiet --all --verbose --message \"${GIT_COMMIT}\";\n if [ \"${?}\" -eq 0 ]; then echo \" done.\"; fi\n /bin/rm -rf ${TRG_DIR} &amp;&amp; mkdir -p \"${TRG_DIR}\";\necho -en \"\\nChecking-Out Index component(s): ... \";\n git checkout-index --prefix=${TRG_DIR}/ -q -f -a\n## Reset: --mixed = reset HEAD and index:\n if [ \"${?}\" -eq 0 ]; then\necho \"done.\"; echo -en \"Resetting HEAD and Index: ... \";\n git reset --soft HEAD^;\n if [ \"${?}\" -eq 0 ]; then\necho \"done.\";\n## Purging Git-specific components and '.empty' files from Target-Dir:\n purge_empty \"${SRC_DIR}\" \"${TRG_DIR}\"\n else echo \"failed.\";\n fi\n## Archiving exported-content:\necho -en \"Archiving Checked-Out component(s): ... \";\n if [ -f \"${TRG_DIR}.tgz\" ]; then /bin/rm ${TRG_DIR}.tgz; fi\n cd ${TRG_DIR} &amp;&amp; tar -czf ${TRG_DIR}.tgz ./; cd ${SRC_DIR}\necho \"done.\";\n## Listing *.tgz file attributes:\n## Warning: Un-TAR this file to a specific directory:\n ls -al ${TRG_DIR}.tgz\n else echo \"failed.\";\n fi\n## Purgin all references to Un-Staged File(s):\n git reset HEAD;\n## Purging SRC/TRG_DIRs variable(s):\n unset SRC_DIR; unset TRG_DIR;\n echo \"\";\n return 0;\n }\n</code></pre>\n\n<blockquote>\n <p>Output:</p>\n \n <p>$ git-export /tmp/rel-1.0.0</p>\n \n <p>Adding '.empty' files to empty folder(s): ... done.</p>\n \n <p>Checking-Out Index component(s): ... done.</p>\n \n <p>Resetting HEAD and Index: ... done.</p>\n \n <p>Purging Git-Specific component(s): ...</p>\n \n <p>'/tmp/rel-1.0.0/{.buildpath}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.project}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.gitignore}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.git}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.gitattributes}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{*.mno}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{*~}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.*~}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{*.swp}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{*.swo}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.DS_Store}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.settings}' files ... done.'</p>\n \n <p>'/tmp/rel-1.0.0/{.empty}' files ... done.'</p>\n \n <p>done.</p>\n \n <p>Archiving Checked-Out component(s): ... done.</p>\n \n <p>-rw-r--r-- 1 admin wheel 25445901 3 Nov 12:57 /tmp/rel-1.0.0.tgz</p>\n \n <p>I have now incorporated the 'git archive' functionality into a single process that makes use of 'create_empty' function and other features.</p>\n</blockquote>\n\n<pre><code>function git-archive () {\n PREFIX=\"${1}\"; ## sudo mkdir -p ${PREFIX}\n REPO_PATH=\"`echo \"${2}\"|awk -F: '{print $1}'`\";\n RELEASE=\"`echo \"${2}\"|awk -F: '{print $2}'`\";\n USER_PATH=\"${PWD}\";\necho \"$PREFIX $REPO_PATH $RELEASE $USER_PATH\";\n## Dynamically added '.empty' files to the Git-Structure:\n cd \"${REPO_PATH}\"; populate_empty .; echo -en \"\\n\";\n# git archive --prefix=git-1.4.0/ -o git-1.4.0.tar.gz v1.4.0\n# e.g.: git-archive /var/www/htdocs /repos/domain.name/website:rel-1.0.0 --explode\n OUTPUT_FILE=\"${USER_PATH}/${RELEASE}.tar.gz\";\n git archive --verbose --prefix=${PREFIX}/ -o ${OUTPUT_FILE} ${RELEASE}\n cd \"${USER_PATH}\";\n if [[ \"${3}\" =~ [--explode] ]]; then\n if [ -d \"./${RELEASE}\" ]; then /bin/rm -rf \"./${RELEASE}\"; fi\n mkdir -p ./${RELEASE}; tar -xzf \"${OUTPUT_FILE}\" -C ./${RELEASE}\n fi\n## Purging SRC/TRG_DIRs variable(s):\n unset PREFIX REPO_PATH RELEASE USER_PATH OUTPUT_FILE;\n return 0;\n }\n</code></pre>\n" }, { "answer_id": 8963061, "author": "Lars Schillingmann", "author_id": 1163648, "author_profile": "https://Stackoverflow.com/users/1163648", "pm_score": 5, "selected": false, "text": "<p>I have hit this page frequently when looking for a way to export a git repository. My answer to this question considers three properties that svn export has by design compared to git, since svn follows a centralized repository approach:</p>\n<ul>\n<li><p>It minimizes the traffic to a remote repository location by not exporting all revisions</p>\n</li>\n<li><p>It does not include meta information in the export directory</p>\n</li>\n<li><p>Exporting a certain branch using svn is accomplished by specifying the appropriate path</p>\n<pre><code> git clone --depth 1 --branch main git://git.somewhere destination_path\n rm -rf destination_path/.git\n</code></pre>\n</li>\n</ul>\n<p>When building a certain release it is useful to clone a stable branch as for example <code>--branch stable</code> or <code>--branch release/0.9</code>.</p>\n" }, { "answer_id": 9416271, "author": "aredridel", "author_id": 306320, "author_profile": "https://Stackoverflow.com/users/306320", "pm_score": 5, "selected": false, "text": "<p>The equivalent of </p>\n\n<pre><code>svn export . otherpath\n</code></pre>\n\n<p>inside an existing repo is</p>\n\n<pre><code>git archive branchname | (cd otherpath; tar x)\n</code></pre>\n\n<p>The equivalent of</p>\n\n<pre><code>svn export url otherpath\n</code></pre>\n\n<p>is</p>\n\n<pre><code>git archive --remote=url branchname | (cd otherpath; tar x)\n</code></pre>\n" }, { "answer_id": 9475192, "author": "Rob Jensen", "author_id": 1236875, "author_profile": "https://Stackoverflow.com/users/1236875", "pm_score": 3, "selected": false, "text": "<p>If you want something that works with submodules this might be worth a go.</p>\n\n<p>Note:</p>\n\n<ul>\n<li>MASTER_DIR = a checkout with your submodules checked out also</li>\n<li>DEST_DIR = where this export will end up</li>\n<li>If you have rsync, I think you'd be able to do the same thing with even less ball ache. </li>\n</ul>\n\n<p>Assumptions:</p>\n\n<ul>\n<li>You need to run this from the parent directory of MASTER_DIR ( i.e from MASTER_DIR cd .. ) </li>\n<li>DEST_DIR is assumed to have been created. This is pretty easy to modify to include the creation of a DEST_DIR if you wanted to</li>\n</ul>\n\n<blockquote>\n <p>cd MASTER_DIR &amp;&amp; tar -zcvf ../DEST_DIR/export.tar.gz --exclude='.git*'\n . &amp;&amp; cd ../DEST_DIR/ &amp;&amp; tar xvfz export.tar.gz &amp;&amp; rm export.tar.gz</p>\n</blockquote>\n" }, { "answer_id": 12094709, "author": "Brandon", "author_id": 334725, "author_profile": "https://Stackoverflow.com/users/334725", "pm_score": 2, "selected": false, "text": "<p>If you need submodules as well, this should do the trick: <a href=\"https://github.com/meitar/git-archive-all.sh/wiki\" rel=\"nofollow\">https://github.com/meitar/git-archive-all.sh/wiki</a></p>\n" }, { "answer_id": 12801609, "author": "orkoden", "author_id": 1329214, "author_profile": "https://Stackoverflow.com/users/1329214", "pm_score": 3, "selected": false, "text": "<p>You can archive a remote repo at any commit as zip file.</p>\n\n<pre><code>git archive --format=zip --output=archive.zip --remote=USERNAME@HOSTNAME:PROJECTNAME.git HASHOFGITCOMMIT\n</code></pre>\n" }, { "answer_id": 19058735, "author": "teleme.io", "author_id": 305945, "author_profile": "https://Stackoverflow.com/users/305945", "pm_score": 4, "selected": false, "text": "<p>As simple as clone then delete the .git folder:</p>\n\n<p><code>\ngit clone url_of_your_repo path_to_export &amp;&amp; rm -rf path_to_export/.git\n</code></p>\n" }, { "answer_id": 19689284, "author": "Anthony Hatzopoulos", "author_id": 881551, "author_profile": "https://Stackoverflow.com/users/881551", "pm_score": 6, "selected": false, "text": "<p><img src=\"https://i.stack.imgur.com/p73W2.png\" alt=\"enter image description here\"></p>\n\n<h3>A special case answer if the repository is hosted on GitHub.</h3>\n\n<p>Just use <code>svn export</code>.</p>\n\n<p>As far as I know Github does not allow <code>archive --remote</code>. Although GitHub is <a href=\"https://github.com/blog/626-announcing-svn-support\" rel=\"noreferrer\">svn compatible</a> and they do have all git repos <code>svn</code> accessible so you could just use <code>svn export</code> like you normally would with a few adjustments to your GitHub url.</p>\n\n<p>For example to export an entire repository, notice how <code>trunk</code> in the URL replaces <code>master</code> (or whatever the <a href=\"https://help.github.com/articles/setting-the-default-branch/\" rel=\"noreferrer\">project's HEAD branch is set to</a>):</p>\n\n<pre><code>svn export https://github.com/username/repo-name/trunk/\n</code></pre>\n\n<p>And you can export a single file or even a certain path or folder:</p>\n\n<pre><code>svn export https://github.com/username/repo-name/trunk/src/lib/folder\n</code></pre>\n\n<h3>Example with <a href=\"https://github.com/jquery/jquery\" rel=\"noreferrer\">jQuery JavaScript Library</a></h3>\n\n<p>The <code>HEAD</code> branch or <strong>master</strong> branch will be available using <code>trunk</code>:</p>\n\n<pre><code>svn ls https://github.com/jquery/jquery/trunk\n</code></pre>\n\n<p>The non-<code>HEAD</code> <strong>branches</strong> will be accessible under <code>/branches/</code>:</p>\n\n<pre><code>svn ls https://github.com/jquery/jquery/branches/2.1-stable\n</code></pre>\n\n<p>All <strong>tags</strong> under <code>/tags/</code> in the same fashion:</p>\n\n<pre><code>svn ls https://github.com/jquery/jquery/tags/2.1.3\n</code></pre>\n" }, { "answer_id": 22702614, "author": "user5286776117878", "author_id": 2069644, "author_profile": "https://Stackoverflow.com/users/2069644", "pm_score": 5, "selected": false, "text": "<p>If you're not excluding files with <code>.gitattributes</code> <code>export-ignore</code> then try <code>git checkout</code></p>\n\n<pre><code>mkdir /path/to/checkout/\ngit --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout -f -q\n</code></pre>\n\n<blockquote>\n <p>-f<br>\n When checking out paths from the index, do not fail upon unmerged\n entries; instead, unmerged entries are ignored.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>-q<br>\n Avoid verbose</p>\n</blockquote>\n\n<p>Additionally you can get any Branch or Tag or from a specific Commit Revision like in SVN just adding the SHA1 (SHA1 in Git is the equivalent to the Revision Number in SVN)</p>\n\n<pre><code>mkdir /path/to/checkout/\ngit --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout 2ef2e1f2de5f3d4f5e87df7d8 -f -q -- ./\n</code></pre>\n\n<p>The <code>/path/to/checkout/</code> must be empty, Git will not delete any file, but will overwrite files with the same name without any warning</p>\n\n<p>UPDATE:\nTo avoid the beheaded problem or to leave intact the working repository when using checkout for export with tags, branches or SHA1, you need to add <code>-- ./</code> at the end</p>\n\n<p>The double dash <code>--</code> tells git that everything after the dashes are paths or files, and also in this case tells <code>git checkout</code> to not change the <code>HEAD</code></p>\n\n<p>Examples:</p>\n\n<p>This command will get just the libs directory and also the <code>readme.txt</code> file from that exactly commit</p>\n\n<pre><code>git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout fef2e1f2de5f3d4f5e87df7d8 -f -q -- ./libs ./docs/readme.txt\n</code></pre>\n\n<p>This will create(overwrite) <code>my_file_2_behind_HEAD.txt</code> two commits behind the head <code>HEAD^2</code></p>\n\n<pre><code>git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout HEAD^2 -f -q -- ./my_file_2_behind_HEAD.txt\n</code></pre>\n\n<p>To get the export of another branch</p>\n\n<pre><code>git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout myotherbranch -f -q -- ./\n</code></pre>\n\n<p>Notice that <code>./</code> is relative to the root of the repository</p>\n" }, { "answer_id": 23299744, "author": "Fuyu Persimmon", "author_id": 2382896, "author_profile": "https://Stackoverflow.com/users/2382896", "pm_score": 3, "selected": false, "text": "<p>This will copy the files in a range of commits (C to G) to a tar file. Note: this will only get the files commited. Not the entire repository. Slightly modified from <a href=\"https://stackoverflow.com/questions/4541300/export-only-modified-and-added-files-with-folder-structure-in-git\">Here</a></p>\n\n<p>Example Commit History</p>\n\n<p>A --> B --> <strong>C --> D --> E --> F --> G</strong> --> H --> I</p>\n\n<pre><code>git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT C~..G | xargs tar -rf myTarFile.tar\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/4541300/export-only-modified-and-added-files-with-folder-structure-in-git\">git-diff-tree Manual Page</a></p>\n\n<p>-r --> recurse into sub-trees</p>\n\n<p>--no-commit-id --> git diff-tree outputs a line with the commit ID when applicable. This flag suppressed the commit ID output.</p>\n\n<p>--name-only --> Show only names of changed files.</p>\n\n<p>--diff-filter=ACMRT --> Select only these files. <a href=\"http://git-scm.com/docs/git-diff-tree\" rel=\"nofollow noreferrer\">See here for full list of files</a></p>\n\n<p>C..G --> Files in this range of commits</p>\n\n<p>C~ --> Include files from Commit C. Not just files since Commit C.</p>\n\n<p>| xargs tar -rf myTarFile --> outputs to tar</p>\n" }, { "answer_id": 23800579, "author": "MichaelMoser", "author_id": 3034482, "author_profile": "https://Stackoverflow.com/users/3034482", "pm_score": 1, "selected": false, "text": "<p>i have the following utility function in my .bashrc file: it creates an archive of the current branch in a git repository.</p>\n\n<pre><code>function garchive()\n{\n if [[ \"x$1\" == \"x-h\" || \"x$1\" == \"x\" ]]; then\n cat &lt;&lt;EOF\nUsage: garchive &lt;archive-name&gt;\ncreate zip archive of the current branch into &lt;archive-name&gt;\nEOF\n else\n local oname=$1\n set -x\n local bname=$(git branch | grep -F \"*\" | sed -e 's#^*##')\n git archive --format zip --output ${oname} ${bname}\n set +x\n fi\n}\n</code></pre>\n" }, { "answer_id": 24760614, "author": "sdaau", "author_id": 277826, "author_profile": "https://Stackoverflow.com/users/277826", "pm_score": 2, "selected": false, "text": "<p>I think <a href=\"https://stackoverflow.com/a/9416271/277826\">@Aredridel</a>'s post was closest, but there's a bit more to that - so I will add this here; the thing is, in <code>svn</code>, if you're in a subfolder of a repo, and you do:</p>\n\n<pre><code>/media/disk/repo_svn/subdir$ svn export . /media/disk2/repo_svn_B/subdir\n</code></pre>\n\n<p>then <code>svn</code> will export all files that are under revision control (they could have also freshly Added; or Modified status) - and if you have other \"junk\" in that directory (and I'm not counting <code>.svn</code> subfolders here, but visible stuff like <code>.o</code> files), it will <em>not</em> be exported; only those files registered by the SVN repo will be exported. For me, one nice thing is that this export also includes files with local changes that have <em>not</em> been committed yet; and another nice thing is that the timestamps of the exported files are the same as the original ones. Or, as <code>svn help export</code> puts it:</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Exports a clean directory tree from the working copy specified by\n PATH1, at revision REV if it is given, otherwise at WORKING, into\n PATH2. ... If REV is not specified, all local\n changes will be preserved. Files not under version control will\n not be copied.</li>\n </ol>\n</blockquote>\n\n<p>To realize that <code>git</code> will not preserve the timestamps, compare the output of these commands (in a subfolder of a <code>git</code> repo of your choice):</p>\n\n<pre><code>/media/disk/git_svn/subdir$ ls -la .\n</code></pre>\n\n<p>... and:</p>\n\n<pre><code>/media/disk/git_svn/subdir$ git archive --format=tar --prefix=junk/ HEAD | (tar -t -v --full-time -f -)\n</code></pre>\n\n<p>... and I, in any case, notice that <code>git archive</code> causes all the timestamps of the archived file to be the same! <code>git help archive</code> says:</p>\n\n<blockquote>\n <p>git archive behaves differently when given a tree ID versus when given a commit ID or tag ID. In the first case the\n current time is used as the modification time of each file in the archive. In the latter case the commit time as recorded\n in the referenced commit object is used instead. </p>\n</blockquote>\n\n<p>... but apparently both cases set the \"modification time of <em>each</em> file\"; thereby <em>not</em> preserving the actual timestamps of those files!</p>\n\n<p>So, in order to also preserve the timestamps, here is a <code>bash</code> script, which is actually a \"one-liner\", albeit somewhat complicated - so below it is posted in multiple lines:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>/media/disk/git_svn/subdir$ git archive --format=tar master | (tar tf -) | (\\\n DEST=\"/media/diskC/tmp/subdirB\"; \\\n CWD=\"$PWD\"; \\\n while read line; do \\\n DN=$(dirname \"$line\"); BN=$(basename \"$line\"); \\\n SRD=\"$CWD\"; TGD=\"$DEST\"; \\\n if [ \"$DN\" != \".\" ]; then \\\n SRD=\"$SRD/$DN\" ; TGD=\"$TGD/$DN\" ; \\\n if [ ! -d \"$TGD\" ] ; then \\\n CMD=\"mkdir \\\"$TGD\\\"; touch -r \\\"$SRD\\\" \\\"$TGD\\\"\"; \\\n echo \"$CMD\"; \\\n eval \"$CMD\"; \\\n fi; \\\n fi; \\\n CMD=\"cp -a \\\"$SRD/$BN\\\" \\\"$TGD/\\\"\"; \\\n echo \"$CMD\"; \\\n eval \"$CMD\"; \\\n done \\\n)\n</code></pre>\n\n<p>Note that it is assumed that you're exporting the contents in \"current\" directory (above, <code>/media/disk/git_svn/subdir</code>) - and the destination you're exporting into is somewhat inconveniently placed, but it is in <code>DEST</code> environment variable. Note that with this script; you must create the <code>DEST</code> directory manually yourself, before running the above script. </p>\n\n<p>After the script is ran, you should be able to compare:</p>\n\n<pre><code>ls -la /media/disk/git_svn/subdir\nls -la /media/diskC/tmp/subdirB # DEST\n</code></pre>\n\n<p>... and hopefully see the same timestamps (for those files that were under version control). </p>\n\n<p>Hope this helps someone,<br>\nCheers!</p>\n" }, { "answer_id": 25060822, "author": "bishop", "author_id": 2908724, "author_profile": "https://Stackoverflow.com/users/2908724", "pm_score": 4, "selected": false, "text": "<p>For GitHub users, the <code>git archive --remote</code> method won't work directly, as <a href=\"https://developer.github.com/v3/repos/contents/#get-archive-link\" rel=\"noreferrer\">the export URL is ephemeral</a>. You must ask GitHub for the URL, then download that URL. <code>curl</code> makes that easy:</p>\n\n<pre><code>curl -L https://api.github.com/repos/VENDOR/PROJECT/tarball | tar xzf -\n</code></pre>\n\n<p>This will give you the exported code in a local directory. Example:</p>\n\n<pre><code>$ curl -L https://api.github.com/repos/jpic/bashworks/tarball | tar xzf -\n$ ls jpic-bashworks-34f4441/\nbreak conf docs hack LICENSE mlog module mpd mtests os README.rst remote todo vcs vps wepcrack\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong><br>\nIf you want the code put into a specific, <em>existing</em> directory (rather than the random one from github):</p>\n\n<pre><code>curl -L https://api.github.com/repos/VENDOR/PROJECT/tarball | \\\ntar xzC /path/you/want --strip 1\n</code></pre>\n" }, { "answer_id": 27788401, "author": "zeeawan", "author_id": 4221299, "author_profile": "https://Stackoverflow.com/users/4221299", "pm_score": 4, "selected": false, "text": "<p>Yes, <a href=\"https://stackoverflow.com/a/163769/4221299\">this</a> is a clean and neat command to archive your code without any git inclusion in the archive and is good to pass around without worrying about any git commit history.</p>\n\n<pre><code>git archive --format zip --output /full/path/to/zipfile.zip master \n</code></pre>\n" }, { "answer_id": 29462605, "author": "B T", "author_id": 122422, "author_profile": "https://Stackoverflow.com/users/122422", "pm_score": 3, "selected": false, "text": "<p>By far the easiest way i've seen to do it (and works on windows as well) is <code>git bundle</code>:</p>\n\n<p><code>git bundle create /some/bundle/path.bundle --all</code></p>\n\n<p>See this answer for more details: <a href=\"https://stackoverflow.com/questions/28522089/how-can-i-copy-my-git-repository-from-my-windows-machine-to-a-linux-machine-via/28522093#28522093\">How can I copy my git repository from my windows machine to a linux machine via usb drive?</a></p>\n" }, { "answer_id": 30810513, "author": "alexis", "author_id": 1342186, "author_profile": "https://Stackoverflow.com/users/1342186", "pm_score": 1, "selected": false, "text": "<p>The option 1 sounds not too efficient. What if there is no space in the client to do a clone and <em>then</em> remove the <code>.git</code> folder?</p>\n\n<p>Today I found myself trying to do this, where the client is a Raspberry Pi with almost no space left. Furthermore, I also want to exclude some heavy folder from the repository.</p>\n\n<p>Option 2 and others answers here do not help in this scenario. Neither <code>git archive</code> (because require to commit a <code>.gitattributes</code> file, and I don't want to save this exclusion in the repository).</p>\n\n<p>Here I share my solution, similar to option 3, but without the need of <code>git clone</code>:</p>\n\n<pre><code>tmp=`mktemp`\ngit ls-tree --name-only -r HEAD &gt; $tmp\nrsync -avz --files-from=$tmp --exclude='fonts/*' . raspberry:\n</code></pre>\n\n<p>Changing the <code>rsync</code> line for an equivalent line for compress will also work as a <code>git archive</code> but with a sort of exclusion option (as is asked <a href=\"https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=466912\" rel=\"nofollow\">here</a>).</p>\n" }, { "answer_id": 48945749, "author": "Tom", "author_id": 7179161, "author_profile": "https://Stackoverflow.com/users/7179161", "pm_score": 2, "selected": false, "text": "<p>I have another solution that works fine if you have a local copy of the repository on the machine where you would like to create the export. In this case move to this repository directory, and enter this command:</p>\n\n<p><code>GIT_WORK_TREE=outputdirectory git checkout -f</code></p>\n\n<p>This is particularly useful if you manage a website with a git repository and would like to checkout a clean version in <code>/var/www/</code>. In this case, add thiscommand in a <code>.git/hooks/post-receive</code> script (<code>hooks/post-receive</code> on a bare repository, which is more suitable in this situation)</p>\n" }, { "answer_id": 49238201, "author": "Ondra Žižka", "author_id": 145989, "author_profile": "https://Stackoverflow.com/users/145989", "pm_score": 3, "selected": false, "text": "<p>As I understand the question, it it more about downloading just certain state from the server, without history, and without data of other branches, rather than extracting a state from a local repository (as many anwsers here do).</p>\n\n<p>That can be done like this:</p>\n\n<pre><code>git clone -b someBranch --depth 1 --single-branch git://somewhere.com/repo.git \\\n&amp;&amp; rm -rf repo/.git/\n</code></pre>\n\n<ul>\n<li><code>--single-branch</code> is available since Git 1.7.10 (April 2012).</li>\n<li><code>--depth</code> is (was?) <a href=\"https://stackoverflow.com/questions/23708231/git-shallow-clone-clone-depth-misses-remote-branches\">reportedly</a> faulty, but for the case of an export, the mentioned issues should not matter.</li>\n</ul>\n" }, { "answer_id": 53150435, "author": "DomTomCat", "author_id": 1150303, "author_profile": "https://Stackoverflow.com/users/1150303", "pm_score": 3, "selected": false, "text": "<p>a git export to a zip archive while adding a prefix (e.g. directory name):</p>\n\n<pre><code>git archive master --prefix=directoryWithinZip/ --format=zip -o out.zip\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
I've been wondering whether there is a good "git export" solution that creates a copy of a tree without the `.git` repository directory. There are at least three methods I know of: 1. `git clone` followed by removing the `.git` repository directory. 2. [`git checkout-index`](http://www.kernel.org/pub/software/scm/git/docs/git-checkout-index.html) alludes to this functionality but starts with "Just read the desired tree into the index..." which I'm not entirely sure how to do. 3. [`git-export`](http://code.google.com/p/git-export/) is a third-party script that essentially does a `git clone` into a temporary location followed by `rsync --exclude='.git'` into the final destination. None of these solutions really strike me as being satisfactory. The closest one to `svn export` might be option 1, because both require the target directory to be empty first. But option 2 seems even better, assuming I can figure out what it means to read a tree into the index.
Probably the simplest way to achieve this is with [`git archive`](https://git-scm.com/docs/git-archive). If you really need just the expanded tree you can do something like this. ``` git archive master | tar -x -C /somewhere/else ``` Most of the time that I need to 'export' something from git, I want a compressed archive in any case so I do something like this. ``` git archive master | bzip2 >source-tree.tar.bz2 ``` ZIP archive: ``` git archive --format zip --output /full/path/to/zipfile.zip master ``` [`git help archive`](https://git-scm.com/docs/git-archive) for more details, it's quite flexible. --- Be aware that even though the archive will not contain the .git directory, it will, however, contain other hidden git-specific files like .gitignore, .gitattributes, etc. If you don't want them in the archive, make sure you use the export-ignore attribute in a .gitattributes file and commit this before doing your archive. [Read more...](http://feeding.cloud.geek.nz/2010/02/excluding-files-from-git-archive.html) --- Note: If you are interested in exporting the index, the command is ``` git checkout-index -a -f --prefix=/destination/path/ ``` (See [Greg's answer](https://stackoverflow.com/a/160719/413020 "Greg's answer") for more details)
160,611
<p>I'm trying to unit test (JUnit) a DAO i've created. I'm using Spring as my framework, my DAO (JdbcPackageDAO) extends SimpleJdbcDaoSupport. The testing class (JdbcPackageDAOTest) extends AbstractTransactionalDataSourceSpringContextTests. I've overridden the configLocations as follows:</p> <pre><code>protected String[] getConfigLocations(){ return new String[] {"classpath:company/dc/test-context.xml"}; } </code></pre> <p>My test-context.xml file is defined as follows:</p> <pre><code>&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&gt; &lt;bean id="dataPackageDao" class="company.data.dao.JdbcPackageDAO"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver"/&gt; &lt;property name="url" value="jdbc:hsqldb:hsql://localhost"/&gt; &lt;property name="username" value="sa" /&gt; &lt;property name="password" value="" /&gt; &lt;/bean&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;company/data/dao/jdbc.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>I'm using HSQL as my backend, it's running in standalone mode. My IDE of choice is eclipse. When I run the class as a JUnit test here's my error (below). I have no clue as to why its happening. hsql.jar is on my build path according to Eclipse.</p> <pre> org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:219) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377) at org.springframework.test.AbstractTransactionalSpringContextTests.startNewTransaction(AbstractTransactionalSpringContextTests.java:387) at org.springframework.test.AbstractTransactionalSpringContextTests.onSetUp(AbstractTransactionalSpringContextTests.java:217) at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:101) at junit.framework.TestCase.runBare(TestCase.java:128) at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) Caused by: java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:241) at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:182) ... 18 more </pre>
[ { "answer_id": 160627, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 2, "selected": false, "text": "<p>It looks like you're not specifying a database name to connect to, should go something like </p>\n\n<pre><code>jdbc:hsqldb:hsql://serverName:port/DBname\n</code></pre>\n" }, { "answer_id": 160673, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 1, "selected": false, "text": "<p>Can you import the driver (org.hsqldb.jdbcDriver) into one of your source files? (To test that the class is actually on your class path).</p>\n\n<p>If you can't import it then you could try including <a href=\"http://sourceforge.net/project/showfiles.php?group_id=23316&amp;package_id=16653&amp;release_id=339171\" rel=\"nofollow noreferrer\">hsqldb.jar</a> in your build path.</p>\n" }, { "answer_id": 160771, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "<p>It might be that </p>\n\n<blockquote>\n <p>hsql://localhost</p>\n</blockquote>\n\n<p>can't be resolved to a file. Look at the sample program here:</p>\n\n<p><a href=\"http://hsqldb.org/doc/guide/apb.html\" rel=\"nofollow noreferrer\">Sample HSQLDB program</a></p>\n\n<p>See if you can get that working first, and then see if you can take that configuration information and use it in the Spring bean configuration.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 161220, "author": "NR.", "author_id": 11701, "author_profile": "https://Stackoverflow.com/users/11701", "pm_score": 0, "selected": false, "text": "<p>I think your HSQL URL is wrong. It should also include the database name,</p>\n\n<p>so something like </p>\n\n<pre><code>jdbc:hsqldb:hsql://localhost/mydatabase \n</code></pre>\n\n<p>if mydatabase is the name of your DB (file). Not including this can (I'm not sure if it is the case here) confuse the parsing of the URL, which may lead to the DriverManagerDS thinking that your driver is not suitable (it is found, but it thinks it is not a good one)</p>\n" }, { "answer_id": 165481, "author": "IaCoder", "author_id": 17337, "author_profile": "https://Stackoverflow.com/users/17337", "pm_score": 2, "selected": false, "text": "<p>Okay so here's the solution. Most everyone made really good points but none solved the problem (THANKS for the help). Here is the solution I found to work.</p>\n\n<ol>\n<li>Move jars from .../web-inf/lib to PROJECT_ROOT/lib</li>\n<li>Alter build path in eclipse to reflect this change.</li>\n<li>cleaned and rebuilt my project.</li>\n<li>ran the junit test and BOOM it worked!</li>\n</ol>\n\n<p>My guess is that it had something to do with how Ganymede reads jars in the /web-inf/lib folder. But who knows... It works now. </p>\n" }, { "answer_id": 391012, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Not sure if it's worth anything, but I had a similar problem where I was getting a \"java.sql.SQLException: No suitable driver found\" error. I found this thread while researching a solution.</p>\n\n<p>The way I ended up solving my problem was to forgo using java.sql.DriverManager to get a connection and instead built up an instance of org.hsqldb.jdbc.jdbcDataSource and used that.</p>\n\n<p>The root cause of my problem (I believe) had to do with the classloader hierarchy and the fact that the JRE was running Java 5. Even though I could successfully load the jdbcDriver class, the classloader behind java.sql.DriverManager was higher up, to the point that it couldn't see the hsqldb.jar I needed.</p>\n\n<p>Anyway, just putting this note here in case someone else stumbles by with a similar problem.</p>\n" }, { "answer_id": 391795, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 4, "selected": false, "text": "<p>\"no suitable driver\" usually means that the syntax for the connection URL is incorrect.</p>\n" }, { "answer_id": 391814, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 2, "selected": false, "text": "<p>If you look at your original connection string:</p>\n\n<pre><code>&lt;property name=\"url\" value=\"jdbc:hsqldb:hsql://localhost\"/&gt;\n</code></pre>\n\n<p>The Hypersonic docs suggest that you're missing an alias after localhost:</p>\n\n<p><a href=\"http://hsqldb.org/doc/guide/ch04.html\" rel=\"nofollow noreferrer\">http://hsqldb.org/doc/guide/ch04.html</a></p>\n" }, { "answer_id": 427969, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I had the same problem with spring, commons-dbcp and oracle 10g.\nUsing this URL I got the 'no suitable driver' error: <strong>jdbc:oracle:[email protected]:1521:kinangop</strong></p>\n\n<p>The above URL is missing a full colon just before the @. After correcting that, the error disappeared.</p>\n" }, { "answer_id": 2262136, "author": "Ivan Koblik", "author_id": 51260, "author_profile": "https://Stackoverflow.com/users/51260", "pm_score": 5, "selected": false, "text": "<p>In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this <a href=\"http://hsqldb.org/doc/guide/running-chapt.html#rgc_connecting_db\" rel=\"noreferrer\">example</a>.</p>\n\n<pre><code>Class.forName(\"org.hsqldb.jdbcDriver\");\n</code></pre>\n\n<p>It triggers static initialization of jdbcDriver class, which is:</p>\n\n<pre><code>static {\n try {\n DriverManager.registerDriver(new jdbcDriver());\n } catch (Exception e) {}\n}\n</code></pre>\n" }, { "answer_id": 4511252, "author": "gianluca", "author_id": 551435, "author_profile": "https://Stackoverflow.com/users/551435", "pm_score": 2, "selected": false, "text": "<p>great I had the similar problem. The advice for all is to check jdbc url sintax</p>\n" }, { "answer_id": 8874619, "author": "arun.bevoor", "author_id": 1151029, "author_profile": "https://Stackoverflow.com/users/1151029", "pm_score": 1, "selected": false, "text": "<p>when try to run datasource connectivity using static main method, first we need to run database connection. This we can achieve in eclipse as bellow.</p>\n\n<p>1) open any IDE(Eclipse or RAD) after opening workspace by default IDE will be opened in JAVA prospective. Try to switch from java to database prospective in order to create datasource as well as virtual database connectivity.</p>\n\n<p>2)in database prospective enter all the details like userName, Password and URL of the particular schema.</p>\n\n<p>3)then try to run main method to access database.</p>\n\n<p>This will resolve the \"serverName undefined\".</p>\n" }, { "answer_id": 11175182, "author": "Emac", "author_id": 1477671, "author_profile": "https://Stackoverflow.com/users/1477671", "pm_score": 1, "selected": false, "text": "<p>As some answered before, this line of code solved the problem</p>\n\n<pre><code>Class.forName(\"org.hsqldb.jdbcDriver\");\n</code></pre>\n\n<p>But my app is running in some tomcats but only in one installation I had to add this code.</p>\n" }, { "answer_id": 17021365, "author": "poonam", "author_id": 1521072, "author_profile": "https://Stackoverflow.com/users/1521072", "pm_score": 0, "selected": false, "text": "<p>I was facing similar problem and to my surprise the problem was in the version of Java.\njava.sql.DriverManager comes from rt.jar was unable to load my driver \"COM.ibm.db2.jdbc.app.DB2Driver\".</p>\n\n<p>I upgraded from jdk 5 and jdk 6 and it worked.</p>\n" }, { "answer_id": 31046083, "author": "CamelTM", "author_id": 1948438, "author_profile": "https://Stackoverflow.com/users/1948438", "pm_score": 0, "selected": false, "text": "<p>In some cases check permissions (ownership).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
I'm trying to unit test (JUnit) a DAO i've created. I'm using Spring as my framework, my DAO (JdbcPackageDAO) extends SimpleJdbcDaoSupport. The testing class (JdbcPackageDAOTest) extends AbstractTransactionalDataSourceSpringContextTests. I've overridden the configLocations as follows: ``` protected String[] getConfigLocations(){ return new String[] {"classpath:company/dc/test-context.xml"}; } ``` My test-context.xml file is defined as follows: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataPackageDao" class="company.data.dao.JdbcPackageDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost"/> <property name="username" value="sa" /> <property name="password" value="" /> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>company/data/dao/jdbc.properties</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ``` I'm using HSQL as my backend, it's running in standalone mode. My IDE of choice is eclipse. When I run the class as a JUnit test here's my error (below). I have no clue as to why its happening. hsql.jar is on my build path according to Eclipse. ``` org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:219) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377) at org.springframework.test.AbstractTransactionalSpringContextTests.startNewTransaction(AbstractTransactionalSpringContextTests.java:387) at org.springframework.test.AbstractTransactionalSpringContextTests.onSetUp(AbstractTransactionalSpringContextTests.java:217) at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:101) at junit.framework.TestCase.runBare(TestCase.java:128) at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:120) at junit.framework.TestSuite.runTest(TestSuite.java:230) at junit.framework.TestSuite.run(TestSuite.java:225) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) Caused by: java.sql.SQLException: No suitable driver found for jdbc:hsqldb:hsql://localhost at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:291) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:277) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:259) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:241) at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:182) ... 18 more ```
In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this [example](http://hsqldb.org/doc/guide/running-chapt.html#rgc_connecting_db). ``` Class.forName("org.hsqldb.jdbcDriver"); ``` It triggers static initialization of jdbcDriver class, which is: ``` static { try { DriverManager.registerDriver(new jdbcDriver()); } catch (Exception e) {} } ```
160,614
<p>I have a Dynamic Data website built in Visual Studio 2008 using .NET 3.5 SP1. The site works OK on my Vista machine, but I get the following error when running it on a Windows XP machine:</p> <blockquote> <p>Server Error in '/FlixManagerWeb' Application. -------------------------------------------------------------------------------- The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. </p> <p>Requested URL: /FlixManagerWeb -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053</p> </blockquote> <p>I have added the .* -> aspnet_isapi.dll mapping in the site config, made sure that it is an "application," but that did not help. Anyone have any luck running a Dynamic Data website on Windows XP? What (if anything) special is required to get it to work?</p>
[ { "answer_id": 160627, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 2, "selected": false, "text": "<p>It looks like you're not specifying a database name to connect to, should go something like </p>\n\n<pre><code>jdbc:hsqldb:hsql://serverName:port/DBname\n</code></pre>\n" }, { "answer_id": 160673, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 1, "selected": false, "text": "<p>Can you import the driver (org.hsqldb.jdbcDriver) into one of your source files? (To test that the class is actually on your class path).</p>\n\n<p>If you can't import it then you could try including <a href=\"http://sourceforge.net/project/showfiles.php?group_id=23316&amp;package_id=16653&amp;release_id=339171\" rel=\"nofollow noreferrer\">hsqldb.jar</a> in your build path.</p>\n" }, { "answer_id": 160771, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "<p>It might be that </p>\n\n<blockquote>\n <p>hsql://localhost</p>\n</blockquote>\n\n<p>can't be resolved to a file. Look at the sample program here:</p>\n\n<p><a href=\"http://hsqldb.org/doc/guide/apb.html\" rel=\"nofollow noreferrer\">Sample HSQLDB program</a></p>\n\n<p>See if you can get that working first, and then see if you can take that configuration information and use it in the Spring bean configuration.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 161220, "author": "NR.", "author_id": 11701, "author_profile": "https://Stackoverflow.com/users/11701", "pm_score": 0, "selected": false, "text": "<p>I think your HSQL URL is wrong. It should also include the database name,</p>\n\n<p>so something like </p>\n\n<pre><code>jdbc:hsqldb:hsql://localhost/mydatabase \n</code></pre>\n\n<p>if mydatabase is the name of your DB (file). Not including this can (I'm not sure if it is the case here) confuse the parsing of the URL, which may lead to the DriverManagerDS thinking that your driver is not suitable (it is found, but it thinks it is not a good one)</p>\n" }, { "answer_id": 165481, "author": "IaCoder", "author_id": 17337, "author_profile": "https://Stackoverflow.com/users/17337", "pm_score": 2, "selected": false, "text": "<p>Okay so here's the solution. Most everyone made really good points but none solved the problem (THANKS for the help). Here is the solution I found to work.</p>\n\n<ol>\n<li>Move jars from .../web-inf/lib to PROJECT_ROOT/lib</li>\n<li>Alter build path in eclipse to reflect this change.</li>\n<li>cleaned and rebuilt my project.</li>\n<li>ran the junit test and BOOM it worked!</li>\n</ol>\n\n<p>My guess is that it had something to do with how Ganymede reads jars in the /web-inf/lib folder. But who knows... It works now. </p>\n" }, { "answer_id": 391012, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Not sure if it's worth anything, but I had a similar problem where I was getting a \"java.sql.SQLException: No suitable driver found\" error. I found this thread while researching a solution.</p>\n\n<p>The way I ended up solving my problem was to forgo using java.sql.DriverManager to get a connection and instead built up an instance of org.hsqldb.jdbc.jdbcDataSource and used that.</p>\n\n<p>The root cause of my problem (I believe) had to do with the classloader hierarchy and the fact that the JRE was running Java 5. Even though I could successfully load the jdbcDriver class, the classloader behind java.sql.DriverManager was higher up, to the point that it couldn't see the hsqldb.jar I needed.</p>\n\n<p>Anyway, just putting this note here in case someone else stumbles by with a similar problem.</p>\n" }, { "answer_id": 391795, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 4, "selected": false, "text": "<p>\"no suitable driver\" usually means that the syntax for the connection URL is incorrect.</p>\n" }, { "answer_id": 391814, "author": "duffymo", "author_id": 37213, "author_profile": "https://Stackoverflow.com/users/37213", "pm_score": 2, "selected": false, "text": "<p>If you look at your original connection string:</p>\n\n<pre><code>&lt;property name=\"url\" value=\"jdbc:hsqldb:hsql://localhost\"/&gt;\n</code></pre>\n\n<p>The Hypersonic docs suggest that you're missing an alias after localhost:</p>\n\n<p><a href=\"http://hsqldb.org/doc/guide/ch04.html\" rel=\"nofollow noreferrer\">http://hsqldb.org/doc/guide/ch04.html</a></p>\n" }, { "answer_id": 427969, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I had the same problem with spring, commons-dbcp and oracle 10g.\nUsing this URL I got the 'no suitable driver' error: <strong>jdbc:oracle:[email protected]:1521:kinangop</strong></p>\n\n<p>The above URL is missing a full colon just before the @. After correcting that, the error disappeared.</p>\n" }, { "answer_id": 2262136, "author": "Ivan Koblik", "author_id": 51260, "author_profile": "https://Stackoverflow.com/users/51260", "pm_score": 5, "selected": false, "text": "<p>In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this <a href=\"http://hsqldb.org/doc/guide/running-chapt.html#rgc_connecting_db\" rel=\"noreferrer\">example</a>.</p>\n\n<pre><code>Class.forName(\"org.hsqldb.jdbcDriver\");\n</code></pre>\n\n<p>It triggers static initialization of jdbcDriver class, which is:</p>\n\n<pre><code>static {\n try {\n DriverManager.registerDriver(new jdbcDriver());\n } catch (Exception e) {}\n}\n</code></pre>\n" }, { "answer_id": 4511252, "author": "gianluca", "author_id": 551435, "author_profile": "https://Stackoverflow.com/users/551435", "pm_score": 2, "selected": false, "text": "<p>great I had the similar problem. The advice for all is to check jdbc url sintax</p>\n" }, { "answer_id": 8874619, "author": "arun.bevoor", "author_id": 1151029, "author_profile": "https://Stackoverflow.com/users/1151029", "pm_score": 1, "selected": false, "text": "<p>when try to run datasource connectivity using static main method, first we need to run database connection. This we can achieve in eclipse as bellow.</p>\n\n<p>1) open any IDE(Eclipse or RAD) after opening workspace by default IDE will be opened in JAVA prospective. Try to switch from java to database prospective in order to create datasource as well as virtual database connectivity.</p>\n\n<p>2)in database prospective enter all the details like userName, Password and URL of the particular schema.</p>\n\n<p>3)then try to run main method to access database.</p>\n\n<p>This will resolve the \"serverName undefined\".</p>\n" }, { "answer_id": 11175182, "author": "Emac", "author_id": 1477671, "author_profile": "https://Stackoverflow.com/users/1477671", "pm_score": 1, "selected": false, "text": "<p>As some answered before, this line of code solved the problem</p>\n\n<pre><code>Class.forName(\"org.hsqldb.jdbcDriver\");\n</code></pre>\n\n<p>But my app is running in some tomcats but only in one installation I had to add this code.</p>\n" }, { "answer_id": 17021365, "author": "poonam", "author_id": 1521072, "author_profile": "https://Stackoverflow.com/users/1521072", "pm_score": 0, "selected": false, "text": "<p>I was facing similar problem and to my surprise the problem was in the version of Java.\njava.sql.DriverManager comes from rt.jar was unable to load my driver \"COM.ibm.db2.jdbc.app.DB2Driver\".</p>\n\n<p>I upgraded from jdk 5 and jdk 6 and it worked.</p>\n" }, { "answer_id": 31046083, "author": "CamelTM", "author_id": 1948438, "author_profile": "https://Stackoverflow.com/users/1948438", "pm_score": 0, "selected": false, "text": "<p>In some cases check permissions (ownership).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2762/" ]
I have a Dynamic Data website built in Visual Studio 2008 using .NET 3.5 SP1. The site works OK on my Vista machine, but I get the following error when running it on a Windows XP machine: > > Server Error in '/FlixManagerWeb' > Application. > -------------------------------------------------------------------------------- The resource cannot be found. > Description: HTTP 404. The resource > you are looking for (or one of its > dependencies) could have been removed, > had its name changed, or is > temporarily unavailable. Please > review the following URL and make sure > that it is spelled correctly. > > > Requested URL: /FlixManagerWeb > -------------------------------------------------------------------------------- Version Information: Microsoft .NET > Framework Version:2.0.50727.3053; > ASP.NET Version:2.0.50727.3053 > > > I have added the .\* -> aspnet\_isapi.dll mapping in the site config, made sure that it is an "application," but that did not help. Anyone have any luck running a Dynamic Data website on Windows XP? What (if anything) special is required to get it to work?
In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this [example](http://hsqldb.org/doc/guide/running-chapt.html#rgc_connecting_db). ``` Class.forName("org.hsqldb.jdbcDriver"); ``` It triggers static initialization of jdbcDriver class, which is: ``` static { try { DriverManager.registerDriver(new jdbcDriver()); } catch (Exception e) {} } ```
160,633
<p>Why are flat text files the state of the art for representing source code?</p> <p>Sure - the preprocessor and compiler need to see a flat file representation of the file, but that's easily created.</p> <p>It seems to me that some form of XML or binary data could represent lots of ideas that are very difficult to track, otherwise.</p> <p>For instance, you could embed UML diagrams right into your code. They could be generated semi-automatically, and annotated by the developers to highlight important aspects of the design. Interaction diagrams in particular. Heck, embedding any user drawing might make things more clear.</p> <p>Another idea is to embed comments from code reviews right into the code.</p> <p>There could be all sorts of aids to make merging multiple branches easier.</p> <p>Something I'm passionate about is not just tracking code coverage, but also looking at the parts of code covered by an automated test. The hard part is keeping track of that code, even as the source is modified. For instance, moving a function from one file to another, etc. This can be done with GUIDs, but they're rather intrusive to embed right in the text file. In a rich file format, they could be automatic and unobtrusive.</p> <p>So why are there no IDEs (to my knowledge, anyway) which allow you to work with code in this way?</p> <p><strong>EDIT:</strong> On October 7th, 2009.</p> <p>Most of you got very hung up on the word "binary" in my question. I retract it. Picture XML, very minimally marking up your code. The instant before you hand it to your normal preprocessor or compiler, you strip out all of the XML markup, and pass on just the source code. In this form, you could still do all of the normal things to the file: diff, merge, edit, work with in a simple and minimal editor, feed them into thousands of tools. Yes, the diff, merge, and edit, directly with the minimal XML markup, does get a tad more complicated. But I think the value could be enormous.</p> <p>If an IDE existed which respected all of the XML, you could add so much more than what we can do today.</p> <p>For instance, your DOxygen comments could actually <em>look</em> like the final DOxygen output.</p> <p>When someone wanted to do a code review, like Code Collaborator, they could mark up the source code, in place.</p> <p>The XML could even be hidden behind comments.</p> <pre><code>// &lt;comment author="mcruikshank" date="2009-10-07"&gt; // Please refactor to Delegate. // &lt;/comment&gt; </code></pre> <p>And then if you want to use vi or emacs, you can just skip over the comments.</p> <p>If I want to use a state-of-the-art editor, I can see that in about a dozen different helpful ways.</p> <p>So, that's my rough idea. It's not "building blocks" of pictures that you drag on the screen... I'm not that nuts. :)</p>
[ { "answer_id": 160646, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 8, "selected": true, "text": "<ul>\n<li>you can diff them</li>\n<li>you can merge them</li>\n<li>anyone can edit them</li>\n<li>they are simple and easy to deal with</li>\n<li>they are universally accessible to thousands of tools</li>\n</ul>\n" }, { "answer_id": 160648, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 4, "selected": false, "text": "<p>Why are essays written in text? Why are legal documents written in text? Why are fantasy novels written in text? Because text is the single best form - for people - of persisting their thoughts.</p>\n\n<p>Text is how people think about, represent, understand, and persist <em>concepts</em> - and their complexities, hierarchies, and interrelationships.</p>\n" }, { "answer_id": 160656, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 5, "selected": false, "text": "<p>In my opinion, any possible benefits are outweighed by being tied to a particular tool.</p>\n\n<p>With plain-text source (that seems to be what you're discussing, rather than <em>flat files</em> per se) I can paste chunks into an email, use simple version control systems (very important!), write code into comments on Stack Overflow, use one of a thousand text editors on any number of platforms, etc.</p>\n\n<p>With some binary representation of code, I need to use a specialized editor to view or edit it. Even if a text-based representation can be produced, you can't trivially roll back changes into the canonical version.</p>\n" }, { "answer_id": 160659, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 4, "selected": false, "text": "<p>Smalltalk is an image-based environment. You are no longer working with code in a file on disk. You are working with and modifying the real objects in runtime. It still is text but classes are not stored in human readable files. Instead the whole object memory (the image) is stored on a file in binary format.</p>\n\n<p>But the biggest complaints of those trying out smalltalk is because it doesn't use files. Most of the file-based tools that we have (vim, emacs, eclipse, vs.net, unix tools) will have to be abandoned in favor of smalltalk's own tools. Not that the tools provided in smalltalk in inferior. It is just different.</p>\n" }, { "answer_id": 160660, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 3, "selected": false, "text": "<p>Ironically there ARE programming constructs that use precisely what you describe.</p>\n\n<p>For example, SQL Server Integration Services, which involve coding logic flow by dragging components into a visual design surface, are saved as XML files describing precisely that back end.</p>\n\n<p>On the other hand SSIS is pretty difficult to source-control. It is also fairly difficult to design any sort of complex logic into it: if you need a little bit more \"control\", you'll need to code VB.NET code into the component, which brings us <em>back</em> to where we started.</p>\n\n<p>I guess that, as a coder, you should consider the fact that for every solution to a problem there are consequences that follow. Not everything could (and some argue, should) be represented in UML. Not everything could be visually represented. Not everything could be simplified enough to have a consistent binary file representation.</p>\n\n<p>That being said, I would posit that the disadvantages of relegating code to binary formats (most of which will also tend to be proprietary) far outweight the advantages of having them in plain text.</p>\n" }, { "answer_id": 160669, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>IMHO, XML and binary formats would be a total mess and wouldn't give any significant benefit.</p>\n\n<p>OTOH, a related idea would be to write into a database, maybe one function per record, or maybe a hierarchical structure. An IDE created around this concept could make navigating source more natural, and easier to hide anything not relevant to the code you're reading at a given moment.</p>\n" }, { "answer_id": 160675, "author": "minty", "author_id": 4491, "author_profile": "https://Stackoverflow.com/users/4491", "pm_score": 0, "selected": false, "text": "<p>The code of your program define the structure that would be created with xml or the binary format. Your programming language is a more direct representation of your program's structure than an XML or Binary representation would be. Have you ever noticed how Word misbehaves on you as you give structure to your document. WordPerfect at least would 'reveal codes' to allow you to see what lay beneath your document. Flat files do the same thing for your program. </p>\n" }, { "answer_id": 160677, "author": "Pitarou", "author_id": 1260685, "author_profile": "https://Stackoverflow.com/users/1260685", "pm_score": 3, "selected": false, "text": "<p>It's a good question. FWIW, I'd love to see a Wiki-style code management tool. Each functional unit would have its own wiki page. The build tools pull together the source code out of the wiki. There would be a \"discuss\" page linked to that page, where people can argue about algorithms, APIs and such like.</p>\n\n<p>Heck, it wouldn't be that hard to hack one up from a pre-existing Wiki implementation. Any takers...?</p>\n" }, { "answer_id": 160685, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 1, "selected": false, "text": "<p>You mention that we should use \"some form of XML\"? What do you think XHTML and XAML are?</p>\n\n<p>Also XML is still just a flat file.</p>\n" }, { "answer_id": 160710, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>Neat idea's. I have myself wondered on a smaller scale ... much smaller, why can't IDE X generate this or that. </p>\n\n<p>I don't know if I am capable as a programmer yet to develop something as cool and complex as your talking about or what I am thinking about, but I would be interested in trying. </p>\n\n<p>Maybe start out with some plugins for .NET, Eclipse, Netbeans, and so on? Show off what can be done, and start a new trend in coding. </p>\n" }, { "answer_id": 160718, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 4, "selected": false, "text": "<p>Lisp programs are not flat files. They are serialization of data structures. This code-as-data is an old idea, and actually one of the greatest idea in computer science.</p>\n" }, { "answer_id": 160752, "author": "Edu Felipe", "author_id": 21648, "author_profile": "https://Stackoverflow.com/users/21648", "pm_score": 3, "selected": false, "text": "<p>Here's why:</p>\n\n<ul>\n<li><p>Human readable. That makes a lot easier to spot a mistake, in both the file and the parsing method. Also can be read out loud. That's one that you just cannot get with XML, and might make a difference, specially in customer support.</p></li>\n<li><p>Insurance against obsolescence. As long as regex exist, it is possible to write a pretty good parser in just a few lines of code.</p></li>\n<li><p>Leverage. Almost everything there is, from revision control systems to editors to filter, can inspect, merge and operate on flat files. Merging XML can be a mess.</p></li>\n<li><p>Ability to integrate them rather easily with UNIX tools, such as grep, cut or sed.</p></li>\n</ul>\n" }, { "answer_id": 160760, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>People have tried for a long time to create an editing environment that goes beyond the flat file and everyone has failed to some extent. The closest I've seen was a prototype for Charles Simonyi's Intentional Programming but then that got downgraded to a visual DSL creation tool.</p>\n\n<p>No matter how the code is stored or represented in memory, in the end it has to be presentable and modifiable as text (<strong>without the formatting changing on you</strong>) since that's the easiest way we know to express most of the abstract concepts that are needed for solving problems by programming.</p>\n\n<p>With flat files you get this for free and any plain old text editor (with the correct character encoding support) will work.</p>\n" }, { "answer_id": 160798, "author": "ramanman", "author_id": 11093, "author_profile": "https://Stackoverflow.com/users/11093", "pm_score": 0, "selected": false, "text": "<p>I think another aspect of this is that the code is what is important. It is what is going to be executed. For example, in your UML example, I would think rather than having UML (presumably created in some editor, not directly related to the \"code\") included in your \"source blob\" would be almost useless. Much better would be to have the UML generated directly from your code, so it describes the exact state the code is in as a tool for understanding the code, rather than as a reminder of what the code should have been. </p>\n\n<p>We've been doing this for years regarding automated doc tools. While the actual programmer generated comments in the code might get out of sync with the code, tools like JavaDoc and the like faithfully represent the methods on an object, return types, arguments, etc. They represent them as they actually exist,not as some artifact that came out of endless design meetings. </p>\n\n<p>It seems to me that if you could arbitrarily add random artifacts to some \"source blob\", these would likely be out of date and less than useful right away. If you can generate such artifacts directly from the code, then the small effort to get your build process to do so is vastly better than the previously mentioned pitfalls of moving away from plain text source files. </p>\n\n<p>Related to this, an <a href=\"http://www.spinellis.gr/pubs/jrnl/2003-IEEESW-umlgraph/html/article.html\" rel=\"nofollow noreferrer\">explanation of why you'd want to use a plain-text UML tool</a> (<a href=\"http://www.umlgraph.org/\" rel=\"nofollow noreferrer\">UMLGraph</a>) seems to apply nearly equally as well to why you want plain-text source files.</p>\n" }, { "answer_id": 160841, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>Old habits die hard, I guess.</p>\n\n<p>Until recently, there weren't many good-quality, high-performing, widely-available libraries for general storage of structured data. And I would emphatically <em>not</em> put XML in that category even today--too verbose, too intensive to process, too finicky.</p>\n\n<p>Nowadays, my favorite thing to use for data that doesn't need to be human-readableis <a href=\"http://sqlite.org\" rel=\"nofollow noreferrer\">SQLite</a> and make a database. It's so incredibly easy to embed a full-featured SQL database into any app... there are bindings for C, Perl, Python, PHP, etc... and it's open-source and really fast and reliable and lightweight.</p>\n\n<p>I &lt;3 SQLite.</p>\n" }, { "answer_id": 160921, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 3, "selected": false, "text": "<p>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;code&gt;Flat files are easier to read.&lt;/code&gt;&lt;/xml&gt;</p>\n" }, { "answer_id": 161004, "author": "David Grigg", "author_id": 24394, "author_profile": "https://Stackoverflow.com/users/24394", "pm_score": 2, "selected": false, "text": "<p>Steve McConnell has it right, as always - you write programs for other programmers (including yourself), not for computers.</p>\n\n<p>That said, Microsoft Visual Studio must internally manage the code you write in a very structured format, or you wouldn't be able to do such things as \"Find All References\" or rename or re-factor variables and methods so readily. I'd be interested if anyone had links to how this works.</p>\n" }, { "answer_id": 161021, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 1, "selected": false, "text": "<p>The trend we are seeing about DSL's are the first thing that comes to mind when reading your question. The problem has been that there does not exist a 1-to-1 relationship between models (like UML) and an implementation. Microsoft among others are working on getting there, so that you can create your app as something UML-like, then code can be generated. And the important thing - as you opt to change your code, the model will reflect this again.</p>\n\n<p>Windows Workflow Foundation is a pretty good example. Of cause there are flat files and/or XML in the background, but you usually end up defining your business logic in the orchestration tool. And that is pretty cool!</p>\n\n<p>We need more of the \"software factories\" thinking, and will see a richer IDE experience in the future, but as long as computers run on zeroes and ones, flat text files can and (probably) will always be an intermediate stage. As stated be several people already, simple text files are very flexible.</p>\n" }, { "answer_id": 161148, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 2, "selected": false, "text": "<p>Actually, roughly 10 years ago, Charles Simonyi's early prototype for intentional programming attempted to move beyond the flat file into a tree representation of code that can be visualized in different ways. Theoretically, a domain expert, a PM, and a software engineer could all see (and piece together) application code in ways that were useful to them, and products could be built on a hierarchy of declarative \"intentions\", digging down to low-level code only as needed.</p>\n\n<p>ETA (per request in the questions) There's a copy of <a href=\"http://research.microsoft.com/research/pubs/view.aspx?tr_id=4\" rel=\"nofollow noreferrer\">one of his early papers</a> on this at the Microsoft research web site. Unfortunately, since Simonyi left MS to start a separate company several years ago, I don't think the prototype is still available for download. I saw some demos back when I was at Microsoft, but I'm not sure how widely his early prototype was distributed.</p>\n\n<p>His company, <a href=\"http://www.intentsoft.com/\" rel=\"nofollow noreferrer\">IntentSoft</a> is still a little quiet about what they're planning to deliver to the market, if anything, but some of the early stuff that came out of MSR was pretty interesting.</p>\n\n<p>The storage model was some binary format, but I'm not sure how much of those details were disclosed during the MSR project, and I'm sure some things have changed since the early implementations.</p>\n" }, { "answer_id": 161188, "author": "Arne Evertsson", "author_id": 16686, "author_profile": "https://Stackoverflow.com/users/16686", "pm_score": 1, "selected": false, "text": "<p>It's pretty obvious why plain text is king. But it is equally obvious why a structured format would be even better.</p>\n\n<p>Just one example: If you rename a method, your diff/merge/source control tool would be able to tell that only one thing had changed. The tools we use today would show a long list of changes, one for every place and file that the method was called or declared.</p>\n\n<p>(By the way, this post doesn't answer the question as you might have noticed)</p>\n" }, { "answer_id": 161240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This might not answer exactly your question but here is an editor allows having an higher view of code:\n<a href=\"http://webpages.charter.net/edreamleo/front.html\" rel=\"nofollow noreferrer\">http://webpages.charter.net/edreamleo/front.html</a></p>\n" }, { "answer_id": 161279, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>I've wistfully wondered the same thing, as described in the answer to:\n<a href=\"https://stackoverflow.com/questions/112996/what-toolapplicationwhatever-do-you-wish-existed#113226\">What tool/application/whatever do you wish existed?</a></p>\n\n<p>While it's easy to imagine a great number of benefits I think the biggest hurdle that would have to be addressed is that no-one has produced a viable alternative.</p>\n\n<p>When people think of alternatives to storing source as text they seem to often immediately think in terms of graphical representations (I'm referring here to the commercial products that have been available - eg. HP-vee).\nAnd if we look at the experience of people like the FPGA designers, we see that programming (exclusively) graphically just doesn't work - hence languages like Verilog and VHDL.</p>\n\n<p>But I don't see that the storage of source necessarily needs to be bound to the method of writing it in the first place.\nEntry of source can be largely done as text - which means that the issues of copying/pasting can still be achieved.\nBut I also see that by allowing merges and rollbacks to be done on the basis of tokenised meta-source we could achieve more accurate and more powerful manipulation tools.</p>\n" }, { "answer_id": 161469, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 1, "selected": false, "text": "<p>For a example of a language that does away with traditional text-programming, see the <a href=\"http://en.wikipedia.org/wiki/Lava_(programming_language)\" rel=\"nofollow noreferrer\">Lava Language</a>.</p>\n\n<p>Another nifty thing I just recently discovered is <a href=\"http://subtextual.org/\" rel=\"nofollow noreferrer\">subtext2</a> (<a href=\"http://subtextual.org/subtext2.html\" rel=\"nofollow noreferrer\">video demo</a>).</p>\n" }, { "answer_id": 161630, "author": "user24456", "author_id": 24456, "author_profile": "https://Stackoverflow.com/users/24456", "pm_score": 0, "selected": false, "text": "<p>I think the reason of why text files are used in development is that they are universal against various development tools. You can look inside or even fix some errors using a simple text editor (you can't do it in a binary file because you never know how any fix would destroy other data). It doesn't mean, however, that text files are best for all those purposes.</p>\n\n<p>Of course, you can diff and merge them. But it doesn't mean that the diff/merge tool understand the distinct structure of the data encoded by this text file. You can do the diff/merge, but (especially seen in XML files) the diff tool won't show you the differences correctly, that is, it will show you where the files differ and which parts of the data the tool \"thinks\" are the same. But it will not show you the differences in the structure of XML file - it will just match lines that look the same.</p>\n\n<p>Regardless whether we're using binary files or text files, it's always better that the diff/merge tools take care of the data structure this file represents rather than the lines and characters. For C++ or Java files, for example, report that some identifier changed its name, report that some section was surrounded with additional if(){}, but, on the other hand, ignore changes in indents or EOL characters. The best approach would be that a file is read into internal structures and dumped using specific format rules. This way the diff-ing will be made through the internal structures and the merge result will be generated from the merged internal structure.</p>\n" }, { "answer_id": 161864, "author": "Michael Dorfman", "author_id": 6741, "author_profile": "https://Stackoverflow.com/users/6741", "pm_score": 2, "selected": false, "text": "<p>Why do text files rule? Because of McIlroy's test. It is vital to have the output of one program be acceptable as the source code for another, and text files are the simplest thing that works.</p>\n" }, { "answer_id": 162755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Anyone ever tryed <a href=\"http://documents.wolfram.com/v5/TheMathematicaBook/APracticalIntroductionToMathematica/UsingTheMathematicaSystem/NBMLImages/1.3.1/1.3.1_13.gif\" rel=\"nofollow noreferrer\"><strong>Mathematica</strong></a>?</p>\n\n<p>The pic above is from an old version but it was the best google could give me.</p>\n\n<p>Anyway...compare the first equation there to <strong>Math.Integrate(1/(Math.Pow(\"x\",3)-1), \"x\")</strong> like you would have to write if you were coding with plain text in most common languages. Imo the mathematical representation is much easier to read, and that is still a pretty small equation.</p>\n\n<p>And yes, you can both input and copy-paste the code as plain text if you want.</p>\n\n<p>See it as the next generation <strong>syntax highlighting</strong>. I bet there are alot of other stuff than math that could take benifit from this kind of representation.</p>\n" }, { "answer_id": 164391, "author": "SeaDrive", "author_id": 19267, "author_profile": "https://Stackoverflow.com/users/19267", "pm_score": 0, "selected": false, "text": "<p>Modern programs are composed of flat pieces, but are they flat? There are usings, and includes, and libraries of objects, etc. An ordinary function call is a peek into a different place. The logic isn't flat, due to having multiple threads, etc.</p>\n" }, { "answer_id": 165093, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.ni.com/labview/\" rel=\"nofollow noreferrer\">Labview</a> and <a href=\"http://www.mathworks.com/products/simulink/\" rel=\"nofollow noreferrer\">Simulink</a> are two graphical programming environments. They are both popular in their fields (interfacing to hardware from a PC, and modeling control systems, respectively), but not used much outside of those fields. I've worked with people who were big fans of both, but never got into them myself.</p>\n" }, { "answer_id": 165158, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 0, "selected": false, "text": "<p>I have the same vision! I really wish this would exists.</p>\n\n<p>You might want to take a look at Fortress, a research language by Sun. It has special support for formulas in source code. The quote below is from Wikipedia</p>\n\n<blockquote>\n <p>Fortress is being designed from the\n outset to have multiple syntactic\n stylesheets. Source code can be\n rendered as ASCII text, in Unicode, or\n as a prettied image. This will allow\n for support of mathematical symbols\n and other symbols in the rendered\n output for easier reading.</p>\n</blockquote>\n\n<p>The major reason for the persistence of text as source is the lack for powertools, as eg version control, for non-text date. This is based on my experience working with Smalltalk, where plain byte-code is kept in a core-dump all time. In a non-text system, with today's tools, team development is a nightmare. </p>\n" }, { "answer_id": 169156, "author": "Brian Vander Plaats", "author_id": 24892, "author_profile": "https://Stackoverflow.com/users/24892", "pm_score": 1, "selected": false, "text": "<p>Visual FoxPro uses dbf table structures to store code and metadata for forms, reports, class libs, etc. These are binary files. It also stores code in prg files that actual text files...</p>\n\n<p>The only advantage I see is being able to use the built in VFP data language to do code searches on those files... other than that it is a liability imo. At least once every few months, one of these files will become corrupted for no apparent reason. Integration with source control and diffs very painful as well. There are workarounds for this, but involve converting the file to text temporarily! </p>\n" }, { "answer_id": 179082, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "<p>Who works with flat files?</p>\n\n<p>Eclipse gives you views into your source so that I can see inner classes, methods and data, all sorted and grouped. if I want to edit the inner class I click on it. While technically there is a flat file underlying I almost never navigate it like that.</p>\n" }, { "answer_id": 450879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One thing not touched on is that some languages have the concept of a source file builtin with respect to things like variable scoping. Changing to something else (like storing functions in a database) would require you to alter the language itself.</p>\n" }, { "answer_id": 451048, "author": "Michael Buen", "author_id": 11432, "author_profile": "https://Stackoverflow.com/users/11432", "pm_score": 0, "selected": false, "text": "<p>While having a drink this night with my friends(programmers too), one of them told me that they use UML to generated code. But he said that they still need to manually edit the generated code, there are some problem domains that can't be easily described with UML.</p>\n\n<p>With all the LINQ-goodness, lambda and all, some problem domains cannot be represented by UML, we still need to make our way around the generated code for the computer to do our bidding.</p>\n\n<p>How could we represent in UML, let alone XML, the following problem? <a href=\"https://stackoverflow.com/questions/448203/linq-to-sql-using-group-by-and-countdistinct\">LINQ to SQL using GROUP BY and COUNT(DISTINCT)</a></p>\n\n<p>The amount of answers to that simple problem is very telling that UML, SQL(the most important assembly language, whatever those ORM guys tell you otherwise), XML are not an XOR proposition. We will still use the combinations of these technology, not using just one of them to the exclusion of others.</p>\n" }, { "answer_id": 1535445, "author": "Rebol Tutorial", "author_id": 2687173, "author_profile": "https://Stackoverflow.com/users/2687173", "pm_score": 0, "selected": false, "text": "<p>It's still flat files because maybe that's how they can sell softwares tools :D</p>\n\n<p>Source Code should be itself Object Oriented that is encapsulated as Member. There is only one Product I know that does so, it exists since very long (Windows 3.0) and designed by Paul Allen himself. It was originally inspired by Hypercard on Mac but as Bill Gates told it:\n<a href=\"http://community.seattletimes.nwsource.com/archive/?date=19900522&amp;slug=1073140\" rel=\"nofollow noreferrer\">http://community.seattletimes.nwsource.com/archive/?date=19900522&amp;slug=1073140</a></p>\n\n<blockquote>\n <p>``It's generations beyond HyperCard,''\n says Gates.</p>\n</blockquote>\n\n<p>Unfortunately they didn't target the right people:</p>\n\n<blockquote>\n <p><code>In pursuing (interests of) software\n developers,'' says Alsop, Asymetrix\n </code>may have made ToolBook too complex\n for the little guy.''</p>\n</blockquote>\n\n<p>They should have targeted Professional Programmers instead of Hobbysts.</p>\n\n<p>Still today on concept level it's still beyond other languages except Rebol of course ;)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8643/" ]
Why are flat text files the state of the art for representing source code? Sure - the preprocessor and compiler need to see a flat file representation of the file, but that's easily created. It seems to me that some form of XML or binary data could represent lots of ideas that are very difficult to track, otherwise. For instance, you could embed UML diagrams right into your code. They could be generated semi-automatically, and annotated by the developers to highlight important aspects of the design. Interaction diagrams in particular. Heck, embedding any user drawing might make things more clear. Another idea is to embed comments from code reviews right into the code. There could be all sorts of aids to make merging multiple branches easier. Something I'm passionate about is not just tracking code coverage, but also looking at the parts of code covered by an automated test. The hard part is keeping track of that code, even as the source is modified. For instance, moving a function from one file to another, etc. This can be done with GUIDs, but they're rather intrusive to embed right in the text file. In a rich file format, they could be automatic and unobtrusive. So why are there no IDEs (to my knowledge, anyway) which allow you to work with code in this way? **EDIT:** On October 7th, 2009. Most of you got very hung up on the word "binary" in my question. I retract it. Picture XML, very minimally marking up your code. The instant before you hand it to your normal preprocessor or compiler, you strip out all of the XML markup, and pass on just the source code. In this form, you could still do all of the normal things to the file: diff, merge, edit, work with in a simple and minimal editor, feed them into thousands of tools. Yes, the diff, merge, and edit, directly with the minimal XML markup, does get a tad more complicated. But I think the value could be enormous. If an IDE existed which respected all of the XML, you could add so much more than what we can do today. For instance, your DOxygen comments could actually *look* like the final DOxygen output. When someone wanted to do a code review, like Code Collaborator, they could mark up the source code, in place. The XML could even be hidden behind comments. ``` // <comment author="mcruikshank" date="2009-10-07"> // Please refactor to Delegate. // </comment> ``` And then if you want to use vi or emacs, you can just skip over the comments. If I want to use a state-of-the-art editor, I can see that in about a dozen different helpful ways. So, that's my rough idea. It's not "building blocks" of pictures that you drag on the screen... I'm not that nuts. :)
* you can diff them * you can merge them * anyone can edit them * they are simple and easy to deal with * they are universally accessible to thousands of tools
160,666
<p>I'd like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:</p> <pre><code>&lt;img src=&quot;whatever.jpeg&quot; width=&quot;100%&quot; height=&quot;100%&quot; /&gt; </code></pre> <p>It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ?</p> <hr /> <p>The solution posted by Wayne <strong>almost</strong> works except for the case where you have a tall image and a wide window. This code is a slight modification of his code which does what I want:</p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; function resizeToMax(id){ myImage = new Image() var img = document.getElementById(id); myImage.src = img.src; if(myImage.width / document.body.clientWidth &gt; myImage.height / document.body.clientHeight){ img.style.width = &quot;100%&quot;; } else { img.style.height = &quot;100%&quot;; } } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;img id=&quot;image&quot; src=&quot;test.gif&quot; onload=&quot;resizeToMax(this.id)&quot;&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 160674, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;img src=\"whatever.jpeg\" width=\"100%\" height=\"auto\" /&gt;\n</code></pre>\n" }, { "answer_id": 160679, "author": "David Smith", "author_id": 17201, "author_profile": "https://Stackoverflow.com/users/17201", "pm_score": 2, "selected": false, "text": "<p>To piggyback on Franci Penov, yes you just want to set one of them. If you have a wide picture, you want to set width to 100% and leave height. If you have a long picture, you want to set height to 100% and leave width.</p>\n" }, { "answer_id": 160717, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 5, "selected": true, "text": "<p>Here's a quick function that will adjust the height or width to 100% depending on which is bigger. Tested in FF3, IE7 &amp; Chrome</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script&gt;\nfunction resizeToMax(id){\n myImage = new Image() \n var img = document.getElementById(id);\n myImage.src = img.src; \n if(myImage.width &gt; myImage.height){\n img.style.width = \"100%\";\n } else {\n img.style.height = \"100%\";\n }\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;img id=\"image\" src=\"test.gif\" onload=\"resizeToMax(this.id)\"&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 160729, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>For this, JavaScript is your friend. What you want to do, is on page load, walk through the dom, and for every image (or alterantively, pass a function an image id if it's just a single image) check if which attribute of the image is greater, it's height or width. </p>\n\n<p>This is the IMAGE itself, not the tag. </p>\n\n<p>Once you got that, then set the corresponding height/width on the tag to 100% and the other to auto</p>\n\n<p>some helpful code--all from off the top of my head, so your mileage may vary on the syntax..</p>\n\n<pre><code>var imgTag = $('myImage'); \nvar imgPath = imgTag.src; \nvar img = new Image(); \nimg.src = imgPath; \nvar mywidth = img.width; \nvar myheight = img.height;\n</code></pre>\n\n<p>As an aside, this would be a much easier task on the server side of things. On the server, you could literally change the size of the image that's getting streamed down tot he browser.</p>\n" }, { "answer_id": 160770, "author": "Samir Talwar", "author_id": 20856, "author_profile": "https://Stackoverflow.com/users/20856", "pm_score": 3, "selected": false, "text": "<p>You don't necessarily want to stretch in a certain direction based on which is bigger. For example, I have a widescreen monitor, so even if it's a wider image than it is tall, stretching it left-to-right may still clip the top and bottom edges off.</p>\n\n<p>You need to calculate the ratio between the window width and height and the image width and height. The smaller one is your controlling axis - the other is dependent. This is true even if both axes are larger than the respective window length.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n// &lt;![CDATA[\nfunction resizeToMax (id) {\n var img = document.getElementById(id);\n myImage = new Image();\n myImage.src = img.src;\n if (window.innerWidth / myImage.width &lt; window.innerHeight / myImage.height) {\n img.style.width = \"100%\";\n } else {\n img.style.height = \"100%\";\n }\n}\n// ]]&gt;\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 12013347, "author": "tito76", "author_id": 1607948, "author_profile": "https://Stackoverflow.com/users/1607948", "pm_score": 0, "selected": false, "text": "<p>Tested on IE and Firefox, plus the first line will center image:</p>\n\n<pre><code>&lt;div align=\"center\"&gt;\n&lt;embed src=\"image.gif\" height=\"100%\"&gt;\n</code></pre>\n\n<p>... also great to preserve aspect ratio with any other size value, so no more annoying calculations =)</p>\n" }, { "answer_id": 12979880, "author": "ondovb", "author_id": 1260565, "author_profile": "https://Stackoverflow.com/users/1260565", "pm_score": 3, "selected": false, "text": "<p>It is also possible to do this with pure CSS using a background image and the <code>background-size:contain</code> property:</p>\n\n<pre><code>&lt;head&gt;\n&lt;style&gt;\n#bigPicture\n{\n width:100%;\n height:100%;\n background:url(http://upload.wikimedia.org/wikipedia/commons/4/44/CatLolCatExample.jpg);\n background-size:contain;\n background-repeat:no-repeat;\n background-position:center;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body style=\"margin:0px\"&gt;\n &lt;div id=\"bigPicture\"&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p>This has the benefit of automatically updating if the container changes aspect ratios, without having to respond to resize events (the Javascript methods, as coded here, can result in cutting off the image when the user resizes the browser). The <code>&lt;embed&gt;</code> method has the same benefit, but CSS is much smoother and has no issues with security warnings.</p>\n\n<p>Caveats:</p>\n\n<ul>\n<li>No <code>&lt;img&gt;</code> element means no context menu and no alt text.</li>\n<li>IE support for <code>background-size:contain</code> is 9+ only, and I couldn't even get this to work in IE9 (for unknown reasons).</li>\n<li>It seems like all the <code>background-*</code> properties have to be specified in the same CSS block as the background image, so multiple images on the same page will each need their own <code>contain</code>, <code>no-repeat</code>, and <code>center</code>.</li>\n</ul>\n" }, { "answer_id": 48269722, "author": "Jasper de Vries", "author_id": 880619, "author_profile": "https://Stackoverflow.com/users/880619", "pm_score": 2, "selected": false, "text": "<p>The easiest way to do so (if you don't need to support IE) is setting the <code>object-fit</code> CSS property to <code>contain</code>:</p>\n\n<pre><code>img { object-fit: contain; }\n</code></pre>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit</a></li>\n<li><a href=\"https://caniuse.com/#search=object-fit\" rel=\"nofollow noreferrer\">https://caniuse.com/#search=object-fit</a></li>\n</ul>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
I'd like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this: ``` <img src="whatever.jpeg" width="100%" height="100%" /> ``` It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ? --- The solution posted by Wayne **almost** works except for the case where you have a tall image and a wide window. This code is a slight modification of his code which does what I want: ```html <html> <head> <script> function resizeToMax(id){ myImage = new Image() var img = document.getElementById(id); myImage.src = img.src; if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){ img.style.width = "100%"; } else { img.style.height = "100%"; } } </script> </head> <body> <img id="image" src="test.gif" onload="resizeToMax(this.id)"> </body> </html> ```
Here's a quick function that will adjust the height or width to 100% depending on which is bigger. Tested in FF3, IE7 & Chrome ``` <html> <head> <script> function resizeToMax(id){ myImage = new Image() var img = document.getElementById(id); myImage.src = img.src; if(myImage.width > myImage.height){ img.style.width = "100%"; } else { img.style.height = "100%"; } } </script> </head> <body> <img id="image" src="test.gif" onload="resizeToMax(this.id)"> </body> </html> ```
160,697
<p>I personally like the <em>exclusive or</em>, <code>^</code>, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write</p> <pre><code>if (boolean1 ^ boolean2) { //do it } </code></pre> <p>than</p> <pre><code>if((boolean1 &amp;&amp; !boolean2) || (boolean2 &amp;&amp; !boolean1)) { //do it } </code></pre> <p>but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations. </p> <p>I'm curious as to the best practices regarding the usage of the <code>^</code> operator.</p>
[ { "answer_id": 160700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "<p>You can simply use <code>!=</code> instead.</p>\n" }, { "answer_id": 160701, "author": "Dre", "author_id": 23033, "author_profile": "https://Stackoverflow.com/users/23033", "pm_score": 4, "selected": false, "text": "<p>I think it'd be okay if you commented it, e.g. <code>// ^ == XOR</code>.</p>\n" }, { "answer_id": 160716, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": -1, "selected": false, "text": "<p>If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming? </p>\n\n<p>The only caution I might state is that \"^\" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.</p>\n\n<pre><code>public static boolean xor(boolean a, boolean b) {\n return (a &amp;&amp; !b) || (b &amp;&amp; !a);\n}\n</code></pre>\n" }, { "answer_id": 160789, "author": "Martin", "author_id": 24364, "author_profile": "https://Stackoverflow.com/users/24364", "pm_score": 5, "selected": false, "text": "<p>I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.</p>\n\n<p>If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.</p>\n" }, { "answer_id": 160932, "author": "Dave Tarkowski", "author_id": 4288, "author_profile": "https://Stackoverflow.com/users/4288", "pm_score": 4, "selected": false, "text": "<p>I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.</p>\n\n<p>My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.</p>\n\n<p>As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.</p>\n" }, { "answer_id": 515268, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>!= is OK to compare two variables. It doesn't work, though, with multiple comparisons. </p>\n" }, { "answer_id": 2612763, "author": "Y--", "author_id": 313385, "author_profile": "https://Stackoverflow.com/users/313385", "pm_score": 3, "selected": false, "text": "<pre><code>if((boolean1 &amp;&amp; !boolean2) || (boolean2 &amp;&amp; !boolean1)) \n{ \n //do it \n} \n</code></pre>\n\n<p>IMHO this code could be simplified:</p>\n\n<pre><code>if(boolean1 != boolean2) \n{ \n //do it \n} \n</code></pre>\n" }, { "answer_id": 4205620, "author": "Chris Rea", "author_id": 269367, "author_profile": "https://Stackoverflow.com/users/269367", "pm_score": -1, "selected": false, "text": "<pre><code>str.contains(\"!=\") ^ str.startsWith(\"not(\")\n</code></pre>\n\n<p>looks better for me than</p>\n\n<pre><code>str.contains(\"!=\") != str.startsWith(\"not(\")\n</code></pre>\n" }, { "answer_id": 5422556, "author": "Nick", "author_id": 675320, "author_profile": "https://Stackoverflow.com/users/675320", "pm_score": -1, "selected": false, "text": "<p>As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.</p>\n\n<p>My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write \"to the rivers of belief\" here :) ).</p>\n" }, { "answer_id": 12995170, "author": "Gunnar Karlsson", "author_id": 898375, "author_profile": "https://Stackoverflow.com/users/898375", "pm_score": 3, "selected": false, "text": "<p>With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is <em>typically</em> used to implement a mask <code>flag toggle</code> behavior:</p>\n\n<pre><code>flags = flags ^ MASK;\n</code></pre>\n\n<p><a href=\"http://vipan.com/htdocs/bitwisehelp.html\" rel=\"nofollow noreferrer\">This</a> article by Vipan Singla explains the usage case more in detail.</p>\n\n<p>If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it. </p>\n" }, { "answer_id": 15030804, "author": "Cory Gross", "author_id": 1359785, "author_profile": "https://Stackoverflow.com/users/1359785", "pm_score": 3, "selected": false, "text": "<p>You could always just wrap it in a function to give it a verbose name:</p>\n\n<pre><code>public static boolean XOR(boolean A, boolean B) {\n return A ^ B;\n}\n</code></pre>\n\n<p>But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking. </p>\n\n<p>You can also <a href=\"https://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow noreferrer\">use XOR to swap the values in two variables without using a third temporary variable</a>.</p>\n\n<pre><code>// Swap the values in A and B\nA ^= B;\nB ^= A;\nA ^= B;\n</code></pre>\n\n<p>Here's a <a href=\"http://stackoverflow.com/questions/249423/how-does-xor-variable-swapping-work\">Stackoverflow question related to XOR swapping</a>.</p>\n" }, { "answer_id": 45646557, "author": "ONE", "author_id": 6439630, "author_profile": "https://Stackoverflow.com/users/6439630", "pm_score": 0, "selected": false, "text": "<p>I personally prefer the \"boolean1 ^ boolean2\" expression due to its succinctness.</p>\n\n<p>If I was in your situation (working in a team), I would strike a compromise by encapsulating the \"boolean1 ^ boolean2\" logic in a function with a descriptive name such as \"isDifferent(boolean1, boolean2)\".</p>\n\n<p>For example, instead of using \"boolean1 ^ boolean2\", you would call \"isDifferent(boolean1, boolean2)\" like so:</p>\n\n<pre><code>if (isDifferent(boolean1, boolean2))\n{\n //do it\n}\n</code></pre>\n\n<p>Your \"isDifferent(boolean1, boolean2)\" function would look like:</p>\n\n<pre><code>private boolean isDifferent(boolean1, boolean2)\n{\n return boolean1 ^ boolean2;\n}\n</code></pre>\n\n<p>Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression \"(boolean1 &amp;&amp; !boolean2) || (boolean2 &amp;&amp; !boolean1)\"!</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17123/" ]
I personally like the *exclusive or*, `^`, operator when it makes sense in the context of boolean checks because of its conciseness. I much prefer to write ``` if (boolean1 ^ boolean2) { //do it } ``` than ``` if((boolean1 && !boolean2) || (boolean2 && !boolean1)) { //do it } ``` but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations. I'm curious as to the best practices regarding the usage of the `^` operator.
You can simply use `!=` instead.
160,724
<p>I'm working on a Google App Engine project. </p> <p>My app is working and looking correct locally, but when I try to upload images in an image directory, they're not being displayed at appspot.</p> <p>As a little troubleshoot, I put a HTML page in "/images/page2.html" and I can load that page at the appspot, but my pages don't display my images. So, it's not a problem with my path.</p> <p>As another sanity check, I'm also uploading a style sheet directory with .css code in it, and that's being read properly. </p> <p>I have a suspicion that the problem lies in my app.yaml file. </p> <p>Any ideas? </p> <p>I don't want to paste all the code here, but here are some of the key lines. The first two work fine. The third does not work: </p> <pre><code>&lt;link type="text/css" rel="stylesheet" href="/stylesheets/style.css" /&gt; &lt;a href="/images/Page2.html"&gt;Page 2&lt;/a&gt; &lt;img src="/images/img.gif"&gt; </code></pre> <p>This is my app.yaml file</p> <pre><code>application: myApp version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /images static_dir: images - url: /.* script: helloworld.py </code></pre>
[ { "answer_id": 165503, "author": "JJ.", "author_id": 9106, "author_profile": "https://Stackoverflow.com/users/9106", "pm_score": 2, "selected": false, "text": "<p>I'll bet your problem is that you're using Windows. </p>\n\n<p>If that's the case, I believe you need a preceding slash for your static_dir value. </p>\n" }, { "answer_id": 183239, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 0, "selected": false, "text": "<p>@jamtoday The preceding slash didn't make a difference, but it did get me started figuring out what each app needs to be told what about my directory structure. </p>\n\n<p>So, I have nothing very conclusive to add, but I wanted to follow up, because I got it working, but I didn't explore all the issues after I got it working. </p>\n\n<p>One change that helped was to stop working from a HwlloWorld/src/ directory and start working in the HelloWorld/ directory. It seems like the dev_appserver picked up all the dependencies, but the remote server didn't. Essentially, the relative path of my local links didn't match the relative path of the links after uploading. </p>\n\n<p>I also realized that the dev-appserver relies on the .yaml file, as well as the appcfg script. That is. . .if you add a directory to your project, and then try to link to files in that directory, you need to add the directory to the .yaml file, and then restart the dev-appserver to pick up on this. </p>\n\n<p>So, there are probably ways to handle what I was originally trying to do if you give the .yaml file the right info, but changing to a different directory structure locally handled it for me. </p>\n" }, { "answer_id": 211073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;img src=\"/images/img.gif\"&gt;\n</code></pre>\n\n<p>this line can't show you the image.\nTry this one:</p>\n\n<p>1-Create a class to handle \"image request\"</p>\n\n<pre><code>class GetImage(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'image/jpg'\n self.response.out.write(image_object)\n</code></pre>\n\n<p>2-In your page.html:</p>\n\n<pre><code>&lt;img src=\"/image\"\n</code></pre>\n\n<p>3-At the main function in your code.py:</p>\n\n<pre><code>application = webapp.WSGIApplication(('/image', GetImage), debug=True)\n</code></pre>\n\n<p>have fun</p>\n" }, { "answer_id": 275705, "author": "Sarp Centel", "author_id": 16622, "author_profile": "https://Stackoverflow.com/users/16622", "pm_score": 2, "selected": false, "text": "<p>You have to configure app.yaml for static content such as images and css files</p>\n\n<p>Example:</p>\n\n<pre><code> url: /(.*\\.(gif|png|jpg))\n static_files: static/\\1\n upload: static/(.*\\.(gif|png|jpg))\n</code></pre>\n\n<p>For more info check out:\n<a href=\"http://code.google.com/appengine/docs/configuringanapp.html\" rel=\"nofollow noreferrer\">http://code.google.com/appengine/docs/configuringanapp.html</a></p>\n" }, { "answer_id": 1021301, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I am using the Java version of App engine, and I faced a similar issues with the server not able to serve static images.</p>\n\n<p>What worked ultimately was to change the AppEngine config file \"appengine-web.xml\" in my case to contain</p>\n\n<pre><code>&lt;static-files&gt;\n&lt;include path=\"**.*\"/&gt;\n &lt;include path=\"/images/**.*\" /&gt;\n&lt;/static-files&gt;\n</code></pre>\n\n<p>My images are in the /images directory and HTML and CSS are in . directory which is at the WEB-INF level</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179/" ]
I'm working on a Google App Engine project. My app is working and looking correct locally, but when I try to upload images in an image directory, they're not being displayed at appspot. As a little troubleshoot, I put a HTML page in "/images/page2.html" and I can load that page at the appspot, but my pages don't display my images. So, it's not a problem with my path. As another sanity check, I'm also uploading a style sheet directory with .css code in it, and that's being read properly. I have a suspicion that the problem lies in my app.yaml file. Any ideas? I don't want to paste all the code here, but here are some of the key lines. The first two work fine. The third does not work: ``` <link type="text/css" rel="stylesheet" href="/stylesheets/style.css" /> <a href="/images/Page2.html">Page 2</a> <img src="/images/img.gif"> ``` This is my app.yaml file ``` application: myApp version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /images static_dir: images - url: /.* script: helloworld.py ```
I'll bet your problem is that you're using Windows. If that's the case, I believe you need a preceding slash for your static\_dir value.
160,726
<p>I have been thinking a lot about unit testing and how to improve the readability of the unit tests. I thought why not give a character to the classes in the unit test to clarify what they do. </p> <p>Here is a simple unit test that I wrote: </p> <pre><code>[TestFixture] public class when_dave_transfers_money_from_wamu_account_to_the_woodforest_account { [Test] public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull() { Dave dave = new Dave(); Wamu wamu = new Wamu(); wamu.Balance = 150; wamu.AddUser(dave); Woodforest woodforest = new Woodforest(); woodforest.AddUser(dave); FundTransferService.Transfer(100, wamu, woodforest); Assert.AreEqual(wamu.Balance, 50); Assert.AreEqual(woodforest.Balance, 100); } } </code></pre> <p>Here is the Dave class: </p> <pre><code>/// &lt;summary&gt; /// This is Dave! /// &lt;/summary&gt; public class Dave : User { public Dave() { FirstName = "Dave"; LastName = "Allen"; } } </code></pre> <p>The unit test name clearly serves the purpose. But, maybe I want to dig a little deeper and assign the Wamu and Woodforest accounts to Dave whenever Dave is created. The problem is that it will move away from readability as I will have to use index values to refer to the account. </p> <p>What are your thoughts on making this more readable? </p>
[ { "answer_id": 160738, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>How about a private helper method in the test fixture</p>\n\n<pre><code>private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()\n</code></pre>\n" }, { "answer_id": 160743, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 0, "selected": false, "text": "<p>I can add Dave to the Wamu and the Woodforest account when Dave is created like this: </p>\n\n<pre><code> public Dave()\n {\n FirstName = \"Dave\";\n LastName = \"Allen\"; \n\n // add accounts for Dave \n\n Wamu wamu = new Wamu();\n wamu.AddUser(this);\n\n Woodforest woodforest = new Woodforest();\n woodforest.AddUser(this); \n }\n</code></pre>\n\n<p>The accounts are added the List collection in the User object from which Dave inherits. </p>\n" }, { "answer_id": 160764, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>when you attempt to instantiate the Wamu instance, shouldn't it throw a WamuNotFoundException?</p>\n" }, { "answer_id": 160786, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "<p>Here is another way to run the test: </p>\n\n<pre><code> [Test]\n public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()\n {\n Dave dave = new Dave();\n\n // we know that dave has wamu and wooforest accounts \n\n dave.WamuAccount(\"Wamu\").Balance = 150;\n\n FundTransferService.Transfer(100, dave.WamuAccount(\"Wamu\"), dave.WoodforestAccount(\n \"Woodforest\"));\n\n Assert.AreEqual(50, dave.WamuAccount(\"Wamu\").Balance);\n Assert.AreEqual(100, dave.WoodforestAccount(\"Woodforest\").Balance); \n }\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
I have been thinking a lot about unit testing and how to improve the readability of the unit tests. I thought why not give a character to the classes in the unit test to clarify what they do. Here is a simple unit test that I wrote: ``` [TestFixture] public class when_dave_transfers_money_from_wamu_account_to_the_woodforest_account { [Test] public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull() { Dave dave = new Dave(); Wamu wamu = new Wamu(); wamu.Balance = 150; wamu.AddUser(dave); Woodforest woodforest = new Woodforest(); woodforest.AddUser(dave); FundTransferService.Transfer(100, wamu, woodforest); Assert.AreEqual(wamu.Balance, 50); Assert.AreEqual(woodforest.Balance, 100); } } ``` Here is the Dave class: ``` /// <summary> /// This is Dave! /// </summary> public class Dave : User { public Dave() { FirstName = "Dave"; LastName = "Allen"; } } ``` The unit test name clearly serves the purpose. But, maybe I want to dig a little deeper and assign the Wamu and Woodforest accounts to Dave whenever Dave is created. The problem is that it will move away from readability as I will have to use index values to refer to the account. What are your thoughts on making this more readable?
How about a private helper method in the test fixture ``` private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp() ```
160,737
<p>I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives. I can't find a way to do this. I'm using VS2008.</p> <p>Whenever I expand the "Project Data" tree, I see only classes in my current project. The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5. I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.</p>
[ { "answer_id": 160738, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>How about a private helper method in the test fixture</p>\n\n<pre><code>private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()\n</code></pre>\n" }, { "answer_id": 160743, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 0, "selected": false, "text": "<p>I can add Dave to the Wamu and the Woodforest account when Dave is created like this: </p>\n\n<pre><code> public Dave()\n {\n FirstName = \"Dave\";\n LastName = \"Allen\"; \n\n // add accounts for Dave \n\n Wamu wamu = new Wamu();\n wamu.AddUser(this);\n\n Woodforest woodforest = new Woodforest();\n woodforest.AddUser(this); \n }\n</code></pre>\n\n<p>The accounts are added the List collection in the User object from which Dave inherits. </p>\n" }, { "answer_id": 160764, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>when you attempt to instantiate the Wamu instance, shouldn't it throw a WamuNotFoundException?</p>\n" }, { "answer_id": 160786, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 1, "selected": false, "text": "<p>Here is another way to run the test: </p>\n\n<pre><code> [Test]\n public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()\n {\n Dave dave = new Dave();\n\n // we know that dave has wamu and wooforest accounts \n\n dave.WamuAccount(\"Wamu\").Balance = 150;\n\n FundTransferService.Transfer(100, dave.WamuAccount(\"Wamu\"), dave.WoodforestAccount(\n \"Woodforest\"));\n\n Assert.AreEqual(50, dave.WamuAccount(\"Wamu\").Balance);\n Assert.AreEqual(100, dave.WoodforestAccount(\"Woodforest\").Balance); \n }\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives. I can't find a way to do this. I'm using VS2008. Whenever I expand the "Project Data" tree, I see only classes in my current project. The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5. I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.
How about a private helper method in the test fixture ``` private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp() ```
160,742
<p>I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this:</p> <pre><code>using System; public class ClassName { public double TheFunction(double input) { // user entered code here } } </code></pre> <p>Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this:</p> <pre><code>string formatString = @" using System; public class ClassName {0} public double TheFunction(double input) {0} {2} {1} {1}"; </code></pre> <p>Then I call string.Format like this:</p> <pre><code>string entireClass = string.Format(formatString, "{", "}", userInput); </code></pre> <p>This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s?</p> <p>BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation.</p>
[ { "answer_id": 160745, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>\"{{\" and \"}}\"</p>\n" }, { "answer_id": 160747, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 6, "selected": true, "text": "<p>Escape them by doubling them up:</p>\n\n<pre><code>string s = String.Format(\"{{ hello to all }}\");\nConsole.WriteLine(s); //prints '{ hello to all }'\n</code></pre>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1</a></p>\n" }, { "answer_id": 160749, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 1, "selected": false, "text": "<p>Double the braces: <code>string.Format(\"{{ {0} }}\", \"Hello, World\");</code> would produce <code>{ Hello, World }</code></p>\n" }, { "answer_id": 160754, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 3, "selected": false, "text": "<p>What I think you want is this...</p>\n\n<pre><code>string formatString = @\"\nusing System;\n\npublic class ClassName\n{{\n public double TheFunction(double input)\n {{\n {0}\n }}\n}}\";\n\nstring entireClass = string.Format(formatString, userInput);\n</code></pre>\n" }, { "answer_id": 161334, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 0, "selected": false, "text": "<p>Be extra extra cautious in who has access to the application. A better solution might be to create a simple parser that only expects a few, limited, commands.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4797/" ]
I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this: ``` using System; public class ClassName { public double TheFunction(double input) { // user entered code here } } ``` Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this: ``` string formatString = @" using System; public class ClassName {0} public double TheFunction(double input) {0} {2} {1} {1}"; ``` Then I call string.Format like this: ``` string entireClass = string.Format(formatString, "{", "}", userInput); ``` This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s? BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation.
Escape them by doubling them up: ``` string s = String.Format("{{ hello to all }}"); Console.WriteLine(s); //prints '{ hello to all }' ``` From <http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1>
160,848
<p>Does the compiler optimize out any multiplications by 1? That is, consider:</p> <pre><code>int a = 1; int b = 5 * a; </code></pre> <p>Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as:</p> <pre><code>const int a = 1; </code></pre>
[ { "answer_id": 160850, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "<p>It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the <strong><code>const</code></strong> it will be left alone.</p>\n\n<p>Your first example compiles to this IL:</p>\n\n<pre><code>.maxstack 2\n.locals init ([0] int32, [1] int32)\n\nldc.i4.1 //load 1\nstloc.0 //store in 1st local variable\nldc.i4.5 //load 5\nldloc.0 //load 1st variable\nmul // 1 * 5\nstloc.1 // store in 2nd local variable \n</code></pre>\n\n<p>The second example compiles to this:</p>\n\n<pre><code>.maxstack 1\n.locals init ( [0] int32 )\n\nldc.i4.5 //load 5 \nstloc.0 //store in local variable\n</code></pre>\n" }, { "answer_id": 160854, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Constant propagation is one of the most common and easiest optimisations.</p>\n" }, { "answer_id": 160865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What the compiler would optimise here is not multiplication by 1 per-se, but rather arithmetic with values known at compile-time. So yeah, a compiler would optimise out all the maths in your example, with or without the <code>const</code>.</p>\n\n<p><strong>Edit:</strong> A <em>competent</em> compiler, I should say.</p>\n" }, { "answer_id": 160891, "author": "Dave Tarkowski", "author_id": 4288, "author_profile": "https://Stackoverflow.com/users/4288", "pm_score": 1, "selected": false, "text": "<p>Looking at the code generated by the mono compiler, the version with the non-const a performs the multiplication at run time. That is, the multiplication is not optimized out. If you make a const, then the multiplication is optimized out.</p>\n\n<p>The Microsoft compiler might have a more aggressive compiler, the best solution is to look at the code generated by the compiler to see what it is doing.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16942/" ]
Does the compiler optimize out any multiplications by 1? That is, consider: ``` int a = 1; int b = 5 * a; ``` Will the expression 5 \* a be optimized into just 5? If not, will it if a is defined as: ``` const int a = 1; ```
It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the **`const`** it will be left alone. Your first example compiles to this IL: ``` .maxstack 2 .locals init ([0] int32, [1] int32) ldc.i4.1 //load 1 stloc.0 //store in 1st local variable ldc.i4.5 //load 5 ldloc.0 //load 1st variable mul // 1 * 5 stloc.1 // store in 2nd local variable ``` The second example compiles to this: ``` .maxstack 1 .locals init ( [0] int32 ) ldc.i4.5 //load 5 stloc.0 //store in local variable ```
160,859
<p>I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs. A link to read about it would be great. A trivial explained example would be even better. Thank you.</p>
[ { "answer_id": 160884, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 1, "selected": false, "text": "<p>Where have you seen the phrase used?</p>\n\n<p>\"Binding\" in Python generally refers to the process by which a variable name ends up pointing to a specific object, whether by assignment or parameter passing or some other means, e.g.:</p>\n\n<pre><code>a = dict(foo=\"bar\", zip=\"zap\", zig=\"zag\") # binds a to a newly-created dict object\nb = a # binds b to that same dictionary\n\ndef crunch(param):\n print param\n\ncrunch(a) # binds the parameter \"param\" in the function crunch to that same dict again\n</code></pre>\n\n<p>So I would guess that \"lambda binding\" refers to the process of binding a lambda function to a variable name, or maybe binding its named parameters to specific objects? There's a pretty good explanation of binding in the Language Reference, at <a href=\"http://docs.python.org/ref/naming.html\" rel=\"nofollow noreferrer\">http://docs.python.org/ref/naming.html</a></p>\n" }, { "answer_id": 160898, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 5, "selected": true, "text": "<p>First, a general definition:</p>\n\n<blockquote>\n <p>When a program or function statement\n is executed, the current values of\n formal parameters are saved (on the\n stack) and within the scope of the\n statement, they are bound to the\n values of the actual arguments made in\n the call. When the statement is\n exited, the original values of those\n formal arguments are restored. This\n protocol is fully recursive. If within\n the body of a statement, something is\n done that causes the formal parameters\n to be bound again, to new values, the\n lambda-binding scheme guarantees that\n this will all happen in an orderly\n manner.</p>\n</blockquote>\n\n<p>Now, there is an excellent <a href=\"http://markmail.org/message/fypalne4rp5curta\" rel=\"nofollow noreferrer\" title=\"Theoretical question about Lambda\">python example in a discussion here</a>:</p>\n\n<p>\"...there is only one binding for <code>x</code>: doing <code>x = 7</code> just changes the value in the pre-existing binding. That's why</p>\n\n<pre><code>def foo(x): \n a = lambda: x \n x = 7 \n b = lambda: x \n return a,b\n</code></pre>\n\n<p>returns two functions that both return 7; if there was a new binding after the <code>x = 7</code>, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested_scopes]....\"</p>\n" }, { "answer_id": 160920, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p>I've never heard that term, but one explanation could be the \"default parameter\" hack used to assign a value directly to a lambda's parameter. Using Swati's example:</p>\n\n<pre><code>def foo(x): \n a = lambda x=x: x \n x = 7 \n b = lambda: x \n return a,b\n\naa, bb = foo(4)\naa() # Prints 4\nbb() # Prints 7\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15073/" ]
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs. A link to read about it would be great. A trivial explained example would be even better. Thank you.
First, a general definition: > > When a program or function statement > is executed, the current values of > formal parameters are saved (on the > stack) and within the scope of the > statement, they are bound to the > values of the actual arguments made in > the call. When the statement is > exited, the original values of those > formal arguments are restored. This > protocol is fully recursive. If within > the body of a statement, something is > done that causes the formal parameters > to be bound again, to new values, the > lambda-binding scheme guarantees that > this will all happen in an orderly > manner. > > > Now, there is an excellent [python example in a discussion here](http://markmail.org/message/fypalne4rp5curta "Theoretical question about Lambda"): "...there is only one binding for `x`: doing `x = 7` just changes the value in the pre-existing binding. That's why ``` def foo(x): a = lambda: x x = 7 b = lambda: x return a,b ``` returns two functions that both return 7; if there was a new binding after the `x = 7`, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested\_scopes]...."
160,876
<p>I have a (from what I can tell) perfectly working Linux setup (Ubuntu 8.04) where all tools (nslookup, curl, wget, firefox, etc) are able to resolve addresses. Yet, the following code fails:</p> <pre><code>$s = new IO::Socket::INET( PeerAddr =&gt; 'stackoverflow.com', PeerPort =&gt; 80, Proto =&gt; 'tcp', ); die "Error: $!\n" unless $s; </code></pre> <p>I verified the following things:</p> <ul> <li><p>Perl is able to resolve addresses with gethostbyname (ie the code below works):</p> <p><code>my $ret = gethostbyname('stackoverflow.com'); print inet_ntoa($ret);</code></p></li> <li><p>The original source code works under Windows</p></li> <li>This is how it supposed to work (ie. it should resolve hostnames), since LWP tries to use this behavior (in fact I stumbled uppon the problem by trying to debug why LWP wasn't working for me)</li> <li>Running the script doesn't emit DNS requests (so it doesn't even try to resolve the name). Verified with Wireshark</li> </ul>
[ { "answer_id": 160907, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": -1, "selected": false, "text": "<p>Make sure that you have the statement </p>\n\n<pre><code>use IO::Socket::INET;\n</code></pre>\n\n<p>At the beginning of your source code. If you leave this out, you are probably getting the error message:</p>\n\n<blockquote>\n <p>Can't locate object method \"new\" via\n package \"IO::Socket::INET\"</p>\n</blockquote>\n\n<p>Beyond that you might verify that DNS is working using Net::DNS::Resoler, see more information <a href=\"http://search.cpan.org/~olaf/Net-DNS-0.63/lib/Net/DNS/Resolver.pm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>use Net::DNS;\n\nmy $res = Net::DNS::Resolver-&gt;new;\n\n# Perform a lookup, using the searchlist if appropriate.\nmy $answer = $res-&gt;search('example.com');\n</code></pre>\n" }, { "answer_id": 160964, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 4, "selected": true, "text": "<p>From a quick look, the following code from IO::Socket::INET</p>\n\n<pre><code>sub _get_addr {\n my($sock,$addr_str, $multi) = @_;\n my @addr;\n if ($multi &amp;&amp; $addr_str !~ /^\\d+(?:\\.\\d+){3}$/) {\n (undef, undef, undef, undef, @addr) = gethostbyname($addr_str);\n } else {\n my $h = inet_aton($addr_str);\n push(@addr, $h) if defined $h;\n }\n @addr;\n}\n</code></pre>\n\n<p>suggests (if you look at the caller of this code) the work-around of adding <code>MultiHomed =&gt; 1,</code> to your code.</p>\n\n<p>Without that work-around, the above code appears to try to call <code>inet_aton(\"hostname.com\")</code> using the inet_aton() from Socket.pm. That works for me in both Win32 and Unix, so I guess that is where the breakage lies for you.</p>\n\n<p>See <a href=\"http://search.cpan.org/src/TOMC/Socket-1.5/Socket.xs\" rel=\"noreferrer\">Socket.xs</a> for the source code of inet_aton:</p>\n\n<pre><code>void\ninet_aton(host)\n char * host\n CODE:\n {\n struct in_addr ip_address;\n struct hostent * phe;\n\n if (phe = gethostbyname(host)) {\n Copy( phe-&gt;h_addr, &amp;ip_address, phe-&gt;h_length, char );\n } else {\n ip_address.s_addr = inet_addr(host);\n }\n\n ST(0) = sv_newmortal();\n if(ip_address.s_addr != INADDR_NONE) {\n sv_setpvn( ST(0), (char *)&amp;ip_address, sizeof ip_address );\n }\n }\n</code></pre>\n\n<p>It appears that the Perl gethostbyname() works better than the C gethostbyname() for you.</p>\n" }, { "answer_id": 175085, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>Could you perhaps tells us exactly <strong>how</strong> your code fails? You've got error checking code in there but you haven't reported what the error is!</p>\n\n<p>I've just tried the original code (with the addition of the \"use IO::Socket::INET\" on my Mac OS X machine and it works fine.</p>\n\n<p>I suspect that the Multihomed option is an unnecessary hack and some other issue is the root cause of your problem.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265/" ]
I have a (from what I can tell) perfectly working Linux setup (Ubuntu 8.04) where all tools (nslookup, curl, wget, firefox, etc) are able to resolve addresses. Yet, the following code fails: ``` $s = new IO::Socket::INET( PeerAddr => 'stackoverflow.com', PeerPort => 80, Proto => 'tcp', ); die "Error: $!\n" unless $s; ``` I verified the following things: * Perl is able to resolve addresses with gethostbyname (ie the code below works): `my $ret = gethostbyname('stackoverflow.com'); print inet_ntoa($ret);` * The original source code works under Windows * This is how it supposed to work (ie. it should resolve hostnames), since LWP tries to use this behavior (in fact I stumbled uppon the problem by trying to debug why LWP wasn't working for me) * Running the script doesn't emit DNS requests (so it doesn't even try to resolve the name). Verified with Wireshark
From a quick look, the following code from IO::Socket::INET ``` sub _get_addr { my($sock,$addr_str, $multi) = @_; my @addr; if ($multi && $addr_str !~ /^\d+(?:\.\d+){3}$/) { (undef, undef, undef, undef, @addr) = gethostbyname($addr_str); } else { my $h = inet_aton($addr_str); push(@addr, $h) if defined $h; } @addr; } ``` suggests (if you look at the caller of this code) the work-around of adding `MultiHomed => 1,` to your code. Without that work-around, the above code appears to try to call `inet_aton("hostname.com")` using the inet\_aton() from Socket.pm. That works for me in both Win32 and Unix, so I guess that is where the breakage lies for you. See [Socket.xs](http://search.cpan.org/src/TOMC/Socket-1.5/Socket.xs) for the source code of inet\_aton: ``` void inet_aton(host) char * host CODE: { struct in_addr ip_address; struct hostent * phe; if (phe = gethostbyname(host)) { Copy( phe->h_addr, &ip_address, phe->h_length, char ); } else { ip_address.s_addr = inet_addr(host); } ST(0) = sv_newmortal(); if(ip_address.s_addr != INADDR_NONE) { sv_setpvn( ST(0), (char *)&ip_address, sizeof ip_address ); } } ``` It appears that the Perl gethostbyname() works better than the C gethostbyname() for you.
160,881
<p>So this is a question for anyone who has had to integrate the building/compilation of legacy projects/code in a Team Build/MSBuild environment - specifically, Visual Basic 6 applications/projects.</p> <p><i>Outside</i> of writing a custom build Task (which I am not against) does anyone have any suggestions on how best to integrate compilation and versioning of legacy VB6 projects into MSBuild builds?</p> <p>I'm aware of the FreeToDev msbuild tasks at <a href="http://www.codeplex.com/freetodevtasks" rel="noreferrer">CodePlex</a> but they've been withdrawn at the moment.</p> <p>Ideally I'm looking to version and compile the code as well as capture the compilation output (especially errors) for the msbuild log.</p> <p>I've seen advice on encapsulating this functionality in a custom task, but really wondered if anyone has tried another solution (aside from executing shell commands) - In essence, does anyone have a "cleaner" solution?</p> <p>Ideally, executing commands using would be a last resort..</p>
[ { "answer_id": 160907, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": -1, "selected": false, "text": "<p>Make sure that you have the statement </p>\n\n<pre><code>use IO::Socket::INET;\n</code></pre>\n\n<p>At the beginning of your source code. If you leave this out, you are probably getting the error message:</p>\n\n<blockquote>\n <p>Can't locate object method \"new\" via\n package \"IO::Socket::INET\"</p>\n</blockquote>\n\n<p>Beyond that you might verify that DNS is working using Net::DNS::Resoler, see more information <a href=\"http://search.cpan.org/~olaf/Net-DNS-0.63/lib/Net/DNS/Resolver.pm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>use Net::DNS;\n\nmy $res = Net::DNS::Resolver-&gt;new;\n\n# Perform a lookup, using the searchlist if appropriate.\nmy $answer = $res-&gt;search('example.com');\n</code></pre>\n" }, { "answer_id": 160964, "author": "tye", "author_id": 21496, "author_profile": "https://Stackoverflow.com/users/21496", "pm_score": 4, "selected": true, "text": "<p>From a quick look, the following code from IO::Socket::INET</p>\n\n<pre><code>sub _get_addr {\n my($sock,$addr_str, $multi) = @_;\n my @addr;\n if ($multi &amp;&amp; $addr_str !~ /^\\d+(?:\\.\\d+){3}$/) {\n (undef, undef, undef, undef, @addr) = gethostbyname($addr_str);\n } else {\n my $h = inet_aton($addr_str);\n push(@addr, $h) if defined $h;\n }\n @addr;\n}\n</code></pre>\n\n<p>suggests (if you look at the caller of this code) the work-around of adding <code>MultiHomed =&gt; 1,</code> to your code.</p>\n\n<p>Without that work-around, the above code appears to try to call <code>inet_aton(\"hostname.com\")</code> using the inet_aton() from Socket.pm. That works for me in both Win32 and Unix, so I guess that is where the breakage lies for you.</p>\n\n<p>See <a href=\"http://search.cpan.org/src/TOMC/Socket-1.5/Socket.xs\" rel=\"noreferrer\">Socket.xs</a> for the source code of inet_aton:</p>\n\n<pre><code>void\ninet_aton(host)\n char * host\n CODE:\n {\n struct in_addr ip_address;\n struct hostent * phe;\n\n if (phe = gethostbyname(host)) {\n Copy( phe-&gt;h_addr, &amp;ip_address, phe-&gt;h_length, char );\n } else {\n ip_address.s_addr = inet_addr(host);\n }\n\n ST(0) = sv_newmortal();\n if(ip_address.s_addr != INADDR_NONE) {\n sv_setpvn( ST(0), (char *)&amp;ip_address, sizeof ip_address );\n }\n }\n</code></pre>\n\n<p>It appears that the Perl gethostbyname() works better than the C gethostbyname() for you.</p>\n" }, { "answer_id": 175085, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>Could you perhaps tells us exactly <strong>how</strong> your code fails? You've got error checking code in there but you haven't reported what the error is!</p>\n\n<p>I've just tried the original code (with the addition of the \"use IO::Socket::INET\" on my Mac OS X machine and it works fine.</p>\n\n<p>I suspect that the Multihomed option is an unnecessary hack and some other issue is the root cause of your problem.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18471/" ]
So this is a question for anyone who has had to integrate the building/compilation of legacy projects/code in a Team Build/MSBuild environment - specifically, Visual Basic 6 applications/projects. *Outside* of writing a custom build Task (which I am not against) does anyone have any suggestions on how best to integrate compilation and versioning of legacy VB6 projects into MSBuild builds? I'm aware of the FreeToDev msbuild tasks at [CodePlex](http://www.codeplex.com/freetodevtasks) but they've been withdrawn at the moment. Ideally I'm looking to version and compile the code as well as capture the compilation output (especially errors) for the msbuild log. I've seen advice on encapsulating this functionality in a custom task, but really wondered if anyone has tried another solution (aside from executing shell commands) - In essence, does anyone have a "cleaner" solution? Ideally, executing commands using would be a last resort..
From a quick look, the following code from IO::Socket::INET ``` sub _get_addr { my($sock,$addr_str, $multi) = @_; my @addr; if ($multi && $addr_str !~ /^\d+(?:\.\d+){3}$/) { (undef, undef, undef, undef, @addr) = gethostbyname($addr_str); } else { my $h = inet_aton($addr_str); push(@addr, $h) if defined $h; } @addr; } ``` suggests (if you look at the caller of this code) the work-around of adding `MultiHomed => 1,` to your code. Without that work-around, the above code appears to try to call `inet_aton("hostname.com")` using the inet\_aton() from Socket.pm. That works for me in both Win32 and Unix, so I guess that is where the breakage lies for you. See [Socket.xs](http://search.cpan.org/src/TOMC/Socket-1.5/Socket.xs) for the source code of inet\_aton: ``` void inet_aton(host) char * host CODE: { struct in_addr ip_address; struct hostent * phe; if (phe = gethostbyname(host)) { Copy( phe->h_addr, &ip_address, phe->h_length, char ); } else { ip_address.s_addr = inet_addr(host); } ST(0) = sv_newmortal(); if(ip_address.s_addr != INADDR_NONE) { sv_setpvn( ST(0), (char *)&ip_address, sizeof ip_address ); } } ``` It appears that the Perl gethostbyname() works better than the C gethostbyname() for you.
160,889
<p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p> <p>One example:</p> <p>I have to get all href tags, their corresponding text and some other text based on a different regex. So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p> <p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides an elegant way to do this by executing "actions" based on expressions. One can control the way lex reading a file too (block / line based read).</p> <p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a make file which wraps all these things. I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything I like in a single programming language itself.</p> <p>Tokenizing is just one of the things that I want to do as part of my application.</p> <p>Apart from perl or python can any language (functional also) do this?</p> <p>I did read about PLY and ANTLR here (<a href="https://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">Parsing, where can I learn about it</a>).</p> <p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p> <p>Thank you.</p>
[ { "answer_id": 160895, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 2, "selected": false, "text": "<p>Have you looked at <a href=\"http://pyparsing.wikispaces.com/\" rel=\"nofollow noreferrer\">PyParsing</a>?</p>\n\n<p>From their homepage:</p>\n\n<p>Here is a program to parse \"Hello, World!\" (or any greeting of the form \", !\"):</p>\n\n<pre><code>from pyparsing import Word, alphas\ngreet = Word( alphas ) + \",\" + Word( alphas ) + \"!\" # &lt;-- grammar defined here\nhello = \"Hello, World!\"\nprint hello, \"-&gt;\", greet.parseString( hello )\n</code></pre>\n\n<p>The program outputs the following:</p>\n\n<pre><code>Hello, World! -&gt; ['Hello', ',', 'World', '!']\n</code></pre>\n" }, { "answer_id": 160896, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 3, "selected": false, "text": "<p>Sounds like you really just want to parse HTML, I recommend looking at any of the wonderful packages for doing so:</p>\n\n<ul>\n<li><a href=\"http://crummy.com/software/BeautifulSoup\" rel=\"nofollow noreferrer\">BeautifulSoup</a></li>\n<li><a href=\"http://codespeak.net/lxml/lxmlhtml.html\" rel=\"nofollow noreferrer\">lxml.html</a></li>\n<li><a href=\"http://code.google.com/p/html5lib/\" rel=\"nofollow noreferrer\">html5lib</a></li>\n</ul>\n\n<p>Or! You can use a parser like one of the following:</p>\n\n<ul>\n<li><a href=\"http://pyparsing.wikispaces.com\" rel=\"nofollow noreferrer\">PyParsing</a></li>\n<li><a href=\"http://dparser.sourceforge.net/\" rel=\"nofollow noreferrer\">DParser</a> - A GLR parser with good python bindings.</li>\n<li><a href=\"http://www.antlr.org\" rel=\"nofollow noreferrer\">ANTLR</a> - A recursive decent parser generator that can generate python code.</li>\n</ul>\n\n<p>This example is from the BeautifulSoup <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html\" rel=\"nofollow noreferrer\">Documentation</a>:</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup, SoupStrainer\nimport re\n\nlinks = SoupStrainer('a')\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=links)]\n# [&lt;a href=\"http://www.bob.com/\"&gt;success&lt;/a&gt;, \n# &lt;a href=\"http://www.bob.com/plasma\"&gt;experiments&lt;/a&gt;, \n# &lt;a href=\"http://www.boogabooga.net/\"&gt;BoogaBooga&lt;/a&gt;]\n\nlinksToBob = SoupStrainer('a', href=re.compile('bob.com/'))\n[tag for tag in BeautifulSoup(doc, parseOnlyThese=linksToBob)]\n# [&lt;a href=\"http://www.bob.com/\"&gt;success&lt;/a&gt;, \n# &lt;a href=\"http://www.bob.com/plasma\"&gt;experiments&lt;/a&gt;]\n</code></pre>\n" }, { "answer_id": 160922, "author": "slashmais", "author_id": 15161, "author_profile": "https://Stackoverflow.com/users/15161", "pm_score": 3, "selected": false, "text": "<p>Look at documentation for following modules on <a href=\"http://www.cpan.org/\" rel=\"nofollow noreferrer\">CPAN</a></p>\n\n<p><a href=\"http://search.cpan.org/search?query=HTML%3A%3ATreeBuilder&amp;mode=all\" rel=\"nofollow noreferrer\">HTML::TreeBuilder</a></p>\n\n<p><a href=\"http://search.cpan.org/author/MSISK/HTML-TableExtract-2.10/lib/HTML/TableExtract.pm\" rel=\"nofollow noreferrer\">HTML::TableExtract</a></p>\n\n<p>and</p>\n\n<p><a href=\"http://search.cpan.org/search?query=parse+recdescent&amp;mode=all\" rel=\"nofollow noreferrer\">Parse::RecDescent</a></p>\n\n<p>I've used these modules to process quite large and complex web-pages.</p>\n" }, { "answer_id": 161146, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 4, "selected": true, "text": "<p>If you're specifically after parsing links out of web-pages, then Perl's <a href=\"http://search.cpan.org/perldoc?WWW::Mechanize\" rel=\"nofollow noreferrer\">WWW::Mechanize</a> module will figure things out for you in a very elegant fashion. Here's a sample program that grabs the first page of Stack Overflow and parses out all the links, printing their text and corresponding URLs:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse WWW::Mechanize;\n\nmy $mech = WWW::Mechanize-&gt;new;\n\n$mech-&gt;get(\"http://stackoverflow.com/\");\n\n$mech-&gt;success or die \"Oh no! Couldn't fetch stackoverflow.com\";\n\nforeach my $link ($mech-&gt;links) {\n print \"* [\",$link-&gt;text, \"] points to \", $link-&gt;url, \"\\n\";\n}\n</code></pre>\n\n<p>In the main loop, each <code>$link</code> is a <a href=\"http://search.cpan.org/perldoc?WWW::Mechanize::Link\" rel=\"nofollow noreferrer\">WWW::Mechanize::Link</a> object, so you're not just constrained to getting the text and URL.</p>\n\n<p>All the best,</p>\n\n<p>Paul</p>\n" }, { "answer_id": 161372, "author": "Corion", "author_id": 11253, "author_profile": "https://Stackoverflow.com/users/11253", "pm_score": 2, "selected": false, "text": "<p>If your problem has anything at all to do with web scraping, I recommend looking at <a href=\"http://search.cpan.org/perldoc?Web::Scraper\" rel=\"nofollow noreferrer\">Web::Scraper</a> , which provides easy element selection via XPath respectively CSS selectors. I have a (German) <a href=\"http://datenzoo.de/pub/gpw2008/web-scraper/web-scraper-talk.html\" rel=\"nofollow noreferrer\">talk on Web::Scraper</a> , but if you run it through babelfish or just look at the code samples, that can help you to get a quick overview of the syntax.</p>\n\n<p>Hand-parsing HTML is onerous and won't give you much over using one of the premade HTML parsers. If your HTML is of very limited variation, you can get by by using clever regular expressions, but if you're already breaking out hard-core parser tools, it sounds as if your HTML is far more regular than what is sane to parse with regular expressions.</p>\n" }, { "answer_id": 161977, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "<p>Also check out <a href=\"http://search.cpan.org/dist/pQuery/\" rel=\"nofollow noreferrer\">pQuery</a> it as a really nice Perlish way of doing this kind of stuff....</p>\n\n<pre><code>use pQuery;\n\npQuery( 'http://www.perl.com' )-&gt;find( 'a' )-&gt;each( \n sub {\n my $pQ = pQuery( $_ ); \n say $pQ-&gt;text, ' -&gt; ', $pQ-&gt;toHtml;\n }\n);\n\n# prints all HTML anchors on www.perl.com\n# =&gt; link text -&gt; anchor HTML\n</code></pre>\n\n<p>However if your requirement is beyond HTML/Web then here is the earlier \"Hello World!\" example in <a href=\"http://search.cpan.org/dist/Parse-RecDescent/lib/Parse/RecDescent.pm\" rel=\"nofollow noreferrer\">Parse::RecDescent</a>...</p>\n\n<pre><code>use strict;\nuse warnings;\nuse Parse::RecDescent;\n\nmy $grammar = q{\n alpha : /\\w+/\n sep : /,|\\s/\n end : '!'\n greet : alpha sep alpha end { shift @item; return \\@item }\n};\n\nmy $parse = Parse::RecDescent-&gt;new( $grammar );\nmy $hello = \"Hello, World!\";\nprint \"$hello -&gt; @{ $parse-&gt;greet( $hello ) }\";\n\n# =&gt; Hello, World! -&gt; Hello , World !\n</code></pre>\n\n<p>Probably too much of a large hammer to crack this nut ;-)</p>\n" }, { "answer_id": 162301, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators\" rel=\"nofollow noreferrer\">perlop</a>:</p>\n\n<blockquote>\n <p>A useful idiom for lex -like scanners\n is <code>/\\G.../gc</code> . You can combine\n several regexps like this to process a\n string part-by-part, doing different\n actions depending on which regexp\n matched. Each regexp tries to match\n where the previous one leaves off.</p>\n\n<pre><code> LOOP:\n {\n print(\" digits\"), redo LOOP if /\\G\\d+\\b[,.;]?\\s*/gc;\n print(\" lowercase\"), redo LOOP if /\\G[a-z]+\\b[,.;]?\\s*/gc;\n print(\" UPPERCASE\"), redo LOOP if /\\G[A-Z]+\\b[,.;]?\\s*/gc;\n print(\" Capitalized\"), redo LOOP if /\\G[A-Z][a-z]+\\b[,.;]?\\s*/gc;\n print(\" MiXeD\"), redo LOOP if /\\G[A-Za-z]+\\b[,.;]?\\s*/gc;\n print(\" alphanumeric\"), redo LOOP if /\\G[A-Za-z0-9]+\\b[,.;]?\\s*/gc;\n print(\" line-noise\"), redo LOOP if /\\G[^A-Za-z0-9]+/gc;\n print \". That's all!\\n\";\n }\n</code></pre>\n</blockquote>\n" }, { "answer_id": 172371, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "<p>Modifying Bruno's example to include error checking:</p>\n\n<pre><code>my $input = \"...\";\nwhile (1) {\n if ($input =~ /\\G(\\w+)/gc) { print \"word: '$1'\\n\"; next }\n if ($input =~ /\\G(\\s+)/gc) { print \"whitespace: '$1'\\n\"; next }\n\n if ($input !~ /\\G\\z/gc) { print \"tokenizing error at character \" . pos($input) . \"\\n\" }\n print \"done!\\n\"; last;\n}\n</code></pre>\n\n<p>(Note that using scalar //g is unfortunately the one place where you really can't avoid using the $1, etc. variables.)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes? One example: I have to get all href tags, their corresponding text and some other text based on a different regex. So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression. I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides an elegant way to do this by executing "actions" based on expressions. One can control the way lex reading a file too (block / line based read). The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a make file which wraps all these things. I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything I like in a single programming language itself. Tokenizing is just one of the things that I want to do as part of my application. Apart from perl or python can any language (functional also) do this? I did read about PLY and ANTLR here ([Parsing, where can I learn about it](https://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085)). But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services? Thank you.
If you're specifically after parsing links out of web-pages, then Perl's [WWW::Mechanize](http://search.cpan.org/perldoc?WWW::Mechanize) module will figure things out for you in a very elegant fashion. Here's a sample program that grabs the first page of Stack Overflow and parses out all the links, printing their text and corresponding URLs: ``` #!/usr/bin/perl use strict; use warnings; use WWW::Mechanize; my $mech = WWW::Mechanize->new; $mech->get("http://stackoverflow.com/"); $mech->success or die "Oh no! Couldn't fetch stackoverflow.com"; foreach my $link ($mech->links) { print "* [",$link->text, "] points to ", $link->url, "\n"; } ``` In the main loop, each `$link` is a [WWW::Mechanize::Link](http://search.cpan.org/perldoc?WWW::Mechanize::Link) object, so you're not just constrained to getting the text and URL. All the best, Paul
160,890
<p>I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:</p> <pre><code>Random.nextInt(74) </code></pre> <p>I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.</p>
[ { "answer_id": 160910, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Same as C, you would do</p>\n\n<pre><code>#include &lt;time.h&gt;\n#include &lt;stdlib.h&gt;\n...\nsrand(time(NULL));\nint r = rand() % 74;\n</code></pre>\n\n<p>(assuming you meant including 0 but excluding 74, which is what your Java example does)</p>\n\n<p><strong>Edit:</strong> Feel free to substitute <code>random()</code> or <code>arc4random()</code> for <code>rand()</code> (which is, as others have pointed out, quite sucky).</p>\n" }, { "answer_id": 161141, "author": "Michael Buckley", "author_id": 22540, "author_profile": "https://Stackoverflow.com/users/22540", "pm_score": 5, "selected": false, "text": "<p>According to the manual page for rand(3), the rand family of functions have been obsoleted by random(3). This is due to the fact that the lower 12 bits of rand() go through a cyclic pattern. To get a random number, just seed the generator by calling srandom() with an unsigned seed, and then call random(). So, the equivalent of the code above would be</p>\n\n<pre><code>#import &lt;stdlib.h&gt;\n#import &lt;time.h&gt;\n\nsrandom(time(NULL));\nrandom() % 74;\n</code></pre>\n\n<p>You'll only need to call srandom() once in your program unless you want to change your seed. Although you said you didn't want a discussion of truly random values, rand() is a pretty bad random number generator, and random() still suffers from modulo bias, as it will generate a number between 0 and RAND_MAX. So, e.g. if RAND_MAX is 3, and you want a random number between 0 and 2, you're twice as likely to get a 0 than a 1 or a 2.</p>\n" }, { "answer_id": 163178, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 11, "selected": true, "text": "<p>You should use the <code>arc4random_uniform()</code> function. It uses a superior algorithm to <code>rand</code>. You don't even need to set a seed.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n// ...\n// ...\nint r = arc4random_uniform(74);\n</code></pre>\n\n<p>The <code>arc4random</code> man page:</p>\n\n<blockquote>\n<pre><code>NAME\n arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator\n\nLIBRARY\n Standard C Library (libc, -lc)\n\nSYNOPSIS\n #include &lt;stdlib.h&gt;\n\n u_int32_t\n arc4random(void);\n\n void\n arc4random_stir(void);\n\n void\n arc4random_addrandom(unsigned char *dat, int datlen);\n\nDESCRIPTION\n The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8\n bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo-\n random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and\n random(3).\n\n The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via\n arc4random_addrandom().\n\n There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically\n initializes itself.\n\nEXAMPLES\n The following produces a drop-in replacement for the traditional rand() and random() functions using\n arc4random():\n\n #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))\n</code></pre>\n</blockquote>\n" }, { "answer_id": 2151334, "author": "Eli", "author_id": 117588, "author_profile": "https://Stackoverflow.com/users/117588", "pm_score": 4, "selected": false, "text": "<p>I wrote my own random number utility class just so that I would have something that functioned a bit more like Math.random() in Java. It has just two functions, and it's all made in C.</p>\n\n<p>Header file:</p>\n\n<pre><code>//Random.h\nvoid initRandomSeed(long firstSeed);\nfloat nextRandomFloat();\n</code></pre>\n\n<p>Implementation file:</p>\n\n<pre><code>//Random.m\nstatic unsigned long seed;\n\nvoid initRandomSeed(long firstSeed)\n{ \n seed = firstSeed;\n}\n\nfloat nextRandomFloat()\n{\n return (((seed= 1664525*seed + 1013904223)&gt;&gt;16) / (float)0x10000);\n}\n</code></pre>\n\n<p>It's a pretty classic way of generating pseudo-randoms. In my app delegate I call:</p>\n\n<pre><code>#import \"Random.h\"\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application\n{\n initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );\n //Do other initialization junk.\n}\n</code></pre>\n\n<p>Then later I just say:</p>\n\n<pre><code>float myRandomNumber = nextRandomFloat() * 74;\n</code></pre>\n\n<p>Note that this method returns a random number between 0.0f (inclusive) and 1.0f (exclusive).</p>\n" }, { "answer_id": 7082580, "author": "yood", "author_id": 31605, "author_profile": "https://Stackoverflow.com/users/31605", "pm_score": 9, "selected": false, "text": "<p>Use the <code>arc4random_uniform(upper_bound)</code> function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.</p>\n\n<pre><code>arc4random_uniform(74)\n</code></pre>\n\n<p><code>arc4random_uniform(upper_bound)</code> avoids <a href=\"https://stackoverflow.com/a/10984975/85950\">modulo bias</a> as described in the man page:</p>\n\n<blockquote>\n <p>arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids \"<a href=\"https://stackoverflow.com/a/10984975/85950\">modulo bias</a>\" when the upper bound is not a power of two.</p>\n</blockquote>\n" }, { "answer_id": 9310745, "author": "Tibidabo", "author_id": 649610, "author_profile": "https://Stackoverflow.com/users/649610", "pm_score": 5, "selected": false, "text": "<p>This will give you a <strong>floating point</strong> number between 0 and 47</p>\n\n<pre><code>float low_bound = 0; \nfloat high_bound = 47;\nfloat rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);\n</code></pre>\n\n<p>Or just simply</p>\n\n<pre><code>float rndValue = (((float)arc4random()/0x100000000)*47);\n</code></pre>\n\n<p>Both lower and upper bound can be <strong>negative</strong> as well. The example code below gives you a random number between -35.76 and +12.09</p>\n\n<pre><code>float low_bound = -35.76; \nfloat high_bound = 12.09;\nfloat rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);\n</code></pre>\n\n<p>Convert result to a rounder <strong>Integer</strong> value:</p>\n\n<pre><code>int intRndValue = (int)(rndValue + 0.5);\n</code></pre>\n" }, { "answer_id": 11101096, "author": "AW101", "author_id": 1321931, "author_profile": "https://Stackoverflow.com/users/1321931", "pm_score": 5, "selected": false, "text": "<p>Better to use <code>arc4random_uniform</code>. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).</p>\n\n<p>The best way to determine if <code>arc4random_uniform</code> is available is to do something like this:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n\nint r = 0;\nif (arc4random_uniform != NULL)\n r = arc4random_uniform (74);\nelse\n r = (arc4random() % 74);\n</code></pre>\n" }, { "answer_id": 17193450, "author": "Groot", "author_id": 1075405, "author_profile": "https://Stackoverflow.com/users/1075405", "pm_score": 6, "selected": false, "text": "<p>I thought I could add a method I use in many projects.</p>\n\n<pre><code>- (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {\n return (NSInteger)(min + arc4random_uniform(max - min + 1));\n}\n</code></pre>\n\n<p>If I end up using it in many files I usually declare a macro as</p>\n\n<pre><code>#define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))\n</code></pre>\n\n<p>E.g.</p>\n\n<pre><code>NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74\n</code></pre>\n\n<p><strong>Note: Only for iOS 4.3/OS&nbsp;X&nbsp;v10.7 (Lion) and later</strong></p>\n" }, { "answer_id": 28693353, "author": "adijazz91", "author_id": 3820802, "author_profile": "https://Stackoverflow.com/users/3820802", "pm_score": 2, "selected": false, "text": "<p>Generate random number between 0 to 99:</p>\n\n<pre><code>int x = arc4random()%100;\n</code></pre>\n\n<p>Generate random number between 500 and 1000:</p>\n\n<pre><code>int x = (arc4random()%501) + 500;\n</code></pre>\n" }, { "answer_id": 30171545, "author": "Tom Howard", "author_id": 1803879, "author_profile": "https://Stackoverflow.com/users/1803879", "pm_score": 3, "selected": false, "text": "<p>There are some great, articulate answers already, but the question asks for a random number between 0 and 74. Use:</p>\n\n<p><code>arc4random_uniform(75)</code></p>\n" }, { "answer_id": 32840929, "author": "soumya", "author_id": 4169569, "author_profile": "https://Stackoverflow.com/users/4169569", "pm_score": 2, "selected": false, "text": "<p>//The following example is going to generate a number between 0 and 73.</p>\n\n<pre><code>int value;\nvalue = (arc4random() % 74);\nNSLog(@\"random number: %i \", value);\n\n//In order to generate 1 to 73, do the following:\nint value1;\nvalue1 = (arc4random() % 73) + 1;\nNSLog(@\"random number step 2: %i \", value1);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<ul>\n<li><p>random number: <strong>72</strong> </p></li>\n<li><p>random number step 2: <strong>52</strong> </p></li>\n</ul>\n" }, { "answer_id": 34371277, "author": "TwoStraws", "author_id": 5041820, "author_profile": "https://Stackoverflow.com/users/5041820", "pm_score": 2, "selected": false, "text": "<p>As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.</p>\n\n<p>You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.</p>\n\n<p>At the simplest level, you can generate a random number from the system's built-in random source like this:</p>\n\n<pre><code>NSInteger rand = [[GKRandomSource sharedRandom] nextInt];\n</code></pre>\n\n<p>That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:</p>\n\n<pre><code>NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];\n</code></pre>\n\n<p>GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:</p>\n\n<pre><code>GKRandomDistribution *d6 = [GKRandomDistribution d6];\n[d6 nextInt];\n</code></pre>\n\n<p>Plus you can shape the random distribution by using things like <code>GKShuffledDistribution</code>.</p>\n" }, { "answer_id": 38388107, "author": "Robert Wasmann", "author_id": 1927253, "author_profile": "https://Stackoverflow.com/users/1927253", "pm_score": 1, "selected": false, "text": "<p>For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:</p>\n\n<pre><code>static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}\nstatic inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}\nstatic inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method: ``` Random.nextInt(74) ``` I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.
You should use the `arc4random_uniform()` function. It uses a superior algorithm to `rand`. You don't even need to set a seed. ``` #include <stdlib.h> // ... // ... int r = arc4random_uniform(74); ``` The `arc4random` man page: > > > ``` > NAME > arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator > > LIBRARY > Standard C Library (libc, -lc) > > SYNOPSIS > #include <stdlib.h> > > u_int32_t > arc4random(void); > > void > arc4random_stir(void); > > void > arc4random_addrandom(unsigned char *dat, int datlen); > > DESCRIPTION > The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8 > bit S-Boxes. The S-Boxes can be in about (2**1700) states. The arc4random() function returns pseudo- > random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and > random(3). > > The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via > arc4random_addrandom(). > > There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically > initializes itself. > > EXAMPLES > The following produces a drop-in replacement for the traditional rand() and random() functions using > arc4random(): > > #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1)) > > ``` > >
160,905
<p>I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields.</p> <p>Here's my models.py:</p> <pre><code>class Tech(models.Model): name = models.CharField(max_length = 30) class Project(models.Model): title = models.CharField(max_length = 50) techs = models.ManyToManyField(Tech) </code></pre> <p>In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server)</p> <p>However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py:</p> <pre><code>class TechInline(admin.TabularInline): model = Tech extra = 5 class ProjectAdmin(admin.ModelAdmin): fields = ['title'] inlines = [] list_display = ('title') admin.site.register(Project, ProjectAdmin) </code></pre> <p>I've tried adding the <code>TechInline</code> class to the <code>inlines</code> list, but that causes a </p> <pre><code>&lt;class 'home.projects.models.Tech'&gt; has no ForeignKey to &lt;class 'home.projects.models.Project'&gt; </code></pre> <p>Error. Also tried adding <code>techs</code> to the <code>fields</code> list, but that gives a </p> <blockquote> <p>no such table: projects_project_techs</p> </blockquote> <p>Error. I verified, and there is no <code>projects_project_techs</code> table, but there is a <code>projects_tech</code> one. Did something perhaps get screwed up in my syncdb? </p> <p>I am using Sqlite as my database if that helps.</p>
[ { "answer_id": 160916, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>I've tried adding the TechInline class to the inlines list, but that causes a</p>\n \n <p>'TechInLine' not defined</p>\n</blockquote>\n\n<p>Is that a straight copy-paste? It looks like you just made a typo -- try <code>TechInline</code> instead of <code>TechInLine</code>.</p>\n\n<p>If your syncdb didn't create the proper table, you can do it manually. Execute this command:</p>\n\n<pre><code>python manage.py sqlreset &lt;myapp&gt;\n</code></pre>\n\n<p>And look for the definition for the <code>projects_project_techs</code> table. Copy and paste it into the client for your database.</p>\n" }, { "answer_id": 161500, "author": "Andrew Ingram", "author_id": 15687, "author_profile": "https://Stackoverflow.com/users/15687", "pm_score": 0, "selected": false, "text": "<p>Assuming your app is called \"projects\", the default name for your techs table will be projects_tech and the projects table will be projects_project.</p>\n\n<p>The many-to-many table should be something like projects_project_techs</p>\n" }, { "answer_id": 162932, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 0, "selected": false, "text": "<p>@John Millikin - Thanks for the sqlreset tip, that put me on the right path. The sqlreset generated code that showed me that the <code>projects_project_techs</code> was never actually created. I ended up just deleting my deb.db database and regenerating it. <code>techs</code> then showed up as it should. </p>\n\n<p>And just as a sidenote, I had to do an <code>admin.site.register(Tech)</code> to be able to create new instances of the class from the Project page too.</p>\n\n<p>I'll probably post another question to see if there is a better way to implement model changes (since I'm pretty sure that is what caused my problem) without wiping the database.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
I'm working on what I think is a pretty standard django site, but am having trouble getting my admin section to display the proper fields. Here's my models.py: ``` class Tech(models.Model): name = models.CharField(max_length = 30) class Project(models.Model): title = models.CharField(max_length = 50) techs = models.ManyToManyField(Tech) ``` In other words, a Project can have different Tech objects and different tech objects can belong to different Projects (Project X was created with Python and Django, Project Y was C# and SQL Server) However, the admin site doesn't display any UI for the Tech objects. Here's my admin.py: ``` class TechInline(admin.TabularInline): model = Tech extra = 5 class ProjectAdmin(admin.ModelAdmin): fields = ['title'] inlines = [] list_display = ('title') admin.site.register(Project, ProjectAdmin) ``` I've tried adding the `TechInline` class to the `inlines` list, but that causes a ``` <class 'home.projects.models.Tech'> has no ForeignKey to <class 'home.projects.models.Project'> ``` Error. Also tried adding `techs` to the `fields` list, but that gives a > > no such table: projects\_project\_techs > > > Error. I verified, and there is no `projects_project_techs` table, but there is a `projects_tech` one. Did something perhaps get screwed up in my syncdb? I am using Sqlite as my database if that helps.
> > I've tried adding the TechInline class to the inlines list, but that causes a > > > 'TechInLine' not defined > > > Is that a straight copy-paste? It looks like you just made a typo -- try `TechInline` instead of `TechInLine`. If your syncdb didn't create the proper table, you can do it manually. Execute this command: ``` python manage.py sqlreset <myapp> ``` And look for the definition for the `projects_project_techs` table. Copy and paste it into the client for your database.
160,923
<p>I am pretty sure I have seen this before, but I haven't found out / remembered how to do it. I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line. </p> <p>Something like:</p> <pre><code>FooBar := Foo(Bar); SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attached WriteLn('Value: ' + FooBar); </code></pre> <p>Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want. It is for some demonstration code.</p> <p>Thanks in advance!</p>
[ { "answer_id": 160993, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": 6, "selected": true, "text": "<p>To trigger the debugger from code (supposedly, I don't have a copy of delphi handy to try):</p>\n\n<pre><code>asm int 3 end;\n</code></pre>\n\n<p>See this page:</p>\n\n<p><a href=\"http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html\" rel=\"noreferrer\">http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html</a></p>\n" }, { "answer_id": 161047, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": false, "text": "<p>As Andreas Hausladen stated in comments to that artice, Win32 API DebugBreak() function is less DOS-ish and works equally well.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255/" ]
I am pretty sure I have seen this before, but I haven't found out / remembered how to do it. I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line. Something like: ``` FooBar := Foo(Bar); SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attached WriteLn('Value: ' + FooBar); ``` Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want. It is for some demonstration code. Thanks in advance!
To trigger the debugger from code (supposedly, I don't have a copy of delphi handy to try): ``` asm int 3 end; ``` See this page: <http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html>
160,924
<p>Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this:</p> <pre><code>jeremy@jeremy-desktop:~$ ps aux | grep firefox jeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefox jeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefox jeremy@jeremy-desktop:~$ kill 7451 </code></pre> <p>What I'd like is a command that would do all that for me. It would take an input string and <code>grep</code> for it (or whatever) in the list of processes, and would kill all the processes in the output:</p> <pre><code>jeremy@jeremy-desktop:~$ killbyname firefox </code></pre> <p>I tried doing it in PHP but <code>exec('ps aux')</code> seems to only show processes that have been executed with <code>exec()</code> in the PHP script itself (so the only process it shows is itself.)</p>
[ { "answer_id": 160926, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 10, "selected": true, "text": "<pre><code>pkill firefox\n</code></pre>\n\n<p>More information: <a href=\"http://linux.about.com/library/cmd/blcmdl1_pkill.htm\" rel=\"noreferrer\">http://linux.about.com/library/cmd/blcmdl1_pkill.htm</a></p>\n" }, { "answer_id": 160928, "author": "Bittercoder", "author_id": 4843, "author_profile": "https://Stackoverflow.com/users/4843", "pm_score": 3, "selected": false, "text": "<p>I normally use the <code>killall</code> command.</p>\n\n<p><a href=\"http://linux.die.net/man/1/killall\" rel=\"nofollow noreferrer\">Check this link</a> for details of this command.</p>\n" }, { "answer_id": 160950, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 6, "selected": false, "text": "<p>You can kill processes by <em>name</em> with <a href=\"http://linux.die.net/man/1/killall\" rel=\"noreferrer\"><code>killall &lt;name&gt;</code></a></p>\n\n<blockquote>\n <p><strong>killall</strong> sends a signal to all\n processes running any of the specified\n commands. If no signal name is\n specified, SIGTERM is sent.</p>\n \n <p>Signals can be specified either by\n name (e.g. <strong>-HUP</strong> or <strong>-SIGHUP</strong> ) or by number (e.g.\n <strong>-1</strong>) or by option <strong>-s</strong>.</p>\n \n <p>If the command name is not regular\n expression (option <strong>-r</strong>) and contains a\n slash (/), processes executing that\n particular file will be selected for\n killing, independent of their name.</p>\n</blockquote>\n\n<p>But if you don't see the process with <code>ps aux</code>, you probably won't have the right to kill it ...</p>\n" }, { "answer_id": 161023, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>If you run GNOME, you can use the system monitor (System->Administration->System Monitor) to kill processes as you would under Windows. KDE will have something similar.</p>\n" }, { "answer_id": 163335, "author": "Walter", "author_id": 23840, "author_profile": "https://Stackoverflow.com/users/23840", "pm_score": 6, "selected": false, "text": "<p>A bit longer alternative:</p>\n\n<pre><code>kill `pidof firefox`\n</code></pre>\n" }, { "answer_id": 15014271, "author": "Dhiraj", "author_id": 1701261, "author_profile": "https://Stackoverflow.com/users/1701261", "pm_score": 4, "selected": false, "text": "<p>On Mac I could not find the pgrep and pkill neither was killall working so wrote a simple one liner script:-</p>\n\n<pre><code>export pid=`ps | grep process_name | awk 'NR==1{print $1}' | cut -d' ' -f1`;kill $pid\n</code></pre>\n\n<p>If there's an easier way of doing this then please share.</p>\n" }, { "answer_id": 16621797, "author": "user2396265", "author_id": 2396265, "author_profile": "https://Stackoverflow.com/users/2396265", "pm_score": 4, "selected": false, "text": "<p>Using <code>killall</code> command:</p>\n<pre><code>killall processname\n</code></pre>\n<p>Use <code>-9</code> or <code>-KILL</code> to forcefully kill the program (the options are similar to the <code>kill</code> command).</p>\n" }, { "answer_id": 23823738, "author": "Chadiso", "author_id": 1847117, "author_profile": "https://Stackoverflow.com/users/1847117", "pm_score": 3, "selected": false, "text": "<p>more correct would be: </p>\n\n<pre><code>export pid=`ps aux | grep process_name | awk 'NR==1{print $2}' | cut -d' ' -f1`;kill -9 $pid\n</code></pre>\n" }, { "answer_id": 26938108, "author": "JayS", "author_id": 1812942, "author_profile": "https://Stackoverflow.com/users/1812942", "pm_score": 3, "selected": false, "text": "<p>To kill with grep:</p>\n\n<pre><code>kill -9 `pgrep myprocess`\n</code></pre>\n" }, { "answer_id": 27820938, "author": "Victor", "author_id": 3029603, "author_profile": "https://Stackoverflow.com/users/3029603", "pm_score": 8, "selected": false, "text": "<p>Also possible to use: </p>\n\n<pre><code>pkill -f \"Process name\"\n</code></pre>\n\n<p>For me, it worked up perfectly. It was what I have been looking for.\npkill doesn't work with name without the flag.</p>\n\n<p>When <code>-f</code> is set, the full command line is used for pattern matching. </p>\n" }, { "answer_id": 34290551, "author": "The Vee", "author_id": 1537925, "author_profile": "https://Stackoverflow.com/users/1537925", "pm_score": 2, "selected": false, "text": "<p>The default <code>kill</code> command accepts command names as an alternative to PID. See <a href=\"http://man7.org/linux/man-pages/man1/kill.1.html#ARGUMENTS\" rel=\"nofollow\">kill (1)</a>. An often occurring trouble is that <code>bash</code> provides its own <code>kill</code> which accepts job numbers, like <code>kill %1</code>, but not command names. This hinders the default command. If the former functionality is more useful to you than the latter, you can disable the <code>bash</code> version by calling</p>\n\n<p><code>enable -n kill</code></p>\n\n<p>For more info see <code>kill</code> and <code>enable</code> entries in <a href=\"http://man7.org/linux/man-pages/man1/bash.1.html#SHELL_BUILTIN%20COMMANDS\" rel=\"nofollow\">bash (1)</a>.</p>\n" }, { "answer_id": 35555148, "author": "Fab", "author_id": 5328150, "author_profile": "https://Stackoverflow.com/users/5328150", "pm_score": 2, "selected": false, "text": "<p>I was asking myself the same question but the problem with the current answers is that they don't <strong>safe check the processes to be killed</strong> so... it could lead to terrible mistakes :)... especially if <strong>several processes matches the pattern</strong>.</p>\n\n<p>As a disclaimer, I'm not a sh pro and there is certainly room for improvement.</p>\n\n<p>So I wrote a little sh script :</p>\n\n<pre><code>#!/bin/sh\n\nkillables=$(ps aux | grep $1 | grep -v mykill | grep -v grep)\nif [ ! \"${killables}\" = \"\" ]\nthen\n echo \"You are going to kill some process:\"\n echo \"${killables}\"\nelse\n echo \"No process with the pattern $1 found.\"\n return\nfi\necho -n \"Is it ok?(Y/N)\"\nread input\nif [ \"$input\" = \"Y\" ]\nthen\n for pid in $(echo \"${killables}\" | awk '{print $2}')\n do\n echo killing $pid \"...\"\n kill $pid \n echo $pid killed\n done\nfi\n</code></pre>\n" }, { "answer_id": 37167657, "author": "query_port", "author_id": 6226193, "author_profile": "https://Stackoverflow.com/users/6226193", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-none prettyprint-override\"><code>ps aux | grep processname | cut -d' ' -f7 | xargs kill -9 $\n</code></pre>\n" }, { "answer_id": 37937865, "author": "Nived Karimpunkara", "author_id": 6492721, "author_profile": "https://Stackoverflow.com/users/6492721", "pm_score": 2, "selected": false, "text": "<p>kill -9 $(ps aux | grep -e myprocessname| awk '{ print $2 }')</p>\n" }, { "answer_id": 38337778, "author": "Tahsin Turkoz", "author_id": 3618397, "author_profile": "https://Stackoverflow.com/users/3618397", "pm_score": 6, "selected": false, "text": "<p>The easiest way to do is first check you are getting right process IDs with:</p>\n<pre><code>pgrep -f [part_of_a_command]\n</code></pre>\n<p>If the result is as expected. Go with:</p>\n<pre><code>pkill -f [part_of_a_command]\n</code></pre>\n<p>If processes get stuck and are unable to accomplish the request you can use kill.</p>\n<pre><code>kill -9 $(pgrep -f [part_of_a_command])\n</code></pre>\n<p>If you want to be on the safe side and only terminate processes that you initially started add <code>-u</code> along with your username</p>\n<pre><code>pkill -f [part_of_a_command] -u [username]\n</code></pre>\n" }, { "answer_id": 39821265, "author": "prosti", "author_id": 5884955, "author_profile": "https://Stackoverflow.com/users/5884955", "pm_score": 5, "selected": false, "text": "<p>Strange, but I haven't seen the solution like this:</p>\n\n<pre><code>kill -9 `pidof firefox`\n</code></pre>\n\n<p>it can also kill multiple processes (multiple pids) like:</p>\n\n<pre><code>kill -9 `pgrep firefox`\n</code></pre>\n\n<p>I prefer <code>pidof</code> since it has single line output:</p>\n\n<pre><code>&gt; pgrep firefox\n6316\n6565\n&gt; pidof firefox\n6565 6316\n</code></pre>\n" }, { "answer_id": 43232096, "author": "Mike", "author_id": 448078, "author_profile": "https://Stackoverflow.com/users/448078", "pm_score": 5, "selected": false, "text": "<p><strong>Kill all processes having <code>snippet</code> in startup path.</strong> You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.</p>\n\n<pre><code>ps ax | grep &lt;snippet&gt; | grep -v grep | awk '{print $1}' | xargs kill\n</code></pre>\n\n<p>* I would preffer pgrep if available</p>\n" }, { "answer_id": 56791395, "author": "Andrey Bochkov", "author_id": 3629114, "author_profile": "https://Stackoverflow.com/users/3629114", "pm_score": 0, "selected": false, "text": "<p>awk oneliner, which parses the header of <code>ps</code> output, so you don't need to care about column numbers (but column names). Support regex. For example, to kill all processes, which executable name (without path) contains word \"firefox\" try</p>\n\n<pre><code>ps -fe | awk 'NR==1{for (i=1; i&lt;=NF; i++) {if ($i==\"COMMAND\") Ncmd=i; else if ($i==\"PID\") Npid=i} if (!Ncmd || !Npid) {print \"wrong or no header\" &gt; \"/dev/stderr\"; exit} }$Ncmd~\"/\"name\"$\"{print \"killing \"$Ncmd\" with PID \" $Npid; system(\"kill \"$Npid)}' name=.*firefox.*\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
Sometimes when I try to start Firefox it says "a Firefox process is already running". So I have to do this: ``` jeremy@jeremy-desktop:~$ ps aux | grep firefox jeremy 7451 25.0 27.4 170536 65680 ? Sl 22:39 1:18 /usr/lib/firefox-3.0.1/firefox jeremy 7578 0.0 0.3 3004 768 pts/0 S+ 22:44 0:00 grep firefox jeremy@jeremy-desktop:~$ kill 7451 ``` What I'd like is a command that would do all that for me. It would take an input string and `grep` for it (or whatever) in the list of processes, and would kill all the processes in the output: ``` jeremy@jeremy-desktop:~$ killbyname firefox ``` I tried doing it in PHP but `exec('ps aux')` seems to only show processes that have been executed with `exec()` in the PHP script itself (so the only process it shows is itself.)
``` pkill firefox ``` More information: <http://linux.about.com/library/cmd/blcmdl1_pkill.htm>
160,930
<p>How can I check if a given number is even or odd in C?</p>
[ { "answer_id": 160934, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 3, "selected": false, "text": "<p>I'd say just divide it by 2 and if there is a 0 remainder, it's even, otherwise it's odd.</p>\n\n<p>Using the modulus (%) makes this easy.</p>\n\n<p>eg.\n4 % 2 = 0 therefore 4 is even\n5 % 2 = 1 therefore 5 is odd</p>\n" }, { "answer_id": 160935, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 10, "selected": true, "text": "<p>Use the modulo (%) operator to check if there's a remainder when dividing by 2:</p>\n\n<pre><code>if (x % 2) { /* x is odd */ }\n</code></pre>\n\n<p>A few people have criticized my answer above stating that using x &amp; 1 is \"faster\" or \"more efficient\". I do not believe this to be the case. </p>\n\n<p>Out of curiosity, I created two trivial test case programs:</p>\n\n<pre><code>/* modulo.c */\n#include &lt;stdio.h&gt;\n\nint main(void)\n{\n int x;\n for (x = 0; x &lt; 10; x++)\n if (x % 2)\n printf(\"%d is odd\\n\", x);\n return 0;\n}\n\n/* and.c */\n#include &lt;stdio.h&gt;\n\nint main(void)\n{\n int x;\n for (x = 0; x &lt; 10; x++)\n if (x &amp; 1)\n printf(\"%d is odd\\n\", x);\n return 0;\n}\n</code></pre>\n\n<p>I then compiled these with gcc 4.1.3 on one of my machines 5 different times:</p>\n\n<ul>\n<li>With no optimization flags.</li>\n<li>With -O</li>\n<li>With -Os</li>\n<li>With -O2</li>\n<li>With -O3</li>\n</ul>\n\n<p>I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a \"new\" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment.</p>\n\n<p>If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know.</p>\n\n<p>Finally, the modulo version is <strong>guaranteed</strong> by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.</p>\n" }, { "answer_id": 160936, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<pre><code>i % 2 == 0\n</code></pre>\n" }, { "answer_id": 160942, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 7, "selected": false, "text": "<p>Use bit arithmetic:</p>\n\n<pre><code>if((x &amp; 1) == 0)\n printf(\"EVEN!\\n\");\nelse\n printf(\"ODD!\\n\");\n</code></pre>\n\n<p>This is faster than using division or modulus.</p>\n" }, { "answer_id": 160944, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 3, "selected": false, "text": "<pre><code>// C#\nbool isEven = ((i % 2) == 0);\n</code></pre>\n" }, { "answer_id": 160958, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 4, "selected": false, "text": "<p>A number is even if, when divided by two, the remainder is 0. A number is odd if, when divided by 2, the remainder is 1.</p>\n\n<pre><code>// Java\npublic static boolean isOdd(int num){\n return num % 2 != 0;\n}\n\n/* C */\nint isOdd(int num){\n return num % 2;\n}\n</code></pre>\n\n<p>Methods are great!</p>\n" }, { "answer_id": 161037, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 2, "selected": false, "text": "<p>The bitwise method depends on the inner representation of the integer. Modulo will work anywhere there is a modulo operator. For example, some systems actually use the low level bits for tagging (like dynamic languages), so the raw x &amp; 1 won't actually work in that case.</p>\n" }, { "answer_id": 161049, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 8, "selected": false, "text": "<p>You guys are waaaaaaaay too efficient. What you really want is:</p>\n\n<pre><code>public boolean isOdd(int num) {\n int i = 0;\n boolean odd = false;\n\n while (i != num) {\n odd = !odd;\n i = i + 1;\n }\n\n return odd;\n}\n</code></pre>\n\n<p>Repeat for <code>isEven</code>.</p>\n\n<p>Of course, that doesn't work for negative numbers. But with brilliance comes sacrifice...</p>\n" }, { "answer_id": 161066, "author": "eugensk", "author_id": 17495, "author_profile": "https://Stackoverflow.com/users/17495", "pm_score": 3, "selected": false, "text": "<p>One more solution to the problem<br>\n<em>(children are welcome to vote)</em></p>\n\n<pre><code>bool isEven(unsigned int x)\n{\n unsigned int half1 = 0, half2 = 0;\n while (x)\n {\n if (x) { half1++; x--; }\n if (x) { half2++; x--; }\n\n }\n return half1 == half2;\n}\n</code></pre>\n" }, { "answer_id": 161326, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 4, "selected": false, "text": "<p>In response to <a href=\"https://stackoverflow.com/questions/160930/how-do-i-check-if-an-integer-is-even-or-odd#160947\">ffpf</a> - I had exactly the same argument with a colleague years ago, and the answer is <strong>no</strong>, it doesn't work with negative numbers.</p>\n\n<p>The C standard stipulates that negative numbers can be represented in 3 ways:</p>\n\n<ul>\n<li>2's complement</li>\n<li>1's complement</li>\n<li>sign and magnitude</li>\n</ul>\n\n<p>Checking like this:</p>\n\n<pre><code>isEven = (x &amp; 1);\n</code></pre>\n\n<p>will work for 2's complement and sign and magnitude representation, but not for 1's complement.</p>\n\n<p>However, I believe that the following will work for all cases:</p>\n\n<pre><code>isEven = (x &amp; 1) ^ ((-1 &amp; 1) | ((x &lt; 0) ? 0 : 1)));\n</code></pre>\n\n<p><sup>Thanks to ffpf for pointing out that the text box was eating everything after my less than character!</sup></p>\n" }, { "answer_id": 161558, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 4, "selected": false, "text": "<p>A nice one is:</p>\n\n<pre><code>/*forward declaration, C compiles in one pass*/\nbool isOdd(unsigned int n);\n\nbool isEven(unsigned int n)\n{\n if (n == 0) \n return true ; // I know 0 is even\n else\n return isOdd(n-1) ; // n is even if n-1 is odd\n}\n\nbool isOdd(unsigned int n)\n{\n if (n == 0)\n return false ;\n else\n return isEven(n-1) ; // n is odd if n-1 is even\n}\n</code></pre>\n\n<p>Note that this method use tail recursion involving two functions. It can be implemented efficiently (turned into a while/until kind of loop) if your compiler supports tail recursion like a Scheme compiler. In this case the stack should not overflow !</p>\n" }, { "answer_id": 161739, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 2, "selected": false, "text": "<p>I know this is just syntactic sugar and <strong>only applicable in .net</strong> but what about extension method...</p>\n\n<pre><code>public static class RudiGroblerExtensions\n{\n public static bool IsOdd(this int i)\n {\n return ((i % 2) != 0);\n }\n}\n</code></pre>\n\n<p>Now you can do the following</p>\n\n<pre><code>int i = 5;\nif (i.IsOdd())\n{\n // Do something...\n}\n</code></pre>\n" }, { "answer_id": 161842, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 5, "selected": false, "text": "<p>[Joke mode=\"on\"]</p>\n\n<pre><code>public enum Evenness\n{\n Unknown = 0,\n Even = 1,\n Odd = 2\n}\n\npublic static Evenness AnalyzeEvenness(object o)\n{\n\n if (o == null)\n return Evenness.Unknown;\n\n string foo = o.ToString();\n\n if (String.IsNullOrEmpty(foo))\n return Evenness.Unknown;\n\n char bar = foo[foo.Length - 1];\n\n switch (bar)\n {\n case '0':\n case '2':\n case '4':\n case '6':\n case '8':\n return Evenness.Even;\n case '1':\n case '3':\n case '5':\n case '7':\n case '9':\n return Evenness.Odd;\n default:\n return Evenness.Unknown;\n }\n}\n</code></pre>\n\n<p>[Joke mode=\"off\"]</p>\n\n<p>EDIT: Added confusing values to the enum.</p>\n" }, { "answer_id": 162835, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>IsOdd(int x) { return true; }</p>\n\n<p>Proof of correctness - consider the set of all positive integers and suppose there is a non-empty set of integers that are not odd. Because positive integers are well-ordered, there will be a smallest not odd number, which in itself is pretty odd, so clearly that number can't be in the set. Therefore this set cannot be non-empty. Repeat for negative integers except look for the greatest not odd number.</p>\n" }, { "answer_id": 162869, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": false, "text": "<p>Portable:</p>\n\n<pre><code>i % 2 ? odd : even;\n</code></pre>\n\n<p>Unportable:</p>\n\n<pre><code>i &amp; 1 ? odd : even;\n\ni &lt;&lt; (BITS_PER_INT - 1) ? odd : even;\n</code></pre>\n" }, { "answer_id": 163188, "author": "Tooony", "author_id": 23864, "author_profile": "https://Stackoverflow.com/users/23864", "pm_score": 0, "selected": false, "text": "<p>For the sake of discussion...</p>\n\n<p>You only need to look at the last digit in any given number to see if it is even or odd. \nSigned, unsigned, positive, negative - they are all the same with regards to this.\nSo this should work all round: -</p>\n\n<pre><code>void tellMeIfItIsAnOddNumberPlease(int iToTest){\n int iLastDigit;\n iLastDigit = iToTest - (iToTest / 10 * 10);\n if (iLastDigit % 2 == 0){\n printf(\"The number %d is even!\\n\", iToTest);\n } else {\n printf(\"The number %d is odd!\\n\", iToTest);\n }\n}\n</code></pre>\n\n<p>The key here is in the third line of code, the division operator performs an integer division, so that result are missing the fraction part of the result. So for example 222 / 10 will give 22 as a result. Then multiply it again with 10 and you have 220. Subtract that from the original 222 and you end up with 2, which by magic is the same number as the last digit in the original number. ;-)\nThe parenthesis are there to remind us of the order the calculation is done in. First do the division and the multiplication, then subtract the result from the original number. We could leave them out, since the priority is higher for division and multiplication than of subtraction, but this gives us \"more readable\" code.</p>\n\n<p>We could make it all completely unreadable if we wanted to. It would make no difference whatsoever for a modern compiler: -</p>\n\n<pre><code>printf(\"%d%s\\n\",iToTest,0==(iToTest-iToTest/10*10)%2?\" is even\":\" is odd\");\n</code></pre>\n\n<p>But it would make the code way harder to maintain in the future. Just imagine that you would like to change the text for odd numbers to \"is not even\". Then someone else later on want to find out what changes you made and perform a svn diff or similar...</p>\n\n<p>If you are not worried about portability but more about speed, you could have a look at the least significant bit. If that bit is set to 1 it is an odd number, if it is 0 it's an even number. \nOn a little endian system, like Intel's x86 architecture it would be something like this: -</p>\n\n<pre><code>if (iToTest &amp; 1) {\n // Even\n} else {\n // Odd\n}\n</code></pre>\n" }, { "answer_id": 166368, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 0, "selected": false, "text": "<p>If you want to be efficient, use bitwise operators (<code>x &amp; 1</code>), but if you want to be readable use modulo 2 (<code>x % 2</code>)</p>\n" }, { "answer_id": 168834, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 2, "selected": false, "text": "<p>In the \"creative but confusing category\" I offer:</p>\n\n<pre><code>int isOdd(int n) { return n ^ n * n ? isOdd(n * n) : n; }\n</code></pre>\n\n<p>A variant on this theme that is specific to Microsoft C++:</p>\n\n<pre><code>__declspec(naked) bool __fastcall isOdd(const int x)\n{\n __asm\n {\n mov eax,ecx\n mul eax\n mul eax\n mul eax\n mul eax\n mul eax\n mul eax\n ret\n }\n}\n</code></pre>\n" }, { "answer_id": 198057, "author": "None", "author_id": 25012, "author_profile": "https://Stackoverflow.com/users/25012", "pm_score": 1, "selected": false, "text": "<pre><code>int isOdd(int i){\n return(i % 2);\n}\n</code></pre>\n\n<p>done.</p>\n" }, { "answer_id": 2345243, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 3, "selected": false, "text": "<p>I would build a table of the parities (0 if even 1 if odd) of the integers (so one could do a lookup :D), but gcc won't let me make arrays of such sizes:</p>\n\n<pre><code>typedef unsigned int uint;\n\nchar parity_uint [UINT_MAX];\nchar parity_sint_shifted [((uint) INT_MAX) + ((uint) abs (INT_MIN))];\nchar* parity_sint = parity_sint_shifted - INT_MIN;\n\nvoid build_parity_tables () {\n char parity = 0;\n unsigned int ui;\n for (ui = 1; ui &lt;= UINT_MAX; ++ui) {\n parity_uint [ui - 1] = parity;\n parity = !parity;\n }\n parity = 0;\n int si;\n for (si = 1; si &lt;= INT_MAX; ++si) {\n parity_sint [si - 1] = parity;\n parity = !parity;\n }\n parity = 1;\n for (si = -1; si &gt;= INT_MIN; --si) {\n parity_sint [si] = parity;\n parity = !parity;\n }\n}\n\nchar uparity (unsigned int n) {\n if (n == 0) {\n return 0;\n }\n return parity_uint [n - 1];\n}\n\nchar sparity (int n) {\n if (n == 0) {\n return 0;\n }\n if (n &lt; 0) {\n ++n;\n }\n return parity_sint [n - 1];\n}\n</code></pre>\n\n<p>So let's instead resort to the mathematical definition of even and odd instead.</p>\n\n<p>An integer n is even if there exists an integer k such that n = 2k.</p>\n\n<p>An integer n is odd if there exists an integer k such that n = 2k + 1.</p>\n\n<p>Here's the code for it:</p>\n\n<pre><code>char even (int n) {\n int k;\n for (k = INT_MIN; k &lt;= INT_MAX; ++k) {\n if (n == 2 * k) {\n return 1;\n }\n }\n return 0;\n}\n\nchar odd (int n) {\n int k;\n for (k = INT_MIN; k &lt;= INT_MAX; ++k) {\n if (n == 2 * k + 1) {\n return 1;\n }\n }\n return 0;\n}\n</code></pre>\n\n<p>Let C-integers denote the possible values of <code>int</code> in a given C compilation. (Note that C-integers is a subset of the integers.)</p>\n\n<p>Now one might worry that for a given n in C-integers that the corresponding integer k might not exist within C-integers. But with a little proof it is can be shown that for all integers n, |n| &lt;= |2n| (*), where |n| is \"n if n is positive and -n otherwise\". In other words, for all n in integers at least one of the following holds (exactly either cases (1 and 2) or cases (3 and 4) in fact but I won't prove it here):</p>\n\n<p>Case 1: n &lt;= 2n.</p>\n\n<p>Case 2: -n &lt;= -2n.</p>\n\n<p>Case 3: -n &lt;= 2n.</p>\n\n<p>Case 4: n &lt;= -2n.</p>\n\n<p>Now take 2k = n. (Such a k does exist if n is even, but I won't prove it here. If n is not even then the loop in <code>even</code> fails to return early anyway, so it doesn't matter.) But this implies k &lt; n if n not 0 by (*) and the fact (again not proven here) that for all m, z in integers 2m = z implies z not equal to m given m is not 0. In the case n is 0, 2*0 = 0 so 0 is even we are done (if n = 0 then 0 is in C-integers because n is in C-integer in the function <code>even</code>, hence k = 0 is in C-integers). Thus such a k in C-integers exists for n in C-integers if n is even.</p>\n\n<p>A similar argument shows that if n is odd, there exists a k in C-integers such that n = 2k + 1.</p>\n\n<p>Hence the functions <code>even</code> and <code>odd</code> presented here will work properly for all C-integers.</p>\n" }, { "answer_id": 10357149, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 2, "selected": false, "text": "<p>Here is an answer in \nJava:</p>\n\n<pre><code>public static boolean isEven (Integer Number) {\n Pattern number = Pattern.compile(\"^.*?(?:[02]|8|(?:6|4))$\");\n String num = Number.toString(Number);\n Boolean numbr = new Boolean(number.matcher(num).matches());\n return numbr.booleanValue();\n}\n</code></pre>\n" }, { "answer_id": 16369720, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Reading this rather entertaining discussion, I remembered that I had a real-world, time-sensitive function that tested for odd and even numbers inside the main loop. It's an integer power function, posted elsewhere on StackOverflow, as follows. The benchmarks were quite surprising. At least in this real-world function, <strong>modulo is slower</strong>, and significantly so. <strong>The winner, by a wide margin, requiring 67% of modulo's time, is an or ( | ) approach</strong>, and is nowhere to be found elsewhere on this page. </p>\n\n<pre><code>static dbl IntPow(dbl st0, int x) {\n UINT OrMask = UINT_MAX -1;\n dbl st1=1.0;\n if(0==x) return (dbl)1.0;\n\n while(1 != x) {\n if (UINT_MAX == (x|OrMask)) { // if LSB is 1... \n //if(x &amp; 1) {\n //if(x % 2) {\n st1 *= st0;\n } \n x = x &gt;&gt; 1; // shift x right 1 bit... \n st0 *= st0;\n }\n return st1 * st0;\n}\n</code></pre>\n\n<p>For 300 million loops, the benchmark timings are as follows. </p>\n\n<p>3.962 the | and mask approach</p>\n\n<p>4.851 the &amp; approach</p>\n\n<p>5.850 the % approach</p>\n\n<p>For people who think theory, or an assembly language listing, settles arguments like these, this should be a cautionary tale. There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy. </p>\n" }, { "answer_id": 18744262, "author": "Astridax", "author_id": 1392407, "author_profile": "https://Stackoverflow.com/users/1392407", "pm_score": 1, "selected": false, "text": "<p>To give more elaboration on the bitwise operator method for those of us who didn't do much boolean algebra during our studies, here is an explanation. Probably not of much use to the OP, but I felt like making it clear why NUMBER &amp; 1 works. </p>\n\n<p>Please note like as someone answered above, the way negative numbers are represented can stop this method working. In fact it can even break the modulo operator method too since each language can differ in how it deals with negative operands. </p>\n\n<p>However if you know that NUMBER will always be positive, this works well.</p>\n\n<p>As Tooony above made the point that only the last digit in binary (and denary) is important.</p>\n\n<p>A boolean logic AND gate dictates that both inputs have to be a 1 (or high voltage) for 1 to be returned.</p>\n\n<p>1 &amp; 0 = 0.</p>\n\n<p>0 &amp; 1 = 0. </p>\n\n<p>0 &amp; 0 = 0.</p>\n\n<p>1 &amp; 1 = 1.</p>\n\n<p>If you represent any number as binary (I have used an 8 bit representation here), odd numbers have 1 at the end, even numbers have 0.</p>\n\n<p>For example:</p>\n\n<p>1 = 00000001</p>\n\n<p>2 = 00000010</p>\n\n<p>3 = 00000011</p>\n\n<p>4 = 00000100</p>\n\n<p>If you take any number and use bitwise AND (&amp; in java) it by 1 it will either return 00000001, = 1 meaning the number is odd. Or 00000000 = 0, meaning the number is even.</p>\n\n<p>E.g</p>\n\n<p>Is odd?</p>\n\n<p>1 &amp; 1 = </p>\n\n<p>00000001 &amp;</p>\n\n<p>00000001 =</p>\n\n<p>00000001 &lt;— Odd</p>\n\n<p>2 &amp; 1 =</p>\n\n<p>00000010 &amp;</p>\n\n<p>00000001 =</p>\n\n<p>00000000 &lt;— Even</p>\n\n<p>54 &amp; 1 =</p>\n\n<p>00000001 &amp;</p>\n\n<p>00110110 =</p>\n\n<p>00000000 &lt;— Even</p>\n\n<p>This is why this works:</p>\n\n<pre><code>if(number &amp; 1){\n\n //Number is odd\n\n} else {\n\n //Number is even\n}\n</code></pre>\n\n<p>Sorry if this is redundant.</p>\n" }, { "answer_id": 21777983, "author": "Kiril Aleksandrov", "author_id": 2243615, "author_profile": "https://Stackoverflow.com/users/2243615", "pm_score": 2, "selected": false, "text": "<p>Try this: <code>return (((a&gt;&gt;1)&lt;&lt;1) == a)</code></p>\n\n<p>Example:</p>\n\n<pre><code>a = 10101011\n-----------------\na&gt;&gt;1 --&gt; 01010101\na&lt;&lt;1 --&gt; 10101010\n\nb = 10011100\n-----------------\nb&gt;&gt;1 --&gt; 01001110\nb&lt;&lt;1 --&gt; 10011100\n</code></pre>\n" }, { "answer_id": 24649002, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>As some people have posted, there are numerous ways to do this. According to <a href=\"http://cc.davelozinski.com/c-sharp/fastest-way-to-check-if-a-number-is-odd-or-even\" rel=\"nofollow\">this website</a>, the fastest way is the modulus operator:</p>\n\n<pre><code>if (x % 2 == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n</code></pre>\n\n<p>However, here is some <a href=\"http://cc.davelozinski.com/c-sharp/fastest-way-to-check-if-a-number-is-odd-or-even\" rel=\"nofollow\">other code that was bench marked</a> by the author which ran slower than the common modulus operation above:</p>\n\n<pre><code>if ((x &amp; 1) == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nSystem.Math.DivRem((long)x, (long)2, out outvalue);\n if ( outvalue == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nif (((x / 2) * 2) == x)\n total += 1; //even number\n else\n total -= 1; //odd number\n\nif (((x &gt;&gt; 1) &lt;&lt; 1) == x)\n total += 1; //even number\n else\n total -= 1; //odd number\n\n while (index &gt; 1)\n index -= 2;\n if (index == 0)\n total += 1; //even number\n else\n total -= 1; //odd number\n\ntempstr = x.ToString();\n index = tempstr.Length - 1;\n //this assumes base 10\n if (tempstr[index] == '0' || tempstr[index] == '2' || tempstr[index] == '4' || tempstr[index] == '6' || tempstr[index] == '8')\n total += 1; //even number\n else\n total -= 1; //odd number\n</code></pre>\n\n<p>How many people even knew of the <a href=\"http://msdn.microsoft.com/en-us/library/system.math.divrem%28v=vs.110%29.aspx\" rel=\"nofollow\">Math.System.DivRem</a> method or why would they use it??</p>\n" }, { "answer_id": 30701091, "author": "Pankaj Prakash", "author_id": 2401088, "author_profile": "https://Stackoverflow.com/users/2401088", "pm_score": 0, "selected": false, "text": "<p>Checking even or odd is a simple task.</p>\n\n<blockquote>\n <p>We know that any number exactly divisible by 2 is even number else odd. </p>\n</blockquote>\n\n<p>We just need to check divisibility of any number and for checking divisibility we use <code>%</code> operator</p>\n\n<p><strong>Checking even odd using if else</strong> </p>\n\n<pre><code>if(num%2 ==0) \n{\n printf(\"Even\");\n}\nelse\n{\n printf(\"Odd\");\n}\n</code></pre>\n\n<p><a href=\"http://codeforwin.org/2015/05/c-program-to-check-even-odd.html\" rel=\"nofollow noreferrer\">C program to check even or odd using if else</a> </p>\n\n<p><strong>Using Conditional/Ternary operator</strong></p>\n\n<pre><code>(num%2 ==0) printf(\"Even\") : printf(\"Odd\");\n</code></pre>\n\n<p><a href=\"http://codeforwin.org/2015/06/c-program-to-check-even-or-odd-using-conditional-operator.html\" rel=\"nofollow noreferrer\">C program to check even or odd using conditional operator</a>. </p>\n\n<p><strong>Using Bitwise operator</strong></p>\n\n<pre><code>if(num &amp; 1) \n{\n printf(\"Odd\");\n}\nelse \n{\n printf(\"Even\");\n}\n</code></pre>\n" }, { "answer_id": 32693856, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Number Zero parity | zero <a href=\"http://tinyurl.com/oexhr3k\" rel=\"nofollow\">http://tinyurl.com/oexhr3k</a></p>\n\n<p>Python code sequence.</p>\n\n<pre><code># defining function for number parity check\ndef parity(number):\n \"\"\"Parity check function\"\"\"\n # if number is 0 (zero) return 'Zero neither ODD nor EVEN',\n # otherwise number&amp;1, checking last bit, if 0, then EVEN, \n # if 1, then ODD.\n return (number == 0 and 'Zero neither ODD nor EVEN') \\\n or (number&amp;1 and 'ODD' or 'EVEN')\n\n# cycle trough numbers from 0 to 13 \nfor number in range(0, 14):\n print \"{0:&gt;4} : {0:08b} : {1:}\".format(number, parity(number))\n</code></pre>\n\n<blockquote>\n <p><strong>Output:</strong></p>\n</blockquote>\n\n<pre><code> 0 : 00000000 : Zero neither ODD nor EVEN\n 1 : 00000001 : ODD\n 2 : 00000010 : EVEN\n 3 : 00000011 : ODD\n 4 : 00000100 : EVEN\n 5 : 00000101 : ODD\n 6 : 00000110 : EVEN\n 7 : 00000111 : ODD\n 8 : 00001000 : EVEN\n 9 : 00001001 : ODD\n 10 : 00001010 : EVEN\n 11 : 00001011 : ODD\n 12 : 00001100 : EVEN\n 13 : 00001101 : ODD\n</code></pre>\n" }, { "answer_id": 37248465, "author": "Moinak Debnath", "author_id": 4061847, "author_profile": "https://Stackoverflow.com/users/4061847", "pm_score": -1, "selected": false, "text": "<p>Modulus operator '%' can be used to check whether a number is odd or even.That is when a number is divided by 2 and if the remainder is 0 then its an even number else its an odd number.<br></p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main()\n{\n int n;//using modulus operator\n scanf(\"%d\",&amp;n);//take input n from STDIN \n printf(\"%s\",n%2==0?\"Even\":\"Odd\");//prints Even/Odd depending on n to STDOUT\n return 0;\n}\n</code></pre>\n\n<p>But using Bit manipulation is quite faster than the above method,so if you take a number and apply logically AND '&amp;' to it ,if the answer is 1 then its even else its odd.That is basically we have to check the last bit of the number n in binary.If the last bit is 0 then n is even else its odd.</p>\n\n<p>for example : suppose N = 15 , in binary N = 1111 , now we AND it with 1</p>\n\n<pre><code> 1111\n 0001\n &amp;-----\n 0001\n</code></pre>\n\n<p>Since the result is 1 the number N=15 is Odd.<br><br>\nAgain,suppose N = 8 , in binary N = 1000 , now we AND it with 1</p>\n\n<pre><code> 1000\n 0001\n &amp;-----\n 0000\n</code></pre>\n\n<p>Since the result is 0 the number N=8 is Even.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n int n;//using AND operator\n scanf(\"%d\",&amp;n);//take input n from STDIN \n printf(\"%s\",n&amp;1?\"Odd\":\"Even\");//prints Even/Odd depending on n to STDOUT\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 40040733, "author": "Lou", "author_id": 1488067, "author_profile": "https://Stackoverflow.com/users/1488067", "pm_score": 2, "selected": false, "text": "<p>This is a follow up to the discussion with @RocketRoy regarding <a href=\"https://stackoverflow.com/a/16369720/1488067\">his answer</a>, but it might be useful to anyone who wants to compare these results.</p>\n\n<p><strong>tl;dr</strong> From what I've seen, Roy's approach (<code>(0xFFFFFFFF == (x | 0xFFFFFFFE)</code>) is not completely optimized to <code>x &amp; 1</code> as the <code>mod</code> approach, but in practice running times should turn out equal in all cases.</p>\n\n<p>So, first I compared the compiled output using <a href=\"https://godbolt.org/g/rkm3Se\" rel=\"nofollow noreferrer\">Compiler Explorer</a>:</p>\n\n<p><strong>Functions tested:</strong></p>\n\n<pre><code>int isOdd_mod(unsigned x) {\n return (x % 2);\n}\n\nint isOdd_and(unsigned x) {\n return (x &amp; 1);\n}\n\nint isOdd_or(unsigned x) {\n return (0xFFFFFFFF == (x | 0xFFFFFFFE));\n} \n</code></pre>\n\n<p><strong>CLang 3.9.0 with -O3:</strong></p>\n\n<pre><code>isOdd_mod(unsigned int): # @isOdd_mod(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n\nisOdd_and(unsigned int): # @isOdd_and(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n\nisOdd_or(unsigned int): # @isOdd_or(unsigned int)\n and edi, 1\n mov eax, edi\n ret\n</code></pre>\n\n<p><strong>GCC 6.2 with -O3:</strong></p>\n\n<pre><code>isOdd_mod(unsigned int):\n mov eax, edi\n and eax, 1\n ret\n\nisOdd_and(unsigned int):\n mov eax, edi\n and eax, 1\n ret\n\nisOdd_or(unsigned int):\n or edi, -2\n xor eax, eax\n cmp edi, -1\n sete al\n ret\n</code></pre>\n\n<p>Hats down to CLang, it realized that all three cases are functionally equal. However, Roy's approach isn't optimized in GCC, so YMMV.</p>\n\n<p>It's similar with Visual Studio; inspecting the disassembly Release x64 (VS2015) for these three functions, I could see that the comparison part is equal for \"mod\" and \"and\" cases, and slightly larger for the Roy's \"or\" case:</p>\n\n<pre><code>// x % 2\ntest bl,1 \nje (some address) \n\n// x &amp; 1\ntest bl,1 \nje (some address) \n\n// Roy's bitwise or\nmov eax,ebx \nor eax,0FFFFFFFEh \ncmp eax,0FFFFFFFFh \njne (some address)\n</code></pre>\n\n<p>However, after running an actual benchmark for comparing these three options (plain mod, bitwise or, bitwise and), results were completely equal (again, Visual Studio 2005 x86/x64, Release build, no debugger attached). </p>\n\n<p>Release assembly uses the <code>test</code> instruction for <code>and</code> and <code>mod</code> cases, while Roy's case uses the <code>cmp eax,0FFFFFFFFh</code> approach, but it's heavily unrolled and optimized so there is no difference in practice.</p>\n\n<p>My results after 20 runs (i7 3610QM, Windows 10 power plan set to High Performance):</p>\n\n<pre>\n[Test: Plain mod 2 ] AVERAGE TIME: 689.29 ms (Relative diff.: +0.000%)\n[Test: Bitwise or ] AVERAGE TIME: 689.63 ms (Relative diff.: +0.048%)\n[Test: Bitwise and ] AVERAGE TIME: 687.80 ms (Relative diff.: -0.217%)\n</pre>\n\n<p>The difference between these options is less than 0.3%, so it's rather obvious the assembly is equal in all cases.</p>\n\n<p>Here is the code if anyone wants to try, with a caveat that I only tested it on Windows (check the <code>#if LINUX</code> conditional for the <code>get_time</code> definition and implement it if needed, taken from <a href=\"https://stackoverflow.com/a/2349941/1488067\">this answer</a>).</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#if LINUX\n#include &lt;sys/time.h&gt;\n#include &lt;sys/resource.h&gt;\ndouble get_time()\n{\n struct timeval t;\n struct timezone tzp;\n gettimeofday(&amp;t, &amp;tzp);\n return t.tv_sec + t.tv_usec*1e-6;\n}\n#else\n#include &lt;windows.h&gt;\ndouble get_time()\n{\n LARGE_INTEGER t, f;\n QueryPerformanceCounter(&amp;t);\n QueryPerformanceFrequency(&amp;f);\n return (double)t.QuadPart / (double)f.QuadPart * 1000.0;\n}\n#endif\n\n#define NUM_ITERATIONS (1000 * 1000 * 1000)\n\n// using a macro to avoid function call overhead\n#define Benchmark(accumulator, name, operation) { \\\n double startTime = get_time(); \\\n double dummySum = 0.0, elapsed; \\\n int x; \\\n for (x = 0; x &lt; NUM_ITERATIONS; x++) { \\\n if (operation) dummySum += x; \\\n } \\\n elapsed = get_time() - startTime; \\\n accumulator += elapsed; \\\n if (dummySum &gt; 2000) \\\n printf(\"[Test: %-12s] %0.2f ms\\r\\n\", name, elapsed); \\\n}\n\nvoid DumpAverage(char *test, double totalTime, double reference)\n{\n printf(\"[Test: %-12s] AVERAGE TIME: %0.2f ms (Relative diff.: %+6.3f%%)\\r\\n\",\n test, totalTime, (totalTime - reference) / reference * 100.0);\n}\n\nint main(void)\n{\n int repeats = 20;\n double runningTimes[3] = { 0 };\n int k;\n\n for (k = 0; k &lt; repeats; k++) {\n printf(\"Run %d of %d...\\r\\n\", k + 1, repeats);\n Benchmark(runningTimes[0], \"Plain mod 2\", (x % 2));\n Benchmark(runningTimes[1], \"Bitwise or\", (0xFFFFFFFF == (x | 0xFFFFFFFE)));\n Benchmark(runningTimes[2], \"Bitwise and\", (x &amp; 1));\n }\n\n {\n double reference = runningTimes[0] / repeats;\n printf(\"\\r\\n\");\n DumpAverage(\"Plain mod 2\", runningTimes[0] / repeats, reference);\n DumpAverage(\"Bitwise or\", runningTimes[1] / repeats, reference);\n DumpAverage(\"Bitwise and\", runningTimes[2] / repeats, reference);\n }\n\n getchar();\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 45432795, "author": "Omar Faruk", "author_id": 5778851, "author_profile": "https://Stackoverflow.com/users/5778851", "pm_score": 1, "selected": false, "text": "<pre><code>I execute this code for ODD &amp; EVEN:\n\n#include &lt;stdio.h&gt;\nint main()\n{\n int number;\n printf(\"Enter an integer: \");\n scanf(\"%d\", &amp;number);\n\n if(number % 2 == 0)\n printf(\"%d is even.\", number);\n else\n printf(\"%d is odd.\", number);\n}\n</code></pre>\n" }, { "answer_id": 50072690, "author": "Beyondo", "author_id": 8524922, "author_profile": "https://Stackoverflow.com/users/8524922", "pm_score": 0, "selected": false, "text": "<h2><strong>+66%</strong> faster &gt; <code>!(i%2) / i%2 == 0</code></h2>\n<pre><code>int isOdd(int n)\n{\n return n &amp; 1;\n}\n</code></pre>\n<p>The code checks the last bit of the integer if it's <strong>1</strong> in Binary</p>\n<h2>Explanation</h2>\n<pre><code>Binary : Decimal\n-------------------\n0000 = 0\n0001 = 1\n0010 = 2\n0011 = 3\n0100 = 4\n0101 = 5\n0110 = 6\n0111 = 7\n1000 = 8\n1001 = 9\nand so on...\n</code></pre>\n<blockquote>\n<p><strong>Notice</strong> the rightmost <strong>bit</strong> is always 1 for <strong>Odd</strong> numbers.</p>\n</blockquote>\n<p>the <strong>&amp;</strong> bitwise AND operator checks the rightmost bit in our <strong>return</strong> line if it's 1<br></p>\n<h2>Think of it as true &amp; false</h2>\n<p>When we compare <strong>n</strong> with <strong>1</strong> which means <code>0001</code> in binary (number of zeros doesn't matter).<br>\nthen let's just Imagine that we have the integer <strong>n</strong> with a size of 1 byte.</p>\n<p>It'd be represented by 8-bit / 8-binary digits.</p>\n<p>If the int <strong>n</strong> was <strong>7</strong> and we compare it with <strong>1</strong>, It's like</p>\n<pre><code>7 (1-byte int)| 0 0 0 0 0 1 1 1\n &amp;\n1 (1-byte int)| 0 0 0 0 0 0 0 1\n********************************************\nResult | F F F F F F F T\n</code></pre>\n<p>Which <strong>F</strong> stands for false and <strong>T</strong> for true.</p>\n<blockquote>\n<p>It <strong>compares</strong> only the rightmost bit if they're both true. So, automagically <code>7 &amp; 1</code> is <strong>T</strong>rue.</p>\n</blockquote>\n<h2>What if I want to check the bit before the rightmost?</h2>\n<p>Simply change <code>n &amp; 1</code> to <code>n &amp; 2</code> which 2 represents <code>0010</code> in Binary and so on.</p>\n<p>I suggest using hexadecimal notation if you're a beginner to bitwise operations<br>\n<code>return n &amp; 1;</code> &gt;&gt; <code>return n &amp; 0x01;</code>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
How can I check if a given number is even or odd in C?
Use the modulo (%) operator to check if there's a remainder when dividing by 2: ``` if (x % 2) { /* x is odd */ } ``` A few people have criticized my answer above stating that using x & 1 is "faster" or "more efficient". I do not believe this to be the case. Out of curiosity, I created two trivial test case programs: ``` /* modulo.c */ #include <stdio.h> int main(void) { int x; for (x = 0; x < 10; x++) if (x % 2) printf("%d is odd\n", x); return 0; } /* and.c */ #include <stdio.h> int main(void) { int x; for (x = 0; x < 10; x++) if (x & 1) printf("%d is odd\n", x); return 0; } ``` I then compiled these with gcc 4.1.3 on one of my machines 5 different times: * With no optimization flags. * With -O * With -Os * With -O2 * With -O3 I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment. If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know. Finally, the modulo version is **guaranteed** by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.
160,954
<p>I have a Rails project which has a Postgres database for the actual application but which needs to pull a heck of a lot of data out of an Oracle database. </p> <p>database.yml looks like</p> <pre><code>development: adapter: postgresql database: blah blah ... oracle_db: adapter: oracle database: blah blah </code></pre> <p>My models which descend from data on the Oracle DB look something like </p> <pre><code>class LegacyDataClass &lt; ActiveRecord::Base establish_connection "oracle_db" set_primary_key :legacy_data_class_id has_one :other_legacy_class, :foreign key =&gt; :other_legacy_class_id_with_funny_column_name ... end </code></pre> <p>Now, by habit I often do a lot of my early development (and this is early development) by coding for a bit and then playing in the Rails console. For example, after defining all the associations for LegacyDataClass I'll start trying things like <code>a = LegacyDataClass.find(:first); puts a.some_association.name</code>. Unexpectedly, this dies with LegacyDataClass not being already loaded. </p> <p>I can then <code>require 'LegacyDataClass'</code> which fixes the problem until I either need to <code>reload!</code>, which won't actually reload it, or until I open a new instance of the console.</p> <p>Thus the questions:</p> <ul> <li><strong>Why</strong> does this happen? Clearly there is some Rails magic I am not understanding.</li> <li>What is the convenient Rails <strong>workaround</strong>?</li> </ul>
[ { "answer_id": 160989, "author": "James Baker", "author_id": 9365, "author_profile": "https://Stackoverflow.com/users/9365", "pm_score": 3, "selected": true, "text": "<p>I believe this might have to do with your model name, rather than your connection. The Rails convention is that model class names are CamelCase, while the files they reside in are lowercase+underscore.</p>\n\n<p>The \"LegacyModel\" class should therefore be in <code>models/legacy_model.rb</code>. Your statement about <code>\"require 'LegacyDataClass'\"</code> indicates that this is not the case, and therefore Rails doesn't know how to automagically load that model.</p>\n" }, { "answer_id": 1225605, "author": "nitecoder", "author_id": 60145, "author_profile": "https://Stackoverflow.com/users/60145", "pm_score": 1, "selected": false, "text": "<p>I wrote something for an app at work that handles connections to other databases' at runtime, it might be able to help.</p>\n\n<p><a href=\"http://github.com/cherring/connection_ninja\" rel=\"nofollow noreferrer\">http://github.com/cherring/connection_ninja</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15046/" ]
I have a Rails project which has a Postgres database for the actual application but which needs to pull a heck of a lot of data out of an Oracle database. database.yml looks like ``` development: adapter: postgresql database: blah blah ... oracle_db: adapter: oracle database: blah blah ``` My models which descend from data on the Oracle DB look something like ``` class LegacyDataClass < ActiveRecord::Base establish_connection "oracle_db" set_primary_key :legacy_data_class_id has_one :other_legacy_class, :foreign key => :other_legacy_class_id_with_funny_column_name ... end ``` Now, by habit I often do a lot of my early development (and this is early development) by coding for a bit and then playing in the Rails console. For example, after defining all the associations for LegacyDataClass I'll start trying things like `a = LegacyDataClass.find(:first); puts a.some_association.name`. Unexpectedly, this dies with LegacyDataClass not being already loaded. I can then `require 'LegacyDataClass'` which fixes the problem until I either need to `reload!`, which won't actually reload it, or until I open a new instance of the console. Thus the questions: * **Why** does this happen? Clearly there is some Rails magic I am not understanding. * What is the convenient Rails **workaround**?
I believe this might have to do with your model name, rather than your connection. The Rails convention is that model class names are CamelCase, while the files they reside in are lowercase+underscore. The "LegacyModel" class should therefore be in `models/legacy_model.rb`. Your statement about `"require 'LegacyDataClass'"` indicates that this is not the case, and therefore Rails doesn't know how to automagically load that model.
160,960
<p>I have a function that takes a struct, and I'm trying to store its variables in array:</p> <pre><code>int detect_prm(Param prm) { int prm_arr[] = {prm.field1, prm.field2, prm.field3}; return 0; } </code></pre> <p>But with <code>gcc -Wall -ansi -pedantic-errors -Werror</code> I get the following error:</p> <blockquote> <p>initializer element is not computable at load time</p> </blockquote> <p>It looks fine to me, what's wrong?</p>
[ { "answer_id": 160969, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 5, "selected": true, "text": "<p>This is illegal in C. Initializer lists must be constant compile time expressions. Do the following instead:</p>\n\n<pre><code>int prm_arr[3];\n\nprm_arr[0] = prm.field1;\nprm_arr[1] = prm.field2;\nprm_arr[2] = prm.field3;\n</code></pre>\n" }, { "answer_id": 161019, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": false, "text": "<p>Mike's answer is absolutely right.</p>\n\n<p>However, if you're able to use the GNU C extensions, or to use the newer and better C99 standard instead (use the <code>--std=c99</code> option), then initializers such as this are perfectly legal. The C99 standard has been out for, well, 9 years, and most C compilers support it quite well... especially this feature.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I have a function that takes a struct, and I'm trying to store its variables in array: ``` int detect_prm(Param prm) { int prm_arr[] = {prm.field1, prm.field2, prm.field3}; return 0; } ``` But with `gcc -Wall -ansi -pedantic-errors -Werror` I get the following error: > > initializer element is not computable at load time > > > It looks fine to me, what's wrong?
This is illegal in C. Initializer lists must be constant compile time expressions. Do the following instead: ``` int prm_arr[3]; prm_arr[0] = prm.field1; prm_arr[1] = prm.field2; prm_arr[2] = prm.field3; ```
160,970
<p>If I have two variables:</p> <pre><code>Object obj; String methodName = "getName"; </code></pre> <p>Without knowing the class of <code>obj</code>, how can I call the method identified by <code>methodName</code> on it?</p> <p>The method being called has no parameters, and a <code>String</code> return value. It's <em>a getter for a Java bean</em>.</p>
[ { "answer_id": 160976, "author": "Owen", "author_id": 11442, "author_profile": "https://Stackoverflow.com/users/11442", "pm_score": 8, "selected": false, "text": "<p>Use <a href=\"http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html\" rel=\"noreferrer\">method invocation</a> from reflection:</p>\n\n<pre><code>Class&lt;?&gt; c = Class.forName(\"class name\");\nMethod method = c.getDeclaredMethod(\"method name\", parameterTypes);\nmethod.invoke(objectToInvokeOn, params);\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li><code>\"class name\"</code> is the name of the class</li>\n<li><code>objectToInvokeOn</code> is of type Object and is the object you want to invoke the method on</li>\n<li><code>\"method name\"</code> is the name of the method you want to call</li>\n<li><code>parameterTypes</code> is of type <code>Class[]</code> and declares the parameters the method takes</li>\n<li><code>params</code> is of type <code>Object[]</code> and declares the parameters to be passed to the method</li>\n</ul>\n" }, { "answer_id": 160979, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 3, "selected": false, "text": "<p>This sounds like something that is doable with the Java Reflection package.</p>\n\n<p><a href=\"http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html\" rel=\"noreferrer\">http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html</a></p>\n\n<p>Particularly under <strong>Invoking Methods by Name:</strong></p>\n\n<p>import java.lang.reflect.*;</p>\n\n<pre><code>public class method2 {\n public int add(int a, int b)\n {\n return a + b;\n }\n\n public static void main(String args[])\n {\n try {\n Class cls = Class.forName(\"method2\");\n Class partypes[] = new Class[2];\n partypes[0] = Integer.TYPE;\n partypes[1] = Integer.TYPE;\n Method meth = cls.getMethod(\n \"add\", partypes);\n method2 methobj = new method2();\n Object arglist[] = new Object[2];\n arglist[0] = new Integer(37);\n arglist[1] = new Integer(47);\n Object retobj \n = meth.invoke(methobj, arglist);\n Integer retval = (Integer)retobj;\n System.out.println(retval.intValue());\n }\n catch (Throwable e) {\n System.err.println(e);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 160980, "author": "chickeninabiscuit", "author_id": 3966, "author_profile": "https://Stackoverflow.com/users/3966", "pm_score": 4, "selected": false, "text": "<pre><code>Object obj;\n\nMethod method = obj.getClass().getMethod(\"methodName\", null);\n\nmethod.invoke(obj, null);\n</code></pre>\n" }, { "answer_id": 161005, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 11, "selected": true, "text": "<p>Coding from the hip, it would be something like:</p>\n\n<pre><code>java.lang.reflect.Method method;\ntry {\n method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);\n} catch (SecurityException e) { ... }\n catch (NoSuchMethodException e) { ... }\n</code></pre>\n\n<p>The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give <code>methodName</code>).</p>\n\n<p>Then you invoke that method by calling</p>\n\n<pre><code>try {\n method.invoke(obj, arg1, arg2,...);\n} catch (IllegalArgumentException e) { ... }\n catch (IllegalAccessException e) { ... }\n catch (InvocationTargetException e) { ... }\n</code></pre>\n\n<p>Again, leave out the arguments in <code>.invoke</code>, if you don't have any. But yeah. Read about <a href=\"http://java.sun.com/docs/books/tutorial/reflect/index.html\" rel=\"noreferrer\">Java Reflection</a></p>\n" }, { "answer_id": 161011, "author": "Petr Macek", "author_id": 15045, "author_profile": "https://Stackoverflow.com/users/15045", "pm_score": 6, "selected": false, "text": "<p>The method can be invoked like this. There are also more possibilities (check the reflection api), but this is the simplest one:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\nimport org.junit.Assert;\nimport org.junit.Test;\n\npublic class ReflectionTest {\n\n private String methodName = \"length\";\n private String valueObject = \"Some object\";\n\n @Test\n public void testGetMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException,\n IllegalAccessException, InvocationTargetException {\n Method m = valueObject.getClass().getMethod(methodName, new Class[] {});\n Object ret = m.invoke(valueObject, new Object[] {});\n Assert.assertEquals(11, ret);\n }\n\n\n\n}\n</code></pre>\n" }, { "answer_id": 161032, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "<p>To complete my colleague's answers, You might want to pay close attention to:</p>\n\n<ul>\n<li>static or instance calls (in one case, you do not need an instance of the class, in the other, you might need to rely on an <strong>existing default constructor</strong> that may or may not be there)</li>\n<li>public or non-public method call (for the latter,<strong>you need to call setAccessible on the method within an doPrivileged block</strong>, other <a href=\"http://findbugs.sourceforge.net/bugDescriptions.html#DP_DO_INSIDE_DO_PRIVILEGED\" rel=\"noreferrer\">findbugs won't be happy</a>)</li>\n<li>encapsulating into one more manageable applicative exception if you want to throw back the numerous java system exceptions (hence the CCException in the code below)</li>\n</ul>\n\n<p>Here is an old java1.4 code which takes into account those points:</p>\n\n<pre><code>/**\n * Allow for instance call, avoiding certain class circular dependencies. &lt;br /&gt;\n * Calls even private method if java Security allows it.\n * @param aninstance instance on which method is invoked (if null, static call)\n * @param classname name of the class containing the method \n * (can be null - ignored, actually - if instance if provided, must be provided if static call)\n * @param amethodname name of the method to invoke\n * @param parameterTypes array of Classes\n * @param parameters array of Object\n * @return resulting Object\n * @throws CCException if any problem\n */\npublic static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException\n{\n Object res;// = null;\n try {\n Class aclass;// = null;\n if(aninstance == null)\n {\n aclass = Class.forName(classname);\n }\n else\n {\n aclass = aninstance.getClass();\n }\n //Class[] parameterTypes = new Class[]{String[].class};\n final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);\n AccessController.doPrivileged(new PrivilegedAction() {\n public Object run() {\n amethod.setAccessible(true);\n return null; // nothing to return\n }\n });\n res = amethod.invoke(aninstance, parameters);\n } catch (final ClassNotFoundException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);\n } catch (final SecurityException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);\n } catch (final NoSuchMethodException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);\n } catch (final IllegalArgumentException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);\n } catch (final IllegalAccessException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);\n } catch (final InvocationTargetException e) {\n throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);\n } \n return res;\n}\n</code></pre>\n" }, { "answer_id": 162462, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": false, "text": "<p>First, don't. Avoid this sort of code. It tends to be really bad code and insecure too (see section 6 of <a href=\"http://java.sun.com/security/seccodeguide.html\" rel=\"noreferrer\">Secure Coding Guidelines for the\nJava Programming Language, version 2.0</a>).</p>\n\n<p><strike>If you must do it, prefer java.beans to reflection. Beans wraps reflection allowing relatively safe and conventional access.</strike></p>\n" }, { "answer_id": 3056891, "author": "SMayne", "author_id": 368639, "author_profile": "https://Stackoverflow.com/users/368639", "pm_score": -1, "selected": false, "text": "<p>for me a pretty simple and fool proof way would be to simply make a method caller method like so:</p>\n\n<pre><code>public static object methodCaller(String methodName)\n{\n if(methodName.equals(\"getName\"))\n return className.getName();\n}\n</code></pre>\n\n<p>then when you need to call the method simply put something like this</p>\n\n<pre><code>//calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory \nSystem.out.println(methodCaller(methodName).toString()); \n</code></pre>\n" }, { "answer_id": 16292985, "author": "anujin", "author_id": 1394305, "author_profile": "https://Stackoverflow.com/users/1394305", "pm_score": 4, "selected": false, "text": "<pre><code>//Step1 - Using string funClass to convert to class\nString funClass = \"package.myclass\";\nClass c = Class.forName(funClass);\n\n//Step2 - instantiate an object of the class abov\nObject o = c.newInstance();\n//Prepare array of the arguments that your function accepts, lets say only one string here\nClass[] paramTypes = new Class[1];\nparamTypes[0]=String.class;\nString methodName = \"mymethod\";\n//Instantiate an object of type method that returns you method name\n Method m = c.getDeclaredMethod(methodName, paramTypes);\n//invoke method with actual params\nm.invoke(o, \"testparam\");\n</code></pre>\n" }, { "answer_id": 30671481, "author": "silver", "author_id": 2806819, "author_profile": "https://Stackoverflow.com/users/2806819", "pm_score": 7, "selected": false, "text": "<p>For those who want a straight-forward code example in Java 7:</p>\n\n<p><strong><code>Dog</code> class:</strong></p>\n\n<pre><code>package com.mypackage.bean;\n\npublic class Dog {\n private String name;\n private int age;\n\n public Dog() {\n // empty constructor\n }\n\n public Dog(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n public void printDog(String name, int age) {\n System.out.println(name + \" is \" + age + \" year(s) old.\");\n }\n}\n</code></pre>\n\n<p><strong><code>ReflectionDemo</code> class:</strong></p>\n\n<pre><code>package com.mypackage.demo;\n\nimport java.lang.reflect.*;\n\npublic class ReflectionDemo {\n\n public static void main(String[] args) throws Exception {\n String dogClassName = \"com.mypackage.bean.Dog\";\n Class&lt;?&gt; dogClass = Class.forName(dogClassName); // convert string classname to class\n Object dog = dogClass.newInstance(); // invoke empty constructor\n\n String methodName = \"\";\n\n // with single parameter, return void\n methodName = \"setName\";\n Method setNameMethod = dog.getClass().getMethod(methodName, String.class);\n setNameMethod.invoke(dog, \"Mishka\"); // pass arg\n\n // without parameters, return string\n methodName = \"getName\";\n Method getNameMethod = dog.getClass().getMethod(methodName);\n String name = (String) getNameMethod.invoke(dog); // explicit cast\n\n // with multiple parameters\n methodName = \"printDog\";\n Class&lt;?&gt;[] paramTypes = {String.class, int.class};\n Method printDogMethod = dog.getClass().getMethod(methodName, paramTypes);\n printDogMethod.invoke(dog, name, 3); // pass args\n }\n}\n</code></pre>\n\n<p><strong>Output:</strong>\n<code>Mishka is 3 year(s) old.</code></p>\n\n<hr>\n\n<p>You can invoke the constructor with parameters this way:</p>\n\n<pre><code>Constructor&lt;?&gt; dogConstructor = dogClass.getConstructor(String.class, int.class);\nObject dog = dogConstructor.newInstance(\"Hachiko\", 10);\n</code></pre>\n\n<p>Alternatively, you can remove</p>\n\n<pre><code>String dogClassName = \"com.mypackage.bean.Dog\";\nClass&lt;?&gt; dogClass = Class.forName(dogClassName);\nObject dog = dogClass.newInstance();\n</code></pre>\n\n<p>and do</p>\n\n<pre><code>Dog dog = new Dog();\n\nMethod method = Dog.class.getMethod(methodName, ...);\nmethod.invoke(dog, ...);\n</code></pre>\n\n<p><strong>Suggested reading:</strong> <a href=\"https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html\" rel=\"noreferrer\">Creating New Class Instances</a></p>\n" }, { "answer_id": 31321045, "author": "nurnachman", "author_id": 403717, "author_profile": "https://Stackoverflow.com/users/403717", "pm_score": 2, "selected": false, "text": "<p>You should use reflection - init a class object, then a method in this class, and then invoke this method on an object with <em>optional</em> parameters. Remember to wrap the following snippet in <em>try-catch</em> block</p>\n\n<p>Hope it helps!</p>\n\n<pre><code>Class&lt;?&gt; aClass = Class.forName(FULLY_QUALIFIED_CLASS_NAME);\nMethod method = aClass.getMethod(methodName, YOUR_PARAM_1.class, YOUR_PARAM_2.class);\nmethod.invoke(OBJECT_TO_RUN_METHOD_ON, YOUR_PARAM_1, YOUR_PARAM_2);\n</code></pre>\n" }, { "answer_id": 33044958, "author": "Gautam", "author_id": 582421, "author_profile": "https://Stackoverflow.com/users/582421", "pm_score": 1, "selected": false, "text": "<p>This is working fine for me :</p>\n\n<pre><code>public class MethodInvokerClass {\n public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {\n Class c = Class.forName(MethodInvokerClass.class.getName());\n Object o = c.newInstance();\n Class[] paramTypes = new Class[1];\n paramTypes[0]=String.class;\n String methodName = \"countWord\";\n Method m = c.getDeclaredMethod(methodName, paramTypes);\n m.invoke(o, \"testparam\");\n}\npublic void countWord(String input){\n System.out.println(\"My input \"+input);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Output: </p>\n\n<p><code>My input testparam</code></p>\n\n<p>I am able to invoke the method by passing its name to another method (like main).</p>\n" }, { "answer_id": 37339469, "author": "Rahul Karankal", "author_id": 5912936, "author_profile": "https://Stackoverflow.com/users/5912936", "pm_score": 3, "selected": false, "text": "<p>Please refer following code may help you.</p>\n\n<pre><code>public static Method method[];\npublic static MethodClass obj;\npublic static String testMethod=\"A\";\n\npublic static void main(String args[]) \n{\n obj=new MethodClass();\n method=obj.getClass().getMethods();\n try\n {\n for(int i=0;i&lt;method.length;i++)\n {\n String name=method[i].getName();\n if(name==testMethod)\n { \n method[i].invoke(name,\"Test Parameters of A\");\n }\n }\n }\n catch(Exception ex)\n {\n System.out.println(ex.getMessage());\n }\n}\n</code></pre>\n\n<p>Thanks....</p>\n" }, { "answer_id": 39601917, "author": "Marcel", "author_id": 5411494, "author_profile": "https://Stackoverflow.com/users/5411494", "pm_score": 3, "selected": false, "text": "<pre><code>try {\n YourClass yourClass = new YourClass();\n Method method = YourClass.class.getMethod(&quot;yourMethodName&quot;, ParameterOfThisMethod.class);\n method.invoke(yourClass, parameter);\n} catch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n" }, { "answer_id": 40758462, "author": "dina", "author_id": 5980143, "author_profile": "https://Stackoverflow.com/users/5980143", "pm_score": 2, "selected": false, "text": "<p>using <code>import java.lang.reflect.*;</code></p>\n\n<pre><code>public static Object launchProcess(String className, String methodName, Class&lt;?&gt;[] argsTypes, Object[] methodArgs)\n throws Exception {\n\n Class&lt;?&gt; processClass = Class.forName(className); // convert string classname to class\n Object process = processClass.newInstance(); // invoke empty constructor\n\n Method aMethod = process.getClass().getMethod(methodName,argsTypes);\n Object res = aMethod.invoke(process, methodArgs); // pass arg\n return(res);\n}\n</code></pre>\n\n<p>and here is how you use it:</p>\n\n<pre><code>String className = \"com.example.helloworld\";\nString methodName = \"print\";\nClass&lt;?&gt;[] argsTypes = {String.class, String.class};\nObject[] methArgs = { \"hello\", \"world\" }; \nlaunchProcess(className, methodName, argsTypes, methArgs);\n</code></pre>\n" }, { "answer_id": 41339316, "author": "Subrahmanya Prasad", "author_id": 5564537, "author_profile": "https://Stackoverflow.com/users/5564537", "pm_score": 3, "selected": false, "text": "<pre><code>Method method = someVariable.class.getMethod(SomeClass);\nString status = (String) method.invoke(method);\n</code></pre>\n\n<p><code>SomeClass</code> is the class and <code>someVariable</code> is a variable.</p>\n" }, { "answer_id": 42519563, "author": "Christian Ullenboom", "author_id": 388317, "author_profile": "https://Stackoverflow.com/users/388317", "pm_score": 3, "selected": false, "text": "<p>If you do the call several times you can use the new method handles introduced in Java 7. Here we go for your method returning a String:</p>\n\n<pre><code>Object obj = new Point( 100, 200 );\nString methodName = \"toString\"; \nClass&lt;String&gt; resultType = String.class;\n\nMethodType mt = MethodType.methodType( resultType );\nMethodHandle methodHandle = MethodHandles.lookup().findVirtual( obj.getClass(), methodName, mt );\nString result = resultType.cast( methodHandle.invoke( obj ) );\n\nSystem.out.println( result ); // java.awt.Point[x=100,y=200]\n</code></pre>\n" }, { "answer_id": 45395762, "author": "user8387971", "author_id": 8387971, "author_profile": "https://Stackoverflow.com/users/8387971", "pm_score": 2, "selected": false, "text": "<h3>Student.java</h3>\n\n<pre><code>class Student{\n int rollno;\n String name;\n\n void m1(int x,int y){\n System.out.println(\"add is\" +(x+y));\n }\n\n private void m3(String name){\n this.name=name;\n System.out.println(\"danger yappa:\"+name);\n }\n void m4(){\n System.out.println(\"This is m4\");\n }\n}\n</code></pre>\n\n<h3>StudentTest.java</h3>\n\n<pre><code>import java.lang.reflect.Method;\npublic class StudentTest{\n\n public static void main(String[] args){\n\n try{\n\n Class cls=Student.class;\n\n Student s=(Student)cls.newInstance();\n\n\n String x=\"kichha\";\n Method mm3=cls.getDeclaredMethod(\"m3\",String.class);\n mm3.setAccessible(true);\n mm3.invoke(s,x);\n\n Method mm1=cls.getDeclaredMethod(\"m1\",int.class,int.class);\n mm1.invoke(s,10,20);\n\n }\n catch(Exception e){\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 54883454, "author": "Sandeep Nalla", "author_id": 8732673, "author_profile": "https://Stackoverflow.com/users/8732673", "pm_score": 3, "selected": false, "text": "<p>Here are the READY TO USE METHODS:</p>\n\n<p><strong>To invoke a method, without Arguments:</strong></p>\n\n<pre><code>public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName).invoke(object);\n}\n</code></pre>\n\n<p><strong>To invoke a method, with Arguments:</strong></p>\n\n<pre><code> public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);\n }\n</code></pre>\n\n<p>Use the above methods as below:</p>\n\n<pre><code>package practice;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class MethodInvoke {\n\n public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {\n String methodName1 = \"methodA\";\n String methodName2 = \"methodB\";\n MethodInvoke object = new MethodInvoke();\n callMethodByName(object, methodName1);\n callMethodByName(object, methodName2, 1, \"Test\");\n }\n\n public static void callMethodByName(Object object, String methodName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName).invoke(object);\n }\n\n public static void callMethodByName(Object object, String methodName, int i, String s) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n object.getClass().getDeclaredMethod(methodName, int.class, String.class).invoke(object, i, s);\n }\n\n void methodA() {\n System.out.println(\"Method A\");\n }\n\n void methodB(int i, String s) {\n System.out.println(\"Method B: \"+\"\\n\\tParam1 - \"+i+\"\\n\\tParam 2 - \"+s);\n }\n}\n</code></pre>\n\n<p><strong>Output:</strong> </p>\n\n<pre>\nMethod A \nMethod B: \n&#9;Param1 - 1 \n&#9;Param 2 - Test</pre>\n" }, { "answer_id": 59969586, "author": "Amir Fo", "author_id": 7580839, "author_profile": "https://Stackoverflow.com/users/7580839", "pm_score": 4, "selected": false, "text": "<h2>Indexing (faster)</h2>\n<p>You can use <code>FunctionalInterface</code> to save methods in a container to index them. You can use array container to invoke them by numbers or hashmap to invoke them by strings. By this trick, you can index your methods to invoke them dynamically <strong>faster</strong>.</p>\n<pre><code>@FunctionalInterface\npublic interface Method {\n double execute(int number);\n}\n\npublic class ShapeArea {\n private final static double PI = 3.14;\n\n private Method[] methods = {\n this::square,\n this::circle\n };\n\n private double square(int number) {\n return number * number;\n }\n\n private double circle(int number) {\n return PI * number * number;\n }\n\n public double run(int methodIndex, int number) {\n return methods[methodIndex].execute(number);\n }\n}\n</code></pre>\n<h2>Lambda syntax</h2>\n<p>You can also use lambda syntax:</p>\n<pre><code>public class ShapeArea {\n private final static double PI = 3.14;\n\n private Method[] methods = {\n number -&gt; {\n return number * number;\n },\n number -&gt; {\n return PI * number * number;\n },\n };\n\n public double run(int methodIndex, int number) {\n return methods[methodIndex].execute(number);\n }\n}\n</code></pre>\n<hr />\n<h2>Edit 2022</h2>\n<p>Just now I was thinking to provide you with a universal solution to work with all possible methods with variant number of arguments:</p>\n<pre><code>@FunctionalInterface\npublic interface Method {\n Object execute(Object ...args);\n}\n\npublic class Methods {\n private Method[] methods = {\n this::square,\n this::rectangle\n };\n\n private double square(int number) {\n return number * number;\n }\n\n private double rectangle(int width, int height) {\n return width * height;\n }\n\n public Method run(int methodIndex) {\n return methods[methodIndex];\n }\n}\n</code></pre>\n<p><strong>Usage</strong>:</p>\n<pre><code>methods.run(1).execute(width, height);\n</code></pre>\n" }, { "answer_id": 60026477, "author": "Andronicus", "author_id": 7606764, "author_profile": "https://Stackoverflow.com/users/7606764", "pm_score": 2, "selected": false, "text": "<p>With <a href=\"https://github.com/jOOQ/jOOR\" rel=\"nofollow noreferrer\">jooR</a> it's merely:</p>\n\n<pre><code>on(obj).call(methodName /*params*/).get()\n</code></pre>\n\n<p>Here is a more elaborate example:</p>\n\n<pre><code>public class TestClass {\n\n public int add(int a, int b) { return a + b; }\n private int mul(int a, int b) { return a * b; }\n static int sub(int a, int b) { return a - b; }\n\n}\n\nimport static org.joor.Reflect.*;\n\npublic class JoorTest {\n\n public static void main(String[] args) {\n int add = on(new TestClass()).call(\"add\", 1, 2).get(); // public\n int mul = on(new TestClass()).call(\"mul\", 3, 4).get(); // private\n int sub = on(TestClass.class).call(\"sub\", 6, 5).get(); // static\n System.out.println(add + \", \" + mul + \", \" + sub);\n }\n}\n</code></pre>\n\n<p>This prints:</p>\n\n<blockquote>\n <p>3, 12, 1</p>\n</blockquote>\n" }, { "answer_id": 65878101, "author": "chrizonline", "author_id": 291779, "author_profile": "https://Stackoverflow.com/users/291779", "pm_score": 1, "selected": false, "text": "<p>For those who are calling the method within the same class from a non-static method, see below codes:</p>\n<pre><code>class Person {\n public void method1() {\n try {\n Method m2 = this.getClass().getDeclaredMethod(&quot;method2&quot;);\n m1.invoke(this);\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n\n public void method2() {\n // Do something\n }\n\n}\n</code></pre>\n" }, { "answer_id": 68720276, "author": "FriskySaga", "author_id": 5849965, "author_profile": "https://Stackoverflow.com/users/5849965", "pm_score": 1, "selected": false, "text": "<p>Suppose you're invoking a static method from a static method within the same class. To do that, you can sample the following code.</p>\n<pre><code>class MainClass\n{\n public static int foo()\n {\n return 123;\n }\n\n public static void main(String[] args)\n {\n Method method = MainClass.class.getMethod(&quot;foo&quot;);\n int result = (int) method.invoke(null); // answer evaluates to 123\n }\n}\n</code></pre>\n<p>To explain, since we're not looking to perform true object-oriented programming here, hence avoiding the creation of unnecessary objects, we will instead leverage the <code>class</code> property to invoke <code>getMethod()</code>.</p>\n<p>Then we will pass in <code>null</code> for the <code>invoke()</code> method because we have no object to perform this operation upon.</p>\n<p>And finally, because we, the programmer, know that we are expecting an integer, then\nwe explicitly cast the return value of the <code>invoke()</code> invocation to an integer.</p>\n<p>Now you may wonder: &quot;What even is the point of doing all this non-object oriented programming in Java?&quot;</p>\n<p>My use case was to solve Project Euler problems in Java. I have a single Java source file containing all the solutions, and I wanted to pass in command line arguments to determine which Project Euler problem to run.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
If I have two variables: ``` Object obj; String methodName = "getName"; ``` Without knowing the class of `obj`, how can I call the method identified by `methodName` on it? The method being called has no parameters, and a `String` return value. It's *a getter for a Java bean*.
Coding from the hip, it would be something like: ``` java.lang.reflect.Method method; try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); } catch (SecurityException e) { ... } catch (NoSuchMethodException e) { ... } ``` The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give `methodName`). Then you invoke that method by calling ``` try { method.invoke(obj, arg1, arg2,...); } catch (IllegalArgumentException e) { ... } catch (IllegalAccessException e) { ... } catch (InvocationTargetException e) { ... } ``` Again, leave out the arguments in `.invoke`, if you don't have any. But yeah. Read about [Java Reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html)
160,974
<p>Basically I have the following class:</p> <pre><code>class StateMachine { ... StateMethod stateA(); StateMethod stateB(); ... }; </code></pre> <p>The methods stateA() and stateB() should be able return pointers to stateA() and stateB(). How to typedef the StateMethod?</p>
[ { "answer_id": 161000, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>My philosophy is don't use raw member function pointers. I don't even really know how to do what you want using raw pointer typedef's the syntax is so horrible. I like using boost::function.</p>\n\n<p>This is <strike>almost</strike> certainly wrong:</p>\n\n<pre><code>class X\n{\n public:\n typedef const boost::function0&lt;Method&gt; Method;\n\n // some kind of mutually recursive state machine\n Method stateA()\n { return boost::bind(&amp;X::stateB, this); }\n Method stateB()\n { return boost::bind(&amp;X::stateA, this); }\n};\n</code></pre>\n\n<p>This problem is definitely a lot harder than first meets the eye</p>\n" }, { "answer_id": 161029, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 2, "selected": false, "text": "<p>EDIT: njsf proved me wrong here. You might find static casting simpler to maintain, however, so I will leave the rest here.</p>\n\n<p><strike>There is no 'correct' static type</strike> since the full type is recursive:</p>\n\n<pre><code>typedef StateMethod (StateMachine::*StateMethod)();\n</code></pre>\n\n<p>Your best bet is to use <code>typedef void (StateMachine::*StateMethod)();</code> then do the ugly <code>state = (StateMethod)(this-&gt;*state)();</code></p>\n\n<p>PS: <code>boost::function</code> requires an explicit return type, at least from my reading of the <a href=\"http://synopsis.fresco.org/boost/Scopes/boost/function0.html\" rel=\"nofollow noreferrer\">docs</a>: <code>boost::function0&lt;ReturnType&gt;</code></p>\n" }, { "answer_id": 161039, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://www.gotw.ca/gotw/057.htm\" rel=\"noreferrer\">GotW #57</a> says to use a proxy class with an implicit conversion for this very purpose.</p>\n\n<pre><code>struct StateMethod;\ntypedef StateMethod (StateMachine:: *FuncPtr)(); \nstruct StateMethod\n{\n StateMethod( FuncPtr pp ) : p( pp ) { }\n operator FuncPtr() { return p; }\n FuncPtr p;\n};\n\nclass StateMachine {\n StateMethod stateA();\n StateMethod stateB();\n};\n\nint main()\n{\n StateMachine *fsm = new StateMachine();\n FuncPtr a = fsm-&gt;stateA(); // natural usage syntax\n return 0;\n} \n\nStateMethod StateMachine::stateA\n{\n return stateA; // natural return syntax\n}\n\nStateMethod StateMachine::stateB\n{\n return stateB;\n}\n</code></pre>\n\n<blockquote>\n <p>This solution has three main\n strengths:</p>\n \n <ol>\n <li><p>It solves the problem as required. Better still, it's type-safe and\n portable.</p></li>\n <li><p>Its machinery is transparent: You get natural syntax for the\n caller/user, and natural syntax for\n the function's own \"return stateA;\"\n statement.</p></li>\n <li><p>It probably has zero overhead: On modern compilers, the proxy class,\n with its storage and functions, should\n inline and optimize away to nothing.</p></li>\n </ol>\n</blockquote>\n" }, { "answer_id": 161040, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 3, "selected": false, "text": "<p>Using just typedef:</p>\n\n<pre><code>class StateMachine { \n\n public: \n\n class StateMethod; \n typedef StateMethod (StateMachine::*statemethod)(); \n\n class StateMethod { \n\n statemethod method; \n StateMachine&amp; obj; \n\n public: \n\n StateMethod(statemethod method_, StateMachine *obj_) \n : method(method_), obj(*obj_) {} \n\n StateMethod operator()() { return (obj.*(method))(); } \n }; \n\n StateMethod stateA() { return StateMethod(&amp;StateMachine::stateA, this); } \n\n StateMethod stateB() { return StateMethod(&amp;StateMachine::stateB, this); } \n\n}; \n</code></pre>\n" }, { "answer_id": 163671, "author": "Assaf Lavie", "author_id": 11208, "author_profile": "https://Stackoverflow.com/users/11208", "pm_score": 0, "selected": false, "text": "<p>I can never remember the horrible C++ function declspec, so whenever I have to find out the syntax that describes a member function, for example, I just induce an intentional compiler error which usually displays the correct syntax for me.</p>\n\n<p>So given:</p>\n\n<pre><code>class StateMachine { \n bool stateA(int someArg); \n};\n</code></pre>\n\n<p>What's the syntax for stateA's typedef? No idea.. so let's try to assign to it something unrelated and see what the compiler says:</p>\n\n<pre><code>char c = StateMachine::stateA\n</code></pre>\n\n<p>Compiler says: </p>\n\n<pre><code>error: a value of type \"bool (StateMachine::*)(int)\" cannot be used to initialize \n an entity of type \"char\" \n</code></pre>\n\n<p>There it is: \"bool (StateMachine::*)(int)\" is our typedef.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
Basically I have the following class: ``` class StateMachine { ... StateMethod stateA(); StateMethod stateB(); ... }; ``` The methods stateA() and stateB() should be able return pointers to stateA() and stateB(). How to typedef the StateMethod?
[GotW #57](http://www.gotw.ca/gotw/057.htm) says to use a proxy class with an implicit conversion for this very purpose. ``` struct StateMethod; typedef StateMethod (StateMachine:: *FuncPtr)(); struct StateMethod { StateMethod( FuncPtr pp ) : p( pp ) { } operator FuncPtr() { return p; } FuncPtr p; }; class StateMachine { StateMethod stateA(); StateMethod stateB(); }; int main() { StateMachine *fsm = new StateMachine(); FuncPtr a = fsm->stateA(); // natural usage syntax return 0; } StateMethod StateMachine::stateA { return stateA; // natural return syntax } StateMethod StateMachine::stateB { return stateB; } ``` > > This solution has three main > strengths: > > > 1. It solves the problem as required. Better still, it's type-safe and > portable. > 2. Its machinery is transparent: You get natural syntax for the > caller/user, and natural syntax for > the function's own "return stateA;" > statement. > 3. It probably has zero overhead: On modern compilers, the proxy class, > with its storage and functions, should > inline and optimize away to nothing. > > >
160,995
<p>I tried this XAML:</p> <pre><code>&lt;Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" /&gt; </code></pre> <p>And this C#:</p> <pre><code>private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { sliderMouseDown = true; } private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { sliderMouseDown = false; } </code></pre> <p>The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false?</p>
[ { "answer_id": 161025, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 5, "selected": true, "text": "<p>Sliders swallow the MouseDown Events (similar to the button).</p>\n\n<p>You can register for the PreviewMouseDown and PreviewMouseUp events which get fired before the slider has a chance to handle them.</p>\n" }, { "answer_id": 168928, "author": "cplotts", "author_id": 22294, "author_profile": "https://Stackoverflow.com/users/22294", "pm_score": 4, "selected": false, "text": "<p>Another way to do it (and possibly better depending on your scenario) is to register an event handler in procedural code like the following:</p>\n\n<pre><code>this.AddHandler\n(\n Slider.MouseLeftButtonDownEvent,\n new MouseButtonEventHandler(slider_MouseLeftButtonDown),\n true\n);\n</code></pre>\n\n<p>Please note the true argument. <strong>It basically says that you want to receive that event even if it has been marked as handled.</strong> Unfortunately, hooking up an event handler like this can only be done from procedural code and not from xaml.</p>\n\n<p>In other words, with this method, you can register an event handler for the normal event (which bubbles) instead of the preview event which tunnels (and therefore occur at different times).</p>\n\n<p>See the Digging Deeper sidebar on page 70 of <em>WPF Unleashed</em> for more info.</p>\n" }, { "answer_id": 10958377, "author": "benjamin.popp", "author_id": 385567, "author_profile": "https://Stackoverflow.com/users/385567", "pm_score": 1, "selected": false, "text": "<p>I'd like to mention that the Slider doesn't quite swallow the entire MouseDown event. By clicking on a tick mark, you <em>can</em> get notified for the event. The Slider won't handle MouseDown events unless they come from the slider's... slider.</p>\n\n<p>Basically if you decide to use the</p>\n\n<pre><code>AddHandler(Slider.MouseLeftButtonDownEvent, ..., true)\n</code></pre>\n\n<p>version with the ticks turned on, be sure that the event was handled previously. If you don't you'll end up with an edge case where you thought the slider was clicked, but it was really a tick. Registering for the Preview event is even worse - you'll pick up the event anywhere, even on the white-space between ticks.</p>\n" }, { "answer_id": 27954933, "author": "Derrick", "author_id": 561759, "author_profile": "https://Stackoverflow.com/users/561759", "pm_score": 3, "selected": false, "text": "<p>Try using LostMouseCapture and GotMouseCapture. </p>\n\n<pre><code> private void sliderr_LostMouseCapture(object sender, MouseEventArgs e)\n\n private void slider_GotMouseCapture(object sender, MouseEventArgs e)\n</code></pre>\n\n<p>GotMouseCapture fires when the user begins dragging the slider, and LostMouseCapture when he releases it.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/160995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23939/" ]
I tried this XAML: ``` <Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" /> ``` And this C#: ``` private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { sliderMouseDown = true; } private void slider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { sliderMouseDown = false; } ``` The sliderMouseDown variable never changes because the MouseLeftButtonDown and MouseLeftButtonUp events are never raised. How can I get this code to work when a user has the left mouse button down on a slider to have a bool value set to true, and when the mouse is up, the bool is set to false?
Sliders swallow the MouseDown Events (similar to the button). You can register for the PreviewMouseDown and PreviewMouseUp events which get fired before the slider has a chance to handle them.
161,003
<p>I'm in the early phases of developing a brand spanking new site with Spring + Tiles. The site needs dynamically generated breadcrumbs.</p> <p>What I mean by dynamic is that the user may reach a certain site from multiple starting points. If I have views for Customers, Orders and Products, the user could reach a Product directly:</p> <pre><code>Products -&gt; Product xyz </code></pre> <p>or the user could reach a product through a customer's order:</p> <pre><code>Customers -&gt; John Doe -&gt; Orders -&gt; Order 123 -&gt; Product xyz </code></pre> <p>What is the best way to achieve breadcrumbs like these in a java environment? I've previously done this by using a request attribute (a Vector of Url objects) that is filled with the Urls in each action/servlet of my webapp (like in the action List of Products). I'm not happy with this solution as it requires adding code to each controller/action for generating the breadcrumb trail. And in a case like viewing a product of given order of given customer, the if-then-else logic needed to determine the trail is awful.</p> <p>Are there any libraries that I could use?</p>
[ { "answer_id": 161034, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>Why don't you just use a session variable that stores the trail? Each view would only have to either append itself to the variable or reset the variable in case of the 'root' views. The code to append it and the code to show it would always be the same and could go in a generic library, you just would call it with a flag to either append or reset the value in the case of storing the trail. </p>\n" }, { "answer_id": 169795, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 0, "selected": false, "text": "<p>Struts2 has a <a href=\"http://cwiki.apache.org/S2PLUGINS/breadcrumbs-plugin.html\" rel=\"nofollow noreferrer\">breadcrumbs</a> plugin.</p>\n" }, { "answer_id": 5120561, "author": "gtosto", "author_id": 634594, "author_profile": "https://Stackoverflow.com/users/634594", "pm_score": 0, "selected": false, "text": "<p>There is a more recent struts<sup>2</sup> breadcrumb plugin <a href=\"http://code.google.com/p/struts2-arianna-plugin/\" rel=\"nofollow\">hosted at google code</a> it is very configurable and should satisfy your needs. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15114/" ]
I'm in the early phases of developing a brand spanking new site with Spring + Tiles. The site needs dynamically generated breadcrumbs. What I mean by dynamic is that the user may reach a certain site from multiple starting points. If I have views for Customers, Orders and Products, the user could reach a Product directly: ``` Products -> Product xyz ``` or the user could reach a product through a customer's order: ``` Customers -> John Doe -> Orders -> Order 123 -> Product xyz ``` What is the best way to achieve breadcrumbs like these in a java environment? I've previously done this by using a request attribute (a Vector of Url objects) that is filled with the Urls in each action/servlet of my webapp (like in the action List of Products). I'm not happy with this solution as it requires adding code to each controller/action for generating the breadcrumb trail. And in a case like viewing a product of given order of given customer, the if-then-else logic needed to determine the trail is awful. Are there any libraries that I could use?
Why don't you just use a session variable that stores the trail? Each view would only have to either append itself to the variable or reset the variable in case of the 'root' views. The code to append it and the code to show it would always be the same and could go in a generic library, you just would call it with a flag to either append or reset the value in the case of storing the trail.
161,022
<p>I have some styles applied to html for example </p> <pre><code>&lt;body style="background: #C3DAF9;"&gt; </code></pre> <p>and when I use forms authentication it is ignored. If I put the style into an external .css file then it works. </p> <p>This doesn't seem like normal behaviour to me. </p>
[ { "answer_id": 161062, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>That's weird. I've experienced this problem but the other way around: when I use external style sheets the external style sheet is the one being ignored, and only my inline CSS works.</p>\n\n<p>The solution to that problem was to add permissions for the folder where the external CSS file resides.</p>\n\n<p>One suggestion: View the source of the rendered page, and check the body tag there. It is possible that the style is being overwritten somewhere with the value of the external CSS file.</p>\n" }, { "answer_id": 161501, "author": "Errico Malatesta", "author_id": 24439, "author_profile": "https://Stackoverflow.com/users/24439", "pm_score": -1, "selected": false, "text": "<p>Yes you should check the output html, and your browser.</p>\n\n<p>If there is no style tag in your html output you could use and try:</p>\n\n<pre><code>&lt;body bgcolor=\"#C3DAF9\"&gt;\n</code></pre>\n" }, { "answer_id": 161579, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 1, "selected": false, "text": "<p>Have you tried inspecting your HTML elements with Firebug? That should hopefully tell you what, if anything, is overriding your CSS.</p>\n" }, { "answer_id": 161595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Learn how to use Firebug and use it to determine what styles are applied to your page. </p>\n" }, { "answer_id": 161601, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>The background style does not take a 'color' value.</p>\n\n<p>You are looking for background-color.</p>\n" }, { "answer_id": 165385, "author": "Stephen Price", "author_id": 24395, "author_profile": "https://Stackoverflow.com/users/24395", "pm_score": 2, "selected": true, "text": "<p>Solved the problem. I'm not sure I understand why it happened but here is the offending code;</p>\n\n<pre><code>if (User.Identity.IsAuthenticated) {\n if (User.Identity is BookingIdentity) {\n BookingIdentity id = (BookingIdentity) User.Identity;\n\n Response.Write(\"&lt;p/&gt;UserName: \" + id.Name);\n }\n}\n</code></pre>\n\n<p>Removing the Response.Write makes everything work again. \nThe Response.Write (which I added to check the user was logged in at same time as the forms authentication) seems to be doing something to the page render? Any ideas?</p>\n\n<p>Turns out that Response.Write was the problem, it essentially aborts the rendering of the rest of the page from that point. (or words to that effect)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24395/" ]
I have some styles applied to html for example ``` <body style="background: #C3DAF9;"> ``` and when I use forms authentication it is ignored. If I put the style into an external .css file then it works. This doesn't seem like normal behaviour to me.
Solved the problem. I'm not sure I understand why it happened but here is the offending code; ``` if (User.Identity.IsAuthenticated) { if (User.Identity is BookingIdentity) { BookingIdentity id = (BookingIdentity) User.Identity; Response.Write("<p/>UserName: " + id.Name); } } ``` Removing the Response.Write makes everything work again. The Response.Write (which I added to check the user was logged in at same time as the forms authentication) seems to be doing something to the page render? Any ideas? Turns out that Response.Write was the problem, it essentially aborts the rendering of the rest of the page from that point. (or words to that effect)
161,027
<p>Let's say I am modelling a process that involves a conversation or exchnage between two actors. For this example, I'll use something easily understandable:-</p> <ol> <li>Supplier creates a price list,</li> <li>Buyer chooses some items to buy and sends a Purchase Order,</li> <li>Supplier receives the purchase order and sends the goods.</li> <li>Supplier sends an invoice</li> <li>Buyer receives the invoice and makes a payment</li> </ol> <p>Of course each of those steps in itself could be quick complicated. How would you split this up into use cases in your requirements document?</p> <p>If this process was treated as a single use-case it could fill a book.</p> <p>Alternatively, making a use case out of each of the above steps would hide some of the essential interaction and flow that should be captured. Would it make sense to have a use case that starts at "Received a purchase order" and finishes at "Send an Invoice" and then another that starts at "Receive an Invoice" and ends at "Makes a Payment"?</p> <p>Any advice?</p>
[ { "answer_id": 161062, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>That's weird. I've experienced this problem but the other way around: when I use external style sheets the external style sheet is the one being ignored, and only my inline CSS works.</p>\n\n<p>The solution to that problem was to add permissions for the folder where the external CSS file resides.</p>\n\n<p>One suggestion: View the source of the rendered page, and check the body tag there. It is possible that the style is being overwritten somewhere with the value of the external CSS file.</p>\n" }, { "answer_id": 161501, "author": "Errico Malatesta", "author_id": 24439, "author_profile": "https://Stackoverflow.com/users/24439", "pm_score": -1, "selected": false, "text": "<p>Yes you should check the output html, and your browser.</p>\n\n<p>If there is no style tag in your html output you could use and try:</p>\n\n<pre><code>&lt;body bgcolor=\"#C3DAF9\"&gt;\n</code></pre>\n" }, { "answer_id": 161579, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 1, "selected": false, "text": "<p>Have you tried inspecting your HTML elements with Firebug? That should hopefully tell you what, if anything, is overriding your CSS.</p>\n" }, { "answer_id": 161595, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Learn how to use Firebug and use it to determine what styles are applied to your page. </p>\n" }, { "answer_id": 161601, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "<p>The background style does not take a 'color' value.</p>\n\n<p>You are looking for background-color.</p>\n" }, { "answer_id": 165385, "author": "Stephen Price", "author_id": 24395, "author_profile": "https://Stackoverflow.com/users/24395", "pm_score": 2, "selected": true, "text": "<p>Solved the problem. I'm not sure I understand why it happened but here is the offending code;</p>\n\n<pre><code>if (User.Identity.IsAuthenticated) {\n if (User.Identity is BookingIdentity) {\n BookingIdentity id = (BookingIdentity) User.Identity;\n\n Response.Write(\"&lt;p/&gt;UserName: \" + id.Name);\n }\n}\n</code></pre>\n\n<p>Removing the Response.Write makes everything work again. \nThe Response.Write (which I added to check the user was logged in at same time as the forms authentication) seems to be doing something to the page render? Any ideas?</p>\n\n<p>Turns out that Response.Write was the problem, it essentially aborts the rendering of the rest of the page from that point. (or words to that effect)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14663/" ]
Let's say I am modelling a process that involves a conversation or exchnage between two actors. For this example, I'll use something easily understandable:- 1. Supplier creates a price list, 2. Buyer chooses some items to buy and sends a Purchase Order, 3. Supplier receives the purchase order and sends the goods. 4. Supplier sends an invoice 5. Buyer receives the invoice and makes a payment Of course each of those steps in itself could be quick complicated. How would you split this up into use cases in your requirements document? If this process was treated as a single use-case it could fill a book. Alternatively, making a use case out of each of the above steps would hide some of the essential interaction and flow that should be captured. Would it make sense to have a use case that starts at "Received a purchase order" and finishes at "Send an Invoice" and then another that starts at "Receive an Invoice" and ends at "Makes a Payment"? Any advice?
Solved the problem. I'm not sure I understand why it happened but here is the offending code; ``` if (User.Identity.IsAuthenticated) { if (User.Identity is BookingIdentity) { BookingIdentity id = (BookingIdentity) User.Identity; Response.Write("<p/>UserName: " + id.Name); } } ``` Removing the Response.Write makes everything work again. The Response.Write (which I added to check the user was logged in at same time as the forms authentication) seems to be doing something to the page render? Any ideas? Turns out that Response.Write was the problem, it essentially aborts the rendering of the rest of the page from that point. (or words to that effect)
161,030
<p>In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages. </p> <p>I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded.</p>
[ { "answer_id": 161035, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 5, "selected": true, "text": "<p>Get the AppDomain for your application and attach to the AssemblyLoad event.</p>\n\n<p>Example (C#): </p>\n\n<pre><code>AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad);\n</code></pre>\n" }, { "answer_id": 161036, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Fusion Log Viewer is your friend.</p>\n\n<p>[edit] Actually this might be too over the top, the AssemblyResolve event is good too[edit]</p>\n" }, { "answer_id": 1578820, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 2, "selected": false, "text": "<p>MS Visual Studio has this functionality built in.</p>\n\n<p>Select 'Module Load Messages' from the context menu of the output window in MS Visual Studio and it will display something like:</p>\n\n<pre><code>Loaded 'C:\\Windows\\assembly\\GAC_64\\mscorlib\\2.0.0.0__b77a5c561934e089\\mscorlib.dll'\nLoaded 'C:\\projects\\trunk\\bin\\Tester.exe', Symbols loaded.\nLoaded 'C:\\projects\\trunk\\bin\\log4net.dll'\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12784/" ]
In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages. I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded.
Get the AppDomain for your application and attach to the AssemblyLoad event. Example (C#): ``` AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad); ```
161,048
<p>I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it?</p> <pre><code>$header = "From: site &lt;[email protected]&gt;\r\n"; $header .= "To: $name &lt;$email&gt;\r\n"; $header .= "Subject: $subject\r\n"; $header .= "Reply-To: site &lt;[email protected]&gt;" . "\r\n"; $header .= "MIME-VERSION: 1.0\r\n"; $header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $phpversion = phpversion(); $header .= "X-Mailer: PHP v$phpversion\r\n"; mail($email,$subject,$body,$header); </code></pre>
[ { "answer_id": 161052, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Don't use HTML in your email.</li>\n<li>Send it via a legitimate mail server with a static IP and reverse-DNS (PTR) that points to the machine's real host name (and matches a forward lookup).</li>\n<li>Include a Message-ID (or ensure that the local mailer adds one for you).</li>\n<li>Run your email through <a href=\"http://spamassassin.apache.org/\" rel=\"noreferrer\">SpamAssassin</a> and see which bad-scoring rules it matches. Avoid matching them.</li>\n<li>Use <a href=\"http://en.wikipedia.org/wiki/DKIM\" rel=\"noreferrer\">DomainKeys Identified Mail</a> to digitally sign your messages.</li>\n</ul>\n" }, { "answer_id": 161069, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 1, "selected": false, "text": "<p>In addition to <a href=\"https://stackoverflow.com/questions/161048/what-do-i-need-for-a-compliant-email-header#161052\">Ted Percival's suggestions</a>, make sure that the IP address the email is coming from is a legitimate source for email according to the <a href=\"http://www.openspf.org/\" rel=\"nofollow noreferrer\">SPF record</a> of site.com. If site.com doesn't have an SPF record, adding one (which allows the IP address in question, of course) may help get the emails past spam filters.</p>\n\n<p>And if absolutely do need to use HTML in your email, make sure that you also include a plain text version as well; you'd use the content type of \"multipart/alternative\" instead of \"text/html\".</p>\n" }, { "answer_id": 161080, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 2, "selected": false, "text": "<p>I just successfully tried the following from my Yahoo! Web Hosting account:</p>\n\n<pre>\n$email = \"[email protected]\";\n$subject = \"Simple test\";\n$body = \"Simple test\";\n$header = \"From: site \\r\\n\";\n$header .= \"To: $name \\r\\n\";\n$header .= \"Subject: $subject\\r\\n\";\n$header .= \"Reply-To: site \" . \"\\r\\n\";\n$header .= \"MIME-VERSION: 1.0\\r\\n\";\n$header .= 'Content-type: text/html; charset=iso-8859-1' . \"\\r\\n\";\n$phpversion = phpversion();\n$header .= \"X-Mailer: PHP v$phpversion\\r\\n\";\nmail($email,$subject,$body,$header);\n</pre>\n\n<p>However, you have some duplication in your header you should only need to do the following:</p>\n\n<pre>\n$email = \"[email protected]\";\n$subject = \"Simple test\";\n$body = \"Simple test\";\n$header = \"From: site \\r\\n\";\n$header .= \"MIME-VERSION: 1.0\\r\\n\";\n$header .= 'Content-type: text/html; charset=iso-8859-1' . \"\\r\\n\";\n$phpversion = phpversion();\n$header .= \"X-Mailer: PHP v$phpversion\\r\\n\";\nmail($email,$subject,$body,$header);\n</pre>\n" }, { "answer_id": 161138, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 1, "selected": false, "text": "<p>Ted's suggestions are good, as are Tim's, but the only way I've ever been able to reliably get email through to Yahoo/Hotmail/etc is to use the PEAR email classes. Try those &amp; (assuming your server is OK) I can pretty much guarantee it'll work.</p>\n" }, { "answer_id": 161219, "author": "Sridhar Iyer", "author_id": 13820, "author_profile": "https://Stackoverflow.com/users/13820", "pm_score": 0, "selected": false, "text": "<p>Check rfc 822 and rfc 2045 for email format. I find python's Email class really easy to work with. I assume php's PEAR does the same (according to earlier mails). Also the header and the body are separated by a \"\\r\\n\\r\\n\", not sure if your code automatically inserts that, but you can try appending that to the header.</p>\n\n<p>I dont think that DK/SPF might be necessary (since there are lots of webservers out there without DK/SPF support). There can be alot of factors that might be causing it to get blocked(atleast 10K different criterions and methods.. p0f,greylisting,greylisting, blacklisting etc etc). Make sure that your email is properly formatted(this makes a BIG difference). Look into libraries that generate the complete header for you.. that way you have least chances of making any mistake.</p>\n" }, { "answer_id": 161727, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 3, "selected": true, "text": "<p>In addition to Ted Percival's suggestions, you could try using <a href=\"http://phpmailer.codeworxtech.com/index.php?pg=phpmailer\" rel=\"nofollow noreferrer\">PHPMailer</a> to create the emails for you rather than manually building the headers. I've used this class extensively and not had any trouble with email being rejected as spam by Yahoo, or anyone else.</p>\n" }, { "answer_id": 165165, "author": "jasonbar", "author_id": 15099, "author_profile": "https://Stackoverflow.com/users/15099", "pm_score": 1, "selected": false, "text": "<p>Ted and Tim have excellent suggestions. As does Shabbyrobe. We use PHPMailer and don't have any problems with spam filters.</p>\n\n<p>One thing to note is that many spam filters will count NOT having a text version against you if you are using a MIME format. You could add all of the headers and the text version yourself, or just let PHPMailer or the PEAR mail library take care of that for you. Having a text version may or may not help, but it is good practice and user friendly.</p>\n\n<p>I realize that your code sample is just that - a sample, but it is worth saying: Do not ever just drop user provided data into your mail headers. Make sure you validate that it is data you expect. It is trivial to turn a php mail script into an open relay, and nobody wants that.</p>\n" }, { "answer_id": 1072998, "author": "The Disintegrator", "author_id": 92462, "author_profile": "https://Stackoverflow.com/users/92462", "pm_score": 0, "selected": false, "text": "<p>Adding a SPF record is very easy. You should try.</p>\n\n<p>This one is for dreamhost plus googlemail\nYou should also ad you webserver ip address (in my case, the line before googlemail)\nThe last line tells the server to do a soft reject (mark as spam but don't delete) I'm using it instead of \"-\" (delete) because google documentation says so :-)</p>\n\n<p>It's a TXT record\nv=spf1\nip4:64.111.100.0/24 ip4:66.33.201.0/24 ip4:66.33.216.0/24\nip4:208.97.132.0/24 ip4:208.97.187.0/24 ip4:208.113.200.0/24 ip4:208.113.244.0/24\nip4:208.97.132.74 ip4:67.205.36.71\ninclude:aspmx.googlemail.com\nmx ~all</p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 2194725, "author": "jschrab", "author_id": 12694, "author_profile": "https://Stackoverflow.com/users/12694", "pm_score": 2, "selected": false, "text": "<p>There is also the possibility that 'sendmail' (which is underneath the PHP mail() function) needs extra parameters. If you have a problem with return headers (such as Return-Path) not being set with what you set them to be, you may need to use the <em>fifth</em> mail() parameter. Example:</p>\n\n<pre><code>mail('[email protected]', 'Subject', $mail_body, $headers, \" -f [email protected]\");\n</code></pre>\n\n<p>There is some further evidence that true vanilla sendmail may have problem with this! Hopefully you have 'postfix' as PHP's underlying mail() support on your target server.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/161048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3800/" ]
I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it? ``` $header = "From: site <[email protected]>\r\n"; $header .= "To: $name <$email>\r\n"; $header .= "Subject: $subject\r\n"; $header .= "Reply-To: site <[email protected]>" . "\r\n"; $header .= "MIME-VERSION: 1.0\r\n"; $header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $phpversion = phpversion(); $header .= "X-Mailer: PHP v$phpversion\r\n"; mail($email,$subject,$body,$header); ```
In addition to Ted Percival's suggestions, you could try using [PHPMailer](http://phpmailer.codeworxtech.com/index.php?pg=phpmailer) to create the emails for you rather than manually building the headers. I've used this class extensively and not had any trouble with email being rejected as spam by Yahoo, or anyone else.