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
260,236
<p>I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function. So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all.</p> <p>For example:</p> <p>MySQL hash -> 464bb2cb3cf18b66</p> <p>MySQL5 hash -> *01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229</p> <p>Thanks!</p>
[ { "answer_id": 260280, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 2, "selected": false, "text": "<p>Why do you want to use mysql password() function?\nEven the Mysql documentation advises against this:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_password\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_password</a></p>\n\n<blockquote>\n <p>The PASSWORD() function is used by the authentication system in MySQL Server; you should not use it in your own applications</p>\n</blockquote>\n\n<p>You can use md5() for example, wich is present in almost every programming language, php and perl included.</p>\n" }, { "answer_id": 260286, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "<p>If you are interested in the algorithm of this function, download the source code and see the file sql/password.c, or check <a href=\"http://www.sfr-fresh.com/unix/privat/tpop3d-1.5.5.tar.gz:a/tpop3d-1.5.5/password.c\" rel=\"noreferrer\">this</a> implementation.</p>\n" }, { "answer_id": 1543873, "author": "defines", "author_id": 120990, "author_profile": "https://Stackoverflow.com/users/120990", "pm_score": 5, "selected": false, "text": "<p>I originally stumbled across this question in my own search for a PHP implementation of the two MySQL password hashing functions. I was unable to find any implementations, so I adapted my own from the MySQL source code (sql/password.c). The following are tested and working in PHP 5.2:</p>\n\n<pre><code>// The following is free for any use provided credit is given where due.\n// This code comes with NO WARRANTY of any kind, including any implied warranty.\n\n/**\n * MySQL \"OLD_PASSWORD()\" AKA MySQL323 HASH FUNCTION\n * This is the password hashing function used in MySQL prior to version 4.1.1\n * By Defines Fineout 10/9/2009 9:12:16 AM\n**/\nfunction mysql_old_password_hash($input, $hex = true)\n{\n $nr = 1345345333; $add = 7; $nr2 = 0x12345671; $tmp = null;\n $inlen = strlen($input);\n for ($i = 0; $i &lt; $inlen; $i++) {\n $byte = substr($input, $i, 1);\n if ($byte == ' ' || $byte == \"\\t\") continue;\n $tmp = ord($byte);\n $nr ^= ((($nr &amp; 63) + $add) * $tmp) + (($nr &lt;&lt; 8) &amp; 0xFFFFFFFF);\n $nr2 += (($nr2 &lt;&lt; 8) &amp; 0xFFFFFFFF) ^ $nr;\n $add += $tmp;\n }\n $out_a = $nr &amp; ((1 &lt;&lt; 31) - 1);\n $out_b = $nr2 &amp; ((1 &lt;&lt; 31) - 1);\n $output = sprintf(\"%08x%08x\", $out_a, $out_b);\n if ($hex) return $output;\n return hex_hash_to_bin($output);\n} //END function mysql_old_password_hash\n\n/**\n * MySQL \"PASSWORD()\" AKA MySQLSHA1 HASH FUNCTION\n * This is the password hashing function used in MySQL since version 4.1.1\n * By Defines Fineout 10/9/2009 9:36:20 AM\n**/\nfunction mysql_password_hash($input, $hex = true)\n{\n $sha1_stage1 = sha1($input, true);\n $output = sha1($sha1_stage1, !$hex);\n return $output;\n} //END function mysql_password_hash\n\n/**\n * Computes each hexidecimal pair into the corresponding binary octet.\n * Similar to mysql hex2octet function.\n**/\nfunction hex_hash_to_bin($hex)\n{\n $bin = \"\";\n $len = strlen($hex);\n for ($i = 0; $i &lt; $len; $i += 2) {\n $byte_hex = substr($hex, $i, 2);\n $byte_dec = hexdec($byte_hex);\n $byte_char = chr($byte_dec);\n $bin .= $byte_char;\n }\n return $bin;\n} //END function hex_hash_to_bin\n</code></pre>\n\n<p>Hopefully someone else will find this useful as well :)</p>\n" }, { "answer_id": 5576372, "author": "TFBW", "author_id": 341930, "author_profile": "https://Stackoverflow.com/users/341930", "pm_score": 1, "selected": false, "text": "<p>Based on the PHP implementation above, here's a Perl example that works.</p>\n\n<pre><code>use Digest::SHA1 qw(sha1 sha1_hex);\nsub password { \"*\".uc(sha1_hex(sha1($_[0]))) }\n</code></pre>\n\n<p>The password function returns the same as the MySQL5 PASSWORD() function.</p>\n\n<p>In answer to \"why would anyone want to do this?\", I use it to generate SQL \"CREATE USER\" statements that don't contain plain-text passwords.</p>\n" }, { "answer_id": 8634675, "author": "Kerem", "author_id": 362780, "author_profile": "https://Stackoverflow.com/users/362780", "pm_score": 3, "selected": false, "text": "<p>Yes, too late but I just came up this implementation on that page: <a href=\"http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html</a></p>\n\n<p>Here is the equivalent php function to mysql password;</p>\n\n<pre><code>function mysql_41_password($in) {\n $p = sha1($in, true);\n $p = sha1($p);\n return '*'. strtoupper($p);\n} \n</code></pre>\n" }, { "answer_id": 9208686, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Bad boys do that in bash with sha1sum ;)</p>\n\n<pre><code>PHRASE=\"password\"; P1=`echo -n \"${PHRASE}\"|sha1sum`; P2=\"*`echo -en $(echo -n ${P1%% *}|sed -E 's/([0-9a-f]{2})/\\\\\\x\\1/g')|sha1sum -b`\"; PASS=\"${P2%% *}\"; echo \"${PASS^^}\"\n</code></pre>\n\n<p>OT, but anyway... :)</p>\n" }, { "answer_id": 49433597, "author": "Matthew Lenz", "author_id": 2051257, "author_profile": "https://Stackoverflow.com/users/2051257", "pm_score": 0, "selected": false, "text": "<p>Perl 5 implementation of old_password() based on the PHP example.</p>\n\n<pre><code>sub old_hash_password {\n my ($password) = @_;\n\n my $nr = 1345345333;\n my $nr2 = 0x12345671;\n my $add = 7;\n\n for (my $i = 0; $i &lt; length($password); $i++) {\n my $byte = substr($password, $i, 1);\n\n next if ($byte eq ' ' || $byte eq \"\\t\");\n\n my $ord_b = ord($byte);\n $nr ^= ((($nr &amp; 63) + $add) * $ord_b) + (($nr &lt;&lt; 8) &amp; 0xFFFFFFFF);\n $nr2 += (($nr2 &lt;&lt; 8) &amp; 0xFFFFFFFF) ^ $nr;\n $add += $ord_b;\n }\n\n my $out_a = $nr &amp; ((1 &lt;&lt; 31) - 1);\n my $out_b = $nr2 &amp; ((1 &lt;&lt; 31) - 1);\n\n return sprintf(\"%08x%08x\", $out_a, $out_b);\n}\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function. So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all. For example: MySQL hash -> 464bb2cb3cf18b66 MySQL5 hash -> \*01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229 Thanks!
I originally stumbled across this question in my own search for a PHP implementation of the two MySQL password hashing functions. I was unable to find any implementations, so I adapted my own from the MySQL source code (sql/password.c). The following are tested and working in PHP 5.2: ``` // The following is free for any use provided credit is given where due. // This code comes with NO WARRANTY of any kind, including any implied warranty. /** * MySQL "OLD_PASSWORD()" AKA MySQL323 HASH FUNCTION * This is the password hashing function used in MySQL prior to version 4.1.1 * By Defines Fineout 10/9/2009 9:12:16 AM **/ function mysql_old_password_hash($input, $hex = true) { $nr = 1345345333; $add = 7; $nr2 = 0x12345671; $tmp = null; $inlen = strlen($input); for ($i = 0; $i < $inlen; $i++) { $byte = substr($input, $i, 1); if ($byte == ' ' || $byte == "\t") continue; $tmp = ord($byte); $nr ^= ((($nr & 63) + $add) * $tmp) + (($nr << 8) & 0xFFFFFFFF); $nr2 += (($nr2 << 8) & 0xFFFFFFFF) ^ $nr; $add += $tmp; } $out_a = $nr & ((1 << 31) - 1); $out_b = $nr2 & ((1 << 31) - 1); $output = sprintf("%08x%08x", $out_a, $out_b); if ($hex) return $output; return hex_hash_to_bin($output); } //END function mysql_old_password_hash /** * MySQL "PASSWORD()" AKA MySQLSHA1 HASH FUNCTION * This is the password hashing function used in MySQL since version 4.1.1 * By Defines Fineout 10/9/2009 9:36:20 AM **/ function mysql_password_hash($input, $hex = true) { $sha1_stage1 = sha1($input, true); $output = sha1($sha1_stage1, !$hex); return $output; } //END function mysql_password_hash /** * Computes each hexidecimal pair into the corresponding binary octet. * Similar to mysql hex2octet function. **/ function hex_hash_to_bin($hex) { $bin = ""; $len = strlen($hex); for ($i = 0; $i < $len; $i += 2) { $byte_hex = substr($hex, $i, 2); $byte_dec = hexdec($byte_hex); $byte_char = chr($byte_dec); $bin .= $byte_char; } return $bin; } //END function hex_hash_to_bin ``` Hopefully someone else will find this useful as well :)
260,252
<p>I have a web-app that I would like to extend to support multiple languages with new URLs. For example, www.example.com/home.do stays English, but www.example.com/es/home.do is Spanish. My first thought was to create a Filter which rewrites incoming urls like /es/home.do to /home.do (and sets the Locale in the Request); this works fine. The Filter wraps the ServletRequest with an HttpServletRequestWrapper which overrides getContextPath() to return the language:</p> <pre><code>class FakeContextRequest extends HttpServletRequestWrapper { private String context = ""; FakeContextRequest(HttpServletRequest request, String context) { super(request); // snip some validation code this.context = request.getContextPath() + context; } @Override public String getContextPath() { return this.context; } } </code></pre> <p>My Filter forwards to the appropriate request as follows:</p> <pre><code>FakeContextRequest fr = new FakeContextRequest(request, lang); fr.getRequestDispatcher(newResourceName).forward(fr, response); </code></pre> <p>My problem is that the next servlet doesn't forward properly. The next servlet (typically a Struts ActionServlet) forwards to a JSP (often using Struts Tiles); when I get to the JSP the HttpServletRequest has been wrapped several times and the object in question reports the context to be empty (the root context, which is where the application is actually deployed).</p> <p>I want the context to be re-written so that all my context-aware code that already exists can automatically insert the language into the URLs that are written. Is this possible?</p> <p><strong>Edit:</strong> I solved my problem by using a wrapped HttpServletResponse instead of a wrapped HttpServletRequest; I rewrite the URL in the response.encodeURL() method.</p>
[ { "answer_id": 260293, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 0, "selected": false, "text": "<p>As far as I know, the conventional way to do this is with the accept-language HTTP header. The presentation language is a presentation detail, which shouldn't be represented by the set of URLs to navigate through the application.</p>\n" }, { "answer_id": 260371, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": true, "text": "<p>I'm not sure that overriding <code>getContextPath()</code> is enough to solve your problem. What if Struts is calling <code>ServletContext.getContextPath()</code> under the covers, or uses <code>getRequestURI()</code>, etc?</p>\n" }, { "answer_id": 288104, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 0, "selected": false, "text": "<p>I solved my problem by doing URL Rewriting in response.encodeURL() and friends. The request object gets wrapped and replaced throughout the request chain but the response object seems to make through unmolested. This works very reliably.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867/" ]
I have a web-app that I would like to extend to support multiple languages with new URLs. For example, www.example.com/home.do stays English, but www.example.com/es/home.do is Spanish. My first thought was to create a Filter which rewrites incoming urls like /es/home.do to /home.do (and sets the Locale in the Request); this works fine. The Filter wraps the ServletRequest with an HttpServletRequestWrapper which overrides getContextPath() to return the language: ``` class FakeContextRequest extends HttpServletRequestWrapper { private String context = ""; FakeContextRequest(HttpServletRequest request, String context) { super(request); // snip some validation code this.context = request.getContextPath() + context; } @Override public String getContextPath() { return this.context; } } ``` My Filter forwards to the appropriate request as follows: ``` FakeContextRequest fr = new FakeContextRequest(request, lang); fr.getRequestDispatcher(newResourceName).forward(fr, response); ``` My problem is that the next servlet doesn't forward properly. The next servlet (typically a Struts ActionServlet) forwards to a JSP (often using Struts Tiles); when I get to the JSP the HttpServletRequest has been wrapped several times and the object in question reports the context to be empty (the root context, which is where the application is actually deployed). I want the context to be re-written so that all my context-aware code that already exists can automatically insert the language into the URLs that are written. Is this possible? **Edit:** I solved my problem by using a wrapped HttpServletResponse instead of a wrapped HttpServletRequest; I rewrite the URL in the response.encodeURL() method.
I'm not sure that overriding `getContextPath()` is enough to solve your problem. What if Struts is calling `ServletContext.getContextPath()` under the covers, or uses `getRequestURI()`, etc?
260,253
<p>A little example</p> <pre><code>TTest&lt;T&gt; = class private f : T; public function ToString : string; end; </code></pre> <p>If is an object then this should work</p> <pre><code>TTest&lt;T&gt;.ToString; begin Result := f.ToString; end; </code></pre> <p>But what happens when is say an integer? This would be ok in .net. of course.</p> <p>I know it won't work, but how do I code this to work with objects AND simple types?</p>
[ { "answer_id": 260266, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>The last example will not work. You need to add a constraint in order to use methods. In this case TObject will be enough:</p>\n\n<pre><code>TTest&lt;T: TObject&gt;.ToString;\nbegin\n Result := T.ToString;\nend;\n</code></pre>\n\n<p>You can use simple types with unrestrained generics, but you are very limited in the use. Because the only valid operations are assignment and comparison (equal and not equal).</p>\n\n<p>In Delphi simple types are no classes, so they don't have methods.\nBut you can do the following:</p>\n\n<pre><code>type\n TToString&lt;T&gt; = reference to function(const AValue: T): string;\n TGenContainer&lt;T&gt; = class\n private\n FValue: T;\n FToString : TToString&lt;T&gt;;\n public\n constructor Create(const AToString: TToString&lt;T&gt;);\n\n function ToString: string;\n\n property Value: T read FValue write FValue;\n end;\n\nconstructor TGenContainer&lt;T&gt;.Create(const AToString: TToString&lt;T&gt;);\nbegin\n FToString := AToString;\nend;\n\nfunction TGenContainer&lt;T&gt;.ToString: string;\nbegin\n Result := FToString(FValue);\nend;\n\n\n\nprocedure TForm2.Button1Click(Sender: TObject);\nvar\n gen : TGenContainer&lt;Integer&gt;;\nbegin\n gen := TGenContainer&lt;Integer&gt;.Create(\n function(const AValue: Integer): string\n begin\n Result := IntToStr(AValue);\n end);\n try\n gen.Value := 17;\n Memo1.Lines.Add(gen.ToString);\n finally\n gen.Free;\n end;\nend;\n</code></pre>\n\n<p>This works fine.</p>\n" }, { "answer_id": 260276, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 0, "selected": false, "text": "<p>I guess I could wrap my simple types in objects, and override the ToString function, but it does defeat the purpose of generics.</p>\n" }, { "answer_id": 260351, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": true, "text": "<p>There are three reasons why Delphi doesn't let you do what you are trying to do in your second example - call the ToString method on a value of an unconstrained type parameter type (or at least that's what I think you were trying to show, since TObject.ToString is an instance method, not a class method, so T.ToString would not work even for TObject).</p>\n\n<ol>\n<li><p>Delphi does not have a rooted type system, and there are very few operations that are common to all types. These operations - copying, assignment, creating locations (fields, locals, parameters, arrays) - are the only operations that are guaranteed to be available on all possible values of the type parameter.</p></li>\n<li><p>Following on from 1, why are the operations restricted to these? Why not permit the operations in the generic class, and only give errors at instantiation time? Well, the first part of the reason is that the design was originally intended to maximize compatibility with .NET and dccil, so things that .NET generics did not permit did not have significant affordances in the Win32 generics design.</p></li>\n<li><p>The second justification for the design is that check-only-at-instantiation-time is problematic. The most famous parametric polymorphism implementation that uses this approach is C++ templates, and it is also famous for its cryptic error messages, as you e.g. try to pass the wrong kind of iterator to an algorithm, and get odd complaints about overloaded operators not being found. The deeper the polymorphism, the worse the problem. In fact, it's so bad that C++ is itself rectifying this fault in the form of C++ 0x Concepts.</p></li>\n</ol>\n\n<p>Hopefully you now understand why operations that aren't guaranteed to be available via constraints cannot be used. However, you can get out of this restriction relatively easily, by providing the operation in the form of a method reference or interface implementation, as Gamecat suggested.</p>\n\n<p>In the future, generics in Delphi for Win32 will likely be extended along similar lines to C++ 0x Concepts, or Haskell type classes, such that type parameters may be constrained to have certain methods, functions and operators available. If it went along type class lines, then type inference may proceed in that fashion too.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
A little example ``` TTest<T> = class private f : T; public function ToString : string; end; ``` If is an object then this should work ``` TTest<T>.ToString; begin Result := f.ToString; end; ``` But what happens when is say an integer? This would be ok in .net. of course. I know it won't work, but how do I code this to work with objects AND simple types?
There are three reasons why Delphi doesn't let you do what you are trying to do in your second example - call the ToString method on a value of an unconstrained type parameter type (or at least that's what I think you were trying to show, since TObject.ToString is an instance method, not a class method, so T.ToString would not work even for TObject). 1. Delphi does not have a rooted type system, and there are very few operations that are common to all types. These operations - copying, assignment, creating locations (fields, locals, parameters, arrays) - are the only operations that are guaranteed to be available on all possible values of the type parameter. 2. Following on from 1, why are the operations restricted to these? Why not permit the operations in the generic class, and only give errors at instantiation time? Well, the first part of the reason is that the design was originally intended to maximize compatibility with .NET and dccil, so things that .NET generics did not permit did not have significant affordances in the Win32 generics design. 3. The second justification for the design is that check-only-at-instantiation-time is problematic. The most famous parametric polymorphism implementation that uses this approach is C++ templates, and it is also famous for its cryptic error messages, as you e.g. try to pass the wrong kind of iterator to an algorithm, and get odd complaints about overloaded operators not being found. The deeper the polymorphism, the worse the problem. In fact, it's so bad that C++ is itself rectifying this fault in the form of C++ 0x Concepts. Hopefully you now understand why operations that aren't guaranteed to be available via constraints cannot be used. However, you can get out of this restriction relatively easily, by providing the operation in the form of a method reference or interface implementation, as Gamecat suggested. In the future, generics in Delphi for Win32 will likely be extended along similar lines to C++ 0x Concepts, or Haskell type classes, such that type parameters may be constrained to have certain methods, functions and operators available. If it went along type class lines, then type inference may proceed in that fashion too.
260,254
<p>I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.</p> <p>Is there a simple way to do this without re-writing the function myself? I searched around for a simple library, but couldn't find anything. Surely this is a common problem.</p>
[ { "answer_id": 260262, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": true, "text": "<p>A simpler approach is to replace everything which is not a character or a number with an underscore.</p>\n\n<p>EDIT: Here's a naive implementation in C:</p>\n\n<pre><code>#include &lt;cctype&gt;\n\nchar *safe_url(const char *str) {\n char *safe = strdup(str);\n for (int i = 0; i &lt; strlen(str); i++) {\n if (isalpha(str[i]))\n safe[i] = str[i];\n else\n safe[i] = '_';\n }\n}\n</code></pre>\n" }, { "answer_id": 260268, "author": "John", "author_id": 13895, "author_profile": "https://Stackoverflow.com/users/13895", "pm_score": 0, "selected": false, "text": "<p>What about <a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/hash.html\" rel=\"nofollow noreferrer\"><code>boost::hash</code></a>?</p>\n" }, { "answer_id": 260313, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 2, "selected": false, "text": "<p>In a similar situation I encoded the key's bytes in hex (where, in your case, the key is the hash of the URL). This doubles the size but is simple, avoids any possible problems with your filesystem mangling the characters, and sorts in the same order as the original key.</p>\n\n<p>(Originally I tried a slightly fancier, more efficient encoding, which I thought escaped any problematic characters, but OS X's filesystem turns out to be crazier than I assumed.)</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33791/" ]
I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename. Is there a simple way to do this without re-writing the function myself? I searched around for a simple library, but couldn't find anything. Surely this is a common problem.
A simpler approach is to replace everything which is not a character or a number with an underscore. EDIT: Here's a naive implementation in C: ``` #include <cctype> char *safe_url(const char *str) { char *safe = strdup(str); for (int i = 0; i < strlen(str); i++) { if (isalpha(str[i])) safe[i] = str[i]; else safe[i] = '_'; } } ```
260,273
<p>I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than:</p> <pre><code>s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" </code></pre>
[ { "answer_id": 260282, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>read the last few Ks of the file, and split that into lines to return only the last 10.</p>\n\n<p>it's quite unlikely the start of that chunk to fall on a line boundary, but you'll discard the first lines anyway.</p>\n" }, { "answer_id": 260287, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 1, "selected": false, "text": "<p>You could read chunks of 1,000 bytes or so from the end of the file into a buffer until you have 10 lines.</p>\n" }, { "answer_id": 260312, "author": "Ryan Ginstrom", "author_id": 10658, "author_profile": "https://Stackoverflow.com/users/10658", "pm_score": 3, "selected": false, "text": "<p>I think reading the last 2 KB or so of the file should make sure you get 10 lines, and shouldn't be too much of a resource hog.</p>\n\n<pre><code>file_handle = open(\"somefile\")\nfile_size = file_handle.tell()\nfile_handle.seek(max(file_size - 2*1024, 0))\n\n# this will get rid of trailing newlines, unlike readlines()\nlast_10 = file_handle.read().splitlines()[-10:]\n\nassert len(last_10) == 10, \"Only read %d lines\" % len(last_10)\n</code></pre>\n" }, { "answer_id": 260324, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 0, "selected": false, "text": "<p>Personally I'd be tempted to break out to the shell and call tail -n10 to load the file. But then I'm not really a Python programmer ;)</p>\n" }, { "answer_id": 260339, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 2, "selected": false, "text": "<p>I think I remember adapting the code from <a href=\"http://manugarg.blogspot.com/2007/04/tailing-in-python.html\" rel=\"nofollow noreferrer\">this blog post from Manu Garg</a> when I had to do something similar.</p>\n" }, { "answer_id": 260352, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 6, "selected": true, "text": "<pre><code># Tail\nfrom __future__ import with_statement\n\nfind_str = \"FIREFOX\" # String to find\nfname = \"g:/autoIt/ActiveWin.log_2\" # File to check\n\nwith open(fname, \"r\") as f:\n f.seek (0, 2) # Seek @ EOF\n fsize = f.tell() # Get Size\n f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars\n lines = f.readlines() # Read to end\n\nlines = lines[-10:] # Get last 10 lines\n\n# This returns True if any line is exactly find_str + \"\\n\"\nprint find_str + \"\\n\" in lines\n\n# If you're searching for a substring\nfor line in lines:\n if find_str in line:\n print True\n break\n</code></pre>\n" }, { "answer_id": 260359, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p>First, a function that returns a list:</p>\n\n<pre><code>def lastNLines(file, N=10, chunksize=1024):\n lines = None\n file.seek(0,2) # go to eof\n size = file.tell()\n for pos in xrange(chunksize,size-1,chunksize):\n # read a chunk\n file.seek(pos,2)\n chunk = file.read(chunksize)\n if lines is None:\n # first time\n lines = chunk.splitlines()\n else:\n # other times, update the 'first' line with\n # the new data, and re-split\n lines[0:1] = (chunk + lines[0]).splitlines()\n if len(lines) &gt; N:\n return lines[-N:]\n file.seek(0)\n chunk = file.read(size-pos)\n lines[0:1] = (chunk + lines[0]).splitlines()\n return lines[-N:]\n</code></pre>\n\n<p>Second, a function that iterates over the lines in reverse order:</p>\n\n<pre><code>def iter_lines_reversed(file, chunksize=1024):\n file.seek(0,2)\n size = file.tell()\n last_line = \"\"\n for pos in xrange(chunksize,size-1,chunksize):\n # read a chunk\n file.seek(pos,2)\n chunk = file.read(chunksize) + last_line\n # split into lines\n lines = chunk.splitlines()\n last_line = lines[0]\n # iterate in reverse order\n for index,line in enumerate(reversed(lines)):\n if index &gt; 0:\n yield line\n # handle the remaining data at the beginning of the file\n file.seek(0)\n chunk = file.read(size-pos) + last_line\n lines = chunk.splitlines()\n for line in reversed(lines):\n yield line\n</code></pre>\n\n<p>For your example:</p>\n\n<pre><code>s = \"foo\"\nfor index, line in enumerate(iter_lines_reversed(fileObj)):\n if line == s:\n print \"FOUND\"\n break\n elif index+1 &gt;= 10:\n break\n</code></pre>\n\n<p><strong>Edit:</strong> Now gets the file-size automaticly<br>\n<strong>Edit2:</strong> Now only iterates for 10 lines.</p>\n" }, { "answer_id": 260394, "author": "Myrddin Emrys", "author_id": 9084, "author_profile": "https://Stackoverflow.com/users/9084", "pm_score": 3, "selected": false, "text": "<p>If you are running Python on a POSIX system, you can use 'tail -10' to retrieve the last few lines. This may be faster than writing your own Python code to get the last 10 lines. Rather than opening the file directly, open a pipe from the command 'tail -10 filename'. If you are certain of the log output though (for example, you know that there are <strong>never</strong> any very long lines that are hundreds or thousands of characters long) then using one of the 'read the last 2KB' approaches listed would be fine.</p>\n" }, { "answer_id": 260407, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>If you're on a unix box, <code>os.popen(\"tail -10 \" + filepath).readlines()</code> will probably be the fastest way. Otherwise, it depends on how robust you want it to be. The methods proposed so far will all fall down, one way or another. For robustness and speed in the most common case you probably want something like a logarithmic search: use file.seek to go to end of the file minus 1000 characters, read it in, check how many lines it contains, then to EOF minus 3000 characters, read in 2000 characters, count the lines, then EOF minus 7000, read in 4000 characters, count the lines, etc. until you have as many lines as you need. But if you know for sure that it's always going to be run on files with sensible line lengths, you may not need that.</p>\n\n<p>You might also find some inspiration in the <a href=\"http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx\" rel=\"nofollow noreferrer\">source code</a> for the unix <code>tail</code> command.</p>\n" }, { "answer_id": 260433, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 5, "selected": false, "text": "<p>Here's an answer like MizardX's, but without its apparent problem of taking quadratic time in the worst case from rescanning the working string repeatedly for newlines as chunks are added.</p>\n<p>Compared to the Active State solution (which also seems to be quadratic), this doesn't blow up given an empty file and does one seek per block read instead of two.</p>\n<p>Compared to spawning 'tail', this is self-contained. (But 'tail' is best if you have it.)</p>\n<p>Compared to grabbing a few kB off the end and hoping it's enough, this works for any line length.</p>\n<pre><code>import os\n\ndef reversed_lines(file):\n &quot;Generate the lines of file in reverse order.&quot;\n part = ''\n for block in reversed_blocks(file):\n for c in reversed(block):\n if c == '\\n' and part:\n yield part[::-1]\n part = ''\n part += c\n if part: yield part[::-1]\n\ndef reversed_blocks(file, blocksize=4096):\n &quot;Generate blocks of file's contents in reverse order.&quot;\n file.seek(0, os.SEEK_END)\n here = file.tell()\n while 0 &lt; here:\n delta = min(blocksize, here)\n here -= delta\n file.seek(here, os.SEEK_SET)\n yield file.read(delta)\n</code></pre>\n<p>To use it as requested:</p>\n<pre><code>from itertools import islice\n\ndef check_last_10_lines(file, key):\n for line in islice(reversed_lines(file), 10):\n if line.rstrip('\\n') == key:\n print 'FOUND'\n break\n</code></pre>\n<p><strong>Edit:</strong> changed map() to itertools.imap() in head(). <strong>Edit 2:</strong> simplified reversed_blocks(). <strong>Edit 3:</strong> avoid rescanning tail for newlines. <strong>Edit 4:</strong> rewrote reversed_lines() because str.splitlines() ignores a final '\\n', as BrianB noticed (thanks).</p>\n<p>Note that in very old Python versions the string concatenation in a loop here will take quadratic time. CPython from at least the last few years avoids this problem automatically.</p>\n" }, { "answer_id": 260648, "author": "user32716", "author_id": 32716, "author_profile": "https://Stackoverflow.com/users/32716", "pm_score": 2, "selected": false, "text": "<p>I ran into that problem, parsing the last hour of LARGE syslog files, and used this function from activestate's recipe site... (<a href=\"http://code.activestate.com/recipes/439045/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/439045/</a>)</p>\n\n<pre><code>!/usr/bin/env python\n# -*-mode: python; coding: iso-8859-1 -*-\n#\n# Copyright (c) Peter Astrand &lt;[email protected]&gt;\n\nimport os\nimport string\n\nclass BackwardsReader:\n \"\"\"Read a file line by line, backwards\"\"\"\n BLKSIZE = 4096\n\n def readline(self):\n while 1:\n newline_pos = string.rfind(self.buf, \"\\n\")\n pos = self.file.tell()\n if newline_pos != -1:\n # Found a newline\n line = self.buf[newline_pos+1:]\n self.buf = self.buf[:newline_pos]\n if pos != 0 or newline_pos != 0 or self.trailing_newline:\n line += \"\\n\"\n return line\n else:\n if pos == 0:\n # Start-of-file\n return \"\"\n else:\n # Need to fill buffer\n toread = min(self.BLKSIZE, pos)\n self.file.seek(-toread, 1)\n self.buf = self.file.read(toread) + self.buf\n self.file.seek(-toread, 1)\n if pos - toread == 0:\n self.buf = \"\\n\" + self.buf\n\n def __init__(self, file):\n self.file = file\n self.buf = \"\"\n self.file.seek(-1, 2)\n self.trailing_newline = 0\n lastchar = self.file.read(1)\n if lastchar == \"\\n\":\n self.trailing_newline = 1\n self.file.seek(-1, 2)\n\n# Example usage\nbr = BackwardsReader(open('bar'))\n\nwhile 1:\n line = br.readline()\n if not line:\n break\n print repr(line)\n</code></pre>\n\n<p>It works really well and is much more efficient then anything like fileObj.readlines()[-10:], which makes python read the entire file into memory and then chops the last ten lines off of it.</p>\n" }, { "answer_id": 260973, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 3, "selected": false, "text": "<p>Here is a version using <code>mmap</code> that seems pretty efficient. The big plus is that <code>mmap</code> will automatically handle the file to memory paging requirements for you.</p>\n\n<pre><code>import os\nfrom mmap import mmap\n\ndef lastn(filename, n):\n # open the file and mmap it\n f = open(filename, 'r+')\n m = mmap(f.fileno(), os.path.getsize(f.name))\n\n nlcount = 0\n i = m.size() - 1 \n if m[i] == '\\n': n += 1\n while nlcount &lt; n and i &gt; 0:\n if m[i] == '\\n': nlcount += 1\n i -= 1\n if i &gt; 0: i += 2\n\n return m[i:].splitlines()\n\ntarget = \"target string\"\nprint [l for l in lastn('somefile', 10) if l == target]\n</code></pre>\n" }, { "answer_id": 262921, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 0, "selected": false, "text": "<p>This solution will read the file only once, but using 2 file object pointers to be able obtain the last N lines of file without re-reading it:</p>\n\n<pre><code>def getLastLines (path, n):\n # return the las N lines from the file indicated in path\n\n fp = open(path)\n for i in range(n):\n line = fp.readline()\n if line == '':\n return []\n\n back = open(path)\n for each in fp:\n back.readline()\n\n result = []\n for line in back:\n result.append(line[:-1])\n\n return result\n\n\n\n\ns = \"foo\"\nlast_bit = getLastLines(r'C:\\Documents and Settings\\ricardo.m.reyes\\My Documents\\desarrollo\\tail.py', 10)\nfor line in last_bit:\n if line == s:\n print \"FOUND\"\n</code></pre>\n" }, { "answer_id": 262988, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 1, "selected": false, "text": "<p>You could also count the lines as you reverse through the file, instead of guessing at a byte offset. </p>\n\n<pre><code>lines = 0\nchunk_size = 1024\n\nf = file('filename')\nf.seek(0, 2)\nf.seek(f.tell() - chunk_size)\n\nwhile True:\n s = f.read(chunk_size)\n lines += s.count('\\n')\n if lines &gt; NUM_OF_LINES:\n break\n f.seek(f.tell() - chunk_size*2)\n</code></pre>\n\n<p>Now the file is at a good position to run <code>readlines()</code>. You also could cache the strings you read the first time, to eliminate reading the same portion of the file twice.</p>\n" }, { "answer_id": 2436554, "author": "AM01", "author_id": 2574254, "author_profile": "https://Stackoverflow.com/users/2574254", "pm_score": 0, "selected": false, "text": "<p>Maybe this might be useful:</p>\n\n<pre><code>import os.path\n\npath = 'path_to_file'\nos.system('tail -n1 ' + path)\n</code></pre>\n" }, { "answer_id": 17841165, "author": "Edd", "author_id": 700673, "author_profile": "https://Stackoverflow.com/users/700673", "pm_score": 2, "selected": false, "text": "<p>I took mhawke's suggestion to use <code>mmap</code> and wrote a version that uses <code>rfind</code>:</p>\n\n<pre><code>from mmap import mmap\nimport sys\n\ndef reverse_file(f):\n mm = mmap(f.fileno(), 0)\n nl = mm.size() - 1\n prev_nl = mm.size()\n while nl &gt; -1:\n nl = mm.rfind('\\n', 0, nl)\n yield mm[nl + 1:prev_nl]\n prev_nl = nl + 1\n\ndef main():\n # Example usage\n with open('test.txt', 'r+') as infile:\n for line in reverse_file(infile):\n sys.stdout.write(line)\n</code></pre>\n" }, { "answer_id": 51750850, "author": "asterio gonzalez", "author_id": 6924622, "author_profile": "https://Stackoverflow.com/users/6924622", "pm_score": 2, "selected": false, "text": "<p>Thanks to the solution by 18 Darius Bacon but with a 30% faster implementation and wrapping into io.BaseIO class.</p>\n\n<pre><code>class ReverseFile(io.IOBase):\n def __init__ (self, filename, headers=1):\n self.fp = open(filename)\n self.headers = headers\n self.reverse = self.reversed_lines()\n self.end_position = -1\n self.current_position = -1\n\n def readline(self, size=-1):\n if self.headers &gt; 0:\n self.headers -= 1\n raw = self.fp.readline(size)\n self.end_position = self.fp.tell()\n return raw\n\n raw = next(self.reverse)\n if self.current_position &gt; self.end_position:\n return raw\n\n raise StopIteration\n\n def reversed_lines(self):\n \"\"\"Generate the lines of file in reverse order.\n \"\"\"\n part = ''\n for block in self.reversed_blocks():\n block = block + part\n block = block.split('\\n')\n block.reverse()\n part = block.pop()\n if block[0] == '':\n block.pop(0)\n\n for line in block:\n yield line + '\\n'\n\n if part:\n yield part\n\n def reversed_blocks(self, blocksize=0xFFFF):\n \"Generate blocks of file's contents in reverse order.\"\n file = self.fp\n file.seek(0, os.SEEK_END)\n here = file.tell()\n while 0 &lt; here:\n delta = min(blocksize, here)\n here -= delta\n file.seek(here, os.SEEK_SET)\n self.current_position = file.tell()\n yield file.read(delta)\n</code></pre>\n\n<p>An example</p>\n\n<pre><code>rev = ReverseFile(filename)\nfor i, line in enumerate(rev):\n print(\"{0}: {1}\".format(i, line.strip()))\n</code></pre>\n" }, { "answer_id": 69370560, "author": "Arpit", "author_id": 12423274, "author_profile": "https://Stackoverflow.com/users/12423274", "pm_score": -1, "selected": false, "text": "<p>This will return the last 10 lines as a list then you can search your line easily. (Python 3 compatible)</p>\n<pre><code>def read_last_n_lines_new(lines_need=10):\n\n with open('Log.txt', 'rb') as f:\n f.seek(0, 2)\n data = []\n lines_found = 0\n while True:\n try:\n f.seek(-1, 1)\n except:\n break\n finally:\n c = f.read(1)\n f.seek(-1, 1)\n if c == b'\\n':\n lines_found = lines_found+1\n if lines_found &gt; lines_need or not c:\n break\n data.insert(0, c.decode('utf-8'))\n \n \n lines = []\n cur = &quot;&quot;\n for l in data:\n if(l == '\\n'):\n lines.append(cur)\n cur = ''\n else:\n cur = cur + l\n return lines\n\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057/" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" ```
``` # Tail from __future__ import with_statement find_str = "FIREFOX" # String to find fname = "g:/autoIt/ActiveWin.log_2" # File to check with open(fname, "r") as f: f.seek (0, 2) # Seek @ EOF fsize = f.tell() # Get Size f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars lines = f.readlines() # Read to end lines = lines[-10:] # Get last 10 lines # This returns True if any line is exactly find_str + "\n" print find_str + "\n" in lines # If you're searching for a substring for line in lines: if find_str in line: print True break ```
260,285
<p>I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction.<br> I've done this inside the window's code behind:</p> <pre> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); Key keyPressed = e.Key; if (keyPressed == Key.W) { gcY += 5; } if (keyPressed == Key.S) { gcY -= 5; } if (keyPressed == Key.A) { gcX += 5; } if (keyPressed == Key.D) { gcX -= 5; } gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY); } </pre> <p>Well, it works, but the movement is jerky. And if I hold on to a key, <kbd>W</kbd> for instance, then it pauses for a split second, before moving.<br> Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key?<br> Thanks.</p>
[ { "answer_id": 260295, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 1, "selected": false, "text": "<p>Yes, you could incorporate the time into your calculation. Currently you add/substract 5 whenever the event fires, and that's not really predictable.</p>\n\n<p>To smoothe the movement make sure you don't fire more often than X times per second by using a DateTime.</p>\n\n<p>like:</p>\n\n<pre><code>private static DateTime nextUpdate\n\nif (nextUpdate &lt;= DateTime.Now)\n{\n//Move\nnextUpdate = DateTime.Now.AddMilliseconds(100);\n}\n</code></pre>\n\n<p>I don't have VS right now, so I'm not perfectly sure for the syntax, but you get the idea.</p>\n" }, { "answer_id": 415016, "author": "Karan", "author_id": 11110, "author_profile": "https://Stackoverflow.com/users/11110", "pm_score": 3, "selected": true, "text": "<p>Currently, your setup is accepting spammed keyinput (holding down a key). The way I've seen it done in most games with event based input is to use a boolean array, <code>keydown[256]</code>, mapping the keyboard (the index being the key value); all values initialized to <code>false</code>.</p>\n\n<p>When the key is pressed, you set the the appropriate index to <code>true</code> in the keydown method and in your game/rendering loop, you call <code>gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);</code> depending on what keys in the array are <code>true</code>. You set the key value to <code>false</code> when the key is released in the keyrelease event method (I'm not sure what it is in C#).</p>\n\n<p>This way you will get smooth scrolling and it wont have a delay in starting up.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33324/" ]
I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction. I've done this inside the window's code behind: ``` protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); Key keyPressed = e.Key; if (keyPressed == Key.W) { gcY += 5; } if (keyPressed == Key.S) { gcY -= 5; } if (keyPressed == Key.A) { gcX += 5; } if (keyPressed == Key.D) { gcX -= 5; } gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY); } ``` Well, it works, but the movement is jerky. And if I hold on to a key, `W` for instance, then it pauses for a split second, before moving. Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key? Thanks.
Currently, your setup is accepting spammed keyinput (holding down a key). The way I've seen it done in most games with event based input is to use a boolean array, `keydown[256]`, mapping the keyboard (the index being the key value); all values initialized to `false`. When the key is pressed, you set the the appropriate index to `true` in the keydown method and in your game/rendering loop, you call `gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);` depending on what keys in the array are `true`. You set the key value to `false` when the key is released in the keyrelease event method (I'm not sure what it is in C#). This way you will get smooth scrolling and it wont have a delay in starting up.
260,307
<p>I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of <em>real</em> customer info.</p> <p>Some of the answers to <a href="https://stackoverflow.com/questions/157600/data-generators-for-sql-server">this question</a> can help me generating NEW test data, but then how do I replace those columns in my production data, but keep the other relevant columns?</p> <p>Let's say I had a table with 10000 fake names. Should I do a cross-join with a SQL update? Or do something like</p> <pre><code>UPDATE table SET lastname = (SELECT TOP 1 name FROM samplenames ORDER By NEWID()) </code></pre>
[ { "answer_id": 260318, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 5, "selected": true, "text": "<p>Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to <a href=\"http://en.wikipedia.org/wiki/AOL_search_data_scandal\" rel=\"noreferrer\">AOL when they released search data a while back</a>. I would attempt to create test data from scratch at all costs before I tried to convert existing customer data. Things may lead you to be able to figure out who the data belonged to using things such as behavioral analysis and other data points that you might not consider sensitive. I would rather be safe than sorry.</p>\n" }, { "answer_id": 260434, "author": "tomjedrz", "author_id": 9852, "author_profile": "https://Stackoverflow.com/users/9852", "pm_score": 4, "selected": false, "text": "<p>This is easier than it sounds if you understand the database. One thing that is necessary is to understand the places where personal info is not normalized. For instance, the customer master file will have a name and address, but the order file will also have a name and address that might be different.</p>\n\n<p>My basic process:</p>\n\n<ol>\n<li>ID the data (i.e. the columns), and the tables which contain those columns. </li>\n<li>ID the \"master\" tables for those columns, and also the non-normailzed instances of those columns. </li>\n<li>Adjust the master files. Rather than trying to randomize them, (or make them phony), connect them to the key of the file. For customer 123, set the name to name123, the address to 123 123rd St, 123town, CA, USA, phone 1231231231. This has the added bonus of making debugging very easy! </li>\n<li>Change the non-normal instances by either updating from the master file <em>or</em> by doing the same kind of de-personalization</li>\n</ol>\n\n<p>It doesn't look pretty, but it works.</p>\n" }, { "answer_id": 32480972, "author": "Sam", "author_id": 328817, "author_profile": "https://Stackoverflow.com/users/328817", "pm_score": 3, "selected": false, "text": "<p>There are a couple of tools out there to remove sensitive data from databases that I've found. Note that I haven't tried any of them myself:</p>\n<ul>\n<li><a href=\"https://github.com/sunitparekh/data-anonymization\" rel=\"nofollow noreferrer\">Data::Anonymization</a>, a RubyGem.</li>\n<li><a href=\"https://github.com/davedash/mysql-anonymous\" rel=\"nofollow noreferrer\">Mysql Anonymous</a>, a Python script.</li>\n</ul>\n<p>There's also a collection of sanitisation DB scripts here which might be helpful: <a href=\"https://gist.github.com/Tyriar/d3635c6b6e32ac406623\" rel=\"nofollow noreferrer\">https://gist.github.com/Tyriar/d3635c6b6e32ac406623</a></p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21398/" ]
I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of *real* customer info. Some of the answers to [this question](https://stackoverflow.com/questions/157600/data-generators-for-sql-server) can help me generating NEW test data, but then how do I replace those columns in my production data, but keep the other relevant columns? Let's say I had a table with 10000 fake names. Should I do a cross-join with a SQL update? Or do something like ``` UPDATE table SET lastname = (SELECT TOP 1 name FROM samplenames ORDER By NEWID()) ```
Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to [AOL when they released search data a while back](http://en.wikipedia.org/wiki/AOL_search_data_scandal). I would attempt to create test data from scratch at all costs before I tried to convert existing customer data. Things may lead you to be able to figure out who the data belonged to using things such as behavioral analysis and other data points that you might not consider sensitive. I would rather be safe than sorry.
260,337
<p>Why does this test program result in a <code>java.lang.IllegalMonitorStateException</code>?</p> <pre><code>public class test { static Integer foo = new Integer(1); public static void main(String[] args) { synchronized(foo) { foo++; foo.notifyAll(); } System.err.println("Success"); } } </code></pre> <p>Result:</p> <pre><code>Exception in thread "main" java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method) at test.main(test.java:6) </code></pre>
[ { "answer_id": 260343, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 7, "selected": true, "text": "<p>You have noted correctly that <code>notifyAll</code> must be called from a synchronized block.</p>\n\n<p>However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked <code>notifyAll</code> on. In fact, the new, incremented <code>foo</code> instance is still confined to the stack, and no other threads could possibly be blocked on a <code>wait</code> call.</p>\n\n<p>You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html\" rel=\"noreferrer\">AtomicInteger</a> meets your needs.</p>\n" }, { "answer_id": 260362, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "<p>As erickson has noted, the code without the postincrement operator works without error:</p>\n\n<pre><code>static Integer foo = new Integer(1);\n\npublic static void main(String[] args) {\n synchronized (foo) {\n foo.notifyAll();\n }\n System.out.println(\"Success\");\n}\n</code></pre>\n\n<p>output:</p>\n\n<blockquote>\n <p>Success</p>\n</blockquote>\n" }, { "answer_id": 260366, "author": "dbt", "author_id": 33811, "author_profile": "https://Stackoverflow.com/users/33811", "pm_score": 2, "selected": false, "text": "<p>You should also be leery of locking or notifying on objects like String and Integer that can be interned by the JVM (to prevent creating a lot of objects that represent the integer 1 or the string \"\").</p>\n" }, { "answer_id": 5358011, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 2, "selected": false, "text": "<p>Incrementing the Integer makes the old foo disappear and be replaced with a brand new object foo which is not synchronized with the previous foo variable. </p>\n\n<p>Here is an implementation of AtomicInteger that erickson suggested above. In this example foo.notifyAll(); does not produce a java.lang.IllegalMonitorStateException beause the AtomicInteger Object is not refreshed when foo.incrementAndGet(); is run.</p>\n\n<pre><code>import java.util.concurrent.atomic.AtomicInteger;\n\npublic class SynchronizeOnAPrimitive {\n static AtomicInteger foo = new AtomicInteger(1);\n public static void main(String[] args) {\n synchronized (foo) {\n foo.incrementAndGet();\n foo.notifyAll();\n }\n System.out.println(\"foo is: \" + foo);\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>foo is: 2\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29264/" ]
Why does this test program result in a `java.lang.IllegalMonitorStateException`? ``` public class test { static Integer foo = new Integer(1); public static void main(String[] args) { synchronized(foo) { foo++; foo.notifyAll(); } System.err.println("Success"); } } ``` Result: ``` Exception in thread "main" java.lang.IllegalMonitorStateException at java.lang.Object.notifyAll(Native Method) at test.main(test.java:6) ```
You have noted correctly that `notifyAll` must be called from a synchronized block. However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked `notifyAll` on. In fact, the new, incremented `foo` instance is still confined to the stack, and no other threads could possibly be blocked on a `wait` call. You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that [AtomicInteger](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html) meets your needs.
260,356
<p>I am experimenting for the first time with css layouts and my experience with CSS is very basic. What I want to achieve is a 2 column layout: left panel and content.<br> I have found this:</p> <pre><code>#leftcontent { position: absolute; left: 10px; top: 10px; width: 170px; border: 1px solid #C0C0C0; padding: 2px; } #centercontent { position: absolute; margin-left: 181px; border:1px solid #C0C0C0; top: 10px; //fix IE5 bug voice-family: "\"}\""; voice-family: inherit; margin-left: 181px; } </code></pre> <p>This displays great in firefox but the content in IE8 goes off the right of the screen, I assume by the length of the <code>#leftcontent</code>. How can I fix this?</p> <p>This is probably quite a simple fix but I have experimented and looked for fixes, but this supposedly should work. I appreciate any help.</p>
[ { "answer_id": 260361, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": -1, "selected": false, "text": "<p>Use a table. It is more suited to the task, way easier to implement and far more reliable across different browsers.</p>\n" }, { "answer_id": 260364, "author": "Samir Talwar", "author_id": 20856, "author_profile": "https://Stackoverflow.com/users/20856", "pm_score": 3, "selected": true, "text": "<p>I'd advise floating the #leftcontent element to the left, and then setting the margin of the #centercontent element to compensate:</p>\n\n<pre><code>#leftcontent {\n float: left;\n width:170px;\n border:1px solid #C0C0C0;\n padding: 2px;\n}\n\n#centercontent {\n margin-left: 181px;\n border:1px solid #C0C0C0;\n}\n</code></pre>\n" }, { "answer_id": 260368, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 1, "selected": false, "text": "<p>Set a width on #centercontent. Whether that be a percentage or a px size that will be what you're looking for.</p>\n" }, { "answer_id": 260384, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>Use the <code>float</code> property to do this. An excellent float tutorial is <a href=\"http://css.maxdesign.com.au/floatutorial/\" rel=\"nofollow noreferrer\">Floatutorial</a>. Here is how your CSS would look using floats:</p>\n\n<pre><code>#leftcontent {\n float: left;\n margin-left: 10px;\n margin-top: 10px;\n width: 170px;\n border: 1px solid #C0C0C0;\n padding: 2px;\n}\n\n#centercontent {\n float: left;\n margin-left: 10px;\n border: 1px solid #C0C0C0;\n margin-top: 10px;\n}\n</code></pre>\n\n<p>Then if you want a div to appear below those divs, you'll have to use this CSS:</p>\n\n<pre><code>#contentbelow {\n clear: both;\n}\n</code></pre>\n\n<p>Also, you should set a width for #centercontent, as floated elements always need an explicit width.</p>\n" }, { "answer_id": 260471, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>What others have said regarding <code>float</code> should help. <em>Additionally</em>, there are two things to check:</p>\n\n<ul>\n<li>Have you tried setting the <code>overflow</code> for the left content, so the browser has a better idea of what to do when something doesn't fit in the space you allowed.</li>\n<li>Have you looked for what element is causing the left side to overflow? Some elements just can't be wrapped, and if they are too wide they will force the width of the entire div to stretch to accommodate them.</li>\n</ul>\n" }, { "answer_id": 260624, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "<p>My favourite method of doing column layouts is using float:left and right.</p>\n\n<p><code>colwrapper</code> is set to 40em width, the <code>margin-...:auto</code> make the div centred (in everything but IE4 or IE5, for some reason)</p>\n\n<p><code>footer</code> appears after both the columns because of the <code>clear:both</code>.</p>\n\n<p>This will scale nicely when you increase the font-size (<code>ctrl and + or -</code>), and you can easily nest columns inside columns (to do a 3 column layout, you do the same thing, but put two divs inside #colleft, and float left/right them)</p>\n\n<pre><code>#colwrapper{\n width:40em;\n margin-left:auto;\n margin-right:auto;\n}\n#colleft{\n float:left;\n width:10em;\n}\n#colright{\n float:right;\n width:30em\n}\n#footer{\n clear:both\n}\n</code></pre>\n\n<p>And the HTML:</p>\n\n<pre><code>&lt;div id=\"colwrapper\"&gt;\n &lt;div id=\"colleft\"&gt;\n left column!\n &lt;/div&gt;\n &lt;div id=\"colright\"&gt;\n right column!\n &lt;/div&gt;\n &lt;div id=\"footer\"&gt;\n footer!\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I am experimenting for the first time with css layouts and my experience with CSS is very basic. What I want to achieve is a 2 column layout: left panel and content. I have found this: ``` #leftcontent { position: absolute; left: 10px; top: 10px; width: 170px; border: 1px solid #C0C0C0; padding: 2px; } #centercontent { position: absolute; margin-left: 181px; border:1px solid #C0C0C0; top: 10px; //fix IE5 bug voice-family: "\"}\""; voice-family: inherit; margin-left: 181px; } ``` This displays great in firefox but the content in IE8 goes off the right of the screen, I assume by the length of the `#leftcontent`. How can I fix this? This is probably quite a simple fix but I have experimented and looked for fixes, but this supposedly should work. I appreciate any help.
I'd advise floating the #leftcontent element to the left, and then setting the margin of the #centercontent element to compensate: ``` #leftcontent { float: left; width:170px; border:1px solid #C0C0C0; padding: 2px; } #centercontent { margin-left: 181px; border:1px solid #C0C0C0; } ```
260,372
<p>I occasionally work on an old project that uses classic asp as a front end and an access database as a backend.</p> <p>I'd like to create a new column in one of the tables that contains logic to calculate its value from the other columns in the row.</p> <p>I know how to do this in a more modern DBMS, but I don't think that access supports it. Keep in mind I'm not using the access frontend, just the Jet DB engine via ODBC.</p> <p>Any pointers?</p>
[ { "answer_id": 260631, "author": "pro3carp3", "author_id": 7899, "author_profile": "https://Stackoverflow.com/users/7899", "pm_score": 2, "selected": false, "text": "<p>Can you just make a calculated column?</p>\n\n<pre><code>SELECT Table1.Col_1, Table1.Col_2, [Col_1]*[Col_2] AS Col_3\nFROM Table1;\n</code></pre>\n" }, { "answer_id": 271275, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": -1, "selected": false, "text": "<p>In a comment, Jonathan Holland asked:</p>\n\n<blockquote>\n <p>I'm wondering if Jet DB's can have\n embedded VBscript in them like you can\n do in Access</p>\n</blockquote>\n\n<p>Why would you want to do something like that in the back end, and not in your ASP front end? Access has saved queries, which are like views, but when used via ODBC, they cannot include VBA functions in them (though there are a few commands that Jet supports directly that <em>may</em> be accessible via ODBC, such as IIf() and Nz() -- but that's a big <em>if</em>).</p>\n\n<p>Retrieve your recordset in ASP and perform your row-by-row calculations. That's the only way to do it if you're using Jet via ODBC (I don't think ADO would work any better, BTW).</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I occasionally work on an old project that uses classic asp as a front end and an access database as a backend. I'd like to create a new column in one of the tables that contains logic to calculate its value from the other columns in the row. I know how to do this in a more modern DBMS, but I don't think that access supports it. Keep in mind I'm not using the access frontend, just the Jet DB engine via ODBC. Any pointers?
Can you just make a calculated column? ``` SELECT Table1.Col_1, Table1.Col_2, [Col_1]*[Col_2] AS Col_3 FROM Table1; ```
260,380
<p>I have a base class with an optional virtual function</p> <pre><code>class Base { virtual void OnlyImplementThisSometimes(int x) {} }; </code></pre> <p>When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:</p> <pre><code>class Base { virtual void OnlyImplementThisSometimes(int x) { x = 0; } }; </code></pre> <p>I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g.</p> <pre><code>class Derived : public Base { void OnlyImplementThisSometimes(int x, int y) { // some code } }; Derived d; Base *b = dynamic_cast&lt;Base *&gt;(&amp;d); b-&gt;OnlyImplementThisSometimes(x); // calls the method in the base class </code></pre> <p>The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?</p>
[ { "answer_id": 260393, "author": "Chris Thompson", "author_id": 5982, "author_profile": "https://Stackoverflow.com/users/5982", "pm_score": 3, "selected": false, "text": "<p>Why define it in the base class? If the base class isn't going to use the method, then just define it as a virtual method in your derived class.</p>\n\n<p>Or the default implementation could throw an exception</p>\n" }, { "answer_id": 260396, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>If you provide a default implementation of a virtual function, it should be a correct implementation for all derived classes that don't override that function. If you can't provide a <em>correct</em> implementation, then my advice would be to make a pure virtual function and leave it up to the derived class to provide an implementation. Derived classes that do not allow the method to be called can throw an exception to ensure that it is not used by mistake.</p>\n" }, { "answer_id": 260412, "author": "nlativy", "author_id": 33635, "author_profile": "https://Stackoverflow.com/users/33635", "pm_score": 6, "selected": true, "text": "<p>Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:</p>\n\n<pre><code>virtual void OnlyImplementThisSometimes(int ) { }\n</code></pre>\n\n<p>Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the 'override' keyword.</p>\n" }, { "answer_id": 260420, "author": "Foredecker", "author_id": 18256, "author_profile": "https://Stackoverflow.com/users/18256", "pm_score": 2, "selected": false, "text": "<p>This is somewhat common in my code. For example, I have classes that are designed for single-threaded operation and multi-threaded. There are a lot of common routines and data. I put all of that in the base class (which has a couple of pure virtual as well).</p>\n\n<p>I implement two empty virtual functions in the base class: Init() and Cleanup(). The single threaded derived class does not impliment them, but the mulit-threaded one does.</p>\n\n<p>I have a factory function create the approprite derived class then return a pointer. The client code only knows about the base class type and it calls Init() and Cleanup(). Both scenarios do the right thing.</p>\n\n<p>Of course, there may be other good suggestions on how to do this, but this idiom works well for a lot of my code.</p>\n" }, { "answer_id": 260425, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "<p>In addition to simply omitting the variable name, in many compilers you can tell the compiler, that you are aware that it is unused and SHUTUP by doing this</p>\n\n<pre><code>int func(int x)\n{\n (void) x;\n}\n</code></pre>\n" }, { "answer_id": 260431, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 2, "selected": false, "text": "<p>It's not a bad practice and it's a common idiom for specifying parts of a class that are optional to implement.</p>\n\n<p>Currently I'm using it for a user input system, because it would be tedious for a user of that class to implement every single method even it he most likely won't use it anyway.</p>\n\n<pre><code>class mouse_listener{\npublic:\n virtual ~mouse_listener() {}\n\n virtual void button_down(mouse_button a_Button) {}\n virtual void button_up(mouse_button a_Button) {}\n virtual void scroll_wheel(mouse_scroll a_Scroll) {}\n virtual void mouse_move_abs(math::point a_Position) {}\n virtual void mouse_move_rel(math::point a_Position) {}\n};\n</code></pre>\n" }, { "answer_id": 260480, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 2, "selected": false, "text": "<p>Btw, if you know your base class, there's never any need to do dynamic <em>up</em>-casts, i.e. from derived to base.</p>\n\n<pre><code>Base *b = &amp;d;\n</code></pre>\n\n<p>Will do just as well, <code>dynamic_cast&lt;&gt;</code> should instead be used when you down-cast, i.e. from base to derived:</p>\n\n<pre><code>if((Derived *d = dynamic_cast&lt;Derived *&gt;(b)) != 0)\n{\n // use d\n}\n</code></pre>\n\n<p>(And of course in the case of down-cast, <code>static_cast&lt;&gt;</code> will usually work as well.)</p>\n" }, { "answer_id": 260483, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": false, "text": "<p>We define a macro <code>_unused</code> as:</p>\n\n<pre><code>#define _unused(x) ((void)x)\n</code></pre>\n\n<p>Then define the function as:</p>\n\n<pre><code>virtual void OnlyImplementThisSometimes(int x) { _unused( x );}\n</code></pre>\n\n<p>This not only keeps the compiler from complaining, but makes it obvious to anyone maintaining the code that you haven't forgotten about x -- you are <em>intentionally</em> ignoring it.</p>\n" }, { "answer_id": 261335, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": -1, "selected": false, "text": "<p>The simplest answer to this is shown below:</p>\n\n<pre><code>class Base {\n virtual void OnlyImplementThisSometimes(int x) { x;}\n};\n</code></pre>\n\n<p>A simple reference to the variable which does absolutely nothing will remove all warnings (from VC++ at highest level anyway).</p>\n" }, { "answer_id": 266618, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>class Base {\n virtual void OnlyImplementThisSometimes(int x) = 0;\n};\n</code></pre>\n\n<p>It's been a while since I've done stuff like that but I believe that is how you declare a virtual function.</p>\n\n<p>Also as others have said, variable names are optional in function declarations like this.</p>\n" } ]
2008/11/03
[ "https://Stackoverflow.com/questions/260380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
I have a base class with an optional virtual function ``` class Base { virtual void OnlyImplementThisSometimes(int x) {} }; ``` When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this: ``` class Base { virtual void OnlyImplementThisSometimes(int x) { x = 0; } }; ``` I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g. ``` class Derived : public Base { void OnlyImplementThisSometimes(int x, int y) { // some code } }; Derived d; Base *b = dynamic_cast<Base *>(&d); b->OnlyImplementThisSometimes(x); // calls the method in the base class ``` The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example: ``` virtual void OnlyImplementThisSometimes(int ) { } ``` Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the 'override' keyword.
260,387
<p>I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how!</p> <pre><code>&lt;?php $dirname = "images/"; $images = scandir($dirname); $dh = opendir($dirname); while ($file = readdir($dh)) { if (substr($file, -4) == ".gif") { print "&lt;option value='$file'&gt;$file&lt;/option&gt;\n"; } } closedir($dh); ?&gt; </code></pre>
[ { "answer_id": 260400, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": "<p>Why are you reading all the filenames using scandir() and then looping through them with the readdir() method? You could just do this:</p>\n\n<pre><code>&lt;?php\n\n$dirname = \"images/\";\n$images = scandir($dirname);\n\n// This is how you sort an array, see http://php.net/sort\nsort($images);\n\n// There's no need to use a directory handler, just loop through your $images array.\nforeach ($images as $file) {\n if (substr($file, -4) == \".gif\") {\n print \"&lt;option value='$file'&gt;$file&lt;/option&gt;\\n\"; }\n }\n}\n\n?&gt;\n</code></pre>\n\n<p>Also you might want to use <a href=\"http://php.net/natsort\" rel=\"nofollow noreferrer\">natsort()</a>, which works the same way as <a href=\"http://php.net/sort\" rel=\"nofollow noreferrer\">sort()</a> but sorts in \"natural order\". (Instead of sorting as <code>1,10,2,20</code> it will sort as <code>1,2,10,20</code>.)</p>\n" }, { "answer_id": 260451, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://php.net/scandir\" rel=\"nofollow noreferrer\">scandir</a></p>\n\n<pre><code>array scandir ( string $directory [, int $sorting_order [, resource $context ]] )\n</code></pre>\n\n<blockquote>\n <p>Returns an array of files and\n directories from the directory .\n Parameters</p>\n \n <p>directory The directory that will be\n scanned.</p>\n \n <p>sorting_order\n <strong>By default, the sorted order is alphabetical in ascending order.</strong> If\n the optional sorting_order is used\n (set to 1), then the sort order is\n alphabetical in descending order.</p>\n</blockquote>\n" }, { "answer_id": 260556, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>$matches = glob(\"*.gif\");\nif ( is_array ( $matches ) ) {\n sort($matches);\n foreach ( $matches as $filename) {\n echo '&lt;option value=\"'.$filename.'\"&gt;.$filename . \"&lt;/option&gt;\";\n }\n}\n</code></pre>\n" }, { "answer_id": 261210, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 0, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/users/2725/william-macdonald\">William Macdonald</a> pointed out <a href=\"https://stackoverflow.com/questions/260387/ordering-a-list-of-files-in-a-folder-using-php#260451\">here</a> <a href=\"http://de3.php.net/scandir\" rel=\"nofollow noreferrer\">scandir()</a> will in fact sort the returning array according to its <code>$sorting_order</code> parameter (or its default: \"By default, the sorted order is alphabetical in ascending order.\"). The problem with your code is, that you generate the array of files in your directory using <code>$images = scandir($dirname);</code> but you do not use the returned array in your code further on. Instead you iterate over the directory contents using another method:</p>\n\n<pre><code>$dh = opendir($dirname);\nwhile ($file = readdir($dh)) {\n if (substr($file, -4) == \".gif\") {\n print \"&lt;option value='$file'&gt;$file&lt;/option&gt;\\n\"; \n }\n}\nclosedir($dh);\n</code></pre>\n\n<p>This is why your result is not sorted.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32972/" ]
I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how! ``` <?php $dirname = "images/"; $images = scandir($dirname); $dh = opendir($dirname); while ($file = readdir($dh)) { if (substr($file, -4) == ".gif") { print "<option value='$file'>$file</option>\n"; } } closedir($dh); ?> ```
Why are you reading all the filenames using scandir() and then looping through them with the readdir() method? You could just do this: ``` <?php $dirname = "images/"; $images = scandir($dirname); // This is how you sort an array, see http://php.net/sort sort($images); // There's no need to use a directory handler, just loop through your $images array. foreach ($images as $file) { if (substr($file, -4) == ".gif") { print "<option value='$file'>$file</option>\n"; } } } ?> ``` Also you might want to use [natsort()](http://php.net/natsort), which works the same way as [sort()](http://php.net/sort) but sorts in "natural order". (Instead of sorting as `1,10,2,20` it will sort as `1,2,10,20`.)
260,391
<p>I have an iphone app where I call these three functions in appDidFinishLaunching:</p> <pre><code>glMatrixMode(GL_PROJECTION); glOrthof(0, rect.size.width, 0, rect.size.height, -1, 1); glMatrixMode(GL_MODELVIEW); </code></pre> <p>When stepping through with the debugger I get EXC BAD ACCESS when I execute the first line. Any ideas why this is happening?</p> <p>Btw I have another application where I do the same thing and it works fine. So I've tried to duplicate everything in that app (#imports, adding OpenGLES framework, etc) but now I'm just stuck.</p>
[ { "answer_id": 262253, "author": "Brian", "author_id": 15901, "author_profile": "https://Stackoverflow.com/users/15901", "pm_score": 2, "selected": false, "text": "<p>I've seen this error in many different situations but never specifically in yours. It usually comes up as a result of the application trying to access memory that has already been released.</p>\n\n<p>Can you confirm that rect is still allocated?</p>\n" }, { "answer_id": 266005, "author": "Brad Larson", "author_id": 19679, "author_profile": "https://Stackoverflow.com/users/19679", "pm_score": 3, "selected": true, "text": "<p>I've run into this with OpenGL calls if two threads are attempting to draw to the OpenGL scene at once. However, that doesn't sound like what you're doing.</p>\n\n<p>Have you properly initialized your display context and framebuffer before this call? For example, in my UIView subclass that does OpenGL drawing, I call the following in its initWithCoder: method:</p>\n\n<pre><code>context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];\n\nif (!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) \n{\n [self release];\n return nil;\n}\n</code></pre>\n\n<p>The createFramebuffer method looks like the following:</p>\n\n<pre><code>- (BOOL)createFramebuffer \n{ \n glGenFramebuffersOES(1, &amp;viewFramebuffer);\n glGenRenderbuffersOES(1, &amp;viewRenderbuffer);\n\n glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);\n glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);\n [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];\n glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);\n\n glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &amp;backingWidth);\n glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &amp;backingHeight);\n\n if (USE_DEPTH_BUFFER) {\n glGenRenderbuffersOES(1, &amp;depthRenderbuffer);\n glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);\n glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);\n glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);\n }\n\n if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) \n {\n return NO;\n }\n\n return YES;\n}\n</code></pre>\n\n<p>This is pretty much boilerplate code, as generated by the OpenGL ES Application template in XCode. Perhaps by not initializing things before calling glMatrixMode(), you're getting a crash.</p>\n\n<p>Also, why are you doing OpenGL drawing in applicationDidFinishLaunching:? Wouldn't a view or view controller be a more appropriate place for OpenGL calls than your UIApplicationDelegate?</p>\n" }, { "answer_id": 568214, "author": "adon", "author_id": 68758, "author_profile": "https://Stackoverflow.com/users/68758", "pm_score": 1, "selected": false, "text": "<p>You need to replace the current matrix with the identity matrix before calling glOrthof. This can be done with glLoadIdentity()</p>\n" }, { "answer_id": 2202423, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Unlikely to be the problem given the date on which you submitted the bug, but you'd also see something like this if you use the Apple example code and run on an ES 2.0 capable device, as it removes the matrix stack from the spec, though the function definitions will remain visible to the compiler since the device also supports ES 1.1.</p>\n" }, { "answer_id": 2893002, "author": "devinkb", "author_id": 230913, "author_profile": "https://Stackoverflow.com/users/230913", "pm_score": 1, "selected": false, "text": "<p>Restart the iPhone Simulator. This issue is definitely due to the OpenGL context not being set properly. I found that sometimes the iPhone Simulator has issues and needs to be restarted for the OpenGL context to get set properly by [EAGLContext setCurrentContext:].</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
I have an iphone app where I call these three functions in appDidFinishLaunching: ``` glMatrixMode(GL_PROJECTION); glOrthof(0, rect.size.width, 0, rect.size.height, -1, 1); glMatrixMode(GL_MODELVIEW); ``` When stepping through with the debugger I get EXC BAD ACCESS when I execute the first line. Any ideas why this is happening? Btw I have another application where I do the same thing and it works fine. So I've tried to duplicate everything in that app (#imports, adding OpenGLES framework, etc) but now I'm just stuck.
I've run into this with OpenGL calls if two threads are attempting to draw to the OpenGL scene at once. However, that doesn't sound like what you're doing. Have you properly initialized your display context and framebuffer before this call? For example, in my UIView subclass that does OpenGL drawing, I call the following in its initWithCoder: method: ``` context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; if (!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer]) { [self release]; return nil; } ``` The createFramebuffer method looks like the following: ``` - (BOOL)createFramebuffer { glGenFramebuffersOES(1, &viewFramebuffer); glGenRenderbuffersOES(1, &viewRenderbuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer]; glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); if (USE_DEPTH_BUFFER) { glGenRenderbuffersOES(1, &depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer); } if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) { return NO; } return YES; } ``` This is pretty much boilerplate code, as generated by the OpenGL ES Application template in XCode. Perhaps by not initializing things before calling glMatrixMode(), you're getting a crash. Also, why are you doing OpenGL drawing in applicationDidFinishLaunching:? Wouldn't a view or view controller be a more appropriate place for OpenGL calls than your UIApplicationDelegate?
260,398
<p>I have a list of stores, departments within the stores, and sales for each department, like so (created using max(sales) in a subquery, but that's not terribly important here I don't think):</p> <pre><code>toronto baskets 500 vancouver baskets 350 halifax baskets 100 toronto noodles 275 vancouver noodles 390 halifax noodles 120 halifax fish 200 </code></pre> <p>I would like to ask for the highest-selling department at each store. The results should look like this:</p> <pre><code>toronto baskets 500 vancouver noodles 275 halifax fish 200 </code></pre> <p>Whenever I use GROUP BY, it includes all the listings from my subquery. Is there a nice clean way to do this without a temporary table?</p>
[ { "answer_id": 260419, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 2, "selected": false, "text": "<p>This works in Oracle, other implementations may have different syntax for analytic functions (or lack them entirely):</p>\n\n<pre><code>select store\n , max(department) keep(dense_rank last order by sales)\n , max(sales)\n from (\n ...query that generates your results...\n )\n group by store\n</code></pre>\n" }, { "answer_id": 260467, "author": "Jeffrey Meyer", "author_id": 2323, "author_profile": "https://Stackoverflow.com/users/2323", "pm_score": 1, "selected": false, "text": "<p>This will work in SQL Server, as of 2005:</p>\n\n<pre><code>with data as\n(select store, department, sales\nfrom &lt;your query&gt;),\n maxsales as\n(select store, sales = max(sales)\nfrom data\ngroup by store)\nselect store, (select top 1 department from data where store = t.store and sales = t.sales order by [your criteria for ties]), sales\nfrom maxsales m\n</code></pre>\n\n<p>I'm assuming you only want to display 1 department in the event of ties, hence the top 1 and [your criteria for ties] to distinguish among them.</p>\n" }, { "answer_id": 260469, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 0, "selected": false, "text": "<p>Maybe this could work. Haven't tried it though, there could be a better solution...</p>\n\n<pre><code>select yourTable.store, dept, sales\nfrom yourTable\njoin (\n select store, max(sales) as maxSales from yourTable group by store\n) tempTable on tempTable.store = yourTable.store \n and tempTable.maxSales = yourTable.sales\n</code></pre>\n" }, { "answer_id": 260473, "author": "Pete", "author_id": 76, "author_profile": "https://Stackoverflow.com/users/76", "pm_score": 2, "selected": false, "text": "<p>This works in Sql Server (2000 and above for sure)</p>\n\n<pre><code>SELECT a.Store, a.Department, a.Sales\nFROM temp a\nINNER JOIN \n(SELECT store, max(sales) as sales\nFROM temp\nGROUP BY Store) b\nON a.Store = b.Store AND a.Sales = b.Sales;\n</code></pre>\n" }, { "answer_id": 260513, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 0, "selected": false, "text": "<p>This will work in SQL Server without temp tables:</p>\n\n<pre><code>SELECT Store, Department, Sales FROM\n(SELECT Store, Department, Sales,\nDENSE_RANK() OVER (PARTITION BY Store\nORDER BY Sales DESC) AS Dense_Rank\nFROM Sales) A WHERE Dense_Rank = 1\n</code></pre>\n\n<p>WHERE \"Sales\" = your original query</p>\n" }, { "answer_id": 260524, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "<p>This will work</p>\n\n<pre><code>Select Store, Department, Sales\nFrom yourTable A\nWhere Sales = (Select Max(Sales)\n From YourTable\n Where Store = A.Store)\n</code></pre>\n" }, { "answer_id": 261775, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "<p>My 2 solutions for SQL 2005 is below. The other ones I can see so far may not return the correct data if two of the sales figures are the same. That depends on your needs though.</p>\n\n<p>The first uses the Row_Number() function, all the rows are ranked from the lowest to the highest sales (then some tie breaking rules). Then the highest rank is chosen per store to get the result.</p>\n\n<p>You can try adding a Partion By clause to the Row_Number function (see BOL) and/or investigate using a inner join instead of an \"in\" clause.</p>\n\n<p>The second, borrowing on Turnkey's idea, again ranks them, but partitions by store, so we can choose the first ranked one. Dense_Rank will possibly give two identical rows the same rank, so if store and department were not unique, it could return two rows. With Row_number the number is unique in the partition.</p>\n\n<p>Some things to be aware of is that this may be slow, but would be faster for most data sets than the sub-query in one of the other solutions. In that solution, the query would have to be run once per row (including sorting etc), which could result in a lot of queries.</p>\n\n<p>Other queries the select the max sales per store and return the data that way, return duplicate rows for a store if two departments happen to have the same sales. The last query shows this.</p>\n\n<pre><code>DECLARE @tbl as TABLE (store varchar(20), department varchar(20), sales int)\n\nINSERT INTO @tbl VALUES ('Toronto', 'Baskets', 500)\nINSERT INTO @tbl VALUES ('Toronto', 'Noodles', 500)\nINSERT INTO @tbl VALUES ('Toronto', 'Fish', 300)\nINSERT INTO @tbl VALUES ('Halifax', 'Fish', 300)\nINSERT INTO @tbl VALUES ('Halifax', 'Baskets', 200)\n\n-- Expect Toronto/Noodles/500 and Halifax/Fish/300\n\n;WITH ranked AS -- Rank the rows by sales from 1 to x\n(\n SELECT \n ROW_NUMBER() OVER (ORDER BY sales, store, department) as 'rank', \n store, department, sales\n FROM @tbl\n)\n\nSELECT store, department, sales\nFROM ranked\nWHERE rank in (\n SELECT max(rank) -- chose the highest ranked per store\n FROM ranked\n GROUP BY store\n)\n\n-- Another way\nSELECT store, department, sales\nFROM (\n SELECT \n DENSE_RANK() OVER (PARTITION BY store ORDER BY sales desc, \nstore desc, department desc) as 'rank',\n store, department, sales\n FROM @tbl\n) tbl\nWHERE rank = 1\n\n\n-- This will bring back 2 rows for Toronto\nselect tbl.store, department, sales\nfrom @tbl tbl\n join (\n select store, max(sales) as maxSales from @tbl group by store\n ) tempTable on tempTable.store = tbl.store \n and tempTable.maxSales = tbl.sales\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a list of stores, departments within the stores, and sales for each department, like so (created using max(sales) in a subquery, but that's not terribly important here I don't think): ``` toronto baskets 500 vancouver baskets 350 halifax baskets 100 toronto noodles 275 vancouver noodles 390 halifax noodles 120 halifax fish 200 ``` I would like to ask for the highest-selling department at each store. The results should look like this: ``` toronto baskets 500 vancouver noodles 275 halifax fish 200 ``` Whenever I use GROUP BY, it includes all the listings from my subquery. Is there a nice clean way to do this without a temporary table?
This works in Oracle, other implementations may have different syntax for analytic functions (or lack them entirely): ``` select store , max(department) keep(dense_rank last order by sales) , max(sales) from ( ...query that generates your results... ) group by store ```
260,399
<p>I know you cannot use a alias column in the where clause for T-SQL; however, has Microsoft provided some kind of workaround for this?</p> <blockquote> <p><strong>Related Questions:</strong> </p> <ul> <li><a href="https://stackoverflow.com/questions/200200/can-you-use-an-alias-in-the-where-clause-in-mysql">Unknown Column In Where Clause</a> </li> <li><a href="https://stackoverflow.com/questions/153598/unknown-column-in-where-clause">Can you use an alias in the WHERE clause in mysql?</a> </li> <li><a href="https://stackoverflow.com/questions/46354/invalid-column-name-error-on-sql-statement-from-openquery-results">“Invalid column name” error on SQL statement from OpenQuery results</a></li> </ul> </blockquote>
[ { "answer_id": 260437, "author": "Jim V.", "author_id": 33819, "author_profile": "https://Stackoverflow.com/users/33819", "pm_score": 6, "selected": true, "text": "<p>One workaround would be to use a derived table.</p>\n\n<p>For example:</p>\n\n<pre><code>select *\nfrom \n (\n select a + b as aliased_column\n from table\n ) dt\nwhere dt.aliased_column = something.\n</code></pre>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 319541, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 1, "selected": false, "text": "<p>Depending on what you are aliasing, you could turn it into a user defined function and reference that in both places. Otherwise your copying the aliased code in several places, which tends to become very ugly and means updating 3+ spots if you are also ordering on that column.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I know you cannot use a alias column in the where clause for T-SQL; however, has Microsoft provided some kind of workaround for this? > > **Related Questions:** > > > * [Unknown Column In Where Clause](https://stackoverflow.com/questions/200200/can-you-use-an-alias-in-the-where-clause-in-mysql) > * [Can you use an alias in the WHERE clause in mysql?](https://stackoverflow.com/questions/153598/unknown-column-in-where-clause) > * [“Invalid column name” error on SQL statement from OpenQuery results](https://stackoverflow.com/questions/46354/invalid-column-name-error-on-sql-statement-from-openquery-results) > > >
One workaround would be to use a derived table. For example: ``` select * from ( select a + b as aliased_column from table ) dt where dt.aliased_column = something. ``` I hope this helps.
260,432
<p>I have the following method in my unit test project:</p> <pre><code> [TestMethod] [HostType("ASP.NET")] [UrlToTest("http://localhost:3418/Web/SysCoord/ChooseEPA.aspx")] [AspNetDevelopmentServerHost("%PathToWebRoot%")] public void TestMethod1() { Page page = TestContext.RequestedPage; Assert.IsTrue(false, "Test ran, at least."); } </code></pre> <p>I'm getting this exception:</p> <p>The test adapter 'WebHostAdapter' threw an exception while running test 'TestMethod1'. The web site could not be configured correctly; getting ASP.NET process information failed. Requesting '<a href="http://localhost:3418/SysCoord/VSEnterpriseHelper.axd" rel="noreferrer">http://localhost:3418/SysCoord/VSEnterpriseHelper.axd</a>' returned an error: The remote server returned an error: (404) Not Found. The remote server returned an error: (404) Not Found.</p> <p>The page works as it should in a browser at the url: <a href="http://localhost:3418/Web/SysCoord/ChooseEPA.aspx" rel="noreferrer">http://localhost:3418/Web/SysCoord/ChooseEPA.aspx</a>. </p> <p>This physical path is: C:\ESI\HR_Connect2\BenefitChangeSystem\Application_DEV\Web\SysCoord.</p> <p>Any ideas would be appreciated.</p> <p><strong>Update 1</strong></p> <p>Added the following to my web.config file per this article. Also made the web.config writable and killed/restarted the development web server. No change in behavior.</p> <pre><code>&lt;location path="VSEnterpriseHelper.axd"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p><strong>Update 2</strong></p> <p>Changing the AspNetDevelopmentServerHost attribute to the equivalent of [AspNetDevelopmentServerHost("%PathToWebRoot%\solutionfolder\webfolder", "/webfolder")] resolved the 404 problem.</p> <p>Unfortunately the test began to return a 500 error instead. Progress, but not much. Trial and error with a clean project led to the conclusion that references to custom classes in the of the web.config were causing the problem.</p> <p>For example:</p> <pre><code> &lt;profile enabled="true" defaultProvider="MyProfileProvider"&gt; &lt;providers&gt; &lt;add name="MyProfileProvider" connectionStringName="ProfileConnectionString" applicationName="/MyApp" type="System.Web.Profile.SqlProfileProvider"/&gt; &lt;/providers&gt; &lt;properties&gt; &lt;add name="Theme" type="String" defaultValue="Default"/&gt; &lt;add name="LastLogon" type="DateTime"/&gt; &lt;add name="LastLogonIp" type="String"/&gt; &lt;!-- &lt;add name="EmployeeSearchCriteria" type="MyApplicationFramework.Profile.EmployeeSearchCriteria"/&gt; &lt;add name="DocumentSearchCriteria" type="MyApplicationFramework.Profile.DocumentSearchCriteria"/&gt; --&gt; &lt;/properties&gt; &lt;/profile&gt; </code></pre> <p>With the criteria types above commented out the test ran fine. With them uncommented, the 500 error was returned.</p> <p>Anyone had a similar problem in the past?</p>
[ { "answer_id": 269052, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>Based on your evidence I would guess that a reference to whichever assembly contains <code>MyApplicationFramework.Profile.EmployeeSearchCriteria</code> is missing from either the unit test project or the web project - though I would really think that you would only require the reference in the web project but I'm not knowledgeable about how the VS web server behaves when used as part of a unit test.</p>\n" }, { "answer_id": 380350, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have faced same problem with unit testing.\nAnd found the problem reason and also solve it.\nThe problem is only with access rights for the directory.</p>\n\n<p>In my case I have installed VSTS on the different drive(d) then default.\nSo only to give the full access rights to the user <strong>PCNAME\\ASPNET</strong> for whole directory <strong>\\Program Files\\Microsoft Visual Studio 9.0</strong>.</p>\n\n<p>I m using the windows XP but if u are using window server then give access rights to the user <strong>NetworkServices</strong>.</p>\n\n<p>By this solution i have solved my problem.\nHope u find something useful from this Answer.</p>\n\n<p>Thanks,\nPriyesh Patel</p>\n" }, { "answer_id": 596475, "author": "ben", "author_id": 7561, "author_profile": "https://Stackoverflow.com/users/7561", "pm_score": 2, "selected": false, "text": "<p>I was getting the same problem as you, however my experience was a little different.</p>\n\n<p>I am on vista x64, my developers are in xp x64...they haven't been having any issues at all. I just upgraded and could not run any unit test for a asp.net MVC project. I was receiving the same 500 error you were receiving.</p>\n\n<p>I turned off code coverage, everything magically started working.</p>\n" }, { "answer_id": 761403, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Comment out the whole bit of web.config like this</p>\n\n<pre><code>&lt;!-- &lt;location path=\"VSEnterpriseHelper.axd\"&gt;\n &lt;system.web&gt;\n &lt;authorization&gt;\n &lt;allow users=\"?\" /&gt;\n &lt;/authorization&gt;\n &lt;/system.web&gt; &lt;/location&gt; --&gt;\n</code></pre>\n\n<p>It worked for me</p>\n" }, { "answer_id": 3316230, "author": "Scott", "author_id": 400003, "author_profile": "https://Stackoverflow.com/users/400003", "pm_score": 0, "selected": false, "text": "<p>Make sure your web application is targeted to Framework 4.0. If you are trying to test a\n2.0, 3.0 or 3.5 project, you will get the (500) Internal Server Error.</p>\n" }, { "answer_id": 3515780, "author": "hal9000", "author_id": 24862, "author_profile": "https://Stackoverflow.com/users/24862", "pm_score": 3, "selected": false, "text": "<p>I found that using vs2010 I am not restricted to just 4.0 applications. I DID however find that if testing a web application and you are using the old System.Web.Extensions version redirect you may get an error. Removing the following section from the <strong>Web.config</strong> file fixed my issue:</p>\n\n<pre><code>&lt;runtime&gt;\n &lt;assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\" appliesTo=\"v2.0.50727\"&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.Extensions\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.Extensions.Design\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;/assemblyBinding&gt;\n&lt;/runtime&gt;\n</code></pre>\n\n<p>Good luck.</p>\n" }, { "answer_id": 3614045, "author": "Bigdog", "author_id": 436476, "author_profile": "https://Stackoverflow.com/users/436476", "pm_score": 1, "selected": false, "text": "<p>I ran into a similar issue testing a webservice where the project is .NET 3.51. I was getting a IIS 500 error. \n I removed the old assembly bindinds as commented by Hal Diggs and it worked. </p>\n" }, { "answer_id": 3984373, "author": "Igor Zevaka", "author_id": 129404, "author_profile": "https://Stackoverflow.com/users/129404", "pm_score": 4, "selected": false, "text": "<p>I've had this problem before and at that point gave up after reading all I could google about it (including this thread).</p>\n\n<p>The solution turned out to be simple in my case. All I had to do was not use ASP.NET test attributes and simply test the MVC project as a DLL.</p>\n\n<h3>Step 1</h3>\n\n<p>Remove the extra attributes from the test.</p>\n\n<pre><code>[TestMethod]\npublic void TestMethod1()\n{\n Page page = TestContext.RequestedPage;\n Assert.IsTrue(false, \"Test ran, at least.\");\n}\n</code></pre>\n\n<h3>Step 2</h3>\n\n<p>In Code Coverage, uncheck the MVC Project and add the MVC Project's DLL manually.</p>\n\n<p><img src=\"https://i.stack.imgur.com/A9H6t.png\" alt=\"alt text\"></p>\n\n<p>Voila, it get instrumented as a normal assembly, no errors, doesn't spin up the Development Server, also doesn't fail the Team Build.</p>\n" }, { "answer_id": 4708986, "author": "Ibsta", "author_id": 577923, "author_profile": "https://Stackoverflow.com/users/577923", "pm_score": 1, "selected": false, "text": "<p>I got the same error message while unit testing a web app with Visual Studio 2010. The only difference is that i was using IIS, ie i ommited the <code>[AspNetDevelopmentServerHost(\"%PathToWebRoot%\")]</code> directive. </p>\n\n<p>I suspect the problem lies in the fact that i was using IIS version 5.1. More here:</p>\n\n<p><a href=\"http://ibsta.blogspot.com/2011/01/unit-testing-fun-under-visual-studio.html\" rel=\"nofollow\">http://ibsta.blogspot.com/2011/01/unit-testing-fun-under-visual-studio.html</a></p>\n" }, { "answer_id": 7740609, "author": "simpsons88", "author_id": 991500, "author_profile": "https://Stackoverflow.com/users/991500", "pm_score": 1, "selected": false, "text": "<p>I setup a default unit test which popped up with the error, that brought me here. I just removed the following (below). Then clicked debug current context and boom, fine :S.</p>\n\n<pre><code> [HostType(\"ASP.NET\")]\n [AspNetDevelopmentServerHost(\"C:\\\\Inetpub\\\\....]\n</code></pre>\n" }, { "answer_id": 41037505, "author": "Rashedul.Rubel", "author_id": 1632305, "author_profile": "https://Stackoverflow.com/users/1632305", "pm_score": 0, "selected": false, "text": "<p>I experienced the same problem. Then I checked the properties of both the web project and the unit test project. And found that target framework was set different from each other. I set the target framework of both the project to .Net framework 4 (in my case). Finally ran the test method again and it worked.</p>\n\n<p>Thanks.</p>\n" }, { "answer_id": 41852964, "author": "Mark", "author_id": 837507, "author_profile": "https://Stackoverflow.com/users/837507", "pm_score": 0, "selected": false, "text": "<p>For me it was Resharper that caused this problem. Once I suspended it (Tools -> Options -> Resharper -> General -> Suspend) everything worked.\n(using VS2010SP1 and Resharper Ultimate 2016.1.2)</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
I have the following method in my unit test project: ``` [TestMethod] [HostType("ASP.NET")] [UrlToTest("http://localhost:3418/Web/SysCoord/ChooseEPA.aspx")] [AspNetDevelopmentServerHost("%PathToWebRoot%")] public void TestMethod1() { Page page = TestContext.RequestedPage; Assert.IsTrue(false, "Test ran, at least."); } ``` I'm getting this exception: The test adapter 'WebHostAdapter' threw an exception while running test 'TestMethod1'. The web site could not be configured correctly; getting ASP.NET process information failed. Requesting '<http://localhost:3418/SysCoord/VSEnterpriseHelper.axd>' returned an error: The remote server returned an error: (404) Not Found. The remote server returned an error: (404) Not Found. The page works as it should in a browser at the url: <http://localhost:3418/Web/SysCoord/ChooseEPA.aspx>. This physical path is: C:\ESI\HR\_Connect2\BenefitChangeSystem\Application\_DEV\Web\SysCoord. Any ideas would be appreciated. **Update 1** Added the following to my web.config file per this article. Also made the web.config writable and killed/restarted the development web server. No change in behavior. ``` <location path="VSEnterpriseHelper.axd"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> ``` **Update 2** Changing the AspNetDevelopmentServerHost attribute to the equivalent of [AspNetDevelopmentServerHost("%PathToWebRoot%\solutionfolder\webfolder", "/webfolder")] resolved the 404 problem. Unfortunately the test began to return a 500 error instead. Progress, but not much. Trial and error with a clean project led to the conclusion that references to custom classes in the of the web.config were causing the problem. For example: ``` <profile enabled="true" defaultProvider="MyProfileProvider"> <providers> <add name="MyProfileProvider" connectionStringName="ProfileConnectionString" applicationName="/MyApp" type="System.Web.Profile.SqlProfileProvider"/> </providers> <properties> <add name="Theme" type="String" defaultValue="Default"/> <add name="LastLogon" type="DateTime"/> <add name="LastLogonIp" type="String"/> <!-- <add name="EmployeeSearchCriteria" type="MyApplicationFramework.Profile.EmployeeSearchCriteria"/> <add name="DocumentSearchCriteria" type="MyApplicationFramework.Profile.DocumentSearchCriteria"/> --> </properties> </profile> ``` With the criteria types above commented out the test ran fine. With them uncommented, the 500 error was returned. Anyone had a similar problem in the past?
I've had this problem before and at that point gave up after reading all I could google about it (including this thread). The solution turned out to be simple in my case. All I had to do was not use ASP.NET test attributes and simply test the MVC project as a DLL. ### Step 1 Remove the extra attributes from the test. ``` [TestMethod] public void TestMethod1() { Page page = TestContext.RequestedPage; Assert.IsTrue(false, "Test ran, at least."); } ``` ### Step 2 In Code Coverage, uncheck the MVC Project and add the MVC Project's DLL manually. ![alt text](https://i.stack.imgur.com/A9H6t.png) Voila, it get instrumented as a normal assembly, no errors, doesn't spin up the Development Server, also doesn't fail the Team Build.
260,436
<p>Disclaimer: the following is a sin against XML. That's why I'm trying to change it with XSLT :)</p> <p>My XML currently looks like this:</p> <pre><code>&lt;root&gt; &lt;object name="blarg" property1="shablarg" property2="werg".../&gt; &lt;object name="yetanotherobject" .../&gt; &lt;/root&gt; </code></pre> <p>Yes, I'm putting all the textual data in attributes. I'm hoping XSLT can save me; I want to move toward something like this:</p> <pre><code>&lt;root&gt; &lt;object&gt; &lt;name&gt;blarg&lt;/name&gt; &lt;property1&gt;shablarg&lt;/name&gt; ... &lt;/object&gt; &lt;object&gt; ... &lt;/object&gt; &lt;/root&gt; </code></pre> <p>I've actually got all of this working so far, with the exception that my sins against XML have been more... exceptional. Some of the tags look like this:</p> <pre><code>&lt;object description = "This is the first line This is the third line. That second line full of whitespace is meaningful"/&gt; </code></pre> <p>I'm using xsltproc under linux, but it doesn't seem to have any options to preserve whitespace. I've attempted to use xsl:preserve-space and xml:space="preserve" to no avail. Every option I've found seems to apply to keeping whitespace within the elements themselves, but not the attributes. Every single time, the above gets changed to:</p> <pre> This is the first line This is the third line. That second line full of whitespace is meaningful </pre> <p>So the question is, can I preserve the attribute whitespace?</p>
[ { "answer_id": 260457, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"http://www.xml.com/axml/testaxml.htm\" rel=\"nofollow noreferrer\">Annotated XML Spec</a>, white space in attribute values are normalized by the XML processor (See the (T) annotation on 3.3.3). So, it looks like the answer is probably no.</p>\n" }, { "answer_id": 260468, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 4, "selected": true, "text": "<p>This is actually a raw XML parsing problem, not something XSLT can help you with. An XML parse must convert the newlines in that attribute value to spaces, as per ‘3.3.3 Attribute-Value Normalization’ in the XML standard. So anything currently reading your description attributes and keeping the newlines in is doing it wrong.</p>\n\n<p>You may be able to recover the newlines by pre-processing the XML to escape the newlines to &amp; #10; character references, as long as you haven't also got newlines where charrefs are disallowed, such as inside tag bodies. Charrefs should survive as control characters through to the attribute value, where you can then turn them into text nodes.</p>\n" }, { "answer_id": 260774, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 1, "selected": false, "text": "<p>As others have pointed out, the XML spec doesn't allow for the preservation of spaces in attributes. In fact, this is one of the few differentiators between what you can do with attributes and elements (the other main one being that elements can contain other tags while attributes cannot).</p>\n\n<p>You will have to process the file outside of XML first in order to preserve the spaces.</p>\n" }, { "answer_id": 29782321, "author": "n611x007", "author_id": 611007, "author_profile": "https://Stackoverflow.com/users/611007", "pm_score": 0, "selected": false, "text": "<p>If you can control your XML processor, you can do it.</p>\n\n<p>From my <a href=\"https://stackoverflow.com/a/29780972/611007\">other answer</a> (which has many references linked):</p>\n\n<p>if you have an XML like</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?&gt;\n&lt;!DOCTYPE elemke [\n&lt;!ATTLIST brush wood CDATA #REQUIRED&gt;\n]&gt;\n\n&lt;elemke&gt;\n&lt;brush wood=\"guy&amp;#xA;threep\"/&gt;\n&lt;/elemke&gt;\n</code></pre>\n\n<p>and an XSL like </p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n\n&lt;xsl:template name=\"split\"&gt;\n &lt;xsl:param name=\"list\" select=\"''\" /&gt;\n &lt;xsl:param name=\"separator\" select=\"'&amp;#xA;'\" /&gt;\n &lt;xsl:if test=\"not($list = '' or $separator = '')\"&gt;\n &lt;xsl:variable name=\"head\" select=\"substring-before(concat($list, $separator), $separator)\" /&gt;\n &lt;xsl:variable name=\"tail\" select=\"substring-after($list, $separator)\" /&gt;\n\n &lt;xsl:value-of select=\"$head\"/&gt;\n &lt;br/&gt;&lt;xsl:text&gt;&amp;#xA;&lt;/xsl:text&gt;\n &lt;xsl:call-template name=\"split\"&gt;\n &lt;xsl:with-param name=\"list\" select=\"$tail\" /&gt;\n &lt;xsl:with-param name=\"separator\" select=\"$separator\" /&gt;\n &lt;/xsl:call-template&gt;\n &lt;/xsl:if&gt;\n&lt;/xsl:template&gt;\n\n\n&lt;xsl:template match=\"brush\"&gt;\n &lt;html&gt;\n &lt;xsl:call-template name=\"split\"&gt;\n &lt;xsl:with-param name=\"list\" select=\"@wood\"/&gt;\n &lt;/xsl:call-template&gt;\n &lt;/html&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>you can get a html like:</p>\n\n<pre><code>&lt;html&gt;guy&lt;br&gt;\n threep&lt;br&gt;\n\n&lt;/html&gt; \n</code></pre>\n\n<p>as tested/produced with a processor like this <a href=\"http://sourceforge.net/projects/saxon/files/Saxon-HE/\" rel=\"nofollow noreferrer\">saxon</a> command line:</p>\n\n<pre><code>java -jar saxon9he.jar -s:in.xml -xsl:in.xsl -o:out.html\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2555346/" ]
Disclaimer: the following is a sin against XML. That's why I'm trying to change it with XSLT :) My XML currently looks like this: ``` <root> <object name="blarg" property1="shablarg" property2="werg".../> <object name="yetanotherobject" .../> </root> ``` Yes, I'm putting all the textual data in attributes. I'm hoping XSLT can save me; I want to move toward something like this: ``` <root> <object> <name>blarg</name> <property1>shablarg</name> ... </object> <object> ... </object> </root> ``` I've actually got all of this working so far, with the exception that my sins against XML have been more... exceptional. Some of the tags look like this: ``` <object description = "This is the first line This is the third line. That second line full of whitespace is meaningful"/> ``` I'm using xsltproc under linux, but it doesn't seem to have any options to preserve whitespace. I've attempted to use xsl:preserve-space and xml:space="preserve" to no avail. Every option I've found seems to apply to keeping whitespace within the elements themselves, but not the attributes. Every single time, the above gets changed to: ``` This is the first line This is the third line. That second line full of whitespace is meaningful ``` So the question is, can I preserve the attribute whitespace?
This is actually a raw XML parsing problem, not something XSLT can help you with. An XML parse must convert the newlines in that attribute value to spaces, as per ‘3.3.3 Attribute-Value Normalization’ in the XML standard. So anything currently reading your description attributes and keeping the newlines in is doing it wrong. You may be able to recover the newlines by pre-processing the XML to escape the newlines to & #10; character references, as long as you haven't also got newlines where charrefs are disallowed, such as inside tag bodies. Charrefs should survive as control characters through to the attribute value, where you can then turn them into text nodes.
260,439
<p>I currently have two text boxes which accept any number. I have a text block that takes the two numbers entered and calculates the average. </p> <p>I was wondering if there was a way I could bind this text block to both text boxes and utilize a custom converter to calculate the average? I currently am catching the text changed events on both text boxes and calculating the average that way, but I am under the assumption data binding would be more efficient and easier.</p>
[ { "answer_id": 260445, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 7, "selected": true, "text": "<p>You're looking for <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding.aspx\" rel=\"noreferrer\"><code>MultiBinding</code></a>.</p>\n\n<p>Your <code>XAML</code> will look something like this:</p>\n\n<pre><code>&lt;TextBlock&gt;\n &lt;TextBlock.Text&gt;\n &lt;MultiBinding Converter=\"{StaticResource myConverter}\"&gt;\n &lt;Binding Path=\"myFirst.Value\" /&gt;\n &lt;Binding Path=\"mySecond.Value\" /&gt;\n &lt;/MultiBinding&gt;\n &lt;/TextBlock.Text&gt;\n&lt;/TextBlock&gt;\n</code></pre>\n\n<p>With reasonable replacements for <code>myConverter</code>, <code>myFirst.Value</code>, and <code>mySecond.Value</code>.</p>\n" }, { "answer_id": 260487, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": 5, "selected": false, "text": "<p>Create a converter that implements IMultiValueConverter. It might look something like this:</p>\n\n<pre><code>class AverageConverter : IMultiValueConverter\n{\n #region IMultiValueConverter Members\n public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n int total = 0;\n int number = 0;\n foreach (object o in values)\n {\n int i;\n bool parsed = int.TryParse(o.ToString(), out i);\n if (parsed)\n {\n total += i;\n number++;\n }\n }\n if (number == 0) return 0;\n return (total/number).ToString();\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\n</code></pre>\n\n<p>A multivalue converter receives an object array, one for each of the bindings. You can process these however you need, depending on whether you're intending it for double or int or whatever.</p>\n\n<p>If the two textboxes are databound, you can use the same bindings in the multibinding for your textblock (remembering to notify when the property changes so that your average is updated), or you can get the text value by referring to the textboxes by ElementName.</p>\n\n<pre><code>&lt;TextBox Text=\"{Binding Value1}\" x:Name=\"TextBox1\" /&gt;\n&lt;TextBox Text=\"{Binding Value2}\" x:Name=\"TextBox2\" /&gt;\n\n&lt;TextBlock&gt;\n &lt;TextBlock.Text&gt;\n &lt;MultiBinding Converter=\"{StaticResource AverageConverter}\"&gt;\n &lt;Binding ElementName=\"TextBox1\" Path=\"Text\" /&gt;\n &lt;Binding ElementName=\"TextBox2\" Path=\"Text\" /&gt;\n &lt;!-- OR --&gt;\n &lt;!-- &lt;Binding Path=\"Value1\" /&gt; --&gt;\n &lt;!-- &lt;Binding Path=\"Value2\" /&gt; --&gt;\n\n &lt;/MultiBinding&gt;\n &lt;/TextBlock.Text&gt;\n&lt;/TextBlock&gt;\n</code></pre>\n" }, { "answer_id": 260493, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": false, "text": "<p>Or, you could make a property in code behind, and bind the TextBlock to that ... I do that all the time, and it's a little simpler than making a converter, then doing that same code there.</p>\n\n<p>Example: (in your code behind of the xaml):</p>\n\n<pre><code>public double AvgValue\n{\n get { return (valueA + valueB) / 2.0; }\n}\n</code></pre>\n\n<p>And then, in your XAML:</p>\n\n<pre><code>&lt;TextBlock Text=\"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=AvgValue}\" /&gt;\n</code></pre>\n\n<p>That's a LOT simpler than a custom converter.</p>\n" }, { "answer_id": 13731125, "author": "Michael Nguyen", "author_id": 788386, "author_profile": "https://Stackoverflow.com/users/788386", "pm_score": 0, "selected": false, "text": "<p>Just to add step-by-step procedure to Timothy's answer:</p>\n\n<ol>\n<li>Setup the View.TextBlock.Text property to bind to the ViewModel.AvgValue property.</li>\n<li>Catch the TextChanged event of the TextBox control, then set the AvgValue in the handler of that TextChanged event.</li>\n<li>As part of that handler in step 2, make sure to raise a property change so that the TextBlock is updated.</li>\n</ol>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23939/" ]
I currently have two text boxes which accept any number. I have a text block that takes the two numbers entered and calculates the average. I was wondering if there was a way I could bind this text block to both text boxes and utilize a custom converter to calculate the average? I currently am catching the text changed events on both text boxes and calculating the average that way, but I am under the assumption data binding would be more efficient and easier.
You're looking for [`MultiBinding`](http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding.aspx). Your `XAML` will look something like this: ``` <TextBlock> <TextBlock.Text> <MultiBinding Converter="{StaticResource myConverter}"> <Binding Path="myFirst.Value" /> <Binding Path="mySecond.Value" /> </MultiBinding> </TextBlock.Text> </TextBlock> ``` With reasonable replacements for `myConverter`, `myFirst.Value`, and `mySecond.Value`.
260,441
<p>In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access.</p> <p>I have managed to create databases and tables, but now how do I make a relationship between two tables?</p> <p>If I have my two tables like this:</p> <pre><code>CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ) ) </code></pre> <p>and</p> <pre><code>CREATE TABLE customers( customer_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, address VARCHAR(20) NOT NULL, city VARCHAR(20) NOT NULL, state VARCHAR(20) NOT NULL, PRIMARY KEY ( customer_id ) ) </code></pre> <p>How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).</p>
[ { "answer_id": 260453, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 8, "selected": true, "text": "<p>If the tables are innodb you can create it like this: </p>\n\n<pre><code>CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY ( account_id ), \n FOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n) ENGINE=INNODB;\n</code></pre>\n\n<p>You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look <a href=\"http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html\" rel=\"noreferrer\">here</a> for more info. </p>\n" }, { "answer_id": 260458, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 4, "selected": false, "text": "<p>Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than </p>\n\n<pre><code>customer_id INT( 4 ) NOT NULL ,\n</code></pre>\n\n<p>make it</p>\n\n<pre><code>customer_id INT( 10 ) NOT NULL ,\n</code></pre>\n\n<p>and make sure your int column in the customers table is int(10) also. </p>\n" }, { "answer_id": 260460, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 7, "selected": false, "text": "<p>as ehogue said, put this in your CREATE TABLE</p>\n\n<pre><code>FOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n</code></pre>\n\n<p>alternatively, if you already have the table created, use an ALTER TABLE command:</p>\n\n<pre><code>ALTER TABLE `accounts`\n ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;\n</code></pre>\n\n<p>One good way to start learning these commands is using the <a href=\"http://dev.mysql.com/downloads/gui-tools/5.0.html\" rel=\"noreferrer\">MySQL GUI Tools</a>, which give you a more \"visual\" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.</p>\n" }, { "answer_id": 260500, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 3, "selected": false, "text": "<p>Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.</p>\n\n<p>If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.</p>\n\n<p>For example, in a query you link two tables in a select statement with a join:</p>\n\n<pre><code>SELECT a, b from table1 LEFT JOIN table2 USING (common_field);\n</code></pre>\n" }, { "answer_id": 14536060, "author": "Musa", "author_id": 2000184, "author_profile": "https://Stackoverflow.com/users/2000184", "pm_score": 1, "selected": false, "text": "<p>One of the rules you have to know is that the table column you want to reference to has to be with the same data type as \nThe referencing table . 2 if you decide to use mysql you have to use InnoDB Engine because according to your question that’s the engine which supports what you want to achieve in mysql .</p>\n\n<p>Bellow is the code try it though the first people to answer this question \nthey 100% provided great answers and please consider them all .</p>\n\n<pre><code>CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY (account_id)\n)ENGINE=InnoDB;\n\nCREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n PRIMARY KEY ( account_id ), \nFOREIGN KEY (customer_id) REFERENCES customers(customer_id) \n)ENGINE=InnoDB; \n</code></pre>\n" }, { "answer_id": 23775708, "author": "user3659515", "author_id": 3659515, "author_profile": "https://Stackoverflow.com/users/3659515", "pm_score": 2, "selected": false, "text": "<p>Here are a couple of resources that will help get started: <a href=\"http://www.anchor.com.au/hosting/support/CreatingAQuickMySQLRelationalDatabase\" rel=\"nofollow\">http://www.anchor.com.au/hosting/support/CreatingAQuickMySQLRelationalDatabase</a> and <a href=\"http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561\" rel=\"nofollow\">http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561</a></p>\n\n<p>Also as others said, use a GUI - try downloading and installing Xampp (or Wamp) which run server-software (Apache and mySQL) on your computer. \nThen when you navigate to //localhost in a browser, select PHPMyAdmin to start working with a mySQL database visually. As mentioned above, used innoDB to allow you to make relationships as you requested. Makes it heaps easier to see what you're doing with the database tables. Just remember to STOP Apache and mySQL services when finished - these can open up ports which can expose you to hacking/malicious threats.</p>\n" }, { "answer_id": 28890883, "author": "user3842431", "author_id": 3842431, "author_profile": "https://Stackoverflow.com/users/3842431", "pm_score": 4, "selected": false, "text": "<pre><code>CREATE TABLE accounts(\n account_id INT NOT NULL AUTO_INCREMENT,\n customer_id INT( 4 ) NOT NULL ,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n PRIMARY KEY ( account_id )\n)\n\nand\n\nCREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n)\n\nHow do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).\n</code></pre>\n<p>You have to ask yourself is this a 1 to 1 relationship or a 1 out of many relationship. That is, does every account have a customer and every customer have an account. Or will there be customers without accounts. Your question implies the latter.</p>\n<p>If you want to have a strict 1 to 1 relationship, just merge the two tables.</p>\n<pre><code>CREATE TABLE customers(\n customer_id INT NOT NULL AUTO_INCREMENT,\n name VARCHAR(20) NOT NULL,\n address VARCHAR(20) NOT NULL,\n city VARCHAR(20) NOT NULL,\n state VARCHAR(20) NOT NULL,\n account_type ENUM( 'savings', 'credit' ) NOT NULL,\n balance FLOAT( 9 ) NOT NULL,\n)\n</code></pre>\n<p>In the other case, the correct way to create a relationship between two tables is to create a relationship table.</p>\n<pre><code>CREATE TABLE customersaccounts(\n customer_id INT NOT NULL,\n account_id INT NOT NULL,\n PRIMARY KEY (customer_id, account_id),\n FOREIGN KEY customer_id references customers (customer_id) on delete cascade,\n FOREIGN KEY account_id references accounts (account_id) on delete cascade\n}\n</code></pre>\n<p>Then if you have a customer_id and want the account info, you join on customersaccounts and accounts:</p>\n<pre><code>SELECT a.*\n FROM customersaccounts ca\n INNER JOIN accounts a ca.account_id=a.account_id\n AND ca.customer_id=mycustomerid;\n</code></pre>\n<p>Because of indexing this will be blindingly quick.</p>\n<p>You could also create a VIEW which gives you the effect of the combined customersaccounts table while keeping them separate</p>\n<pre><code>CREATE VIEW customeraccounts AS \n SELECT a.*, c.* FROM customersaccounts ca\n INNER JOIN accounts a ON ca.account_id=a.account_id\n INNER JOIN customers c ON ca.customer_id=c.customer_id;\n</code></pre>\n" }, { "answer_id": 52351148, "author": "Anayat", "author_id": 10369848, "author_profile": "https://Stackoverflow.com/users/10369848", "pm_score": 0, "selected": false, "text": "<pre><code>create table departement(\n dep_id int primary key auto_increment,\n dep_name varchar(100) not null,\n dep_descriptin text,\n dep_photo varchar(100) not null,\n dep_video varchar(300) not null\n);\n\ncreate table newsfeeds(\n news_id int primary key auto_increment,\n news_title varchar(200) not null,\n news_description text,\n news_photo varchar(300) ,\n news_date varchar(30) not null,\n news_video varchar(300),\n news_comment varchar(200),\n news_departement int foreign key(dep_id) references departement(dep_id)\n);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access. I have managed to create databases and tables, but now how do I make a relationship between two tables? If I have my two tables like this: ``` CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ) ) ``` and ``` CREATE TABLE customers( customer_id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, address VARCHAR(20) NOT NULL, city VARCHAR(20) NOT NULL, state VARCHAR(20) NOT NULL, PRIMARY KEY ( customer_id ) ) ``` How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer\_id (to indicate who owns it).
If the tables are innodb you can create it like this: ``` CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ), FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ) ENGINE=INNODB; ``` You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look [here](http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html) for more info.
260,464
<p>I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:</p> <pre><code>warning: HEAP[test.exe]: warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1 </code></pre> <p>How can I track down where this is happening at? Viewing the memory doesn't give me any clues.</p> <p>Thanks!</p>
[ { "answer_id": 260496, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>So you're busting your heap. Here's a nice <a href=\"http://www.cs.princeton.edu/courses/archive/spring99/cs126/help/gdbtut.html\" rel=\"nofollow noreferrer\">GDB tutorial</a> to keep in mind.</p>\n\n<p>My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way. </p>\n\n<p>Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).</p>\n" }, { "answer_id": 264845, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 1, "selected": false, "text": "<p>You can probably use a feature called a \"watch point\". This is like a break point but the debugger stops when the memory is modified.</p>\n\n<p>I gave a rough idea on how to use this in an <a href=\"https://stackoverflow.com/questions/7525/of-memory-management-heap-corruption-and-c#71983\">answer</a> to a different question.</p>\n" }, { "answer_id": 264848, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p>If you can use other tools, I highly recommend trying out <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">Valgrind</a>. It is an instrumentation framework, that can run your code in a manner that allows it to, typically, stop at the exact instruction that causes the error. Heap errors are usually easy to find, this way.</p>\n" }, { "answer_id": 1123178, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 1, "selected": false, "text": "<p>One thing you can try, as this is the same sort of thing as the standard libc, with the MALLOC_CHECK_ envronment variable configured (man libc).</p>\n\n<p>If you keep from exiting gdb (if your application quit's, just use \"r\" to re-run it), you can setup a memory breakpoint at that address, \"hbreak 0x64EA569\", also use \"help hbreak\" to configure condition's or other breakpoitn enable/disable options to prevent excessively entering that breakpoint.... </p>\n\n<p>You can just configure a log file, set log ... setup a stack trace on every break, \"display/bt -4\", then hit r, and just hold down the enter key and let it scroll by \n\"or use c ## to continue x times... etc..\", eventually you will see that same assertion, then you will now have (due to the display/bt) a stacktrace which you can corolate to what code was modifying on that address...</p>\n" }, { "answer_id": 16990738, "author": "Rafał", "author_id": 1048556, "author_profile": "https://Stackoverflow.com/users/1048556", "pm_score": 0, "selected": false, "text": "<p>I had similar problem when I was trying to realloc array of pointers to my structures, but instead I was reallocating as array of ints (because I got the code from tutorial and forgot to change it). The compiler wasnt correcting me because it cannot be checked whats in size argument.\nMy variable was:</p>\n\n<p><code>itemsetList_t ** iteration_isets;</code></p>\n\n<p>So in realloc instead of having:</p>\n\n<p><code>iteration_isets = realloc(iteration_isets, sizeof(itemsetList_t *) * max_elem);</code></p>\n\n<p>I had:</p>\n\n<p><code>iteration_isets = realloc(iteration_isets, sizeof(int) * max_elem);</code></p>\n\n<p>And this caused my heap problem.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3175/" ]
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like: ``` warning: HEAP[test.exe]: warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1 ``` How can I track down where this is happening at? Viewing the memory doesn't give me any clues. Thanks!
So you're busting your heap. Here's a nice [GDB tutorial](http://www.cs.princeton.edu/courses/archive/spring99/cs126/help/gdbtut.html) to keep in mind. My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way. Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).
260,484
<p>How do I query the iPhone's current IP address?</p>
[ { "answer_id": 2913196, "author": "arifwidi", "author_id": 212915, "author_profile": "https://Stackoverflow.com/users/212915", "pm_score": 2, "selected": false, "text": "<p>You can try to use similar to this service:\n<a href=\"http://automation.whatismyip.com/n09230945.asp\" rel=\"nofollow noreferrer\">Whatismyip</a> and capture the string :)</p>\n\n<p>Credit to Erica Sadun's iPhone Developer's Cookbok, 2nd ed, page 555.</p>\n" }, { "answer_id": 2913328, "author": "Krumelur", "author_id": 292477, "author_profile": "https://Stackoverflow.com/users/292477", "pm_score": 4, "selected": false, "text": "<p>If you want the <strong>external</strong> IP address (the one used to connect from outside the local network), you need to query a server on the external network. A quick search yielded the following: <a href=\"http://checkip.dyndns.org\" rel=\"noreferrer\">http://checkip.dyndns.org</a>, <a href=\"http://www.whatismyip.com\" rel=\"noreferrer\">http://www.whatismyip.com</a>. It is quite simple to load the page using e.g. <pre>[NSData dataWithContentsOfURL:url]</pre></p>\n\n<p>and do some string manipulation to retrieve the IP address.</p>\n\n<p>If you want the <strong>internal</strong> IP address (the one assigned e.g. by DHCP to your device), what you can usually do is to resolve the device's hostname, i.e.</p>\n\n<pre><code>\n/*\nReturns the local IP, or NULL on failure.\n*/\nconst char* GetLocalIP() {\n char buf[256];\n if(gethostname(buf,sizeof(buf)))\n return NULL;\n struct hostent* he = gethostbyname(buf);\n if(!he)\n return NULL;\n for(int i=0; he->h_addr_list[i]; i++) {\n char* ip = inet_ntoa(*(struct in_addr*)he->h_addr_list[i]);\n if(ip != (char*)-1) return ip;\n }\n return NULL;\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I query the iPhone's current IP address?
If you want the **external** IP address (the one used to connect from outside the local network), you need to query a server on the external network. A quick search yielded the following: <http://checkip.dyndns.org>, <http://www.whatismyip.com>. It is quite simple to load the page using e.g. ``` [NSData dataWithContentsOfURL:url] ``` and do some string manipulation to retrieve the IP address. If you want the **internal** IP address (the one assigned e.g. by DHCP to your device), what you can usually do is to resolve the device's hostname, i.e. ``` /* Returns the local IP, or NULL on failure. */ const char* GetLocalIP() { char buf[256]; if(gethostname(buf,sizeof(buf))) return NULL; struct hostent* he = gethostbyname(buf); if(!he) return NULL; for(int i=0; he->h_addr_list[i]; i++) { char* ip = inet_ntoa(*(struct in_addr*)he->h_addr_list[i]); if(ip != (char*)-1) return ip; } return NULL; } ```
260,491
<p>I'm developing a library for use in other apps and this library has lots of debugging and logging statements thanks to NLog.</p> <p>Is it possible to exclude the reference to NLog.dll when I switch to release mode?</p> <p>Cheers,</p>
[ { "answer_id": 260522, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 0, "selected": false, "text": "<p>I can't think of a good way to do this. Unless maybe you wrote a stub reference for NLog.dll. Since you are using the reference in your code I don't see how you could just remove it in your release. </p>\n\n<p>Probably too late now but in the future you could write a class to wrap NLog.dll and then just change it in one place so it wouldn't actually log in the release version. Or have some sort of flag.</p>\n" }, { "answer_id": 260530, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>The only way I know is to take the reference out completely and call the assembly via reflection. Then, you should only log if the assembly loads.</p>\n" }, { "answer_id": 260548, "author": "Mash", "author_id": 33854, "author_profile": "https://Stackoverflow.com/users/33854", "pm_score": -1, "selected": false, "text": "<p>There is no reason for removing a reference in case you are sure that no code will be in use from that DLL. In that case you can simply remove DLL.</p>\n" }, { "answer_id": 260566, "author": "Scott P", "author_id": 33848, "author_profile": "https://Stackoverflow.com/users/33848", "pm_score": -1, "selected": false, "text": "<p>Why would you want to do that? </p>\n\n<p>If you want to stop logging, you can programatically turn off the logging. The performance hit will be minimal. (I have had great success with NLog even when logging cross process.) </p>\n\n<p>Otherwise, you need to wrap it as described above.</p>\n\n<p>-Scott</p>\n" }, { "answer_id": 860601, "author": "Sander Rijken", "author_id": 5555, "author_profile": "https://Stackoverflow.com/users/5555", "pm_score": 6, "selected": true, "text": "<p>You can manually edit the csproj file, and do something like this:</p>\n\n<pre><code>&lt;Reference Include=\"NLog\" Condition=\"'$(Configuration)' == 'Debug'\" /&gt;\n</code></pre>\n\n<p>This only makes it reference that assembly in Debug. I wouldn't recommend doing this often though, because this behavior isn't reflected in the references list in Visual Studio when you change the configuration. It does work when compiling though</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
I'm developing a library for use in other apps and this library has lots of debugging and logging statements thanks to NLog. Is it possible to exclude the reference to NLog.dll when I switch to release mode? Cheers,
You can manually edit the csproj file, and do something like this: ``` <Reference Include="NLog" Condition="'$(Configuration)' == 'Debug'" /> ``` This only makes it reference that assembly in Debug. I wouldn't recommend doing this often though, because this behavior isn't reflected in the references list in Visual Studio when you change the configuration. It does work when compiling though
260,511
<p>Here is my short implementation of <a href="http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication" rel="noreferrer">Russian Peasant Multiplication</a>. How can it be improved?</p> <p><em>Restrictions</em> : only works when a>0,b>0</p> <pre><code>for(p=0;p+=(a&amp;1)*b,a!=1;a&gt;&gt;=1,b&lt;&lt;=1); </code></pre>
[ { "answer_id": 260529, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 2, "selected": false, "text": "<p>I think it's incomplete, and very hard to read. What specific sort of feedback were you looking for?</p>\n" }, { "answer_id": 260546, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p><code>p</code> is not initialised.</p>\n\n<p>What happens if <code>a</code> is zero?</p>\n\n<p>What happens if <code>a</code> is negative?</p>\n\n<p><strong>Update:</strong> I see that you have updated the question to address the above problems. While your code now appears to work as stated (except for the overflow problem), it's still less readable than it should be.</p>\n" }, { "answer_id": 260552, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 4, "selected": false, "text": "<p>I think it's terrible\nThis is exactly the same code from the compiler's point of view, and (hopefully) a lot clearer</p>\n\n<pre><code>int sum = 0;\nwhile(1)\n{\n sum += (a &amp; 1) * b;\n if(a == 1)\n break;\n\n a = a / 2;\n b = b * 2;\n}\n</code></pre>\n\n<p>And now I've written it out, I understand it.</p>\n" }, { "answer_id": 260568, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 3, "selected": false, "text": "<p>There is still a multiplication in the loop. If you wanted to reduce the cost of the multiplications, you could use this instead:</p>\n\n<pre><code>for(p=0;p+=(-(a&amp;1))&amp;b,a!=1;a&gt;&gt;=1,b&lt;&lt;=1);\n</code></pre>\n" }, { "answer_id": 260569, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 2, "selected": false, "text": "<p>This is for a code obfuscation contest? I think you can do better. Use misleading variable names instead of meaningless ones, for starters.</p>\n" }, { "answer_id": 260662, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<pre><code>int RussianPeasant(int a, int b)\n{\n // sum = a * b\n int sum = 0;\n while (a != 0)\n {\n if ((a &amp; 1) != 0)\n sum += b;\n b &lt;&lt;= 1;\n a &gt;&gt;= 1;\n }\n return sum;\n}\n</code></pre>\n" }, { "answer_id": 260893, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 7, "selected": true, "text": "<p>It can be improved by adding whitespace, proper indentation, and a proper function body:</p>\n\n<pre><code>int peasant_mult (int a, int b) {\n for (p = 0;\n p += (a &amp; 1) * b, a != 1;\n a /= 2, b *= 2);\n return p;}\n</code></pre>\n\n<p>See? Now it's clear how the three parts of the <code>for</code> declaration are used. Remember, programs are written mainly for human eyes. Unreadable code is always bad code.</p>\n\n<p>And now, for my personal amusement, a tail recursive version:</p>\n\n<pre>\n(defun peasant-mult (a b &optional (sum 0))\n \"returns the product of a and b,\n achieved by peasant multiplication.\"\n (if (= a 1)\n (+ b sum)\n (peasant-mult (floor (/ a 2))\n (* b 2)\n (+ sum (* b (logand a 1))))))\n</pre>\n" }, { "answer_id": 261414, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "<p>I don't find it particularly terrible, obfuscated or unreadable, as others put it, and I don't understand all those downvotes. This said, here is how I would \"improve\" it:</p>\n\n<pre><code>// Russian Peasant Multiplication ( p &lt;- a*b, only works when a&gt;0, b&gt;0 )\n// See http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication\nfor( p=0; p+=(a&1)*b, a!=1; a&gt;&gt;=1,b&lt;&lt;=1 );\n</code></pre>\n" }, { "answer_id": 286768, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 4, "selected": false, "text": "<p>There is an really easy way to improve this:</p>\n\n<pre><code>p = a * b;\n</code></pre>\n\n<p>It has even the advantage that a or b could be less than 0.</p>\n\n<p>If you look how it really works, you will see, that it is just the normal manual multiplication performed binary. You computer does it internaly this way (1), so the easiest way to use the russian peasant method is to use the builtin multiplication.</p>\n\n<p>(1) Maybe it has a more sophasticated algorithm, but in principle you can say, it works with this algorithm</p>\n" }, { "answer_id": 1172612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Answer with no multiplication or division:</p>\n\n<pre><code>function RPM(int a, int b){\n int rtn;\n for(rtn=0;rtn+=(a&amp;1)*b,a!=1;a&gt;&gt;=1,b&lt;&lt;=1);\n return rtn;\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34051/" ]
Here is my short implementation of [Russian Peasant Multiplication](http://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication). How can it be improved? *Restrictions* : only works when a>0,b>0 ``` for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1); ```
It can be improved by adding whitespace, proper indentation, and a proper function body: ``` int peasant_mult (int a, int b) { for (p = 0; p += (a & 1) * b, a != 1; a /= 2, b *= 2); return p;} ``` See? Now it's clear how the three parts of the `for` declaration are used. Remember, programs are written mainly for human eyes. Unreadable code is always bad code. And now, for my personal amusement, a tail recursive version: ``` (defun peasant-mult (a b &optional (sum 0)) "returns the product of a and b, achieved by peasant multiplication." (if (= a 1) (+ b sum) (peasant-mult (floor (/ a 2)) (* b 2) (+ sum (* b (logand a 1)))))) ```
260,523
<p>I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the <em>UITableViewCell Class Reference</em> but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.</p> <p>How can we use a color other than those defined in the reference?</p>
[ { "answer_id": 260697, "author": "Jeffrey Forbes", "author_id": 28019, "author_profile": "https://Stackoverflow.com/users/28019", "pm_score": 2, "selected": false, "text": "<p>Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:</p>\n\n<pre><code>UIView* selectedView; //inside your header\n\n- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{\n\n UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];\n selectedView = [[UIView alloc] initWithFrame:[cell frame]];\n selectedView.backgroundColor = [UIColor greenColor]; //whatever\n\n [cell insertSubview:selectedView atIndex:0]; //tweak this as necessary\n [selectedView release]; //clean up\n\n}\n</code></pre>\n\n<p>You can choose to animate this view out when it gets deselected and will satisfy your requirements.</p>\n" }, { "answer_id": 758493, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 7, "selected": true, "text": "<p>The best way to set the selection is to set the <code>selectedBackgroundView</code> on the cell when you construct it.</p>\n\n<p>i.e.</p>\n\n<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n\n static NSString *CellIdentifier = @\"Cell\";\n UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];\n if (cell == nil) {\n cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];\n cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"SelectedCellBackground.png\"]] autorelease];\n }\n\n // configure the cell\n}\n</code></pre>\n\n<p>The image used should have a nice gradient (like the default selection). If you just want a flat color, you can use a UIView instead of a <code>UIImageView</code> and set the <code>backgroundColor</code> to the color you want.</p>\n\n<p>This background is then automatically applied when the row is selected.</p>\n" }, { "answer_id": 1844211, "author": "Paul", "author_id": 224415, "author_profile": "https://Stackoverflow.com/users/224415", "pm_score": 5, "selected": false, "text": "<p>Setting the <code>selectedBackgroundView</code> seems to have no effect when the <code>cell.selectionStyle</code> is set to <code>UITableViewCellSelectionStyleNone</code>. When I don't set the style is just uses the default gray. </p>\n\n<p>Using the first suggestion that inserts the custom <code>UIView</code> into the cell does manipulate the cell but it doesn't show up when the cell is touched, only after the selected action is completed which is too late because I'm pushing to a new view. How do I get the selected view in the cell to display before the beginning of the selected operation?</p>\n" }, { "answer_id": 11600123, "author": "Charles Marsh", "author_id": 1450892, "author_profile": "https://Stackoverflow.com/users/1450892", "pm_score": 3, "selected": false, "text": "<p>I tried some of the above, and <strong>I actually prefer to create my own subclass of UITableViewCell and then override the touchesBegan/touchesCancelled/touchesEnded methods</strong>. To do this, ignore all the selectedBackgroundView and highlightedColor properties on the cell, and instead just set these colors manually whenever one of the above methods are called. For example, if you want to set the cell to have a green background with red text, try this (within your custom cell subclass):</p>\n\n<pre><code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n{\n //Set backgorund\n self.backgroundColor = [UIColor themeBlue];\n\n //Set text\n self.textLabel.textColor = [UIColor themeWhite];\n\n //Call super\n [super touchesBegan:touches withEvent:event];\n}\n</code></pre>\n\n<p>Note that for this to work, you need to set:</p>\n\n<pre><code>self.selectionStyle = UITableViewCellSelectionStyleNone;\n</code></pre>\n\n<p>Otherwise, you'll first get the current selection style.</p>\n\n<p>EDIT: \nI suggest using the touchesCancelled method to revert back to the original cell colors, but just ignore the touchesEnded method.</p>\n" }, { "answer_id": 11633174, "author": "Willster", "author_id": 385619, "author_profile": "https://Stackoverflow.com/users/385619", "pm_score": 4, "selected": false, "text": "<p>If you have subclassed a UITableViewCell, then you can customise the various elements of the cell by overriding the following:</p>\n\n<pre><code>- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if(highlighted) {\n self.backgroundColor = [UIColor redColor];\n } else {\n self.backgroundColor = [UIColor clearColor];\n }\n\n [super setHighlighted:highlighted animated:animated];\n}\n</code></pre>\n\n<p>EDIT for iOS7:\nas Sasho stated, you also need </p>\n\n<pre><code>cell.selectionStyle = UITableViewCellSelectionStyleNone\n</code></pre>\n" }, { "answer_id": 13070898, "author": "bentford", "author_id": 946, "author_profile": "https://Stackoverflow.com/users/946", "pm_score": 1, "selected": false, "text": "<p>Sublcass UITableViewCell and override <code>setHighlighted:animated:</code></p>\n\n<p>You can define a custom selection color color by setting the backgroundColor (see WIllster's answer):</p>\n\n<pre><code>- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if(highlighted) {\n self.backgroundColor = [UIColor redColor];\n } else {\n self.backgroundColor = [UIColor clearColor];\n }\n\n [super setHighlighted:highlighted animated:animated];\n}\n</code></pre>\n\n<p>You can define a custom background image by setting the backgroundView property:</p>\n\n<pre><code>- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {\n if( highlighted == YES )\n self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"seasonal_list_event_bar_default.png\"]];\n else\n self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"seasonal_list_event_bar_active.png\"]];\n\n\n [super setHighlighted:highlighted animated:animated];\n}\n</code></pre>\n" }, { "answer_id": 17469723, "author": "PK86", "author_id": 952193, "author_profile": "https://Stackoverflow.com/users/952193", "pm_score": 0, "selected": false, "text": "<pre><code>- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { \n// Set Highlighted Color \nif (highlighted) { \nself.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];\n } else { \n self.backgroundColor = [UIColor clearColor]; \n } \n}\n</code></pre>\n" }, { "answer_id": 38100301, "author": "Ishwar Hingu", "author_id": 5022598, "author_profile": "https://Stackoverflow.com/users/5022598", "pm_score": 0, "selected": false, "text": "<pre><code>- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n return YES;\n}\n\n- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n // Add your Colour.\n SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];\n [self setCellColor:Ripple_Colour ForCell:cell]; //highlight colour\n}\n\n- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {\n // Reset Colour.\n SocialTableViewCell *cell = (SocialTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];\n [self setCellColor:Ripple_Colour ForCell:cell]; //normal color\n\n}\n\n- (void)setCellColor:(UIColor *)color ForCell:(UITableViewCell *)cell {\n cell.contentView.backgroundColor = color;\n cell.backgroundColor = color;\n}\n</code></pre>\n" }, { "answer_id": 48623625, "author": "Prateekro", "author_id": 2714340, "author_profile": "https://Stackoverflow.com/users/2714340", "pm_score": 0, "selected": false, "text": "<p>To add a custom color use the below code. And to make it transparent use <code>alpha: 0.0</code></p>\n\n<pre><code>cell.selectedBackgroundView = UIView(frame: CGRect.zero)\ncell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)\n</code></pre>\n\n<p>If you use custom color and want to give it rounded corner look use:</p>\n\n<pre><code>cell.layer.cornerRadius = 8\n</code></pre>\n\n<p>Also, use this for better animation and feel</p>\n\n<pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n\n tableView.deselectRow(at: indexPath, animated: true)\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the *UITableViewCell Class Reference* but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference. How can we use a color other than those defined in the reference?
The best way to set the selection is to set the `selectedBackgroundView` on the cell when you construct it. i.e. ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SelectedCellBackground.png"]] autorelease]; } // configure the cell } ``` The image used should have a nice gradient (like the default selection). If you just want a flat color, you can use a UIView instead of a `UIImageView` and set the `backgroundColor` to the color you want. This background is then automatically applied when the row is selected.
260,531
<p>How have you explained nested arrays to a programmer. I'm thinking someone that has an entry level understanding of programming, but is trying to do more complicated coding.</p> <p>The array with array works, but they can't quite get their mind around the idea.</p> <p><strong>Edit:</strong> example of a nested array:</p> <pre><code>array( 'array1' =&gt; array( 'key1' =&gt; 'val1', 'key2' =&gt; 'val2', ), 'array2' =&gt; array( 'key1' =&gt; 'val1', 'key2' =&gt; 'val2', ), ); </code></pre> <p>Of course, they are usually more complicated than this and maybe that's the problem.</p>
[ { "answer_id": 260537, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 4, "selected": true, "text": "<p>Tell them to think of an array as a list- it helps to give them something less abstract, like a grocery list. Then, a nested array is simply a list of lists.</p>\n\n<p>Maybe I have a todo list, a grocery list, and a wishlist at amazon.com . Now I have a list of all of my lists, and I can look at all of those elements in each list by stepping through them.</p>\n" }, { "answer_id": 260543, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>How have you explained it? It doesn't seem like a big jump for someone that understands one dimensional arrays to be able to grasp the concept that instead of an int or a string that each array element contains another array instead. </p>\n\n<p>Perhaps an analogy comparing directories will help, a one dimensional array would be analogous to a directory that contains a bunch of files, a two-dimensional array to a directory which contains several other directories, each containing a bunch of files, etc.</p>\n" }, { "answer_id": 260547, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>If you are looking at C type, non-ragged, arrays, comparing it to numbers, the base 10 part, and there digits might help. Another good source for this same effect would be time as it has a non uniform base 60s = 1m, 60m = 1h, 24h = 1day, 7day = 1week</p>\n" }, { "answer_id": 260551, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "<p>Use a bitmap as an example. In C, you can make a bitmap of an <code>X</code> like this:</p>\n\n<pre><code>int x[5][5] = {\n { 1,0,0,0,1 },\n { 0,1,0,1,0 },\n { 0,0,1,0,0 },\n { 0,1,0,1,0 },\n { 1,0,0,0,1 }\n};\n</code></pre>\n\n<p>Then show them how to use nested <code>for</code> loops to display the bitmap.</p>\n\n<p>Examples always help, and this also gets them to think of nested arrays as multi-dimensional arrays. Actually it's probably better to understand multi-dimensional arrays in a language like C before learning about the \"nested\" arrays in languages like Python where you can have different levels of nesting in the same array.</p>\n" }, { "answer_id": 260553, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 1, "selected": false, "text": "<p>Sports can provide appropriate analogies to describe applying nested arrays. A team is an array of people, a competition is an array of teams that play against each other.</p>\n\n<p>However its a case of finding the analogy that clicks with the learner. Find the right analogy and you'll get even the slowest of learners to understand. Just ensure you're analogies are water tight. Like abstractions, they are leaky.</p>\n" }, { "answer_id": 260565, "author": "thursdaysgeek", "author_id": 22523, "author_profile": "https://Stackoverflow.com/users/22523", "pm_score": 3, "selected": false, "text": "<p>A nested array is a set within a set. So, a library has a set of books, a book has a set of chapters. A chapter has a set of paragraphs, a paragraph has a set of sentences. A sentence has a set of words. </p>\n\n<pre><code>For each book in library\n\n For each chapter in book\n\n For each paragraph in chapter\n</code></pre>\n\n<p>etc...</p>\n" }, { "answer_id": 260575, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>A concrete example is the index at the back of a book. A list of words, each word associated with a list of page numbers. </p>\n\n<p>apples - 1, 2, 3-4<br>\nbears - 32-35, 79, 83<br>\ncats - 14, 15 </p>\n" }, { "answer_id": 260581, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 0, "selected": false, "text": "<p>2 dimensions is easy to explain. Just think of a table. 3 dimensions just think of a cube or other 3d image. 4 dimensions think of a series of images like a movie with the 4th dimension being time.</p>\n\n<p>4+ dimensions is hard to visualize using that model. But think of it as a filing cabinet with another file cabinet inside helps. You open the drawer and out pops a filing cabinet. You find the drawer you want and open that drawer and out pops another filing cabinet....over and over until finally you get your paper.</p>\n" }, { "answer_id": 260584, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 2, "selected": false, "text": "<p>Draw it.</p>\n\n<p>A variable is a box<br>\n1 dimensional array is a row of boxes.<br>\n2 dimensional array is a grid of boxes.<br>\n3 dimensional array is a cube of boxes.</p>\n\n<p>If they have having trouble with the general concept, don't attempt to visually explain 4 dimensions.</p>\n" }, { "answer_id": 260785, "author": "user33891", "author_id": 33891, "author_profile": "https://Stackoverflow.com/users/33891", "pm_score": 0, "selected": false, "text": "<p>Perhaps you are explaining it from the context of someone who understands an array of arrays. I would attempt to trick them into realizing that they already understand them by starting at the smallest(read inner array)...and slowly expanding out, giving them plenty of time to ask questions until they are done. </p>\n\n<p>Drawing helps, but you need to give the student in this case some information and go slowly, most programmers I know tend to go to fast and to like to explain things EVEN when the listener no longer is tracking what is being said.</p>\n\n<p>I am a metaphor guy, so I would probably cook something up about a series of boxes with each one numbered, each box then containing a similiar(but much smaller series) also numbered. I would take this to only two levels get understanding and then perhaps talk about 3 dimensions for confirmation. But I would avoid 4 dimensions on the grounds that they may get hung in the idea that there is no such thing as 4 dimensions, or you can't measure time, or other such metaphorical landmines/distractions...cause that's the other problem, programmers tend to be ADD and enjoy getting side tracked.</p>\n\n<p>Also why aren't you using a hash of hashes, much easier to reference. :)</p>\n\n<p>Bottom line, baby steps.</p>\n" }, { "answer_id": 260988, "author": "Scott Evernden", "author_id": 11397, "author_profile": "https://Stackoverflow.com/users/11397", "pm_score": 0, "selected": false, "text": "<p>an array is just an object - a thing. everything should be simple to understand once they get that</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
How have you explained nested arrays to a programmer. I'm thinking someone that has an entry level understanding of programming, but is trying to do more complicated coding. The array with array works, but they can't quite get their mind around the idea. **Edit:** example of a nested array: ``` array( 'array1' => array( 'key1' => 'val1', 'key2' => 'val2', ), 'array2' => array( 'key1' => 'val1', 'key2' => 'val2', ), ); ``` Of course, they are usually more complicated than this and maybe that's the problem.
Tell them to think of an array as a list- it helps to give them something less abstract, like a grocery list. Then, a nested array is simply a list of lists. Maybe I have a todo list, a grocery list, and a wishlist at amazon.com . Now I have a list of all of my lists, and I can look at all of those elements in each list by stepping through them.
260,540
<p>Please advise how to scrape AJAX pages.</p>
[ { "answer_id": 260557, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 2, "selected": false, "text": "<p>Depends on the ajax page. The first part of screen scraping is determining how the page works. Is there some sort of variable you can iterate through to request all the data from the page? Personally I've used <a href=\"http://www.velocityscape.com/\" rel=\"nofollow noreferrer\">Web Scraper Plus</a> for a lot of screen scraping related tasks because it is cheap, not difficult to get started, non-programmers can get it working relatively quickly.</p>\n\n<p>Side Note: Terms of Use is probably somewhere you might want to check before doing this. Depending on the site iterating through everything may raise some flags. </p>\n" }, { "answer_id": 260558, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "<p>If you can get at it, try examining the DOM tree. <a href=\"http://selenium.openqa.org/\" rel=\"noreferrer\">Selenium</a> does this as a part of testing a page. It also has functions to click buttons and follow links, which may be useful.</p>\n" }, { "answer_id": 260614, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p><strong>Overview:</strong></p>\n\n<p>All screen scraping first requires manual review of the page you want to extract resources from. When dealing with AJAX you usually just need to analyze a bit more than just simply the HTML. </p>\n\n<p>When dealing with AJAX this just means that the value you want is not in the initial HTML document that you requested, but that javascript will be exectued which asks the server for the extra information you want. </p>\n\n<p>You can therefore usually simply analyze the javascript and see which request the javascript makes and just call this URL instead from the start. </p>\n\n<hr>\n\n<p><strong>Example:</strong></p>\n\n<p>Take this as an example, assume the page you want to scrape from has the following script:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction ajaxFunction()\n{\nvar xmlHttp;\ntry\n {\n // Firefox, Opera 8.0+, Safari\n xmlHttp=new XMLHttpRequest();\n }\ncatch (e)\n {\n // Internet Explorer\n try\n {\n xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");\n }\n catch (e)\n {\n try\n {\n xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n catch (e)\n {\n alert(\"Your browser does not support AJAX!\");\n return false;\n }\n }\n }\n xmlHttp.onreadystatechange=function()\n {\n if(xmlHttp.readyState==4)\n {\n document.myForm.time.value=xmlHttp.responseText;\n }\n }\n xmlHttp.open(\"GET\",\"time.asp\",true);\n xmlHttp.send(null);\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Then all you need to do is instead do an HTTP request to time.asp of the same server instead. <a href=\"http://www.w3schools.com/Ajax/ajax_server.asp\" rel=\"noreferrer\">Example from w3schools</a>.</p>\n\n<hr>\n\n<p><strong>Advanced scraping with C++:</strong> </p>\n\n<p>For complex usage, and if you're using C++ you could also consider using the firefox javascript engine <a href=\"http://www.mozilla.org/js/spidermonkey/\" rel=\"noreferrer\">SpiderMonkey</a> to execute the javascript on a page. </p>\n\n<p><strong>Advanced scraping with Java:</strong></p>\n\n<p>For complex usage, and if you're using Java you could also consider using the firefox javascript engine for Java <a href=\"http://www.mozilla.org/rhino/\" rel=\"noreferrer\">Rhino</a></p>\n\n<p><strong>Advanced scraping with .NET:</strong></p>\n\n<p>For complex usage, and if you're using .Net you could also consider using the Microsoft.vsa assembly. Recently replaced with ICodeCompiler/CodeDOM.</p>\n" }, { "answer_id": 5623299, "author": "Alex", "author_id": 702411, "author_profile": "https://Stackoverflow.com/users/702411", "pm_score": 1, "selected": false, "text": "<p>As a low cost solution you can also try <a href=\"http://webiussoft.com\" rel=\"nofollow\">SWExplorerAutomation</a> (SWEA). The program creates an automation API for any Web application developed with HTML, DHTML or AJAX. </p>\n" }, { "answer_id": 6484022, "author": "Deepan Prabhu Babu", "author_id": 596634, "author_profile": "https://Stackoverflow.com/users/596634", "pm_score": 0, "selected": false, "text": "<p>I have previously linked to MIT's solvent and EnvJS as my answers to scrape off Ajax pages. These projects seem no longer accessible.</p>\n\n<p>Out of sheer necessity, I have invented another way to actually scrape off Ajax pages, and it has worked for tough sites like findthecompany which have methods to find headless javascript engines and show no data.</p>\n\n<p>The technique is to use chrome extensions to do scraping. Chrome extensions are the best place to scrape off Ajax pages because they actually allow us access to javascript modified DOM. The technique is as follows, I will certainly open source the code in sometime. Create a chrome extension ( assuming you know how to create one, and its architecture and capabilities. This is easy to learn and practice as there are lots of samples),</p>\n\n<ol>\n<li>Use content scripts to access the DOM, by using xpath. Pretty much get the entire list or table or dynamically rendered content using xpath into a variable as string HTML Nodes. ( Only content scripts can access DOM but they can't contact a URL using XMLHTTP )</li>\n<li>From content script, using message passing, message the entire stripped DOM as string, to a background script. ( Background scripts can talk to URLs but can't touch the DOM ). We use message passing to get these to talk.</li>\n<li>You can use various events to loop through web pages and pass each stripped HTML Node content to the background script.</li>\n<li>Now use the background script, to talk to an external server (on localhost), a simple one created using Nodejs/python. Just send the entire HTML Nodes as string, to the server, where the server would just persist the content posted to it, into files, with appropriate variables to identify page numbers or URLs.</li>\n<li>Now you have scraped AJAX content ( HTML Nodes as string ), but these are partial html nodes. Now you can use your favorite XPATH library to load these into memory and use XPATH to scrape information into Tables or text.</li>\n</ol>\n\n<p>Please comment if you cant understand and I can write it better. ( first attempt ). Also, I am trying to release sample code as soon as possible.</p>\n" }, { "answer_id": 16468467, "author": "sw.", "author_id": 88231, "author_profile": "https://Stackoverflow.com/users/88231", "pm_score": 2, "selected": false, "text": "<p>The best way to scrape web pages using Ajax or in general pages using Javascript is with a browser itself or a headless browser (a browser without GUI). Currently <a href=\"http://phantomjs.org/\" rel=\"nofollow\">phantomjs</a> is a well promoted headless browser using WebKit. An alternative that I used with success is <a href=\"http://htmlunit.sourceforge.net/\" rel=\"nofollow\">HtmlUnit</a> (in Java or .NET via <a href=\"http://www.ikvm.net/\" rel=\"nofollow\">IKVM</a>, which is a simulated browser. Another known alternative is using a web automation tool like <a href=\"http://docs.seleniumhq.org/\" rel=\"nofollow\">Selenium</a>.</p>\n\n<p>I wrote many articles about this subject like <a href=\"http://blog.databigbang.com/web-scraping-ajax-and-javascript-sites/\" rel=\"nofollow\">web scraping Ajax and Javascript sites</a> and <a href=\"http://blog.databigbang.com/automated-browserless-oauth-authentication-for-twitter/\" rel=\"nofollow\">automated browserless OAuth authentication for Twitter</a>. At the end of the first article there are a lot of extra resources that I have been compiling since 2011.</p>\n" }, { "answer_id": 17638017, "author": "yxc", "author_id": 2254730, "author_profile": "https://Stackoverflow.com/users/2254730", "pm_score": 2, "selected": false, "text": "<p>I think Brian R. Bondy's answer is useful when the source code is easy to read. I prefer an easy way using tools like Wireshark or HttpAnalyzer to capture the packet and get the url from the \"Host\" field and the \"GET\" field.</p>\n\n<p>For example,I capture a packet like the following:</p>\n\n<pre><code>GET /hqzx/quote.aspx?type=3&amp;market=1&amp;sorttype=3&amp;updown=up&amp;page=1&amp;count=8&amp;time=164330 \n HTTP/1.1\nAccept: */*\nReferer: http://quote.hexun.com/stock/default.aspx\nAccept-Language: zh-cn\nAccept-Encoding: gzip, deflate\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\nHost: quote.tool.hexun.com\nConnection: Keep-Alive\n</code></pre>\n\n<p>Then the URL is : </p>\n\n<pre><code>http://quote.tool.hexun.com/hqzx/quote.aspx?type=3&amp;market=1&amp;sorttype=3&amp;updown=up&amp;page=1&amp;count=8&amp;time=164330\n</code></pre>\n" }, { "answer_id": 21653575, "author": "mattspain", "author_id": 2794310, "author_profile": "https://Stackoverflow.com/users/2794310", "pm_score": 3, "selected": false, "text": "<p>In my opinion the simpliest solution is to use <a href=\"http://casperjs.org/\">Casperjs</a>, a framework based on the WebKit headless browser phantomjs.</p>\n\n<p>The whole page is loaded, and it's very easy to scrape any ajax-related data.\nYou can check this basic tutorial to learn <a href=\"http://www.youtube.com/watch?v=Kefil5tCL9o\">Automating &amp; Scraping with PhantomJS and CasperJS</a></p>\n\n<p>You can also give a look at this example code, on how to scrape google suggests keywords :</p>\n\n<pre><code>/*global casper:true*/\nvar casper = require('casper').create();\nvar suggestions = [];\nvar word = casper.cli.get(0);\n\nif (!word) {\n casper.echo('please provide a word').exit(1);\n}\n\ncasper.start('http://www.google.com/', function() {\n this.sendKeys('input[name=q]', word);\n});\n\ncasper.waitFor(function() {\n return this.fetchText('.gsq_a table span').indexOf(word) === 0\n}, function() {\n suggestions = this.evaluate(function() {\n var nodes = document.querySelectorAll('.gsq_a table span');\n return [].map.call(nodes, function(node){\n return node.textContent;\n });\n });\n});\n\ncasper.run(function() {\n this.echo(suggestions.join('\\n')).exit();\n});\n</code></pre>\n" }, { "answer_id": 33174184, "author": "TTT", "author_id": 515902, "author_profile": "https://Stackoverflow.com/users/515902", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"https://github.com/Tomtomgo/phearjs/\" rel=\"nofollow\">PhearJS</a>, but that might be partially because I built it.</p>\n\n<p>That said, it's a service you run in the background that speaks HTTP(S) and renders pages as JSON for you, including any metadata you might need.</p>\n" }, { "answer_id": 47696020, "author": "hekimgil", "author_id": 1312745, "author_profile": "https://Stackoverflow.com/users/1312745", "pm_score": 1, "selected": false, "text": "<p>Selenium WebDriver is a good solution: you program a browser and you automate what needs to be done in the browser. Browsers (Chrome, Firefox, etc) provide their own drivers that work with Selenium. Since it works as an automated <strong>REAL browser</strong>, the pages (including javascript and Ajax) get loaded as they do with a human using that browser.</p>\n\n<p>The downside is that it is slow (since you would most probably like to wait for all images and scripts to load before you do your scraping on that single page).</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34051/" ]
Please advise how to scrape AJAX pages.
**Overview:** All screen scraping first requires manual review of the page you want to extract resources from. When dealing with AJAX you usually just need to analyze a bit more than just simply the HTML. When dealing with AJAX this just means that the value you want is not in the initial HTML document that you requested, but that javascript will be exectued which asks the server for the extra information you want. You can therefore usually simply analyze the javascript and see which request the javascript makes and just call this URL instead from the start. --- **Example:** Take this as an example, assume the page you want to scrape from has the following script: ``` <script type="text/javascript"> function ajaxFunction() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.myForm.time.value=xmlHttp.responseText; } } xmlHttp.open("GET","time.asp",true); xmlHttp.send(null); } </script> ``` Then all you need to do is instead do an HTTP request to time.asp of the same server instead. [Example from w3schools](http://www.w3schools.com/Ajax/ajax_server.asp). --- **Advanced scraping with C++:** For complex usage, and if you're using C++ you could also consider using the firefox javascript engine [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) to execute the javascript on a page. **Advanced scraping with Java:** For complex usage, and if you're using Java you could also consider using the firefox javascript engine for Java [Rhino](http://www.mozilla.org/rhino/) **Advanced scraping with .NET:** For complex usage, and if you're using .Net you could also consider using the Microsoft.vsa assembly. Recently replaced with ICodeCompiler/CodeDOM.
260,594
<p>My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss. </p> <p>For example, my MDB looks something like:</p> <pre><code>@MessageDriven(mappedName = "ExampleMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"), @ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"), }) @ResourceAdapter(value = "wmq.jmsra.rar") @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @TransactionManagement(TransactionManagementType.BEAN) public class MyMDB implements MessageListener { ..... } </code></pre> <p>But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.</p>
[ { "answer_id": 260796, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 6, "selected": true, "text": "<p>Make your own CPAN mirror with exactly what you want. <a href=\"http://www.stratopan.com\" rel=\"noreferrer\">Stratopan.com</a>, a service, and <a href=\"http://www.metacpan.org/module/Pinto\" rel=\"noreferrer\">Pinto</a>, tools that's built on top of, can help you do that.</p>\n\n<p>The CPAN tools only install the latest version of any distribution because PAUSE only indexes the latest version. However, you can create your own, private CPAN that has exactly the distributions that you want. Once you have your own CPAN mirror with only what you want, you point your CPAN tools at only that mirror so it only installs those versions. More on that in a minute.</p>\n\n<p>Now, you want to have several versions of that. You can create as many mirrors as you like, and you can also put the mirrors in source control so you can check out any version of the mirror that you like. </p>\n\n<p>Tools such as CPAN::Mini::Inject can help you set up your own CPAN. Check out <a href=\"http://www.slideshare.net/brian_d_foy\" rel=\"noreferrer\">my talks on Slideshare</a> for the basic examples, and some of <a href=\"http://vimeo.com/user493904/videos\" rel=\"noreferrer\">my videos on Vimeo</a> for some of the demonstrations. Look at anything that has \"CPAN\" or \"BackPAN\" in the title. I think I might have some stuff about it in <a href=\"http://www.theperlreview.com\" rel=\"noreferrer\">The Perl Review</a> too, or should by the next issue. :)</p>\n\n<p>Lately, I've been working on a program called dpan (for DarkPAN) that can look at random directories, find Perl distributions in them, and create the structure and index files that you need. You run dpan, you get a URL to point your CPAN client toward, and off you go. It's part of my MyCPAN-Indexer project, which is in <a href=\"http://github.com/briandfoy/mycpan-indexer/tree/master\" rel=\"noreferrer\">Github</a>. It's not quite ready for unsupervised public use because I mostly work with corporate clients to customize their setup. If you're interested in that, feel free to ask me questions though.</p>\n\n<p>Also, I recently released <a href=\"http://search.cpan.org/dist/CPAN-PackageDetails\" rel=\"noreferrer\">CPAN::PackageDetails</a> that can help you build the right index file. It's still a bit young too, but again, if you need something special, just ask.</p>\n" }, { "answer_id": 267783, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 7, "selected": false, "text": "<p>bdfoy has the best large scale solution, but if you just want to install a few modules you can ask the CPAN shell to install a specific distribution by referencing a path to a tarball (relative to the top of the CPAN tree).</p>\n\n<pre><code>cpan&gt; install MSCHWERN/Test-Simple-0.62.tar.gz\n</code></pre>\n\n<p>Throw a URL to BackPAN into your URL list and you can install any older version.</p>\n\n<pre><code>cpan&gt; o conf urllist push http://backpan.perl.org/\n</code></pre>\n\n<p>This is in the <a href=\"https://metacpan.org/pod/CPAN#pod12\" rel=\"noreferrer\">CPAN.pm FAQ</a> under \"how do I install a 'DEVELOPER RELEASE' of a module?\"</p>\n" }, { "answer_id": 17101846, "author": "G. Cito", "author_id": 2019415, "author_profile": "https://Stackoverflow.com/users/2019415", "pm_score": 3, "selected": false, "text": "<p><em>[It's almost five years on and this is a well-asked and well-answered question that has had a lot of views. Since this page must still come up in Google searches, an update can't hurt.]</em></p>\n\n<p><a href=\"https://metacpan.org/module/Carton\"><code>Carton</code></a> is worth mentioning here. <code>Carton</code> is a relatively recent tool in the same style as <code>App::cpanminus</code>, <code>App::cpanoutdated</code>, <code>perlbrew</code>, <em>et. al.</em> The author (Miyagawa) calls it \"alpha\" quality, but even in its current state carton helps simplify the maintenance of multiple environments of version tuned modules across machines. </p>\n\n<p><a href=\"https://metacpan.org/release/Pinto\"><code>Pinto</code></a> too is another recent tool relevant to some of the responses (in fact one of the respondents is a contributor). </p>\n" }, { "answer_id": 20410602, "author": "Jeffrey Ryan Thalhammer", "author_id": 1229730, "author_profile": "https://Stackoverflow.com/users/1229730", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stratopan.com\" rel=\"nofollow noreferrer\">Stratopan.com</a> is another alternative. Stratopan provides private CPANs in the cloud. You can fill your Stratopan repository with specific versions of modules (and their dependencies) and then install them using the standard Perl tool chain. The repository changes only when <em>you</em> decide to change it, so you'll get always get the versions of the modules that you want.</p>\n<p><em>Disclaimer: I operate Stratopan.</em></p>\n" }, { "answer_id": 30540984, "author": "Ether", "author_id": 40468, "author_profile": "https://Stackoverflow.com/users/40468", "pm_score": 5, "selected": false, "text": "<pre><code>cpan install App::cpanminus\ncpanm Your::[email protected]\n</code></pre>\n\n<p>(Carton, as referenced in other answers, uses <code>cpanm</code> underneath to resolve explicit version requirements.)</p>\n" }, { "answer_id": 36158342, "author": "Randall", "author_id": 584940, "author_profile": "https://Stackoverflow.com/users/584940", "pm_score": 2, "selected": false, "text": "<p>It seems that creating a <code>cpanfile</code> listing all your modules and desired versions (using the <code>== &lt;version&gt;</code> syntax to lock it to a specific release) could serve well here, too. That would mean using <code>Carton</code> or <code>cpanm</code> for installing the modules.</p>\n\n<p>Doing this would have the benefit of being able to quickly/easily tweak the file to test upgrading specific modules in a dev or staging environment - something that a private CPAN mirror wouldn't let you do (without creating multiple mirrors).</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33864/" ]
My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss. For example, my MDB looks something like: ``` @MessageDriven(mappedName = "ExampleMDB", activationConfig = { @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"), @ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"), @ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"), }) @ResourceAdapter(value = "wmq.jmsra.rar") @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @TransactionManagement(TransactionManagementType.BEAN) public class MyMDB implements MessageListener { ..... } ``` But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.
Make your own CPAN mirror with exactly what you want. [Stratopan.com](http://www.stratopan.com), a service, and [Pinto](http://www.metacpan.org/module/Pinto), tools that's built on top of, can help you do that. The CPAN tools only install the latest version of any distribution because PAUSE only indexes the latest version. However, you can create your own, private CPAN that has exactly the distributions that you want. Once you have your own CPAN mirror with only what you want, you point your CPAN tools at only that mirror so it only installs those versions. More on that in a minute. Now, you want to have several versions of that. You can create as many mirrors as you like, and you can also put the mirrors in source control so you can check out any version of the mirror that you like. Tools such as CPAN::Mini::Inject can help you set up your own CPAN. Check out [my talks on Slideshare](http://www.slideshare.net/brian_d_foy) for the basic examples, and some of [my videos on Vimeo](http://vimeo.com/user493904/videos) for some of the demonstrations. Look at anything that has "CPAN" or "BackPAN" in the title. I think I might have some stuff about it in [The Perl Review](http://www.theperlreview.com) too, or should by the next issue. :) Lately, I've been working on a program called dpan (for DarkPAN) that can look at random directories, find Perl distributions in them, and create the structure and index files that you need. You run dpan, you get a URL to point your CPAN client toward, and off you go. It's part of my MyCPAN-Indexer project, which is in [Github](http://github.com/briandfoy/mycpan-indexer/tree/master). It's not quite ready for unsupervised public use because I mostly work with corporate clients to customize their setup. If you're interested in that, feel free to ask me questions though. Also, I recently released [CPAN::PackageDetails](http://search.cpan.org/dist/CPAN-PackageDetails) that can help you build the right index file. It's still a bit young too, but again, if you need something special, just ask.
260,597
<p>I'd like to receive error logs via email. For example, if a <code>Warning-level</code> error message should occur, I'd like to get an email about it.</p> <p>How can I get that working in CodeIgniter?</p>
[ { "answer_id": 260655, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 5, "selected": true, "text": "<p>You could extend the Exception core class to do it.</p>\n\n<p>Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path.</p>\n\n<p>Make a file MY_Exceptions.php and place it in /application/libraries/ (Or in /application/core/ for CI 2)</p>\n\n<pre><code>class MY_Exceptions extends CI_Exceptions {\n\n function __construct()\n {\n parent::__construct();\n }\n\n function log_exception($severity, $message, $filepath, $line)\n\n { \n if (ENVIRONMENT === 'production') {\n $ci =&amp; get_instance();\n\n $ci-&gt;load-&gt;library('email');\n $ci-&gt;email-&gt;from('[email protected]', 'Your Name');\n $ci-&gt;email-&gt;to('[email protected]');\n $ci-&gt;email-&gt;cc('[email protected]');\n $ci-&gt;email-&gt;bcc('[email protected]');\n $ci-&gt;email-&gt;subject('error');\n $ci-&gt;email-&gt;message('Severity: '.$severity.' --&gt; '.$message. ' '.$filepath.' '.$line);\n $ci-&gt;email-&gt;send();\n }\n\n\n parent::log_exception($severity, $message, $filepath, $line);\n }\n\n}\n</code></pre>\n" }, { "answer_id": 260660, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "<p>Oh, another option is to get a logrotation application that supports emailing digests. Not sure what platform you are on, but you could just have something monitor the error_log file and send you updates, might not be as neat and certainly you would be limited to only information in the error_log. (error_log is Apache, CI has a /logs/ folder in system, and IIS has the Windows Events)</p>\n" }, { "answer_id": 3379089, "author": "Jon Terry", "author_id": 407576, "author_profile": "https://Stackoverflow.com/users/407576", "pm_score": 2, "selected": false, "text": "<p>One thing that is left out of the solution is that you have to grab CodeIgniters super object to load and use the email library (or any of CodeIgniters other libraries and native functions).</p>\n\n<pre><code>$CI =&amp; get_instance();\n</code></pre>\n\n<p>After you have done that you use <code>$CI</code> instead of <code>$this</code> to load the email library and set all of the parameters. For more information <a href=\"http://codeigniter.com/user_guide/general/creating_libraries.html\" rel=\"nofollow noreferrer\">click here</a> and look under the <strong>Utilizing CodeIgniter Resources within Your Library</strong> section.</p>\n" }, { "answer_id": 4198474, "author": "James", "author_id": 25251, "author_profile": "https://Stackoverflow.com/users/25251", "pm_score": 0, "selected": false, "text": "<p>I'm just about to release an open source project that does this, and more. It collects errors, sends them to an issue tracker, detects duplicates, turns them into issues and emails staff.</p>\n\n<p>Details are at <a href=\"https://sourceforge.net/news/?group_id=317819&amp;id=293422\" rel=\"nofollow\">https://sourceforge.net/news/?group_id=317819&amp;id=293422</a> and the version 0.1.7 it mentions is due out in a couple of days.</p>\n\n<p>The open source tracker is at <a href=\"http://elastik.sourceforge.net/\" rel=\"nofollow\">http://elastik.sourceforge.net/</a></p>\n\n<p>Any feedback welcome, Thanks</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to receive error logs via email. For example, if a `Warning-level` error message should occur, I'd like to get an email about it. How can I get that working in CodeIgniter?
You could extend the Exception core class to do it. Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path. Make a file MY\_Exceptions.php and place it in /application/libraries/ (Or in /application/core/ for CI 2) ``` class MY_Exceptions extends CI_Exceptions { function __construct() { parent::__construct(); } function log_exception($severity, $message, $filepath, $line) { if (ENVIRONMENT === 'production') { $ci =& get_instance(); $ci->load->library('email'); $ci->email->from('[email protected]', 'Your Name'); $ci->email->to('[email protected]'); $ci->email->cc('[email protected]'); $ci->email->bcc('[email protected]'); $ci->email->subject('error'); $ci->email->message('Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line); $ci->email->send(); } parent::log_exception($severity, $message, $filepath, $line); } } ```
260,615
<p>I am trying this in my Form Load Event</p> <p><pre><code> cmdCancel.Attributes.Add("onClick", "document.forms[0].reset();return false;") </pre></code></p> <p>but it doesn't clear my form. My form is a "ContentPage", part of a masterpage.</p> <p>Am I missing something?</p>
[ { "answer_id": 260629, "author": "pearcewg", "author_id": 24126, "author_profile": "https://Stackoverflow.com/users/24126", "pm_score": 0, "selected": false, "text": "<p>Shouldn't cancel take you away from the form entry page?\nIt sounds like you are trying to code \"reset\", but you are functionally attempting \"cancel\".</p>\n\n<p>Personally, I always have an event that fires on \"cleanup\" and does all form cleanup that I need to do (not just for reset form fields).</p>\n" }, { "answer_id": 260630, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code> cmdCancel.Attributes.Add(\"onClick\",\"document.getElementById('\" + this.Page.ClientId + \"').reset(); return false;\");\n</code></pre>\n" }, { "answer_id": 260653, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 1, "selected": false, "text": "<p>A call to \"Reset\" on a form resets the values to what was supplied in the markup for the page. So if there are any values supplied (via ViewState or any other mechanism) that is what the fields will be reset to, not blank.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
I am trying this in my Form Load Event ``` cmdCancel.Attributes.Add("onClick", "document.forms[0].reset();return false;") ``` but it doesn't clear my form. My form is a "ContentPage", part of a masterpage. Am I missing something?
Try this: ``` cmdCancel.Attributes.Add("onClick","document.getElementById('" + this.Page.ClientId + "').reset(); return false;"); ```
260,626
<p>What does "type-safe" mean?</p>
[ { "answer_id": 260640, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": false, "text": "<p>Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.</p>\n\n<p>Some simple examples:</p>\n\n<pre><code>// Fails, Trying to put an integer in a string\nString one = 1;\n// Also fails.\nint foo = \"bar\";\n</code></pre>\n\n<p>This also applies to method arguments, since you are passing explicit types to them:</p>\n\n<pre><code>int AddTwoNumbers(int a, int b)\n{\n return a + b;\n}\n</code></pre>\n\n<p>If I tried to call that using:</p>\n\n<pre><code>int Sum = AddTwoNumbers(5, \"5\");\n</code></pre>\n\n<p>The compiler would throw an error, because I am passing a string (\"5\"), and it is expecting an integer.</p>\n\n<p>In a loosely typed language, such as javascript, I can do the following:</p>\n\n<pre><code>function AddTwoNumbers(a, b)\n{\n return a + b;\n}\n</code></pre>\n\n<p>if I call it like this:</p>\n\n<pre><code>Sum = AddTwoNumbers(5, \"5\");\n</code></pre>\n\n<p>Javascript automaticly converts the 5 to a string, and returns \"55\". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:</p>\n\n<pre><code>function AddTwoNumbers(a, b)\n{\n return Number(a) + Number(b);\n}\n</code></pre>\n\n<p>Or, possibly:</p>\n\n<pre><code>function AddOnlyTwoNumbers(a, b)\n{\n if (isNaN(a) || isNaN(b))\n return false;\n return Number(a) + Number(b);\n}\n</code></pre>\n\n<p>if I call it like this:</p>\n\n<pre><code>Sum = AddTwoNumbers(5, \" dogs\");\n</code></pre>\n\n<p>Javascript automatically converts the 5 to a string, and appends them, to return \"5 dogs\".</p>\n\n<p>Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.</p>\n\n<p>While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.</p>\n\n<p>Now, back to C#...</p>\n\n<p>C# supports a language feature called <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#C.23\" rel=\"noreferrer\">covariance</a>, this basically means that you can substitute a base type for a child type and not cause an error, for example:</p>\n\n<pre><code> public class Foo : Bar\n {\n }\n</code></pre>\n\n<p>Here, I created a new class (Foo) that subclasses Bar. I can now create a method:</p>\n\n<pre><code> void DoSomething(Bar myBar)\n</code></pre>\n\n<p>And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.</p>\n\n<p>However, you cannot do the inverse:</p>\n\n<pre><code>void DoSomething(Foo myFoo)\n</code></pre>\n\n<p>In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.</p>\n\n<p>Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)</p>\n" }, { "answer_id": 260652, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>An explanation from a liberal arts major, not a comp sci major:</p>\n\n<p>When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.</p>\n\n<p>For example, in C#, I define a function as:</p>\n\n<pre><code> void foo(int arg)\n</code></pre>\n\n<p>The compiler will then stop me from doing this: </p>\n\n<pre><code> // call foo\n foo(\"hello world\")\n</code></pre>\n\n<p>In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.</p>\n\n<p>Type safe languages try to catch more at \"compile time\".</p>\n\n<p>On the down side, with type safe languages, when you have a string like \"123\" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, \"The answer is 123\", you have to write more code to convert/cast it to a string.</p>\n" }, { "answer_id": 260657, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "<p>Try this explanation on...</p>\n\n<p>TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).</p>\n\n<p>For non-typesafe behavior, consider this:</p>\n\n<pre><code>object x = 89;\nint y;\n</code></pre>\n\n<p>if you attempt to do this:</p>\n\n<pre><code>y = x;\n</code></pre>\n\n<p>the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:</p>\n\n<pre><code>y = Convert.ToInt32( x );\n</code></pre>\n\n<p>The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other. </p>\n\n<p>Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out. </p>\n\n<p>For example:</p>\n\n<pre><code>Session[ \"x\" ] = 34;\n</code></pre>\n\n<p>works fine. But to assign the integer value back, you'll need to:</p>\n\n<pre><code>int i = Convert.ToInt32( Session[ \"x\" ] );\n</code></pre>\n\n<p>Read about generics for ways that facility helps you easily implement typesafe collections. </p>\n\n<p>C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).</p>\n" }, { "answer_id": 260678, "author": "Jared Farrish", "author_id": 451969, "author_profile": "https://Stackoverflow.com/users/451969", "pm_score": 2, "selected": false, "text": "<p>Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.</p>\n\n<p>In practice, this means that 7 (an integer type) is different from \"7\" (a quoted character of string type).</p>\n\n<p>PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) \"7\" to an (integer) 7 if you try to add \"7\" + 3, although sometimes you have to do this explicitly (and Javascript uses the \"+\" character for concatenation).</p>\n\n<p>C/C++/Java will not understand that, or will concatenate the result into \"73\" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.</p>\n\n<p>Type-safety is very useful. The solution to the above \"7\" + 3 would be to type cast (int) \"7\" + 3 (equals 10).</p>\n" }, { "answer_id": 260767, "author": "Jay Godse", "author_id": 33890, "author_profile": "https://Stackoverflow.com/users/33890", "pm_score": 1, "selected": false, "text": "<p>Type-safe means that the set of values that may be assigned to a program variable must fit well-defined and testable criteria. Type-safe variables lead to more robust programs because the algorithms that manipulate the variables can trust that the variable will only take one of a well-defined set of values. Keeping this trust ensures the integrity and quality of the data and the program. </p>\n\n<p>For many variables, the set of values that may be assigned to a variable is defined at the time the program is written. For example, a variable called \"colour\" may be allowed to take on the values \"red\", \"green\", or \"blue\" and never any other values. For other variables those criteria may change at run-time. For example, a variable called \"colour\" may only be allowed to take on values in the \"name\" column of a \"Colours\" table in a relational database, where \"red, \"green\", and \"blue\", are three values for \"name\" in the \"Colours\" table, but some other part of the computer program may be able to add to that list while the program is running, and the variable can take on the new values after they are added to the Colours table. </p>\n\n<p>Many type-safe languages give the illusion of \"type-safety\" by insisting on strictly defining types for variables and only allowing a variable to be assigned values of the same \"type\". There are a couple of problems with this approach. For example, a program may have a variable \"yearOfBirth\" which is the year a person was born, and it is tempting to type-cast it as a short integer. However, it is not a short integer. This year, it is a number that is less than 2009 and greater than -10000. However, this set grows by 1 every year as the program runs. Making this a \"short int\" is not adequate. What is needed to make this variable type-safe is a run-time validation function that ensures that the number is always greater than -10000 and less than the next calendar year. There is no compiler that can enforce such criteria because these criteria are always unique characteristics of the problem domain. </p>\n\n<p>Languages that use dynamic typing (or duck-typing, or manifest typing) such as Perl, Python, Ruby, SQLite, and Lua don't have the notion of typed variables. This forces the programmer to write a run-time validation routine for every variable to ensure that it is correct, or endure the consequences of unexplained run-time exceptions. In my experience, programmers in statically typed languages such as C, C++, Java, and C# are often lulled into thinking that statically defined types is all they need to do to get the benefits of type-safety. This is simply not true for many useful computer programs, and it is hard to predict if it is true for any particular computer program. </p>\n\n<p>The long &amp; the short.... Do you want type-safety? If so, then write run-time functions to ensure that when a variable is assigned a value, it conforms to well-defined criteria. The down-side is that it makes domain analysis really difficult for most computer programs because you have to explicitly define the criteria for each program variable. </p>\n" }, { "answer_id": 260983, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 5, "selected": false, "text": "<p>Many answers here conflate type-safety with static-typing and dynamic-typing. A dynamically typed language (like smalltalk) can be type-safe as well.</p>\n\n<p>A short answer: a language is considered type-safe if no operation leads to undefined behavior. Many consider the requirement of explicit type conversions necessary for a language to be <em>strictly</em> typed, as automatic conversions can sometimes leads to well defined but unexpected/unintuitive behaviors.</p>\n" }, { "answer_id": 7917143, "author": "Jonuz", "author_id": 249088, "author_profile": "https://Stackoverflow.com/users/249088", "pm_score": 2, "selected": false, "text": "<p>Type-Safe is code that accesses only the memory locations it is authorized to access, and only in well-defined, allowable ways. \nType-safe code cannot perform an operation on an object that is invalid for that object. The C# and VB.NET language compilers always produce type-safe code, which is verified to be type-safe during JIT compilation.</p>\n" }, { "answer_id": 21144117, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 3, "selected": false, "text": "<p>To get a better understanding do watch the below video which demonstrates code in type safe language (C#) and NOT type safe language ( javascript).</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=Rlw_njQhkxw\" rel=\"noreferrer\">http://www.youtube.com/watch?v=Rlw_njQhkxw</a></p>\n\n<p>Now for the long text.</p>\n\n<p>Type safety means preventing type errors. Type error occurs when data type of one type is assigned to other type UNKNOWINGLY and we get undesirable results.</p>\n\n<p>For instance JavaScript is a NOT a type safe language. In the below code “num” is a numeric variable and “str” is string. Javascript allows me to do “num + str” , now GUESS will it do arithmetic or concatenation .</p>\n\n<p>Now for the below code the results are “55” but the important point is the confusion created what kind of operation it will do. </p>\n\n<p>This is happening because javascript is not a type safe language. Its allowing to set one type of data to the other type without restrictions.</p>\n\n<pre><code>&lt;script&gt;\nvar num = 5; // numeric\nvar str = \"5\"; // string\nvar z = num + str; // arthimetic or concat ????\nalert(z); // displays “55”\n&lt;/script&gt;\n</code></pre>\n\n<p>C# is a type safe language. It does not allow one data type to be assigned to other data type. The below code does not allow “+” operator on different data types.</p>\n\n<p><img src=\"https://i.stack.imgur.com/0XOpK.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 25157350, "author": "Nicolas Rinaudo", "author_id": 1370349, "author_profile": "https://Stackoverflow.com/users/1370349", "pm_score": 6, "selected": false, "text": "<p>Type-safety should not be confused with static / dynamic typing or strong / weak typing.</p>\n\n<p>A type-safe language is one where the only operations that one can execute on data are the ones that are condoned by the data's type. That is, if your data is of type <code>X</code> and <code>X</code> doesn't support operation <code>y</code>, then the language will not allow you to to execute <code>y(X)</code>.</p>\n\n<p>This definition doesn't set rules on <em>when</em> this is checked. It can be at compile time (static typing) or at runtime (dynamic typing), typically through exceptions. It can be a bit of both: some statically typed languages allow you to cast data from one type to another, and the validity of casts must be checked at runtime (imagine that you're trying to cast an <code>Object</code> to a <code>Consumer</code> - the compiler has no way of knowing whether it's acceptable or not).</p>\n\n<p>Type-safety does not necessarily mean strongly typed, either - some languages are notoriously weakly typed, but still arguably type safe. Take Javascript, for example: its type system is as weak as they come, but still strictly defined. It allows automatic casting of data (say, strings to ints), but within well defined rules. There is to my knowledge no case where a Javascript program will behave in an undefined fashion, and if you're clever enough (I'm not), you should be able to predict what will happen when reading Javascript code.</p>\n\n<p>An example of a type-unsafe programming language is C: reading / writing an array value outside of the array's bounds has an undefined behaviour <em>by specification</em>. It's impossible to predict what will happen. C is a language that has a type system, but is not type safe.</p>\n" }, { "answer_id": 31738610, "author": "Khursheed", "author_id": 4158948, "author_profile": "https://Stackoverflow.com/users/4158948", "pm_score": 4, "selected": false, "text": "<p>A programming language that is 'type-safe' means following things:</p>\n\n<ol>\n<li>You can't read from uninitialized variables</li>\n<li>You can't index arrays beyond their bounds</li>\n<li>You can't perform unchecked type casts</li>\n</ol>\n" }, { "answer_id": 48176188, "author": "Gr3go", "author_id": 3536926, "author_profile": "https://Stackoverflow.com/users/3536926", "pm_score": 5, "selected": false, "text": "<p>Type safety is not just a compile time constraint, but a <strong>run time</strong> constraint. I feel even after all this time, we can add further clarity to this. </p>\n\n<p>There are 2 main issues related to type safety. Memory** and data type (with its corresponding operations).</p>\n\n<h2>Memory**</h2>\n\n<p>A <code>char</code> typically requires 1 byte per character, or 8 bits (depends on language, Java and C# store unicode chars which require 16 bits).\nAn <code>int</code> requires 4 bytes, or 32 bits (usually).</p>\n\n<p>Visually:</p>\n\n<p><code>char: |-|-|-|-|-|-|-|-|</code></p>\n\n<p><code>int : |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p>A type safe language does not allow an int to be inserted into a char at <em>run-time</em> (this should throw some kind of class cast or out of memory exception). However, in a type unsafe language, you would overwrite existing data in 3 more adjacent bytes of memory.</p>\n\n<p><code>int &gt;&gt; char:</code></p>\n\n<p><code>|-|-|-|-|-|-|-|-| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?|</code></p>\n\n<p>In the above case, the 3 bytes to the right are overwritten, so any pointers to that memory (say 3 consecutive chars) which expect to get a predictable char value will now have garbage. This causes <code>undefined</code> behavior in your program (or worse, possibly in other programs depending on how the OS allocates memory - very unlikely these days). </p>\n\n<p>** <em>While this first issue is not technically about data type, type safe languages address it inherently and it visually describes the issue to those unaware of how memory allocation \"looks\".</em></p>\n\n<h2>Data Type</h2>\n\n<p>The more subtle and direct type issue is where two data types use the same memory allocation. Take a int vs an unsigned int. Both are 32 bits. (Just as easily could be a char[4] and an int, but the more common issue is uint vs. int).</p>\n\n<p><code>|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p><code>|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p>A type unsafe language allows the programmer to reference a properly allocated span of 32 bits, but when the value of a unsigned int is read into the space of an int (or vice versa), we again have <code>undefined</code> behavior. Imagine the problems this could cause in a banking program: </p>\n\n<blockquote>\n <p>\"Dude! I overdrafted $30 and now I have $65,506 left!!\"</p>\n</blockquote>\n\n<p>...'course, banking programs use much larger data types. ;) LOL!</p>\n\n<p>As others have already pointed out, the next issue is computational operations on types. That has already been sufficiently covered.</p>\n\n<h2>Speed vs Safety</h2>\n\n<p>Most programmers today never need to worry about such things unless they are using something like C or C++. Both of these languages allow programmers to easily violate type safety at run time (direct memory referencing) despite the compilers' best efforts to minimize the risk. HOWEVER, this is not all bad. </p>\n\n<p>One reason these languages are so computationally fast is they are not burdened by verifying type compatibility during run time operations like, for example, Java. They assume the developer is a good rational being who won't add a string and an int together and for that, the developer is rewarded with speed/efficiency.</p>\n" }, { "answer_id": 53514734, "author": "azizsagi", "author_id": 6060508, "author_profile": "https://Stackoverflow.com/users/6060508", "pm_score": 3, "selected": false, "text": "<p><strong>Concept:</strong></p>\n\n<p>To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like </p>\n\n<ol>\n<li>no wrong data type e.g. can't save or initialized a variable of string type with integer</li>\n<li>Out of bound indexes are not accessible</li>\n<li>Allow only the specific memory location </li>\n</ol>\n\n<p>so it is all about the safety of the types of your storage in terms of variables. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What does "type-safe" mean?
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable. Some simple examples: ``` // Fails, Trying to put an integer in a string String one = 1; // Also fails. int foo = "bar"; ``` This also applies to method arguments, since you are passing explicit types to them: ``` int AddTwoNumbers(int a, int b) { return a + b; } ``` If I tried to call that using: ``` int Sum = AddTwoNumbers(5, "5"); ``` The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer. In a loosely typed language, such as javascript, I can do the following: ``` function AddTwoNumbers(a, b) { return a + b; } ``` if I call it like this: ``` Sum = AddTwoNumbers(5, "5"); ``` Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like: ``` function AddTwoNumbers(a, b) { return Number(a) + Number(b); } ``` Or, possibly: ``` function AddOnlyTwoNumbers(a, b) { if (isNaN(a) || isNaN(b)) return false; return Number(a) + Number(b); } ``` if I call it like this: ``` Sum = AddTwoNumbers(5, " dogs"); ``` Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs". Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting. While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake. Now, back to C#... C# supports a language feature called [covariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#C.23), this basically means that you can substitute a base type for a child type and not cause an error, for example: ``` public class Foo : Bar { } ``` Here, I created a new class (Foo) that subclasses Bar. I can now create a method: ``` void DoSomething(Bar myBar) ``` And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar. However, you cannot do the inverse: ``` void DoSomething(Foo myFoo) ``` In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class. Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)
260,627
<p>This drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? At the moment it says "select a file" every time.</p> <pre><code>&lt;select name="image" type="text" class="box" id="image" value="&lt;?=$image;?&gt;"&gt; &lt;option value='empty'&gt;Select a file&lt;/option&gt; &lt;?php $dirname = "images/"; $images = scandir($dirname); // This is how you sort an array, see http://php.net/sort natsort($images); // There's no need to use a directory handler, just loop through your $images array. foreach ($images as $file) { if (substr($file, -4) == ".gif") { print "&lt;option value='$file'&gt;$file&lt;/option&gt;\n"; } } ?&gt; &lt;/select&gt; </code></pre>
[ { "answer_id": 260640, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 8, "selected": false, "text": "<p>Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.</p>\n\n<p>Some simple examples:</p>\n\n<pre><code>// Fails, Trying to put an integer in a string\nString one = 1;\n// Also fails.\nint foo = \"bar\";\n</code></pre>\n\n<p>This also applies to method arguments, since you are passing explicit types to them:</p>\n\n<pre><code>int AddTwoNumbers(int a, int b)\n{\n return a + b;\n}\n</code></pre>\n\n<p>If I tried to call that using:</p>\n\n<pre><code>int Sum = AddTwoNumbers(5, \"5\");\n</code></pre>\n\n<p>The compiler would throw an error, because I am passing a string (\"5\"), and it is expecting an integer.</p>\n\n<p>In a loosely typed language, such as javascript, I can do the following:</p>\n\n<pre><code>function AddTwoNumbers(a, b)\n{\n return a + b;\n}\n</code></pre>\n\n<p>if I call it like this:</p>\n\n<pre><code>Sum = AddTwoNumbers(5, \"5\");\n</code></pre>\n\n<p>Javascript automaticly converts the 5 to a string, and returns \"55\". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:</p>\n\n<pre><code>function AddTwoNumbers(a, b)\n{\n return Number(a) + Number(b);\n}\n</code></pre>\n\n<p>Or, possibly:</p>\n\n<pre><code>function AddOnlyTwoNumbers(a, b)\n{\n if (isNaN(a) || isNaN(b))\n return false;\n return Number(a) + Number(b);\n}\n</code></pre>\n\n<p>if I call it like this:</p>\n\n<pre><code>Sum = AddTwoNumbers(5, \" dogs\");\n</code></pre>\n\n<p>Javascript automatically converts the 5 to a string, and appends them, to return \"5 dogs\".</p>\n\n<p>Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.</p>\n\n<p>While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.</p>\n\n<p>Now, back to C#...</p>\n\n<p>C# supports a language feature called <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#C.23\" rel=\"noreferrer\">covariance</a>, this basically means that you can substitute a base type for a child type and not cause an error, for example:</p>\n\n<pre><code> public class Foo : Bar\n {\n }\n</code></pre>\n\n<p>Here, I created a new class (Foo) that subclasses Bar. I can now create a method:</p>\n\n<pre><code> void DoSomething(Bar myBar)\n</code></pre>\n\n<p>And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.</p>\n\n<p>However, you cannot do the inverse:</p>\n\n<pre><code>void DoSomething(Foo myFoo)\n</code></pre>\n\n<p>In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.</p>\n\n<p>Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)</p>\n" }, { "answer_id": 260652, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>An explanation from a liberal arts major, not a comp sci major:</p>\n\n<p>When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.</p>\n\n<p>For example, in C#, I define a function as:</p>\n\n<pre><code> void foo(int arg)\n</code></pre>\n\n<p>The compiler will then stop me from doing this: </p>\n\n<pre><code> // call foo\n foo(\"hello world\")\n</code></pre>\n\n<p>In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.</p>\n\n<p>Type safe languages try to catch more at \"compile time\".</p>\n\n<p>On the down side, with type safe languages, when you have a string like \"123\" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, \"The answer is 123\", you have to write more code to convert/cast it to a string.</p>\n" }, { "answer_id": 260657, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": "<p>Try this explanation on...</p>\n\n<p>TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).</p>\n\n<p>For non-typesafe behavior, consider this:</p>\n\n<pre><code>object x = 89;\nint y;\n</code></pre>\n\n<p>if you attempt to do this:</p>\n\n<pre><code>y = x;\n</code></pre>\n\n<p>the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:</p>\n\n<pre><code>y = Convert.ToInt32( x );\n</code></pre>\n\n<p>The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other. </p>\n\n<p>Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out. </p>\n\n<p>For example:</p>\n\n<pre><code>Session[ \"x\" ] = 34;\n</code></pre>\n\n<p>works fine. But to assign the integer value back, you'll need to:</p>\n\n<pre><code>int i = Convert.ToInt32( Session[ \"x\" ] );\n</code></pre>\n\n<p>Read about generics for ways that facility helps you easily implement typesafe collections. </p>\n\n<p>C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).</p>\n" }, { "answer_id": 260678, "author": "Jared Farrish", "author_id": 451969, "author_profile": "https://Stackoverflow.com/users/451969", "pm_score": 2, "selected": false, "text": "<p>Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.</p>\n\n<p>In practice, this means that 7 (an integer type) is different from \"7\" (a quoted character of string type).</p>\n\n<p>PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) \"7\" to an (integer) 7 if you try to add \"7\" + 3, although sometimes you have to do this explicitly (and Javascript uses the \"+\" character for concatenation).</p>\n\n<p>C/C++/Java will not understand that, or will concatenate the result into \"73\" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.</p>\n\n<p>Type-safety is very useful. The solution to the above \"7\" + 3 would be to type cast (int) \"7\" + 3 (equals 10).</p>\n" }, { "answer_id": 260767, "author": "Jay Godse", "author_id": 33890, "author_profile": "https://Stackoverflow.com/users/33890", "pm_score": 1, "selected": false, "text": "<p>Type-safe means that the set of values that may be assigned to a program variable must fit well-defined and testable criteria. Type-safe variables lead to more robust programs because the algorithms that manipulate the variables can trust that the variable will only take one of a well-defined set of values. Keeping this trust ensures the integrity and quality of the data and the program. </p>\n\n<p>For many variables, the set of values that may be assigned to a variable is defined at the time the program is written. For example, a variable called \"colour\" may be allowed to take on the values \"red\", \"green\", or \"blue\" and never any other values. For other variables those criteria may change at run-time. For example, a variable called \"colour\" may only be allowed to take on values in the \"name\" column of a \"Colours\" table in a relational database, where \"red, \"green\", and \"blue\", are three values for \"name\" in the \"Colours\" table, but some other part of the computer program may be able to add to that list while the program is running, and the variable can take on the new values after they are added to the Colours table. </p>\n\n<p>Many type-safe languages give the illusion of \"type-safety\" by insisting on strictly defining types for variables and only allowing a variable to be assigned values of the same \"type\". There are a couple of problems with this approach. For example, a program may have a variable \"yearOfBirth\" which is the year a person was born, and it is tempting to type-cast it as a short integer. However, it is not a short integer. This year, it is a number that is less than 2009 and greater than -10000. However, this set grows by 1 every year as the program runs. Making this a \"short int\" is not adequate. What is needed to make this variable type-safe is a run-time validation function that ensures that the number is always greater than -10000 and less than the next calendar year. There is no compiler that can enforce such criteria because these criteria are always unique characteristics of the problem domain. </p>\n\n<p>Languages that use dynamic typing (or duck-typing, or manifest typing) such as Perl, Python, Ruby, SQLite, and Lua don't have the notion of typed variables. This forces the programmer to write a run-time validation routine for every variable to ensure that it is correct, or endure the consequences of unexplained run-time exceptions. In my experience, programmers in statically typed languages such as C, C++, Java, and C# are often lulled into thinking that statically defined types is all they need to do to get the benefits of type-safety. This is simply not true for many useful computer programs, and it is hard to predict if it is true for any particular computer program. </p>\n\n<p>The long &amp; the short.... Do you want type-safety? If so, then write run-time functions to ensure that when a variable is assigned a value, it conforms to well-defined criteria. The down-side is that it makes domain analysis really difficult for most computer programs because you have to explicitly define the criteria for each program variable. </p>\n" }, { "answer_id": 260983, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 5, "selected": false, "text": "<p>Many answers here conflate type-safety with static-typing and dynamic-typing. A dynamically typed language (like smalltalk) can be type-safe as well.</p>\n\n<p>A short answer: a language is considered type-safe if no operation leads to undefined behavior. Many consider the requirement of explicit type conversions necessary for a language to be <em>strictly</em> typed, as automatic conversions can sometimes leads to well defined but unexpected/unintuitive behaviors.</p>\n" }, { "answer_id": 7917143, "author": "Jonuz", "author_id": 249088, "author_profile": "https://Stackoverflow.com/users/249088", "pm_score": 2, "selected": false, "text": "<p>Type-Safe is code that accesses only the memory locations it is authorized to access, and only in well-defined, allowable ways. \nType-safe code cannot perform an operation on an object that is invalid for that object. The C# and VB.NET language compilers always produce type-safe code, which is verified to be type-safe during JIT compilation.</p>\n" }, { "answer_id": 21144117, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 3, "selected": false, "text": "<p>To get a better understanding do watch the below video which demonstrates code in type safe language (C#) and NOT type safe language ( javascript).</p>\n\n<p><a href=\"http://www.youtube.com/watch?v=Rlw_njQhkxw\" rel=\"noreferrer\">http://www.youtube.com/watch?v=Rlw_njQhkxw</a></p>\n\n<p>Now for the long text.</p>\n\n<p>Type safety means preventing type errors. Type error occurs when data type of one type is assigned to other type UNKNOWINGLY and we get undesirable results.</p>\n\n<p>For instance JavaScript is a NOT a type safe language. In the below code “num” is a numeric variable and “str” is string. Javascript allows me to do “num + str” , now GUESS will it do arithmetic or concatenation .</p>\n\n<p>Now for the below code the results are “55” but the important point is the confusion created what kind of operation it will do. </p>\n\n<p>This is happening because javascript is not a type safe language. Its allowing to set one type of data to the other type without restrictions.</p>\n\n<pre><code>&lt;script&gt;\nvar num = 5; // numeric\nvar str = \"5\"; // string\nvar z = num + str; // arthimetic or concat ????\nalert(z); // displays “55”\n&lt;/script&gt;\n</code></pre>\n\n<p>C# is a type safe language. It does not allow one data type to be assigned to other data type. The below code does not allow “+” operator on different data types.</p>\n\n<p><img src=\"https://i.stack.imgur.com/0XOpK.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 25157350, "author": "Nicolas Rinaudo", "author_id": 1370349, "author_profile": "https://Stackoverflow.com/users/1370349", "pm_score": 6, "selected": false, "text": "<p>Type-safety should not be confused with static / dynamic typing or strong / weak typing.</p>\n\n<p>A type-safe language is one where the only operations that one can execute on data are the ones that are condoned by the data's type. That is, if your data is of type <code>X</code> and <code>X</code> doesn't support operation <code>y</code>, then the language will not allow you to to execute <code>y(X)</code>.</p>\n\n<p>This definition doesn't set rules on <em>when</em> this is checked. It can be at compile time (static typing) or at runtime (dynamic typing), typically through exceptions. It can be a bit of both: some statically typed languages allow you to cast data from one type to another, and the validity of casts must be checked at runtime (imagine that you're trying to cast an <code>Object</code> to a <code>Consumer</code> - the compiler has no way of knowing whether it's acceptable or not).</p>\n\n<p>Type-safety does not necessarily mean strongly typed, either - some languages are notoriously weakly typed, but still arguably type safe. Take Javascript, for example: its type system is as weak as they come, but still strictly defined. It allows automatic casting of data (say, strings to ints), but within well defined rules. There is to my knowledge no case where a Javascript program will behave in an undefined fashion, and if you're clever enough (I'm not), you should be able to predict what will happen when reading Javascript code.</p>\n\n<p>An example of a type-unsafe programming language is C: reading / writing an array value outside of the array's bounds has an undefined behaviour <em>by specification</em>. It's impossible to predict what will happen. C is a language that has a type system, but is not type safe.</p>\n" }, { "answer_id": 31738610, "author": "Khursheed", "author_id": 4158948, "author_profile": "https://Stackoverflow.com/users/4158948", "pm_score": 4, "selected": false, "text": "<p>A programming language that is 'type-safe' means following things:</p>\n\n<ol>\n<li>You can't read from uninitialized variables</li>\n<li>You can't index arrays beyond their bounds</li>\n<li>You can't perform unchecked type casts</li>\n</ol>\n" }, { "answer_id": 48176188, "author": "Gr3go", "author_id": 3536926, "author_profile": "https://Stackoverflow.com/users/3536926", "pm_score": 5, "selected": false, "text": "<p>Type safety is not just a compile time constraint, but a <strong>run time</strong> constraint. I feel even after all this time, we can add further clarity to this. </p>\n\n<p>There are 2 main issues related to type safety. Memory** and data type (with its corresponding operations).</p>\n\n<h2>Memory**</h2>\n\n<p>A <code>char</code> typically requires 1 byte per character, or 8 bits (depends on language, Java and C# store unicode chars which require 16 bits).\nAn <code>int</code> requires 4 bytes, or 32 bits (usually).</p>\n\n<p>Visually:</p>\n\n<p><code>char: |-|-|-|-|-|-|-|-|</code></p>\n\n<p><code>int : |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p>A type safe language does not allow an int to be inserted into a char at <em>run-time</em> (this should throw some kind of class cast or out of memory exception). However, in a type unsafe language, you would overwrite existing data in 3 more adjacent bytes of memory.</p>\n\n<p><code>int &gt;&gt; char:</code></p>\n\n<p><code>|-|-|-|-|-|-|-|-| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?| |?|?|?|?|?|?|?|?|</code></p>\n\n<p>In the above case, the 3 bytes to the right are overwritten, so any pointers to that memory (say 3 consecutive chars) which expect to get a predictable char value will now have garbage. This causes <code>undefined</code> behavior in your program (or worse, possibly in other programs depending on how the OS allocates memory - very unlikely these days). </p>\n\n<p>** <em>While this first issue is not technically about data type, type safe languages address it inherently and it visually describes the issue to those unaware of how memory allocation \"looks\".</em></p>\n\n<h2>Data Type</h2>\n\n<p>The more subtle and direct type issue is where two data types use the same memory allocation. Take a int vs an unsigned int. Both are 32 bits. (Just as easily could be a char[4] and an int, but the more common issue is uint vs. int).</p>\n\n<p><code>|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p><code>|-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-| |-|-|-|-|-|-|-|-|</code></p>\n\n<p>A type unsafe language allows the programmer to reference a properly allocated span of 32 bits, but when the value of a unsigned int is read into the space of an int (or vice versa), we again have <code>undefined</code> behavior. Imagine the problems this could cause in a banking program: </p>\n\n<blockquote>\n <p>\"Dude! I overdrafted $30 and now I have $65,506 left!!\"</p>\n</blockquote>\n\n<p>...'course, banking programs use much larger data types. ;) LOL!</p>\n\n<p>As others have already pointed out, the next issue is computational operations on types. That has already been sufficiently covered.</p>\n\n<h2>Speed vs Safety</h2>\n\n<p>Most programmers today never need to worry about such things unless they are using something like C or C++. Both of these languages allow programmers to easily violate type safety at run time (direct memory referencing) despite the compilers' best efforts to minimize the risk. HOWEVER, this is not all bad. </p>\n\n<p>One reason these languages are so computationally fast is they are not burdened by verifying type compatibility during run time operations like, for example, Java. They assume the developer is a good rational being who won't add a string and an int together and for that, the developer is rewarded with speed/efficiency.</p>\n" }, { "answer_id": 53514734, "author": "azizsagi", "author_id": 6060508, "author_profile": "https://Stackoverflow.com/users/6060508", "pm_score": 3, "selected": false, "text": "<p><strong>Concept:</strong></p>\n\n<p>To be very simple Type Safe like the meanings, it makes sure that type of the variable should be safe like </p>\n\n<ol>\n<li>no wrong data type e.g. can't save or initialized a variable of string type with integer</li>\n<li>Out of bound indexes are not accessible</li>\n<li>Allow only the specific memory location </li>\n</ol>\n\n<p>so it is all about the safety of the types of your storage in terms of variables. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32972/" ]
This drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? At the moment it says "select a file" every time. ``` <select name="image" type="text" class="box" id="image" value="<?=$image;?>"> <option value='empty'>Select a file</option> <?php $dirname = "images/"; $images = scandir($dirname); // This is how you sort an array, see http://php.net/sort natsort($images); // There's no need to use a directory handler, just loop through your $images array. foreach ($images as $file) { if (substr($file, -4) == ".gif") { print "<option value='$file'>$file</option>\n"; } } ?> </select> ```
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable. Some simple examples: ``` // Fails, Trying to put an integer in a string String one = 1; // Also fails. int foo = "bar"; ``` This also applies to method arguments, since you are passing explicit types to them: ``` int AddTwoNumbers(int a, int b) { return a + b; } ``` If I tried to call that using: ``` int Sum = AddTwoNumbers(5, "5"); ``` The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer. In a loosely typed language, such as javascript, I can do the following: ``` function AddTwoNumbers(a, b) { return a + b; } ``` if I call it like this: ``` Sum = AddTwoNumbers(5, "5"); ``` Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like: ``` function AddTwoNumbers(a, b) { return Number(a) + Number(b); } ``` Or, possibly: ``` function AddOnlyTwoNumbers(a, b) { if (isNaN(a) || isNaN(b)) return false; return Number(a) + Number(b); } ``` if I call it like this: ``` Sum = AddTwoNumbers(5, " dogs"); ``` Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs". Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting. While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake. Now, back to C#... C# supports a language feature called [covariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#C.23), this basically means that you can substitute a base type for a child type and not cause an error, for example: ``` public class Foo : Bar { } ``` Here, I created a new class (Foo) that subclasses Bar. I can now create a method: ``` void DoSomething(Bar myBar) ``` And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar. However, you cannot do the inverse: ``` void DoSomething(Foo myFoo) ``` In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class. Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)
260,658
<p>Via command line, I usually do this:</p> <pre><code>cp -rRp /path/to/a\_folder/. /path/to/another\_folder </code></pre> <p>This copies just the contents underneath <strong>a_folder</strong> to <strong>another_folder</strong>. In SVN I need to do the same thing, but can't figure it out. I always end up with this:</p> <pre><code>/path/to/another\_folder/a\_folder </code></pre> <p>SVN throws up even when I try this:</p> <pre><code>svn copy file:///path/to/a\_folder/* file:///path/to/another\_folder </code></pre> <p>It says it does not exist.</p> <p><strong>EDIT:</strong></p> <p>This would probably help. The directory structure for my project looks like this:</p> <pre><code>my_project /branches /tags /trunk /vendor /1.1 </code></pre> <p>I need to get the contents of 1.1 under vendor into the trunk without it actually copying the 1.1 folder.</p>
[ { "answer_id": 260706, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 4, "selected": true, "text": "<p>Have you considered using svn merge?</p>\n\n<p>Given a repo like this:</p>\n\n<pre><code>trunk/a_folder/foo\ntrunk/a_folder/bar\ntrunk/new_folder/baz\n</code></pre>\n\n<p>use these commands to merge the foo and bar directories:</p>\n\n<pre><code>cd trunk/new_folder\nsvn merge -r1:HEAD http://svn/repo/trunk/a_folder .\n</code></pre>\n" }, { "answer_id": 260737, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "<p>You're very, very close:</p>\n\n<pre><code>svn copy -m\"Copy Directory\" file:///path/to/a_folder file:///path/to/another_folder\n</code></pre>\n\n<p>just drop the <code>/*</code> from the first argument.</p>\n" }, { "answer_id": 261055, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 5, "selected": false, "text": "<p>As you've certainly discovered, <b>copying to a target directory that already exists</b> won't work:</p>\n\n<pre>svn cp svn://my_project/vendor/1.1 svn://my_project/trunk</pre>\n\n<p>because trunk already exists, so you'd end up with:</p>\n\n<pre>svn://my_project/trunk/1.1</pre>\n\n<p>Using <strong>merge</strong> has the unfortunate property of not keeping history of the vendor 1.1 tag in subversion prior to 1.5 which introduced merge tracking. You may not care. In this case merge would be the correct solution:</p>\n\n<pre>\nsvn co svn://my_project/trunk trunk-wc\nsvn merge svn://my_project/trunk svn://my_project/vendor/1.1 trunk-wc\n</pre>\n\n<p>The best way to read this merge is: First determine the changes necessary to to make <code>trunk</code> identical to <code>vendor/1.1</code>, then apply those changes to the given working copy (also of trunk, in this case). </p>\n\n<p>I should point out that this merge will effectively blow away anything that was in trunk previously. So, if you have local (non-vendor) modifications already on the trunk, you'll want to apply just the changes between 1.1 and the previous vendor drop:</p>\n\n<pre>\nsvn co svn://my_project/trunk trunk-wc\nsvn merge svn://my_project/vendor/1.0 svn://my_prjoect/vendor/1.1 trunk-wc\n</pre>\n\n<p>If <strong>trunk exists, but is empty</strong> you've got two choices: replace the trunk, or write a little shell loop:</p>\n\n<p><strong>Replacing the trunk</strong> looks like this:</p>\n\n<pre>\nsvn rm svn://my_project/trunk\nsvn cp svn://my_project/vendor/1.1 svn://my_project/trunk\n</pre>\n\n<p><strong>Leveraging the shell</strong> (bash):</p>\n\n<pre>\nsvn co svn://my_project/trunk trunk\nsvn co svn://my_project/vendor/1.1 1.1\n( cd 1.1\n for x in * ; do\n svn cp $x ../trunk\n done \n)\nsvn ci trunk\n</pre>\n" }, { "answer_id": 10020147, "author": "Mike Wodarczyk", "author_id": 1313982, "author_profile": "https://Stackoverflow.com/users/1313982", "pm_score": 2, "selected": false, "text": "<p>I think that what you want is that the contents of the trunk end up in the <code>/tags/version-1.0/</code> folder without there being an extra <code>/trunk</code> folder there. i.e. This is bad: <code>/tags/version-1.0/trunk/stuff</code>. This is good: <code>/tags/version-1.0/stuff</code>.</p>\n\n<p>To get this I do a 2 step process:</p>\n\n<pre><code>svn copy http://localhost/MyProject/trunk http://localhost/MyProject/tags/\n\n# now I have /MyProject/tags/trunk\n\nsvn rename http://localhost/MyProject/tags/trunk http://localhost/MyProject/tags/version-1.0\n</code></pre>\n" }, { "answer_id": 11315358, "author": "dushshantha", "author_id": 258115, "author_profile": "https://Stackoverflow.com/users/258115", "pm_score": 3, "selected": false, "text": "<p>This link explains a workaround.</p>\n\n<p><a href=\"http://svn.haxx.se/users/archive-2004-12/1537.shtml\" rel=\"noreferrer\">http://svn.haxx.se/users/archive-2004-12/1537.shtml</a></p>\n\n<p>Basically what it says is that if the destination folder is not existing in the repo, you will get the contencts of your source folder in the destination folder.</p>\n\n<p>See below example. The folder 07-03-2012 does not exist in your repo. Once you execute the below command, you will get the contents of HEAD folder in 07-03-2012. </p>\n\n<pre><code>svn cp &lt;URL&gt;/HEAD/ &lt;URL&gt;/branches/07-03-2012 -m \"test\"\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Via command line, I usually do this: ``` cp -rRp /path/to/a\_folder/. /path/to/another\_folder ``` This copies just the contents underneath **a\_folder** to **another\_folder**. In SVN I need to do the same thing, but can't figure it out. I always end up with this: ``` /path/to/another\_folder/a\_folder ``` SVN throws up even when I try this: ``` svn copy file:///path/to/a\_folder/* file:///path/to/another\_folder ``` It says it does not exist. **EDIT:** This would probably help. The directory structure for my project looks like this: ``` my_project /branches /tags /trunk /vendor /1.1 ``` I need to get the contents of 1.1 under vendor into the trunk without it actually copying the 1.1 folder.
Have you considered using svn merge? Given a repo like this: ``` trunk/a_folder/foo trunk/a_folder/bar trunk/new_folder/baz ``` use these commands to merge the foo and bar directories: ``` cd trunk/new_folder svn merge -r1:HEAD http://svn/repo/trunk/a_folder . ```
260,663
<p>I started web programming with raw PHP, gradually moving on to its various frameworks, then to Django and Rails. In every framework I've used, pretty much everything I need to do with a database (even involving relatively complex things like many-to-many relationships) could be taken care of by the automatically generated database API without much work. Those few operations that were more complex could be done with straight SQL or by tying together multiple API calls.</p> <p>Now I'm starting to learn Java, and it's confusing me that the language celebrated for being so robust for back-end infrastructure requires so much more code (doesn't that mean harder to maintain?) to do simple things. Example from a tutorial: say you want to search by last name. You write the method in the DAO using Hibernate query language, then you write a method in the Service to call it (couldn't that be automated?), then you call the Service method from the controller. Whereas in any other framework I've worked with, you could call something to the effect of</p> <pre><code>Person.find_by_last_name(request.POST['last_name']) </code></pre> <p>Straight out of the controller - you don't have to write anything custom to do something like that.</p> <p>Is there some kind of code generation I haven't found yet? Something in Eclipse? Just doesn't seem right to me that the language regraded as one of the best choices for complex back-ends is so much harder to work with. Is there something I'm missing?</p>
[ { "answer_id": 260673, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 1, "selected": false, "text": "<p>I would suggest that you look at the <a href=\"http://www.springframework.org/\" rel=\"nofollow noreferrer\">Spring</a> framework for Java.</p>\n\n<p>I haven't personally used it, but I've heard good things about it. From what I understand it provides the same sort of functionality that you would get Django and Rails.</p>\n" }, { "answer_id": 260704, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>Get <a href=\"http://ibatis.apache.org/\" rel=\"nofollow noreferrer\">iBatis</a> for Java. It isn't as robust as Django's ORM (nothing is), but it's a big, big step above JDBC.</p>\n" }, { "answer_id": 260732, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://grails.org\" rel=\"nofollow noreferrer\">Grails</a> for the win. Groovy is very similar to Java but with a lot of nice dynamic language additions/simplifications. Grails has GORM, which is exactly what you're looking for.</p>\n" }, { "answer_id": 260746, "author": "CodingWithSpike", "author_id": 28278, "author_profile": "https://Stackoverflow.com/users/28278", "pm_score": 2, "selected": false, "text": "<p>In the example you mention, it looks like they are using more of a tiered architecture than you are used to.</p>\n\n<pre><code>Controller -&gt; Service -&gt; DAO\n</code></pre>\n\n<p>This provides for separation within the app. This is also completely dependent on the architecture of your application, not really Java as a language. Technically there is nothing in Java that would stop you from calling a Hibernate query in your controller. It just wouldn't constitute good design.</p>\n\n<p>Another thing to consider is that the 'Service' could be something like an EJB, which may have the role of Transaction management, so that multiple calls to the DAO/Hibernate can be wrappered in a single transaction that will automatically commit or rollback on success / exception.</p>\n\n<p>Again though, this is all in the architecture / framework that you are using, not Java as a language.</p>\n" }, { "answer_id": 260768, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Well yeah, but it's not separation that's the concern for me. With these other database APIs, concerns are separated - it's not that custom DB logic is written in the controller (which I know is bad form) but that it's automatically generated. The call looks exactly the same from the controller, the difference is that with Java/Hibernate I had to write it myself and with Django/Rails/Symfony/Cake it was already there for me.</p>\n\n<p>Grails looks very interesting. The main reason I'm learning Java, though, is because I want to at least be able to work with something I can use professionally. I'm not sure Grails fits that bill, though because it is Java perhaps the Enterprise will warm up to it moreso than Rails.</p>\n\n<p>Django is the most beautiful piece of code I have ever worked with, but it's not trusted by the kind of businesses who can afford custom web apps, which is the market I think I want to be in.</p>\n\n<p>iBATIS looks very promising - looking through the JPetStore code it appears it does a bit more automatically. But did all that SQL have to be hand-coded? Because then I'd be back where I started.</p>\n\n<p>Spring has a great and reasonably easy to work with interface layer (MVC), and it ties components together pretty nicely. Though it can be used to integrate an ORM into an app, as far as I know it's not one.</p>\n" }, { "answer_id": 260935, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "<p>Part of the the reason that you don't get automatically generated database APIs in Java is that as a compiled language without macros (like Lisp) it cannot do runtime code generation. Dynamically typed script languages like Ruby have that capability.</p>\n\n<p>Another part of the reason is cultural: the J2EE world has tended to prefer configuration over convention for the last decade. The major reason for this preference is that enterprisey apps often have to work with lots of crufty assumptions that bring with it all sorts of \"weird\" edge cases. It is what it is. These assumptions stand in stark contrast to what the newer frameworks like Rails assume. </p>\n\n<p>That said, I don't think there's anything to prevent a Java ORM API from generating database APIs at compile time. My guess is that <a href=\"http://www.nakedobjects.org/home/index.shtml\" rel=\"nofollow noreferrer\">Naked Objects</a> is more up your alley.</p>\n" }, { "answer_id": 261063, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 1, "selected": false, "text": "<p>I'd suggest you use Seam. It is a very good controller, that does not force you to have fully multitiered ap. It is fully integrated with JPA (Java Persistence Api) that does ORM.</p>\n\n<p>Features</p>\n\n<ol>\n<li>Has very nice scoping - you can have objects scoped to Session, pageload, conversation (conversation is an unit of work from user perispective).</li>\n<li>Does not require much XML.</li>\n<li>Does not require much boilerplate code!</li>\n<li>Is easy to learn (you may even generate framework project from entity classes or db schema; it will still require much of work, but it will at least cut down boilerplate code) </li>\n<li>Very nice security (you may either use role based security, or use rules framework)</li>\n</ol>\n\n<p>When writing webpage you use beans (normal java objects).</p>\n\n<p>You may write:</p>\n\n<pre><code> #{PersonHome.instance.name} \n</code></pre>\n\n<p>which will evaluate to the value of name of a person. If in request parameter there was person id it will be passed to PersonHome component (if it was annotated properly), and person bean will be loaded transparently from the db.</p>\n\n<p>And you may even write:</p>\n\n<pre><code>&lt;h:commandLink action=\"#{PersonHome.delete(person}\"&gt;\n</code></pre>\n\n<p>Where controllerBean is java bean, and <code>delete</code> takes person object. It will be transparently translated to link that will have person id parameter, that will transparently be translated to bean before action method will be fired. </p>\n\n<p>The only caveat for now is that it somewhat limits your choice of view framework: it works only with RichFaces, GWT, and something else that I cant remember now ;). </p>\n\n<p>PS. </p>\n\n<p>Yes I'm a huge fan of seam :). </p>\n" }, { "answer_id": 352911, "author": "PEELY", "author_id": 17641, "author_profile": "https://Stackoverflow.com/users/17641", "pm_score": 0, "selected": false, "text": "<p><em>Just doesn't seem right to me that the language regraded as one of the best choices for complex back-ends is so much harder to work with. Is there something I'm missing?</em></p>\n\n<p>The reason for this is the amount of time Java has been deployed in the Enterprise.</p>\n\n<p>It's not that Java is more mature than, say, Ruby, it's just that Java has been used for longer and has been proven by risk averse IT departments.</p>\n\n<p>One recommended way in is therefore via JRuby (+Rails), as that runs on the Java VM, and the IT department don't need to install or reconfigure anything...</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I started web programming with raw PHP, gradually moving on to its various frameworks, then to Django and Rails. In every framework I've used, pretty much everything I need to do with a database (even involving relatively complex things like many-to-many relationships) could be taken care of by the automatically generated database API without much work. Those few operations that were more complex could be done with straight SQL or by tying together multiple API calls. Now I'm starting to learn Java, and it's confusing me that the language celebrated for being so robust for back-end infrastructure requires so much more code (doesn't that mean harder to maintain?) to do simple things. Example from a tutorial: say you want to search by last name. You write the method in the DAO using Hibernate query language, then you write a method in the Service to call it (couldn't that be automated?), then you call the Service method from the controller. Whereas in any other framework I've worked with, you could call something to the effect of ``` Person.find_by_last_name(request.POST['last_name']) ``` Straight out of the controller - you don't have to write anything custom to do something like that. Is there some kind of code generation I haven't found yet? Something in Eclipse? Just doesn't seem right to me that the language regraded as one of the best choices for complex back-ends is so much harder to work with. Is there something I'm missing?
[Grails](http://grails.org) for the win. Groovy is very similar to Java but with a lot of nice dynamic language additions/simplifications. Grails has GORM, which is exactly what you're looking for.
260,666
<p>Can an abstract class have a constructor?</p> <p>If so, how can it be used and for what purposes?</p>
[ { "answer_id": 260686, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Consider this:</p>\n\n<pre><code>abstract class Product { \n int value;\n public Product( int val ) {\n value= val;\n }\n abstract public int multiply();\n}\n\nclass TimesTwo extends Product {\n public int mutiply() {\n return value * 2;\n }\n}\n</code></pre>\n\n<p>The superclass is abstract and has a constructor.</p>\n" }, { "answer_id": 260710, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 6, "selected": false, "text": "<p>Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.</p>\n" }, { "answer_id": 260755, "author": "Michael Rutherfurd", "author_id": 33889, "author_profile": "https://Stackoverflow.com/users/33889", "pm_score": 11, "selected": true, "text": "<p>Yes, an abstract class can have a constructor. Consider this:</p>\n\n<pre><code>abstract class Product { \n int multiplyBy;\n public Product( int multiplyBy ) {\n this.multiplyBy = multiplyBy;\n }\n\n public int mutiply(int val) {\n return multiplyBy * val;\n }\n}\n\nclass TimesTwo extends Product {\n public TimesTwo() {\n super(2);\n }\n}\n\nclass TimesWhat extends Product {\n public TimesWhat(int what) {\n super(what);\n }\n}\n</code></pre>\n\n<p>The superclass <code>Product</code> is abstract and has a constructor. The concrete class <code>TimesTwo</code> has a constructor that just hardcodes the value 2. The concrete class <code>TimesWhat</code> has a constructor that allows the caller to specify the value.</p>\n\n<p>Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.</p>\n\n<blockquote>\n <p>NOTE: As there is no default (or no-arg) constructor in the parent\n abstract class, the constructor used in subclass must explicitly call\n the parent constructor.</p>\n</blockquote>\n" }, { "answer_id": 261159, "author": "jfpoilpret", "author_id": 1440720, "author_profile": "https://Stackoverflow.com/users/1440720", "pm_score": 7, "selected": false, "text": "<p>You would define a constructor in an abstract class if you are in one of these situations:</p>\n\n<ul>\n<li>you want to perform some\ninitialization (to fields of the\nabstract class) before the\ninstantiation of a subclass actually\ntakes place</li>\n<li>you have defined final fields in the\nabstract class but you did not\ninitialize them in the declaration\nitself; in this case, you MUST have\na constructor to initialize these\nfields</li>\n</ul>\n\n<p>Note that:</p>\n\n<ul>\n<li>you may define more than one\nconstructor (with different\narguments)</li>\n<li>you can (should?) define all your\nconstructors protected (making them\npublic is pointless anyway)</li>\n<li>your subclass constructor(s) can\ncall one constructor of the abstract\nclass; it may even <strong>have to</strong> call it\n(if there is no no-arg constructor\nin the abstract class)</li>\n</ul>\n\n<p>In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).</p>\n" }, { "answer_id": 16623315, "author": "Aniket Thakur", "author_id": 2396539, "author_profile": "https://Stackoverflow.com/users/2396539", "pm_score": 6, "selected": false, "text": "<p><strong>Yes</strong>! <strong>Abstract classes can have constructors</strong>!</p>\n\n<p>Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class.</p>\n\n<p>When we create an object of any subclass all the constructors in the corresponding inheritance tree are invoked in the top to bottom approach. The same case applies to abstract classes. Though we cannot create an object of an abstract class, when we create an object of a class which is concrete and subclass of the abstract class, the constructor of the abstract class is automatically invoked. Hence we can have a constructor in abstract classes.</p>\n\n<p>Note: A non-abstract class cannot have abstract methods but an abstract class can have a non-abstract method. Reason is similar to that of constructors, difference being instead of getting invoked automatically we can call super(). Also, there is nothing like an abstract constructor as it makes no sense at all.</p>\n" }, { "answer_id": 17714904, "author": "jaideep", "author_id": 2587223, "author_profile": "https://Stackoverflow.com/users/2587223", "pm_score": 2, "selected": false, "text": "<p>As described by javafuns <a href=\"http://www.geekinterview.com/question_details/77988\" rel=\"nofollow\">here</a>, this is an example:</p>\n\n<pre><code>public abstract class TestEngine\n{\n private String engineId;\n private String engineName;\n\n public TestEngine(String engineId , String engineName)\n {\n this.engineId = engineId;\n this.engineName = engineName;\n }\n //public gettors and settors\n public abstract void scheduleTest();\n}\n\n\npublic class JavaTestEngine extends TestEngine\n{\n\n private String typeName;\n\n public JavaTestEngine(String engineId , String engineName , String typeName)\n {\n super(engineId , engineName);\n this.typeName = typeName;\n }\n\n public void scheduleTest()\n {\n //do Stuff\n }\n}\n</code></pre>\n" }, { "answer_id": 17769203, "author": "Jacob", "author_id": 2603515, "author_profile": "https://Stackoverflow.com/users/2603515", "pm_score": 3, "selected": false, "text": "<p>Yes it can, abstract classes constructors are generally used for super calls for initialization events common to all the subclasses</p>\n" }, { "answer_id": 18754509, "author": "MattC", "author_id": 1375627, "author_profile": "https://Stackoverflow.com/users/1375627", "pm_score": 4, "selected": false, "text": "<p>Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).</p>\n\n<p>A good example of an abstract class having a constructor is the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html\" rel=\"noreferrer\">Calendar</a> class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#GregorianCalendar%28%29\" rel=\"noreferrer\">GregorianCalendar</a> is an example of a class that extends Calendar.</p>\n" }, { "answer_id": 20413581, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "<p>In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:</p>\n\n<ul>\n<li><p>A means by which code can request the creation of an instance of Fnord</p></li>\n<li><p>A means by which an instance <em>of a type derived from Fnord</em> which is under construction can request that all base-class features be initialized.</p></li>\n</ul>\n\n<p>While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.</p>\n" }, { "answer_id": 23188064, "author": "Sandeep", "author_id": 3554840, "author_profile": "https://Stackoverflow.com/users/3554840", "pm_score": -1, "selected": false, "text": "<p>Yes..It is like any other class. It can have a constructor and it is called after creating object for the base class.</p>\n" }, { "answer_id": 28560577, "author": "Kedar Parikh", "author_id": 4575227, "author_profile": "https://Stackoverflow.com/users/4575227", "pm_score": 1, "selected": false, "text": "<p>Yes surely you can add one, as already mentioned for initialization of Abstract class variables.\nBUT if you dont explicitly declare one, it anyways has an implicit constructor for \"Constructor Chaining\" to work. </p>\n" }, { "answer_id": 29781391, "author": "Ketan G", "author_id": 4252869, "author_profile": "https://Stackoverflow.com/users/4252869", "pm_score": 3, "selected": false, "text": "<p><strong>Yes, Abstract Classes can have constructors !</strong> </p>\n\n<p>Here is an example using constructor in abstract class:</p>\n\n<pre><code>abstract class Figure { \n\n double dim1; \n double dim2; \n\n Figure(double a, double b) { \n dim1 = a; \n dim2 = b; \n }\n\n // area is now an abstract method \n\n abstract double area(); \n\n}\n\n\nclass Rectangle extends Figure { \n Rectangle(double a, double b) { \n super(a, b); \n } \n // override area for rectangle \n double area() { \n System.out.println(\"Inside Area for Rectangle.\"); \n return dim1 * dim2; \n } \n}\n\nclass Triangle extends Figure { \n Triangle(double a, double b) { \n super(a, b); \n } \n // override area for right triangle \n double area() { \n System.out.println(\"Inside Area for Triangle.\"); \n return dim1 * dim2 / 2; \n } \n}\n\nclass AbstractAreas { \n public static void main(String args[]) { \n // Figure f = new Figure(10, 10); // illegal now \n Rectangle r = new Rectangle(9, 5); \n Triangle t = new Triangle(10, 8); \n Figure figref; // this is OK, no object is created \n figref = r; \n System.out.println(\"Area is \" + figref.area()); \n figref = t; \n System.out.println(\"Area is \" + figref.area()); \n } \n}\n</code></pre>\n\n<p>So I think you got the answer.</p>\n" }, { "answer_id": 31016904, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 2, "selected": false, "text": "<p>Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check <a href=\"https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.1\" rel=\"nofollow\">JLS</a>:</p>\n\n<blockquote>\n <p><strong>It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation\n expression</strong>.</p>\n \n <p>A subclass of an abstract class that is not itself abstract may be\n instantiated, resulting in the execution of a constructor for the\n abstract class and, therefore, the execution of the field initializers\n for instance variables of that class.</p>\n</blockquote>\n" }, { "answer_id": 31405155, "author": "Anilkumar K S", "author_id": 5114930, "author_profile": "https://Stackoverflow.com/users/5114930", "pm_score": 1, "selected": false, "text": "<p>In order to achieve constructor chaining, the abstract class will have a constructor.\nThe compiler keeps Super() statement inside the subclass constructor, which will call the superclass constructor. If there were no constructors for abstract classes then java rules are violated and we can't achieve constructor chaining.</p>\n" }, { "answer_id": 33993977, "author": "Alok", "author_id": 5471827, "author_profile": "https://Stackoverflow.com/users/5471827", "pm_score": 3, "selected": false, "text": "<p>An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?</p>\n\n<p>Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor. </p>\n\n<p>so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor. </p>\n" }, { "answer_id": 37337990, "author": "Raj Baral", "author_id": 6348730, "author_profile": "https://Stackoverflow.com/users/6348730", "pm_score": 3, "selected": false, "text": "<p>Of Course, abstract class can have a constructor.Generally class constructor is used to initialise fields.So, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents code duplication.</p>\n\n<p>We cannot create an instance of an abstract class,But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called.</p>\n\n<p>Reference :<a href=\"http://csharp-video-tutorials.blogspot.com/2013/10/part-8-can-abstract-class-have.html\" rel=\"nofollow noreferrer\">This Article</a></p>\n" }, { "answer_id": 45959363, "author": "Shubhamhackz", "author_id": 6915572, "author_profile": "https://Stackoverflow.com/users/6915572", "pm_score": 1, "selected": false, "text": "<p>Yes, an Abstract Class can have a Constructor. You Can Overload as many Constructor as you want in an Abstract Class. These Contractors Can be used to Initialized the initial state of the Objects Extending the Abstract Class. As we know we can't make an object of an Abstract Class because Objects are Created by the \"new\" keywords and not by the constructors...they are there for only initializing the state of the subclass Objects.</p>\n" }, { "answer_id": 46075444, "author": "Harshil", "author_id": 1636874, "author_profile": "https://Stackoverflow.com/users/1636874", "pm_score": 3, "selected": false, "text": "<p>Although there are many good answers, I would like to give my 2 cents.</p>\n\n<p>Constructor <strong>DOES NOT BUILD THE OBJECT</strong>. It is used to initialize an object.</p>\n\n<p>Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class.\nAbove holds true for all classes - nested, abstract, anonymous, etc. </p>\n\n<p>An abstract class (unlike interface) can have non-final non-static fields which need initialization. You can write your own constructor in the abstract class to do that. But, in that case, there won't be any default constructor.</p>\n\n<pre><code>public abstract class Abs{\n int i;\n int j;\n public Abs(int i,int j){\n this.i = i;\n this.j = j;\n System.out.println(i+\" \"+j);\n }\n}\n</code></pre>\n\n<p>Be careful while extending above abstract class, you have to explicitly call super from each constructor. The first line of any constructor calls to super(). if you do not explicitly call super(), Java will do that for you.\nBelow code will not compile:</p>\n\n<pre><code>public class Imp extends Abs{\n\npublic Imp(int i, int j,int k, int l){\n System.out.println(\"2 arg\");\n}\n}\n</code></pre>\n\n<p>You have to use it like below example:</p>\n\n<pre><code>public class Imp extends Abs{\n\npublic Imp(int i, int j,int k, int l){\n super(i,j);\n System.out.println(\"2 arg\");\n}\n}\n</code></pre>\n" }, { "answer_id": 46250908, "author": "chamzz.dot", "author_id": 5983136, "author_profile": "https://Stackoverflow.com/users/5983136", "pm_score": 2, "selected": false, "text": "<p>yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.</p>\n\n<pre><code>// An abstract class with constructor\nabstract class Base {\nBase() { System.out.println(\"Base Constructor Called\"); }\nabstract void fun();\n }\nclass Derived extends Base {\nDerived() { System.out.println(\"Derived Constructor Called\"); }\nvoid fun() { System.out.println(\"Derived fun() called\"); }\n }\n\nclass Main {\npublic static void main(String args[]) { \n Derived d = new Derived();\n }\n\n}\n</code></pre>\n\n<p>This is the output of the above code,</p>\n\n<p>Base Constructor Called\nDerived Constructor Called</p>\n\n<p>references:\n<a href=\"http://www.geeksforgeeks.org/abstract-classes-in-java/\" rel=\"nofollow noreferrer\">enter link description here</a></p>\n" }, { "answer_id": 48429852, "author": "karto", "author_id": 648608, "author_profile": "https://Stackoverflow.com/users/648608", "pm_score": 0, "selected": false, "text": "<p>The purpose of the constructor in a class is used to <strong>initialize fields</strong> but not to \"build objects\". When you try to create a new instance of an abstract SuperClass, the compiler will give you an error. However, we can inherit an abstract class Employee and make use of its constructor by setting its variables See example below</p>\n\n<pre><code>public abstract class Employee {\n private String EmpName;\n abstract double calcSalary();\n\n Employee(String name) {\n this.EmpName = name;// constructor of abstract class super class\n }\n}\n\nclass Manager extends Employee{\n Manager(String name) {\n super(name);// setting the name in the constructor of sub class\n }\ndouble calcSalary() {\n return 0;\n }\n}\n</code></pre>\n" }, { "answer_id": 50002677, "author": "Arun Raaj", "author_id": 4334162, "author_profile": "https://Stackoverflow.com/users/4334162", "pm_score": 1, "selected": false, "text": "<p>Since an <strong>abstract class</strong> can have variables of all access modifiers, they have to be initialized to default values, so constructor is necessary.\nAs you instantiate the child class, a constructor of an abstract class is invoked and variables are initialized.</p>\n\n<p>On the contrary, an <strong>interface</strong> does contain only constant variables means they are already initialized. So interface doesn't need a constructor.</p>\n" }, { "answer_id": 57777918, "author": "sachit", "author_id": 8097510, "author_profile": "https://Stackoverflow.com/users/8097510", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>package Test1;\n\npublic class AbstractClassConstructor {\n\n public AbstractClassConstructor() {\n \n }\n\n public static void main(String args[]) {\n Demo obj = new Test(&quot;Test of code has started&quot;);\n obj.test1();\n }\n}\n\nabstract class Demo{\n protected final String demoValue;\n \n public Demo(String testName){\n this.demoValue = testName;\n }\n \n public abstract boolean test1();\n}\n\nclass Test extends Demo{\n \n public Test(String name){\n super(name);\n }\n\n @Override\n public boolean test1() {\n System.out.println( this.demoValue + &quot; Demo test started&quot;);\n return true;\n }\n \n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33885/" ]
Can an abstract class have a constructor? If so, how can it be used and for what purposes?
Yes, an abstract class can have a constructor. Consider this: ``` abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } } ``` The superclass `Product` is abstract and has a constructor. The concrete class `TimesTwo` has a constructor that just hardcodes the value 2. The concrete class `TimesWhat` has a constructor that allows the caller to specify the value. Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class. > > NOTE: As there is no default (or no-arg) constructor in the parent > abstract class, the constructor used in subclass must explicitly call > the parent constructor. > > >
260,668
<p>I'm curious about people's experiences using AR's to_xml() to build non-entity fields (as in, not an attribute of the model you are serializing, but perhaps, utilizing the attributes in the process) from a controller. </p> <p>to_xml seems to supply a few options for doing this. </p> <p>One is by passing in references to methods on the object being acted on: during the serialization process, these methods are invoked and their results are added to the generated document. I'd like to avoid this path because some of the generated data, while depending on the object's attributes, could be outside of the scope of the model itself -- e.g., building a URL to a particular items "show" action. Plus, it requires too much forethought. I'd like to just be able to change the resultant document by tweaking the to_xml code from the controller. I don't want the hassle of having to declare a method in the object as well. </p> <p>The same goes for overriding to_xml in each object. </p> <p>The other two options seem to fit the bill a little better: one is by passing in procs in the serialization options that generate these fields, and the other is by passing in a block that will yielded to after serialization the objects attributes. These provide the kind of at-the-point-of-invocation customizing that I'm looking for, and in addition, their declarations bind the scope to the controller so that they have access to the same stuff that the controller does, but these methods seem critically limited: AFAICT they contain no reference to the object being serialized. They contain references to the builder object, which, sure I guess you could parse within the block/proc and find the attributes that have already been serialized and use them, but that's a harangue, or at least uneasy and suboptimal. </p> <p>Correct me if I'm wrong here, but what is the point of having procs/blocks available when serializing one or more objects if you have to access to the object itself.</p> <p>Anyway, please tell me how I'm wrong, because it seems like I must be overlooking something here. </p> <p>Oh and yeah, I know that I could write my own view. I'm trying to leverage respond_to and to_xml to achieve minimal extra files/lines. (Though, that is what I resorted to when I couldn't figure out how to do this with AR's serialization.)</p> <p>**EDIT 3.29.09 -- I just submitted a patch for this to Rails. If you're interested, show some support :) <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml" rel="nofollow noreferrer">https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml</a></p>
[ { "answer_id": 260686, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Consider this:</p>\n\n<pre><code>abstract class Product { \n int value;\n public Product( int val ) {\n value= val;\n }\n abstract public int multiply();\n}\n\nclass TimesTwo extends Product {\n public int mutiply() {\n return value * 2;\n }\n}\n</code></pre>\n\n<p>The superclass is abstract and has a constructor.</p>\n" }, { "answer_id": 260710, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 6, "selected": false, "text": "<p>Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.</p>\n" }, { "answer_id": 260755, "author": "Michael Rutherfurd", "author_id": 33889, "author_profile": "https://Stackoverflow.com/users/33889", "pm_score": 11, "selected": true, "text": "<p>Yes, an abstract class can have a constructor. Consider this:</p>\n\n<pre><code>abstract class Product { \n int multiplyBy;\n public Product( int multiplyBy ) {\n this.multiplyBy = multiplyBy;\n }\n\n public int mutiply(int val) {\n return multiplyBy * val;\n }\n}\n\nclass TimesTwo extends Product {\n public TimesTwo() {\n super(2);\n }\n}\n\nclass TimesWhat extends Product {\n public TimesWhat(int what) {\n super(what);\n }\n}\n</code></pre>\n\n<p>The superclass <code>Product</code> is abstract and has a constructor. The concrete class <code>TimesTwo</code> has a constructor that just hardcodes the value 2. The concrete class <code>TimesWhat</code> has a constructor that allows the caller to specify the value.</p>\n\n<p>Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.</p>\n\n<blockquote>\n <p>NOTE: As there is no default (or no-arg) constructor in the parent\n abstract class, the constructor used in subclass must explicitly call\n the parent constructor.</p>\n</blockquote>\n" }, { "answer_id": 261159, "author": "jfpoilpret", "author_id": 1440720, "author_profile": "https://Stackoverflow.com/users/1440720", "pm_score": 7, "selected": false, "text": "<p>You would define a constructor in an abstract class if you are in one of these situations:</p>\n\n<ul>\n<li>you want to perform some\ninitialization (to fields of the\nabstract class) before the\ninstantiation of a subclass actually\ntakes place</li>\n<li>you have defined final fields in the\nabstract class but you did not\ninitialize them in the declaration\nitself; in this case, you MUST have\na constructor to initialize these\nfields</li>\n</ul>\n\n<p>Note that:</p>\n\n<ul>\n<li>you may define more than one\nconstructor (with different\narguments)</li>\n<li>you can (should?) define all your\nconstructors protected (making them\npublic is pointless anyway)</li>\n<li>your subclass constructor(s) can\ncall one constructor of the abstract\nclass; it may even <strong>have to</strong> call it\n(if there is no no-arg constructor\nin the abstract class)</li>\n</ul>\n\n<p>In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).</p>\n" }, { "answer_id": 16623315, "author": "Aniket Thakur", "author_id": 2396539, "author_profile": "https://Stackoverflow.com/users/2396539", "pm_score": 6, "selected": false, "text": "<p><strong>Yes</strong>! <strong>Abstract classes can have constructors</strong>!</p>\n\n<p>Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class.</p>\n\n<p>When we create an object of any subclass all the constructors in the corresponding inheritance tree are invoked in the top to bottom approach. The same case applies to abstract classes. Though we cannot create an object of an abstract class, when we create an object of a class which is concrete and subclass of the abstract class, the constructor of the abstract class is automatically invoked. Hence we can have a constructor in abstract classes.</p>\n\n<p>Note: A non-abstract class cannot have abstract methods but an abstract class can have a non-abstract method. Reason is similar to that of constructors, difference being instead of getting invoked automatically we can call super(). Also, there is nothing like an abstract constructor as it makes no sense at all.</p>\n" }, { "answer_id": 17714904, "author": "jaideep", "author_id": 2587223, "author_profile": "https://Stackoverflow.com/users/2587223", "pm_score": 2, "selected": false, "text": "<p>As described by javafuns <a href=\"http://www.geekinterview.com/question_details/77988\" rel=\"nofollow\">here</a>, this is an example:</p>\n\n<pre><code>public abstract class TestEngine\n{\n private String engineId;\n private String engineName;\n\n public TestEngine(String engineId , String engineName)\n {\n this.engineId = engineId;\n this.engineName = engineName;\n }\n //public gettors and settors\n public abstract void scheduleTest();\n}\n\n\npublic class JavaTestEngine extends TestEngine\n{\n\n private String typeName;\n\n public JavaTestEngine(String engineId , String engineName , String typeName)\n {\n super(engineId , engineName);\n this.typeName = typeName;\n }\n\n public void scheduleTest()\n {\n //do Stuff\n }\n}\n</code></pre>\n" }, { "answer_id": 17769203, "author": "Jacob", "author_id": 2603515, "author_profile": "https://Stackoverflow.com/users/2603515", "pm_score": 3, "selected": false, "text": "<p>Yes it can, abstract classes constructors are generally used for super calls for initialization events common to all the subclasses</p>\n" }, { "answer_id": 18754509, "author": "MattC", "author_id": 1375627, "author_profile": "https://Stackoverflow.com/users/1375627", "pm_score": 4, "selected": false, "text": "<p>Not only can it, it always does. If you do not specify one then it has a default no arg constructor, just like any other class. In fact, ALL classes, including nested and anonymous classes, will get a default constructor if one is not specified (in the case of anonymous classes it is impossible to specify one, so you will always get the default constructor).</p>\n\n<p>A good example of an abstract class having a constructor is the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html\" rel=\"noreferrer\">Calendar</a> class. You get a Calendar object by calling Calendar.getInstance(), but it also has constructors which are protected. The reason its constructors are protected is so that only its subclasses can call them (or classes in the same package, but since it's abstract, that doesn't apply). <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#GregorianCalendar%28%29\" rel=\"noreferrer\">GregorianCalendar</a> is an example of a class that extends Calendar.</p>\n" }, { "answer_id": 20413581, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "<p>In a concrete class, declaration of a constructor for a concrete type Fnord effectively exposes two things:</p>\n\n<ul>\n<li><p>A means by which code can request the creation of an instance of Fnord</p></li>\n<li><p>A means by which an instance <em>of a type derived from Fnord</em> which is under construction can request that all base-class features be initialized.</p></li>\n</ul>\n\n<p>While there should perhaps be a means by which these two abilities could be controlled separately, for every concrete type one definition will enable both. Although the first ability is not meaningful for an abstract class, the second ability is just as meaningful for an abstract class as it would be for any other, and thus its declaration is just as necessary and useful.</p>\n" }, { "answer_id": 23188064, "author": "Sandeep", "author_id": 3554840, "author_profile": "https://Stackoverflow.com/users/3554840", "pm_score": -1, "selected": false, "text": "<p>Yes..It is like any other class. It can have a constructor and it is called after creating object for the base class.</p>\n" }, { "answer_id": 28560577, "author": "Kedar Parikh", "author_id": 4575227, "author_profile": "https://Stackoverflow.com/users/4575227", "pm_score": 1, "selected": false, "text": "<p>Yes surely you can add one, as already mentioned for initialization of Abstract class variables.\nBUT if you dont explicitly declare one, it anyways has an implicit constructor for \"Constructor Chaining\" to work. </p>\n" }, { "answer_id": 29781391, "author": "Ketan G", "author_id": 4252869, "author_profile": "https://Stackoverflow.com/users/4252869", "pm_score": 3, "selected": false, "text": "<p><strong>Yes, Abstract Classes can have constructors !</strong> </p>\n\n<p>Here is an example using constructor in abstract class:</p>\n\n<pre><code>abstract class Figure { \n\n double dim1; \n double dim2; \n\n Figure(double a, double b) { \n dim1 = a; \n dim2 = b; \n }\n\n // area is now an abstract method \n\n abstract double area(); \n\n}\n\n\nclass Rectangle extends Figure { \n Rectangle(double a, double b) { \n super(a, b); \n } \n // override area for rectangle \n double area() { \n System.out.println(\"Inside Area for Rectangle.\"); \n return dim1 * dim2; \n } \n}\n\nclass Triangle extends Figure { \n Triangle(double a, double b) { \n super(a, b); \n } \n // override area for right triangle \n double area() { \n System.out.println(\"Inside Area for Triangle.\"); \n return dim1 * dim2 / 2; \n } \n}\n\nclass AbstractAreas { \n public static void main(String args[]) { \n // Figure f = new Figure(10, 10); // illegal now \n Rectangle r = new Rectangle(9, 5); \n Triangle t = new Triangle(10, 8); \n Figure figref; // this is OK, no object is created \n figref = r; \n System.out.println(\"Area is \" + figref.area()); \n figref = t; \n System.out.println(\"Area is \" + figref.area()); \n } \n}\n</code></pre>\n\n<p>So I think you got the answer.</p>\n" }, { "answer_id": 31016904, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 2, "selected": false, "text": "<p>Abstract class can have a constructor though it cannot be instantiated. But the constructor defined in an abstract class can be used for instantiation of concrete class of this abstract class. Check <a href=\"https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.1\" rel=\"nofollow\">JLS</a>:</p>\n\n<blockquote>\n <p><strong>It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation\n expression</strong>.</p>\n \n <p>A subclass of an abstract class that is not itself abstract may be\n instantiated, resulting in the execution of a constructor for the\n abstract class and, therefore, the execution of the field initializers\n for instance variables of that class.</p>\n</blockquote>\n" }, { "answer_id": 31405155, "author": "Anilkumar K S", "author_id": 5114930, "author_profile": "https://Stackoverflow.com/users/5114930", "pm_score": 1, "selected": false, "text": "<p>In order to achieve constructor chaining, the abstract class will have a constructor.\nThe compiler keeps Super() statement inside the subclass constructor, which will call the superclass constructor. If there were no constructors for abstract classes then java rules are violated and we can't achieve constructor chaining.</p>\n" }, { "answer_id": 33993977, "author": "Alok", "author_id": 5471827, "author_profile": "https://Stackoverflow.com/users/5471827", "pm_score": 3, "selected": false, "text": "<p>An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?</p>\n\n<p>Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor. </p>\n\n<p>so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor. </p>\n" }, { "answer_id": 37337990, "author": "Raj Baral", "author_id": 6348730, "author_profile": "https://Stackoverflow.com/users/6348730", "pm_score": 3, "selected": false, "text": "<p>Of Course, abstract class can have a constructor.Generally class constructor is used to initialise fields.So, an abstract class constructor is used to initialise fields of the abstract class. You would provide a constructor for an abstract class if you want to initialise certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child class. This prevents code duplication.</p>\n\n<p>We cannot create an instance of an abstract class,But we can create instances of classes those are derived from the abstract class. So, when an instance of derived class is created, the parent abstract class constructor is automatically called.</p>\n\n<p>Reference :<a href=\"http://csharp-video-tutorials.blogspot.com/2013/10/part-8-can-abstract-class-have.html\" rel=\"nofollow noreferrer\">This Article</a></p>\n" }, { "answer_id": 45959363, "author": "Shubhamhackz", "author_id": 6915572, "author_profile": "https://Stackoverflow.com/users/6915572", "pm_score": 1, "selected": false, "text": "<p>Yes, an Abstract Class can have a Constructor. You Can Overload as many Constructor as you want in an Abstract Class. These Contractors Can be used to Initialized the initial state of the Objects Extending the Abstract Class. As we know we can't make an object of an Abstract Class because Objects are Created by the \"new\" keywords and not by the constructors...they are there for only initializing the state of the subclass Objects.</p>\n" }, { "answer_id": 46075444, "author": "Harshil", "author_id": 1636874, "author_profile": "https://Stackoverflow.com/users/1636874", "pm_score": 3, "selected": false, "text": "<p>Although there are many good answers, I would like to give my 2 cents.</p>\n\n<p>Constructor <strong>DOES NOT BUILD THE OBJECT</strong>. It is used to initialize an object.</p>\n\n<p>Yes, an Abstract class always has a constructor. If you do not define your own constructor, the compiler will give a default constructor to the Abstract class.\nAbove holds true for all classes - nested, abstract, anonymous, etc. </p>\n\n<p>An abstract class (unlike interface) can have non-final non-static fields which need initialization. You can write your own constructor in the abstract class to do that. But, in that case, there won't be any default constructor.</p>\n\n<pre><code>public abstract class Abs{\n int i;\n int j;\n public Abs(int i,int j){\n this.i = i;\n this.j = j;\n System.out.println(i+\" \"+j);\n }\n}\n</code></pre>\n\n<p>Be careful while extending above abstract class, you have to explicitly call super from each constructor. The first line of any constructor calls to super(). if you do not explicitly call super(), Java will do that for you.\nBelow code will not compile:</p>\n\n<pre><code>public class Imp extends Abs{\n\npublic Imp(int i, int j,int k, int l){\n System.out.println(\"2 arg\");\n}\n}\n</code></pre>\n\n<p>You have to use it like below example:</p>\n\n<pre><code>public class Imp extends Abs{\n\npublic Imp(int i, int j,int k, int l){\n super(i,j);\n System.out.println(\"2 arg\");\n}\n}\n</code></pre>\n" }, { "answer_id": 46250908, "author": "chamzz.dot", "author_id": 5983136, "author_profile": "https://Stackoverflow.com/users/5983136", "pm_score": 2, "selected": false, "text": "<p>yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.</p>\n\n<pre><code>// An abstract class with constructor\nabstract class Base {\nBase() { System.out.println(\"Base Constructor Called\"); }\nabstract void fun();\n }\nclass Derived extends Base {\nDerived() { System.out.println(\"Derived Constructor Called\"); }\nvoid fun() { System.out.println(\"Derived fun() called\"); }\n }\n\nclass Main {\npublic static void main(String args[]) { \n Derived d = new Derived();\n }\n\n}\n</code></pre>\n\n<p>This is the output of the above code,</p>\n\n<p>Base Constructor Called\nDerived Constructor Called</p>\n\n<p>references:\n<a href=\"http://www.geeksforgeeks.org/abstract-classes-in-java/\" rel=\"nofollow noreferrer\">enter link description here</a></p>\n" }, { "answer_id": 48429852, "author": "karto", "author_id": 648608, "author_profile": "https://Stackoverflow.com/users/648608", "pm_score": 0, "selected": false, "text": "<p>The purpose of the constructor in a class is used to <strong>initialize fields</strong> but not to \"build objects\". When you try to create a new instance of an abstract SuperClass, the compiler will give you an error. However, we can inherit an abstract class Employee and make use of its constructor by setting its variables See example below</p>\n\n<pre><code>public abstract class Employee {\n private String EmpName;\n abstract double calcSalary();\n\n Employee(String name) {\n this.EmpName = name;// constructor of abstract class super class\n }\n}\n\nclass Manager extends Employee{\n Manager(String name) {\n super(name);// setting the name in the constructor of sub class\n }\ndouble calcSalary() {\n return 0;\n }\n}\n</code></pre>\n" }, { "answer_id": 50002677, "author": "Arun Raaj", "author_id": 4334162, "author_profile": "https://Stackoverflow.com/users/4334162", "pm_score": 1, "selected": false, "text": "<p>Since an <strong>abstract class</strong> can have variables of all access modifiers, they have to be initialized to default values, so constructor is necessary.\nAs you instantiate the child class, a constructor of an abstract class is invoked and variables are initialized.</p>\n\n<p>On the contrary, an <strong>interface</strong> does contain only constant variables means they are already initialized. So interface doesn't need a constructor.</p>\n" }, { "answer_id": 57777918, "author": "sachit", "author_id": 8097510, "author_profile": "https://Stackoverflow.com/users/8097510", "pm_score": 0, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>package Test1;\n\npublic class AbstractClassConstructor {\n\n public AbstractClassConstructor() {\n \n }\n\n public static void main(String args[]) {\n Demo obj = new Test(&quot;Test of code has started&quot;);\n obj.test1();\n }\n}\n\nabstract class Demo{\n protected final String demoValue;\n \n public Demo(String testName){\n this.demoValue = testName;\n }\n \n public abstract boolean test1();\n}\n\nclass Test extends Demo{\n \n public Test(String name){\n super(name);\n }\n\n @Override\n public boolean test1() {\n System.out.println( this.demoValue + &quot; Demo test started&quot;);\n return true;\n }\n \n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33866/" ]
I'm curious about people's experiences using AR's to\_xml() to build non-entity fields (as in, not an attribute of the model you are serializing, but perhaps, utilizing the attributes in the process) from a controller. to\_xml seems to supply a few options for doing this. One is by passing in references to methods on the object being acted on: during the serialization process, these methods are invoked and their results are added to the generated document. I'd like to avoid this path because some of the generated data, while depending on the object's attributes, could be outside of the scope of the model itself -- e.g., building a URL to a particular items "show" action. Plus, it requires too much forethought. I'd like to just be able to change the resultant document by tweaking the to\_xml code from the controller. I don't want the hassle of having to declare a method in the object as well. The same goes for overriding to\_xml in each object. The other two options seem to fit the bill a little better: one is by passing in procs in the serialization options that generate these fields, and the other is by passing in a block that will yielded to after serialization the objects attributes. These provide the kind of at-the-point-of-invocation customizing that I'm looking for, and in addition, their declarations bind the scope to the controller so that they have access to the same stuff that the controller does, but these methods seem critically limited: AFAICT they contain no reference to the object being serialized. They contain references to the builder object, which, sure I guess you could parse within the block/proc and find the attributes that have already been serialized and use them, but that's a harangue, or at least uneasy and suboptimal. Correct me if I'm wrong here, but what is the point of having procs/blocks available when serializing one or more objects if you have to access to the object itself. Anyway, please tell me how I'm wrong, because it seems like I must be overlooking something here. Oh and yeah, I know that I could write my own view. I'm trying to leverage respond\_to and to\_xml to achieve minimal extra files/lines. (Though, that is what I resorted to when I couldn't figure out how to do this with AR's serialization.) \*\*EDIT 3.29.09 -- I just submitted a patch for this to Rails. If you're interested, show some support :) <https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml>
Yes, an abstract class can have a constructor. Consider this: ``` abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public TimesTwo() { super(2); } } class TimesWhat extends Product { public TimesWhat(int what) { super(what); } } ``` The superclass `Product` is abstract and has a constructor. The concrete class `TimesTwo` has a constructor that just hardcodes the value 2. The concrete class `TimesWhat` has a constructor that allows the caller to specify the value. Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class. > > NOTE: As there is no default (or no-arg) constructor in the parent > abstract class, the constructor used in subclass must explicitly call > the parent constructor. > > >
260,679
<p>If I have a table like:</p> <pre><code>CREATE TABLE FRED ( recordId number(18) primary key, firstName varchar2(50) ); </code></pre> <p>Is there an easy way to clone it's structure (not it's data) into another table of a given name. Basically I want to create table with exactly the same structure, but a different name, so that I can perform some functionality on it. I want to do this in code obviously. Java preferably, but most other languages should be similar.</p>
[ { "answer_id": 260689, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 3, "selected": false, "text": "<p>CREATE TABLE tablename AS SELECT * FROM orginaltable WHERE 1=2;</p>\n\n<p>Edit: The WHERE clause prohibits any rows from qualifying.</p>\n" }, { "answer_id": 260771, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 5, "selected": true, "text": "<p>If you're looking a way to find the exact DDL to recreate the table, including the storage clause, you can use </p>\n\n<pre><code>select dbms_metadata.get_ddl('TABLE', 'TABLE_NAME', 'SCHEMA_NAME') from dual\n</code></pre>\n\n<p>as described <a href=\"http://www.troygeek.com/articles/ExtractingOracleDDLCommandLine/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 62470385, "author": "Priya Ranjan Kumar", "author_id": 6869840, "author_profile": "https://Stackoverflow.com/users/6869840", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT INTO TARGET_TABLE FROM SOURCE_TABLE;\nOR\n\nCREATE TABLE TARGET_TABLE_NAME AS SELECT * FROM SOURCE_TABLE;\n</code></pre>\n\n<p>if you want to copy only the structure then add the Where Clause <code>WHERE 1=2</code>.</p>\n\n<p>I hope it will be helpful.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
If I have a table like: ``` CREATE TABLE FRED ( recordId number(18) primary key, firstName varchar2(50) ); ``` Is there an easy way to clone it's structure (not it's data) into another table of a given name. Basically I want to create table with exactly the same structure, but a different name, so that I can perform some functionality on it. I want to do this in code obviously. Java preferably, but most other languages should be similar.
If you're looking a way to find the exact DDL to recreate the table, including the storage clause, you can use ``` select dbms_metadata.get_ddl('TABLE', 'TABLE_NAME', 'SCHEMA_NAME') from dual ``` as described [here](http://www.troygeek.com/articles/ExtractingOracleDDLCommandLine/).
260,701
<p>I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you). For instance:</p> <p>PHP: $token = md5($var1 . $var2);</p> <p>I found VB especially troublesome to do in one line.</p>
[ { "answer_id": 260715, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "<p><strong>Python</strong></p>\n\n<pre><code>token = __import__('md5').new(var1 + var2).hexdigest()\n</code></pre>\n\n<p>or, if <code>md5</code> is alrady imported:</p>\n\n<pre><code>token = md5.new(var1 + var2).hexdigest()\n</code></pre>\n\n<p><em>Thanks to Greg Hewgill</em></p>\n" }, { "answer_id": 260717, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>There is a kind of universality in how this is to be accomplished. Typically, one defines a routine called <code>md5_in_one_line</code> (or <code>Md5InOneLine</code>) once, and uses it all over the place, just as one would use a library routine.</p>\n\n<p>So for example, once one defines <code>Md5InOneLine</code> in C#, it's an easy one-liner to get the right results.</p>\n" }, { "answer_id": 260722, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>Does it really matter if you can do MD5 in one line. If it's that much trouble that you can't do it in VB in 1 line, then write your own function. Then, when you need to do MD5 in VB in one line, just call that function.</p>\n\n<p>If doing it all in 1 line of code is all that important, here is 1 line of VB. that doesn't use the System.Web Namespace.</p>\n\n<pre><code>Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider() : Dim HashBytes() As Byte : Dim MD5Str As String = \"\" : HashBytes = MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(\"MyString\")) : For i As Integer = 0 To HashBytes.Length - 1 : MD5Str &amp;= HashBytes(i).ToString(\"x\").PadLeft(2, \"0\") : Next\n</code></pre>\n\n<p>This will hash \"MyString\" and store the MD5 sum in MD5Str.</p>\n" }, { "answer_id": 260725, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<p>C#:</p>\n\n<pre><code>string hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, \"md5\");\n</code></pre>\n\n<p>VB is virtually the same.</p>\n\n<p>Here it is not using the System.Web namespace:</p>\n\n<pre><code>string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input)));\n</code></pre>\n\n<p>Or in readable form:</p>\n\n<pre><code>string hash =\n Convert.ToBase64String\n (new System.Security.Cryptography.MD5CryptoServiceProvider()\n .ComputeHash\n (System.Text.Encoding.UTF8.GetBytes\n (input)\n )\n );\n</code></pre>\n" }, { "answer_id": 260736, "author": "Drew Hall", "author_id": 23934, "author_profile": "https://Stackoverflow.com/users/23934", "pm_score": 1, "selected": false, "text": "<p>Aren't you really just asking \"what languages have std. library support for MD5?\" As Justice said, in any language that supports it, it'll just be a function call storing the result in a string variable. Even without built-in support, you could write that function in any language!</p>\n" }, { "answer_id": 260780, "author": "Michal", "author_id": 21672, "author_profile": "https://Stackoverflow.com/users/21672", "pm_score": 1, "selected": false, "text": "<p>Just in case you need VBScript:\ndownload the <a href=\"http://www.webdevbros.net/2007/12/29/using-gravatar-in-classic-asp/\" rel=\"nofollow noreferrer\">MD5 class</a> from webdevbros and then with one line:</p>\n\n<pre><code>hash = (new MD5).hash(\"some value\")\n</code></pre>\n" }, { "answer_id": 260809, "author": "user33891", "author_id": 33891, "author_profile": "https://Stackoverflow.com/users/33891", "pm_score": 0, "selected": false, "text": "<p>Coldfusion has a bunch of hashing algorithms, MD5 is the default.</p>\n\n<p>cfset var md5hashresult = hash(\"string to hash\") </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33886/" ]
I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you). For instance: PHP: $token = md5($var1 . $var2); I found VB especially troublesome to do in one line.
C#: ``` string hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "md5"); ``` VB is virtually the same. Here it is not using the System.Web namespace: ``` string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); ``` Or in readable form: ``` string hash = Convert.ToBase64String (new System.Security.Cryptography.MD5CryptoServiceProvider() .ComputeHash (System.Text.Encoding.UTF8.GetBytes (input) ) ); ```
260,703
<p>Here is some simple Perl to count the number of times a value occurs in an array. This runs without any warnings.</p> <pre><code>use warnings; use strict; my @data = qw(1 1 2 3 4 5 5 5 9); my %histogram; foreach (@data) { $histogram{$_}++; } </code></pre> <p>When the loop body is changed to</p> <pre><code>$histogram{$_} = $histogram{$_} + 1; </code></pre> <p>Perl warns "Use of uninitialized value in addition".</p> <p>What is going on under the hood? Why is the value initialized when supplied as an operand to the ++ operator and uninitialized with the + operator?</p>
[ { "answer_id": 260724, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 5, "selected": true, "text": "<p>The + operator evaluates both the form to the left and the form to the right of it, then returns the sum of both. The hash call evaluation does not see any special context.</p>\n\n<p>The ++ operator has some special magic built in. Quoting from the perlop manpage, regarding the ++ operator: </p>\n\n<blockquote>\n <p>\"undef\" is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than \"undef\").</p>\n</blockquote>\n\n<p><em>edit</em>: To elaborate on the difference, ++ changes the value in place, while + just takes its arguments as input. When + sees an undefined value, typically something has gone wrong, but for ++, your hash manipulation example is very typical -- the user wants to treat undef as 0, instead of having to check and initialize everytime. So it seems that it makes sense to treat these operators this way.</p>\n" }, { "answer_id": 260762, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>It's not that Perl necessarily initializes values, but that it doesn't always warn about them. Don't try to think about a rule for this because you'll always find exceptions, and just when you think you have it figured out, the next version of Perl will change the warnings on you.</p>\n\n<p>In this case, as Harleqin said, the auto-increment operators have a special case.</p>\n" }, { "answer_id": 260862, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 0, "selected": false, "text": "<p>As Brian mentioned: it still does it, it just warns you. Warnings tell you about certain manipulations with effects you might not have intended. </p>\n\n<p>You are specifically <em>asking</em> for the value of <code>$histogram{$_}</code>, adding 1 to it and then assigning it to the same slot. It's the same way that I wouldn't expect autovivification to work here:</p>\n\n<pre><code>my $hash_ref = $hash_for{$key_level_1};\n$hash_ref-&gt;{$key_level_2} = $value;\n</code></pre>\n\n<p>as it does here:</p>\n\n<pre><code>$hash_for{$key_level_1}{$key_level_2} = $value;\n</code></pre>\n\n<p>Magic probably does not work like optimization. And optimizing compiler would notice that <code>a = a + 1</code> is the same thing as <code>a++</code> so that were there an increment operator in the assembly language, it could use that optimized instruction instead of pretending that it needed to preserve the first value, and then overwriting it because it isn't actually needed. </p>\n\n<p>Optimization is extra scrutiny and overhead once for improved performance every run. But there is no guarantee in a dynamic language that you aren't adding overhead at the same rate you would otherwise be trying to reduce it. </p>\n" }, { "answer_id": 260925, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "<p>Certain operators deliberately omit the \"uninitialized\" warning for your convenience\nbecause they are commonly used in situations where a 0 or \"\" default value for the left or only operand makes sense.</p>\n\n<p>These are: ++ and -- (either pre or post), +=, -=, .=, |=, ^=, &amp;&amp;=, ||=.</p>\n\n<p>Note that some of these erroneously give the warning when used on a tied variable: see the tests marked TODO in <a href=\"http://perl5.git.perl.org/perl.git/blob/HEAD:/t/op/assignwarn.t\" rel=\"nofollow noreferrer\">http://perl5.git.perl.org/perl.git/blob/HEAD:/t/op/assignwarn.t</a>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25164/" ]
Here is some simple Perl to count the number of times a value occurs in an array. This runs without any warnings. ``` use warnings; use strict; my @data = qw(1 1 2 3 4 5 5 5 9); my %histogram; foreach (@data) { $histogram{$_}++; } ``` When the loop body is changed to ``` $histogram{$_} = $histogram{$_} + 1; ``` Perl warns "Use of uninitialized value in addition". What is going on under the hood? Why is the value initialized when supplied as an operand to the ++ operator and uninitialized with the + operator?
The + operator evaluates both the form to the left and the form to the right of it, then returns the sum of both. The hash call evaluation does not see any special context. The ++ operator has some special magic built in. Quoting from the perlop manpage, regarding the ++ operator: > > "undef" is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than "undef"). > > > *edit*: To elaborate on the difference, ++ changes the value in place, while + just takes its arguments as input. When + sees an undefined value, typically something has gone wrong, but for ++, your hash manipulation example is very typical -- the user wants to treat undef as 0, instead of having to check and initialize everytime. So it seems that it makes sense to treat these operators this way.
260,716
<p>I'm using a <code>RichTextBox</code> (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys.... For example, I don't want <kbd>Ctrl</kbd>+<kbd>I</kbd> to make the text italic via the RichText method, but to instead run my own method for processing the text.</p> <p>Any ideas?</p>
[ { "answer_id": 260821, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>Set the RichtTextBox.ShortcutsEnabled property to true and then handle the shortcuts yourself, using the KeyUp event. E.G.</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n this.textBox1.ShortcutsEnabled = false;\n this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);\n }\n\n void textBox1_KeyUp(object sender, KeyEventArgs e)\n {\n if (e.Control == true &amp;&amp; e.KeyCode == Keys.X)\n MessageBox.Show(\"Overriding ctrl+x\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 260859, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 4, "selected": true, "text": "<p><kbd>Ctrl</kbd>+<kbd>I</kbd> isn't one of the default shortcuts affected by the ShortcutsEnabled property.</p>\n<p>The following code intercepts the <kbd>Ctrl</kbd>+<kbd>I</kbd> in the KeyDown event so you can do anything you want inside the if block, just make sure to suppress the key press like I've shown.</p>\n<pre><code>private void YourRichTextBox_KeyDown(object sender, KeyEventArgs e)\n{\n if ((Control.ModifierKeys &amp; Keys.Control) == Keys.Control &amp;&amp; e.KeyCode == Keys.I)\n {\n // do whatever you want to do here...\n e.SuppressKeyPress = true;\n }\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
I'm using a `RichTextBox` (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys.... For example, I don't want `Ctrl`+`I` to make the text italic via the RichText method, but to instead run my own method for processing the text. Any ideas?
`Ctrl`+`I` isn't one of the default shortcuts affected by the ShortcutsEnabled property. The following code intercepts the `Ctrl`+`I` in the KeyDown event so you can do anything you want inside the if block, just make sure to suppress the key press like I've shown. ``` private void YourRichTextBox_KeyDown(object sender, KeyEventArgs e) { if ((Control.ModifierKeys & Keys.Control) == Keys.Control && e.KeyCode == Keys.I) { // do whatever you want to do here... e.SuppressKeyPress = true; } } ```
260,744
<p>An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of <code>protected</code> and <code>public</code> is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?</p>
[ { "answer_id": 260751, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 3, "selected": false, "text": "<p>If this behavior is true, and I'm not sure it is, you should always use the most restricted scope available for your application to function. So in that case, I would recommend using protected.</p>\n" }, { "answer_id": 260779, "author": "Jordan Stewart", "author_id": 33338, "author_profile": "https://Stackoverflow.com/users/33338", "pm_score": 6, "selected": true, "text": "<blockquote>\n <blockquote>\n <p>since the abstract type seems to indicate that technically a public constructor will act very much protected</p>\n </blockquote>\n \n <p>This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation <em>will inherit the abstract class' methods and visibility</em></p>\n \n <p>So the abstract class can certainly have public constructors.</p>\n</blockquote>\n\n<p>Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:</p>\n\n<pre><code>public class Scratch\n{\n public static abstract class A\n {\n public A( int i ) {}\n }\n\n public static class B extends A\n {\n private B() { super(0); };\n }\n}\n</code></pre>\n" }, { "answer_id": 260826, "author": "Nrj", "author_id": 11614, "author_profile": "https://Stackoverflow.com/users/11614", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>since the abstract type seems to indicate that technically a public constructor will act very much protected</p>\n</blockquote>\n\n<p>Umm... for abstract classes this constructor scope [public or protected] is not of much difference since the instantiation is not allowed [even if public]. Since it is meant to be invoked by the subclass, it can invoke either public or protected constructor seamlessly.</p>\n\n<p>Its completely on choice what to use. I generally prefer public as it is in most of the cases.</p>\n" }, { "answer_id": 260951, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 1, "selected": false, "text": "<p>At the very least, an abstract class should have a protected constructor. It's not strictly necessary since it's not possible to use the constructor anyway but it makes the contract explicit.</p>\n\n<p>Another option is to make the constructor private. This is only a good idea though if all of the implementations of the class are private inner classes. A rare but useful example. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15075/" ]
An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of `protected` and `public` is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?
> > > > > > since the abstract type seems to indicate that technically a public constructor will act very much protected > > > > > > > > > This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation *will inherit the abstract class' methods and visibility* > > > So the abstract class can certainly have public constructors. > > > Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.: ``` public class Scratch { public static abstract class A { public A( int i ) {} } public static class B extends A { private B() { super(0); }; } } ```
260,745
<p>I have a menu with an animation going on, but I want to disable the click while the animation is happening.</p> <pre><code>&lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; $("div").click(function() { $(this).animate({height: "200px"}, 2000); return false; }); </code></pre> <p>However, I want to disable all the buttons while the event is happening, AND disable the div that was clicked. </p> <p>I was thinking of adding a class to the div that's clicked and putting the click only on the divs without that class:</p> <pre><code>$("div").not("clicked").click(function() { $(this).animate({height: "200px"}, 2000).addClass("clicked"); return false; }); </code></pre> <p>But this doesn't appear to work (I think it does logically)?</p> <p>Any help appreciated.</p> <p>Cheers,<br /> Steve</p>
[ { "answer_id": 260789, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 5, "selected": true, "text": "<pre><code>$(\"div\").click(function() {\n if (!$(this).parent().children().is(':animated')) {\n $(this).animate({height: \"200px\"}, 2000); \n }\n return false;\n});\n</code></pre>\n" }, { "answer_id": 260793, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 0, "selected": false, "text": "<p>You could do something like this...</p>\n\n<pre><code>$(function() { \n $(\"div\").click(function() { \n\n //check to see if any of the divs are animating\n if ($(\"div\").is(\":animated\")) { \n alert(\"busy\"); \n return; \n }\n\n //whatever your animation is \n var div = $(this);\n div.slideUp(3000, function(){ div.slideDown(1000); });\n\n });\n\n});\n</code></pre>\n\n<p>This will animate the click so long as any div is not currently animating. I'm most likely put all those divs in a container and not just simply refer to div, since it could affect a lot more on the page than just your menu,</p>\n" }, { "answer_id": 263756, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p>How do I leave the clicked &lt;div&gt; disabled after the animation's occurred? I've added a class to the div that's been clicked, but doing the following doesn't appear to work:</p>\n\n<pre><code>&lt;div&gt;&lt;/div&gt;\n&lt;div class=\"active\"&gt;&lt;/div&gt;\n&lt;div&gt;&lt;/div&gt;\n\n$(\"div\").not('active').click(function() {\n if (!$(this).parent().children().is(':animated')) {\n $(this).animate({height: \"200px\"}, 2000); \n }\n return false;\n});\n</code></pre>\n\n<p>I suspect I'm missing something with regard to the way .not works</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
I have a menu with an animation going on, but I want to disable the click while the animation is happening. ``` <div></div> <div></div> <div></div> $("div").click(function() { $(this).animate({height: "200px"}, 2000); return false; }); ``` However, I want to disable all the buttons while the event is happening, AND disable the div that was clicked. I was thinking of adding a class to the div that's clicked and putting the click only on the divs without that class: ``` $("div").not("clicked").click(function() { $(this).animate({height: "200px"}, 2000).addClass("clicked"); return false; }); ``` But this doesn't appear to work (I think it does logically)? Any help appreciated. Cheers, Steve
``` $("div").click(function() { if (!$(this).parent().children().is(':animated')) { $(this).animate({height: "200px"}, 2000); } return false; }); ```
260,749
<p>I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?</p>
[ { "answer_id": 260866, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "<p>Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like <a href=\"http://www.w3schools.com/JS/js_cookies.asp\" rel=\"nofollow noreferrer\">this</a> example, you can use other libraries, like <a href=\"http://code.google.com/p/cookie-js/\" rel=\"nofollow noreferrer\">cookie-js</a>, a small <em>(&lt; 100 lines)</em> utility for cookie access.</p>\n\n<p>I personally use jQuery on my projects, and I use the <a href=\"http://plugins.jquery.com/cookie/\" rel=\"nofollow noreferrer\">jQuery Cookie Plugin</a>, it's really simple to use:</p>\n\n<pre><code>var cookieName = \"increment\";\n\nif ($.cookie(cookieName) == null){\n $.cookie(cookieName, 1, { expires: 10 });\n}else{\n var newValue = Number($.cookie(cookieName)) + 1;\n $.cookie(cookieName, newValue, { expires: 10 });\n}\n</code></pre>\n" }, { "answer_id": 260880, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": true, "text": "<p>Stolen from <a href=\"http://www.quirksmode.org/js/cookies.html#script\" rel=\"noreferrer\">http://www.quirksmode.org/js/cookies.html#script</a></p>\n\n<pre><code>function createCookie(name,value,days) {\n if (days) {\n var date = new Date();\n date.setTime(date.getTime()+(days*24*60*60*1000));\n var expires = \"; expires=\"+date.toUTCString();\n }\n else var expires = \"\";\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n}\n\nfunction readCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i &lt; ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n}\n\nfunction eraseCookie(name) {\n createCookie(name,\"\",-1);\n}\n</code></pre>\n\n<p>using it:</p>\n\n<pre><code>var oldCount = parseInt(readCookie('hitCount'), 10) || 0;\ncreateCookie('hitCount', oldCount + 1, 7);\n</code></pre>\n\n<p>as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using <code>foo++</code> or <code>++foo</code> will actually cast for you, but it's safer to know exactly what you're working with:</p>\n\n<pre><code>var x = \"5\"; // x = \"5\" (string)\nx += 1; // x = \"51\" (string!)\nx += 5; // x = \"515\" (string!)\n++x; // x = 516 (number)\n</code></pre>\n" }, { "answer_id": 16061433, "author": "Eugene Kuzmenko", "author_id": 584211, "author_profile": "https://Stackoverflow.com/users/584211", "pm_score": 2, "selected": false, "text": "<p>the best way is always the simplest:</p>\n\n<pre><code>function getCookie(name) {\n return (name = (document.cookie + ';').match(new RegExp(name + '=.*;'))) &amp;&amp; name[0].split(/=|;/)[1];\n}\n\n// the default lifetime is 365 days\nfunction setCookie(name, value, days) {\n var e = new Date;\n e.setDate(e.getDate() + (days || 365));\n document.cookie = name + \"=\" + value + ';expires=' + e.toUTCString() + ';path=/;domain=.' + document.domain;\n}\n</code></pre>\n\n<p>these functions expect the value to be a simple string, but you can always JSON.stringify it if you want or maybe do something else with it...</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30099/" ]
I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?
Stolen from <http://www.quirksmode.org/js/cookies.html#script> ``` function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toUTCString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } ``` using it: ``` var oldCount = parseInt(readCookie('hitCount'), 10) || 0; createCookie('hitCount', oldCount + 1, 7); ``` as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using `foo++` or `++foo` will actually cast for you, but it's safer to know exactly what you're working with: ``` var x = "5"; // x = "5" (string) x += 1; // x = "51" (string!) x += 5; // x = "515" (string!) ++x; // x = 516 (number) ```
260,817
<p>I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to:</p> <pre><code>public string Foo() { set { Assert.IsNotNull(value); Assert.IsTrue(value.Contains("bar")); _foo = value; } } </code></pre> <p>I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.</p>
[ { "answer_id": 260833, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<p>Aside from using an external library, you have a simple assert in System.Diagnostics:</p>\n\n<pre><code>using System.Diagnostics\n\nDebug.Assert(value != null);\nDebug.Assert(value == true);\n</code></pre>\n\n<p>Not very useful, I know.</p>\n" }, { "answer_id": 260837, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Spec_sharp\" rel=\"nofollow noreferrer\">Spec#</a> is a popular <a href=\"http://research.microsoft.com/SpecSharp/\" rel=\"nofollow noreferrer\">microsoft research project</a> that allows for some DBC constructs, like checking post and pre conditions. For example a binary search can be implemented with pre and post conditions along with loop invariants. <a href=\"http://www.rosemarymonahan.com/specsharp/\" rel=\"nofollow noreferrer\">This example and more:</a></p>\n\n<pre><code> public static int BinarySearch(int[]! a, int key)\n requires forall{int i in (0: a.Length), int j in (i: a.Length); a[i] &lt;= a[j]};\n ensures 0 &lt;= result ==&gt; a[result] == key;\n ensures result &lt; 0 ==&gt; forall{int i in (0: a.Length); a[i] != key};\n {\n int low = 0;\n int high = a.Length - 1;\n\n while (low &lt;= high)\n invariant high+1 &lt;= a.Length;\n invariant forall{int i in (0: low); a[i] != key};\n invariant forall{int i in (high+1: a.Length); a[i] != key};\n {\n int mid = (low + high) / 2;\n int midVal = a[mid];\n\n if (midVal &lt; key) {\n low = mid + 1;\n } else if (key &lt; midVal) {\n high = mid - 1;\n } else {\n return mid; // key found\n }\n }\n return -(low + 1); // key not found.\n }\n</code></pre>\n\n<p>Note that using the Spec# language yields <em>compile time checking</em> for DBC constructs, which to me, is the best way to take advantage of DBC. Often, relying on runtime assertions becomes a headache in production and people generally elect to <a href=\"https://stackoverflow.com/questions/117171/design-by-contract-tests-by-assert-or-by-exception\">use exceptions</a> instead.</p>\n\n<p>There are <a href=\"http://en.wikipedia.org/wiki/Design_by_contract#Language_support\" rel=\"nofollow noreferrer\">other languages</a> that embrace DBC concepts as first class constructs, namely <a href=\"http://en.wikipedia.org/wiki/Eiffel_(programming_language)\" rel=\"nofollow noreferrer\">Eiffel</a> which is also available for the .NET platform.</p>\n" }, { "answer_id": 260939, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>You may want to check out <a href=\"http://www.codeplex.com/umbrella\" rel=\"nofollow noreferrer\">nVentive Umbrella</a>:</p>\n\n<pre><code>using System;\nusing nVentive.Umbrella.Validation;\nusing nVentive.Umbrella.Extensions;\n\nnamespace Namespace\n{\n public static class StringValidationExtensionPoint\n {\n public static string Contains(this ValidationExtensionPoint&lt;string&gt; vep, string value)\n {\n if (vep.ExtendedValue.IndexOf(value, StringComparison.InvariantCultureIgnoreCase) == -1)\n throw new ArgumentException(String.Format(\"Must contain '{0}'.\", value));\n\n return vep.ExtendedValue;\n }\n }\n\n class Class\n {\n private string _foo;\n public string Foo\n {\n set\n {\n _foo = value.Validation()\n .NotNull(\"Foo\")\n .Validation()\n .Contains(\"bar\");\n }\n }\n }\n}\n</code></pre>\n\n<p>I wish the Validation extensions were builders so you could do <code>_foo = value.Validation().NotNull(\"Foo\").Contains(\"bar\").Value;</code> but it is what it is (fortunately its open source so making it a builder is a trivial change).</p>\n\n<p>And as an alternative solution you could <a href=\"http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx\" rel=\"nofollow noreferrer\">consider domain validation</a>.</p>\n\n<p>Finally the <a href=\"http://msdn.microsoft.com/en-us/library/dd129617.aspx\" rel=\"nofollow noreferrer\">new M languages</a>, <a href=\"http://msdn.microsoft.com/en-us/oslo/default.aspx\" rel=\"nofollow noreferrer\">as part of Oslo</a>, support restrictions on their extents and fields which translate both to T-SQL validation and a CLR class with functioning validation tests (though Oslo is a long time off from release).</p>\n" }, { "answer_id": 260943, "author": "Hamish Smith", "author_id": 15572, "author_profile": "https://Stackoverflow.com/users/15572", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://code.google.com/p/moq/source/browse/trunk/Source/Guard.cs\" rel=\"nofollow noreferrer\">Looking over the code for Moq I saw that they use a class called 'Guard' that provides static methods for checking pre and post conditions</a>. I thought that was neat and very clear. It expresses what I'd be thinking about when implementing design by contract checks in my code. </p>\n\n<p>e.g.</p>\n\n<pre><code>public void Foo(Bar param)\n{\n Guard.ArgumentNotNull(param);\n} \n</code></pre>\n\n<p>I thought it was a neat way to express design by contract checks.</p>\n" }, { "answer_id": 267671, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 7, "selected": true, "text": "<blockquote>\n<h2>C# 4.0 Code Contracts</h2>\n</blockquote>\n<p>Microsoft has released a library for design by contract in version 4.0 of the .net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code.</p>\n<p>Here are some Microsoft resources:</p>\n<ul>\n<li><a href=\"http://research.microsoft.com/en-us/projects/contracts/\" rel=\"noreferrer\">The main Microsoft Research site</a></li>\n<li><a href=\"http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf\" rel=\"noreferrer\">The user manual</a></li>\n<li><a href=\"http://channel9.msdn.com/pdc2008/TL51/\" rel=\"noreferrer\">The 2008 PDC presentation</a></li>\n<li><a href=\"http://microsoftpdc.com/Sessions/VTL01\" rel=\"noreferrer\">The 2009 PDC presentation</a></li>\n</ul>\n<p>Here are some other resources:</p>\n<ul>\n<li><a href=\"http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/08/code-contracts-and-net-4-0-spec-comes-alive.aspx\" rel=\"noreferrer\">Code Contracts for .NET 4.0 - Spec# Comes Alive</a></li>\n<li><a href=\"http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/14/net-code-contracts-and-tdd-are-complementary.aspx\" rel=\"noreferrer\">.NET Code Contracts and TDD Are Complementary</a></li>\n<li><a href=\"http://devlicio.us/blogs/derik_whittaker/archive/2009/07/01/code-contracts-primer-part-5-utilizing-object-invariants.aspx\" rel=\"noreferrer\">Code Contracts Primer – Part 5: Utilizing Object Invariants</a></li>\n<li><a href=\"http://devlicio.us/blogs/derik_whittaker/archive/2010/05/14/code-contracts-primer-part-6-interface-contracts.aspx\" rel=\"noreferrer\">Code Contracts Primer – Part 6 Interface Contracts</a></li>\n</ul>\n" }, { "answer_id": 2338931, "author": "Tomasz Modelski", "author_id": 195922, "author_profile": "https://Stackoverflow.com/users/195922", "pm_score": 1, "selected": false, "text": "<p>For my current project (february 2010, VS 2008) I've choose <a href=\"http://lightcontracts.codeplex.com/\" rel=\"nofollow noreferrer\">http://lightcontracts.codeplex.com/</a> </p>\n\n<p>Simple, it's just runtime validation, without any weird complexity, you don't need to derive from some 'strange' base classes, no AOP, VS integration which won't work on some developer workstations, etc. </p>\n\n<p>Simplicity over complexity. </p>\n" }, { "answer_id": 3155694, "author": "ligaoren", "author_id": 248524, "author_profile": "https://Stackoverflow.com/users/248524", "pm_score": 3, "selected": false, "text": "<p>There has an answer in .net Fx 4.0:</p>\n\n<p>System.Diagnostics.Contracts</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd264808.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd264808.aspx</a></p>\n\n<pre><code>Contract.Requires(newNumber &gt; 0, “Failed contract: negative”);\nContract.Ensures(list.Count == Contract.OldValue(list.Count) + 1);\n</code></pre>\n" }, { "answer_id": 5192802, "author": "Richard C", "author_id": 494701, "author_profile": "https://Stackoverflow.com/users/494701", "pm_score": 1, "selected": false, "text": "<p>The most straightforward way, and the way used in the .NET Framework itself, is to do:</p>\n\n<pre><code>public string Foo()\n{\n set {\n if (value == null)\n throw new ArgumentNullException(\"value\");\n if (!value.Contains(\"bar\"))\n throw new ArgumentException(@\"value should contain \"\"bar\"\"\", \"value\");\n\n _foo = value;\n }\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27613/" ]
I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to: ``` public string Foo() { set { Assert.IsNotNull(value); Assert.IsTrue(value.Contains("bar")); _foo = value; } } ``` I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.
> > C# 4.0 Code Contracts > --------------------- > > > Microsoft has released a library for design by contract in version 4.0 of the .net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code. Here are some Microsoft resources: * [The main Microsoft Research site](http://research.microsoft.com/en-us/projects/contracts/) * [The user manual](http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf) * [The 2008 PDC presentation](http://channel9.msdn.com/pdc2008/TL51/) * [The 2009 PDC presentation](http://microsoftpdc.com/Sessions/VTL01) Here are some other resources: * [Code Contracts for .NET 4.0 - Spec# Comes Alive](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/08/code-contracts-and-net-4-0-spec-comes-alive.aspx) * [.NET Code Contracts and TDD Are Complementary](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/14/net-code-contracts-and-tdd-are-complementary.aspx) * [Code Contracts Primer – Part 5: Utilizing Object Invariants](http://devlicio.us/blogs/derik_whittaker/archive/2009/07/01/code-contracts-primer-part-5-utilizing-object-invariants.aspx) * [Code Contracts Primer – Part 6 Interface Contracts](http://devlicio.us/blogs/derik_whittaker/archive/2010/05/14/code-contracts-primer-part-6-interface-contracts.aspx)
260,825
<p>We have been having serious trouble getting an application we devlop running with UAC enabled for long.</p> <p>Once installed (the installer fails almost immediately with UAC) it appears that UAC can be turned on and have the application work. However, after a while, it will stop working with strange errors about cannot find a file that it just created.</p> <p>Just to get this straight: </p> <pre> XP as admin: Fine XP as limited user: Fine Vista no UAC admin: Fine Vista no UAC limited: Fine Vista UAC admin: FAIL Vista UAC limited: FAIL </pre> <p>The software contains no privilege checks anywhere. If I understand the documentation correctly, anything working as a limited user should work with UAC; however this is proving not to be the case.</p> <p>EDIT: I must apologize for asking a problem much harder than it originally appeared. We have in fact found at least one bug in folder virtualization and think there are more out there. At this point, the only reasonable hope to get it running is to find an API call that can be executed as a limited user that disables folder virtualization for the calling process and any process it spawns (recursively). The reason we cannot just add a manifest is that the software calls into third-party software that actaully can vary per machine.</p>
[ { "answer_id": 260841, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Where is the application trying to write the file? If it is trying to write to it's install location under Program Files you may get strange errors since writing here is not allowed under Vista and any files created here are actually created in a virtual folder elsewhere - though to the application they (usually) appear to be where it expects them.</p>\n\n<p>You may want to try running the application in XP compatibility mode.</p>\n" }, { "answer_id": 261272, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 2, "selected": false, "text": "<p>Look up virtualization of the filesystem and registry on Windows Vista. If your app uses certain parts of the filesystem and/or registry you will find that your app \"works\" - that is, the APIs succeed with no errors - but that data isn't stored where you expect. In particular, many areas that would have been shared between multiple users on one machine are now out-of-bounds, and the data actually goes into some storage that is specific to the current user. You'll only find out some time later that users aren't actually sharing the same data.</p>\n\n<p>There is a way to stop this Virtualization from happening. Provide a manifest file for your application to say that it knows about UAC, as described here...\n<a href=\"http://msdn.microsoft.com/en-us/library/bb756929.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb756929.aspx</a>.</p>\n\n<p>It doesn't matter specifically what level of privilege you ask for in the manifest file. The mere presence of it says that your app understands UAC and the OS won't try to be clever and virtualize access to \"privileged\" areas of the filesystem or registry. API calls will simply fail if you don't have the necessary privilege to access those things, and that will be a lot easier for you to debug.</p>\n" }, { "answer_id": 1413368, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": true, "text": "<p>After all this time I found a solution that works.</p>\n\n<ol>\n<li><p>Install somewhere else besides Program Files. This neatly sidesteps the filesystem virtualization that seems to be causing all the problems.</p></li>\n<li><p>Disable virtualization on the application's HLKM registry key. this fixes the one remaining glitch involving system updates.</p></li>\n</ol>\n\n<p>Reference material: <A HREF=\"http://msdn.microsoft.com/en-us/library/aa965884%28VS.85%29.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/aa965884%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa965884%28VS.85%29.aspx</a></A></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14768/" ]
We have been having serious trouble getting an application we devlop running with UAC enabled for long. Once installed (the installer fails almost immediately with UAC) it appears that UAC can be turned on and have the application work. However, after a while, it will stop working with strange errors about cannot find a file that it just created. Just to get this straight: ``` XP as admin: Fine XP as limited user: Fine Vista no UAC admin: Fine Vista no UAC limited: Fine Vista UAC admin: FAIL Vista UAC limited: FAIL ``` The software contains no privilege checks anywhere. If I understand the documentation correctly, anything working as a limited user should work with UAC; however this is proving not to be the case. EDIT: I must apologize for asking a problem much harder than it originally appeared. We have in fact found at least one bug in folder virtualization and think there are more out there. At this point, the only reasonable hope to get it running is to find an API call that can be executed as a limited user that disables folder virtualization for the calling process and any process it spawns (recursively). The reason we cannot just add a manifest is that the software calls into third-party software that actaully can vary per machine.
After all this time I found a solution that works. 1. Install somewhere else besides Program Files. This neatly sidesteps the filesystem virtualization that seems to be causing all the problems. 2. Disable virtualization on the application's HLKM registry key. this fixes the one remaining glitch involving system updates. Reference material: [<http://msdn.microsoft.com/en-us/library/aa965884%28VS.85%29.aspx>](http://msdn.microsoft.com/en-us/library/aa965884%28VS.85%29.aspx)
260,847
<p>I have written a few MSBuild custom tasks that work well and are use in our CruiseControl.NET build process.</p> <p>I am modifying one, and wish to unit test it by calling the Task's Execute() method. </p> <p>However, if it encounters a line containing </p> <pre><code>Log.LogMessage("some message here"); </code></pre> <p>it throws an InvalidOperationException:</p> <p><em>Task attempted to log before it was initialized. Message was...</em></p> <p>Any suggestions? (In the past I have mostly unit-tested Internal static methods on my custom tasks to avoid such problems.)</p>
[ { "answer_id": 274660, "author": "evilhomer", "author_id": 2806, "author_profile": "https://Stackoverflow.com/users/2806", "pm_score": 3, "selected": false, "text": "<p>If you have implemented the interface ITask you will have to initialise the Log class yourself.</p>\n\n<p>Otherwise you should just inherit from <strong>Task</strong> in Microsoft.Build.Utilities.dll\nThat implements <strong>ITask</strong> and does a lot of the leg work for you.</p>\n\n<p>Here is the reference page for building a custom task, it explains quite a lot of it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/t9883dzc.aspx\" rel=\"noreferrer\">Building a custom MSBuild task reference</a></p>\n\n<p>Also worth a look is </p>\n\n<p><a href=\"http://blogs.msdn.com/msbuild/archive/2005/09/28/474951.aspx\" rel=\"noreferrer\">How to debug a custom MSBuild task</a></p>\n\n<p>Other then that could you post the MSBuild XML you are using for calling your custom task.\nThe code itself would obviously be the most help :-)</p>\n" }, { "answer_id": 287704, "author": "Tim Bailey", "author_id": 1077232, "author_profile": "https://Stackoverflow.com/users/1077232", "pm_score": 4, "selected": false, "text": "<p>I have found that the log instance does not work unless the task is running inside msbuild, so I usually wrap my calls to Log, then check the value of BuildEngine to determin if I am running inside msbuild. As below.</p>\n\n<p>Tim</p>\n\n<pre><code>private void LogFormat(string message, params object[] args)\n{\n if (this.BuildEngine != null)\n {\n this.Log.LogMessage(message, args);\n }\n else\n {\n Console.WriteLine(message, args);\n }\n}\n</code></pre>\n" }, { "answer_id": 305402, "author": "Branstar", "author_id": 39324, "author_profile": "https://Stackoverflow.com/users/39324", "pm_score": 6, "selected": true, "text": "<p>You need to set the .BuildEngine property of the custom task you are calling. </p>\n\n<p>You can set it to the same BuildEngine your current task is using to include the output seamlessly.</p>\n\n<pre><code>Task myCustomTask = new CustomTask();\nmyCustomTask.BuildEngine = this.BuildEngine;\nmyCustomTask.Execute();\n</code></pre>\n" }, { "answer_id": 5611069, "author": "Tim Murphy", "author_id": 22941, "author_profile": "https://Stackoverflow.com/users/22941", "pm_score": 3, "selected": false, "text": "<p>@Kiff comment on mock/stub IBuildEngine is a good idea. Here is my FakeBuildEngine. C# and VB.NET examples provided.</p>\n\n<p><strong>VB.NET</strong></p>\n\n<pre><code>Imports System\nImports System.Collections.Generic\nImports Microsoft.Build.Framework\n\nPublic Class FakeBuildEngine\n Implements IBuildEngine\n\n // It's just a test helper so public fields is fine.\n Public LogErrorEvents As New List(Of BuildErrorEventArgs)\n Public LogMessageEvents As New List(Of BuildMessageEventArgs)\n Public LogCustomEvents As New List(Of CustomBuildEventArgs)\n Public LogWarningEvents As New List(Of BuildWarningEventArgs)\n\n Public Function BuildProjectFile(\n projectFileName As String, \n targetNames() As String, \n globalProperties As System.Collections.IDictionary, \n targetOutputs As System.Collections.IDictionary) As Boolean\n Implements IBuildEngine.BuildProjectFile\n\n Throw New NotImplementedException\n\n End Function\n\n Public ReadOnly Property ColumnNumberOfTaskNode As Integer \n Implements IBuildEngine.ColumnNumberOfTaskNode\n Get\n Return 0\n End Get\n End Property\n\n Public ReadOnly Property ContinueOnError As Boolean\n Implements IBuildEngine.ContinueOnError\n Get\n Throw New NotImplementedException\n End Get\n End Property\n\n Public ReadOnly Property LineNumberOfTaskNode As Integer\n Implements IBuildEngine.LineNumberOfTaskNode\n Get\n Return 0\n End Get\n End Property\n\n Public Sub LogCustomEvent(e As CustomBuildEventArgs)\n Implements IBuildEngine.LogCustomEvent\n LogCustomEvents.Add(e)\n End Sub\n\n Public Sub LogErrorEvent(e As BuildErrorEventArgs)\n Implements IBuildEngine.LogErrorEvent\n LogErrorEvents.Add(e)\n End Sub\n\n Public Sub LogMessageEvent(e As BuildMessageEventArgs)\n Implements IBuildEngine.LogMessageEvent\n LogMessageEvents.Add(e)\n End Sub\n\n Public Sub LogWarningEvent(e As BuildWarningEventArgs)\n Implements IBuildEngine.LogWarningEvent\n LogWarningEvents.Add(e)\n End Sub\n\n Public ReadOnly Property ProjectFileOfTaskNode As String\n Implements IBuildEngine.ProjectFileOfTaskNode\n Get\n Return \"fake ProjectFileOfTaskNode\"\n End Get\n End Property\n\nEnd Class\n</code></pre>\n\n<p><strong>C#</strong></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.Build.Framework;\n\npublic class FakeBuildEngine : IBuildEngine\n{\n\n // It's just a test helper so public fields is fine.\n public List&lt;BuildErrorEventArgs&gt; LogErrorEvents = new List&lt;BuildErrorEventArgs&gt;();\n\n public List&lt;BuildMessageEventArgs&gt; LogMessageEvents = \n new List&lt;BuildMessageEventArgs&gt;();\n\n public List&lt;CustomBuildEventArgs&gt; LogCustomEvents = \n new List&lt;CustomBuildEventArgs&gt;();\n\n public List&lt;BuildWarningEventArgs&gt; LogWarningEvents =\n new List&lt;BuildWarningEventArgs&gt;();\n\n public bool BuildProjectFile(\n string projectFileName, string[] targetNames, \n System.Collections.IDictionary globalProperties, \n System.Collections.IDictionary targetOutputs)\n {\n throw new NotImplementedException();\n }\n\n public int ColumnNumberOfTaskNode\n {\n get { return 0; }\n }\n\n public bool ContinueOnError\n {\n get\n {\n throw new NotImplementedException();\n }\n }\n\n public int LineNumberOfTaskNode\n {\n get { return 0; }\n }\n\n public void LogCustomEvent(CustomBuildEventArgs e)\n {\n LogCustomEvents.Add(e);\n }\n\n public void LogErrorEvent(BuildErrorEventArgs e)\n {\n LogErrorEvents.Add(e);\n }\n\n public void LogMessageEvent(BuildMessageEventArgs e)\n {\n LogMessageEvents.Add(e);\n }\n\n public void LogWarningEvent(BuildWarningEventArgs e)\n {\n LogWarningEvents.Add(e);\n }\n\n public string ProjectFileOfTaskNode\n {\n get { return \"fake ProjectFileOfTaskNode\"; }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 9559323, "author": "Raymond Hallquist", "author_id": 1248707, "author_profile": "https://Stackoverflow.com/users/1248707", "pm_score": 2, "selected": false, "text": "<p>I had the same problem. I solved it by stubbing the build engine. Like so (AppSettings is the MsBuild Task Name):</p>\n\n<pre><code>using Microsoft.Build.Framework;\nusing NUnit.Framework;\nusing Rhino.Mocks;\n\nnamespace NameSpace\n{\n [TestFixture]\n public class Tests\n {\n [Test]\n public void Test()\n {\n MockRepository mock = new MockRepository();\n IBuildEngine engine = mock.Stub&lt;IBuildEngine&gt;();\n\n var appSettings = new AppSettings();\n appSettings.BuildEngine = engine;\n appSettings.Execute();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 39265647, "author": "Jan Hlavsa", "author_id": 5922573, "author_profile": "https://Stackoverflow.com/users/5922573", "pm_score": 0, "selected": false, "text": "<p>In assembly <code>System.Web</code> in <code>namespace</code> <code>System.Web.Compilation</code> is a class <code>MockEngine</code> which implements <code>IBuildEngine</code> <code>interface</code> in a way which describes Tim Murphy. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30183/" ]
I have written a few MSBuild custom tasks that work well and are use in our CruiseControl.NET build process. I am modifying one, and wish to unit test it by calling the Task's Execute() method. However, if it encounters a line containing ``` Log.LogMessage("some message here"); ``` it throws an InvalidOperationException: *Task attempted to log before it was initialized. Message was...* Any suggestions? (In the past I have mostly unit-tested Internal static methods on my custom tasks to avoid such problems.)
You need to set the .BuildEngine property of the custom task you are calling. You can set it to the same BuildEngine your current task is using to include the output seamlessly. ``` Task myCustomTask = new CustomTask(); myCustomTask.BuildEngine = this.BuildEngine; myCustomTask.Execute(); ```
260,857
<p>I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?</p> <p>I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?</p>
[ { "answer_id": 260873, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 4, "selected": false, "text": "<p>The favicon is declared in the head tag with something like:</p>\n\n<pre><code>&lt;link rel=\"shortcut icon\" type=\"image/ico\" href=\"favicon.ico\"&gt;\n</code></pre>\n\n<p>You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.</p>\n" }, { "answer_id": 260876, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 10, "selected": true, "text": "<p>Why not?</p>\n<pre><code>var link = document.querySelector(&quot;link[rel~='icon']&quot;);\nif (!link) {\n link = document.createElement('link');\n link.rel = 'icon';\n document.getElementsByTagName('head')[0].appendChild(link);\n}\nlink.href = 'https://stackoverflow.com/favicon.ico';\n</code></pre>\n" }, { "answer_id": 260877, "author": "fserb", "author_id": 3702, "author_profile": "https://Stackoverflow.com/users/3702", "pm_score": 6, "selected": false, "text": "<p>If you have the following HTML snippet:</p>\n\n<pre><code>&lt;link id=\"favicon\" rel=\"shortcut icon\" type=\"image/png\" href=\"favicon.png\" /&gt;\n</code></pre>\n\n<p>You can change the favicon using Javascript by changing the HREF element on this link, for instance (assuming you're using JQuery):</p>\n\n<pre><code>$(\"#favicon\").attr(\"href\",\"favicon2.png\");\n</code></pre>\n\n<p>You can also create a Canvas element and set the HREF as a ToDataURL() of the canvas, much like the <a href=\"http://www.p01.org/releases/DHTML_contests/files/DEFENDER_of_the_favicon/\" rel=\"noreferrer\">Favicon Defender</a> does.</p>\n" }, { "answer_id": 260878, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 2, "selected": false, "text": "<p>According to <a href=\"http://en.wikipedia.org/wiki/Favicon\" rel=\"nofollow noreferrer\">WikiPedia</a>, you can specify which favicon file to load using the <code>link</code> tag in the <code>head</code> section, with a parameter of <code>rel=\"icon\"</code>. </p>\n\n<p>For example:</p>\n\n<pre><code> &lt;link rel=\"icon\" type=\"image/png\" href=\"/path/image.png\"&gt;\n</code></pre>\n\n<p>I imagine if you wanted to write some dynamic content for that call, you would have access to cookies so you could retrieve your session information that way and present appropriate content.</p>\n\n<p>You may fall foul of file formats (IE reportedly only supports it's .ICO format, whilst most everyone else supports PNG and GIF images) and possibly caching issues, both on the browser and through proxies. This would be because of the original itention of favicon, specifically, for marking a bookmark with a site's mini-logo.</p>\n" }, { "answer_id": 2919795, "author": "cryo", "author_id": 304185, "author_profile": "https://Stackoverflow.com/users/304185", "pm_score": 3, "selected": false, "text": "<p>Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an <code>iframe</code> etc in it) changes as far as I can tell:</p>\n\n<pre><code>var IE = navigator.userAgent.indexOf(\"MSIE\")!=-1\nvar favicon = {\n change: function(iconURL) {\n if (arguments.length == 2) {\n document.title = optionalDocTitle}\n this.addLink(iconURL, \"icon\")\n this.addLink(iconURL, \"shortcut icon\")\n\n // Google Chrome HACK - whenever an IFrame changes location \n // (even to about:blank), it updates the favicon for some reason\n // It doesn't work on Safari at all though :-(\n if (!IE) { // Disable the IE \"click\" sound\n if (!window.__IFrame) {\n __IFrame = document.createElement('iframe')\n var s = __IFrame.style\n s.height = s.width = s.left = s.top = s.border = 0\n s.position = 'absolute'\n s.visibility = 'hidden'\n document.body.appendChild(__IFrame)}\n __IFrame.src = 'about:blank'}},\n\n addLink: function(iconURL, relValue) {\n var link = document.createElement(\"link\")\n link.type = \"image/x-icon\"\n link.rel = relValue\n link.href = iconURL\n this.removeLinkIfExists(relValue)\n this.docHead.appendChild(link)},\n\n removeLinkIfExists: function(relValue) {\n var links = this.docHead.getElementsByTagName(\"link\");\n for (var i=0; i&lt;links.length; i++) {\n var link = links[i]\n if (link.type == \"image/x-icon\" &amp;&amp; link.rel == relValue) {\n this.docHead.removeChild(link)\n return}}}, // Assuming only one match at most.\n\n docHead: document.getElementsByTagName(\"head\")[0]}\n</code></pre>\n\n<p>To change favicons, just go <code>favicon.change(\"ICON URL\")</code> using the above.</p>\n\n<p>(credits to <a href=\"http://softwareas.com/dynamic-favicons\" rel=\"noreferrer\">http://softwareas.com/dynamic-favicons</a> for the code I based this on.)</p>\n" }, { "answer_id": 2995536, "author": "Mathias Bynens", "author_id": 96656, "author_profile": "https://Stackoverflow.com/users/96656", "pm_score": 7, "selected": false, "text": "<p>Here’s some code that works in Firefox, Opera, and Chrome (unlike every other answer posted here). Here is a different <a href=\"http://www.enhanceie.com/test/favicon/dynamic.htm\" rel=\"noreferrer\">demo of code that works in IE11</a> too. The following example might not work in Safari or Internet Explorer.</p>\n\n<pre><code>/*!\n * Dynamically changing favicons with JavaScript\n * Works in all A-grade browsers except Safari and Internet Explorer\n * Demo: http://mathiasbynens.be/demo/dynamic-favicons\n */\n\n// HTML5™, baby! http://mathiasbynens.be/notes/document-head\ndocument.head = document.head || document.getElementsByTagName('head')[0];\n\nfunction changeFavicon(src) {\n var link = document.createElement('link'),\n oldLink = document.getElementById('dynamic-favicon');\n link.id = 'dynamic-favicon';\n link.rel = 'shortcut icon';\n link.href = src;\n if (oldLink) {\n document.head.removeChild(oldLink);\n }\n document.head.appendChild(link);\n}\n</code></pre>\n\n<p>You would then use it as follows:</p>\n\n<pre><code>var btn = document.getElementsByTagName('button')[0];\nbtn.onclick = function() {\n changeFavicon('http://www.google.com/favicon.ico');\n};\n</code></pre>\n\n<p><a href=\"http://gist.github.com/428626\" rel=\"noreferrer\">Fork away</a> or <a href=\"http://mathiasbynens.be/demo/dynamic-favicons\" rel=\"noreferrer\">view a demo</a>.</p>\n" }, { "answer_id": 4784297, "author": "Greg", "author_id": 587766, "author_profile": "https://Stackoverflow.com/users/587766", "pm_score": 2, "selected": false, "text": "<p>The only way to make this work for IE is to set you web server to treat requests for *.ico to call your server side scripting language (PHP, .NET, etc). Also setup *.ico to redirect to a single script and have this script deliver the correct favicon file. I'm sure there is still going to be some interesting issues with cache if you want to be able to bounce back and forth in the same browser between different favicons.</p>\n" }, { "answer_id": 6475913, "author": "Dan", "author_id": 815015, "author_profile": "https://Stackoverflow.com/users/815015", "pm_score": 2, "selected": false, "text": "<p>I would use Greg's approach and make a custom handler for favicon.ico\nHere is a (simplified) handler that works:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Web;\n\nnamespace FaviconOverrider\n{\n public class IcoHandler : IHttpHandler\n {\n public void ProcessRequest(HttpContext context)\n {\n context.Response.ContentType = \"image/x-icon\";\n byte[] imageData = imageToByteArray(context.Server.MapPath(\"/ear.ico\"));\n context.Response.BinaryWrite(imageData);\n }\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n public byte[] imageToByteArray(string imagePath)\n {\n byte[] imageByteArray;\n using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))\n {\n imageByteArray = new byte[fs.Length];\n fs.Read(imageByteArray, 0, imageByteArray.Length);\n }\n\n return imageByteArray;\n }\n }\n}\n</code></pre>\n\n<p>Then you can use that handler in the httpHandlers section of the web config in IIS6 or use the 'Handler Mappings' feature in IIS7.</p>\n" }, { "answer_id": 24223694, "author": "vorillaz", "author_id": 910701, "author_profile": "https://Stackoverflow.com/users/910701", "pm_score": 6, "selected": false, "text": "<p><strong>jQuery Version:</strong></p>\n\n<pre><code>$(\"link[rel='shortcut icon']\").attr(\"href\", \"favicon.ico\");\n</code></pre>\n\n<p>or even better:</p>\n\n<pre><code>$(\"link[rel*='icon']\").attr(\"href\", \"favicon.ico\");\n</code></pre>\n\n<p><strong>Vanilla JS version:</strong></p>\n\n<pre><code>document.querySelector(\"link[rel='shortcut icon']\").href = \"favicon.ico\";\n\ndocument.querySelector(\"link[rel*='icon']\").href = \"favicon.ico\";\n</code></pre>\n" }, { "answer_id": 35960429, "author": "Michał Perłakowski", "author_id": 3853934, "author_profile": "https://Stackoverflow.com/users/3853934", "pm_score": 5, "selected": false, "text": "<p>A more modern approach:</p>\n\n<pre><code>const changeFavicon = link =&gt; {\n let $favicon = document.querySelector('link[rel=\"icon\"]')\n // If a &lt;link rel=\"icon\"&gt; element already exists,\n // change its href to the given link.\n if ($favicon !== null) {\n $favicon.href = link\n // Otherwise, create a new element and append it to &lt;head&gt;.\n } else {\n $favicon = document.createElement(\"link\")\n $favicon.rel = \"icon\"\n $favicon.href = link\n document.head.appendChild($favicon)\n }\n}\n</code></pre>\n\n<p>You can then use it like this:</p>\n\n<pre><code>changeFavicon(\"http://www.stackoverflow.com/favicon.ico\")\n</code></pre>\n" }, { "answer_id": 45302044, "author": "MemeDeveloper", "author_id": 661584, "author_profile": "https://Stackoverflow.com/users/661584", "pm_score": 2, "selected": false, "text": "<p><strong>Yes totally possible</strong></p>\n\n<ul>\n<li>Use a <strong>querystring</strong> after the favicon.ico (and other files links -\nsee answer link below) </li>\n<li>Simply make sure the server responds to the \"someUserId\" with\nthe correct image file (that could be <strong>static</strong> routing rules, or\n<strong>dynamic</strong> server side code).</li>\n</ul>\n\n<p>e.g. </p>\n\n<pre><code>&lt;link rel=\"shortcut icon\" href=\"/favicon.ico?userId=someUserId\"&gt;\n</code></pre>\n\n<p>Then <em>whatever server side language / framework</em> you use should easily be able to find the <em>file based on the userId</em> and serve it up in <em>response to that request</em>. </p>\n\n<p><strong>But to do favicons properly</strong> (its actually a <strong><em>really</strong> complex subject</em>) please see the answer here <a href=\"https://stackoverflow.com/a/45301651/661584\">https://stackoverflow.com/a/45301651/661584</a> </p>\n\n<p><strong>A lot lot easier</strong> than working out all the details yourself. </p>\n\n<p>Enjoy. </p>\n" }, { "answer_id": 47785522, "author": "Oscar Nevarez", "author_id": 1028871, "author_profile": "https://Stackoverflow.com/users/1028871", "pm_score": 2, "selected": false, "text": "<p>I use <a href=\"http://lab.ejci.net/favico.js/\" rel=\"nofollow noreferrer\">favico.js</a> in my projects.</p>\n\n<p>It allows to change the favicon to a range of predefined shapes and also custom ones.</p>\n\n<p>Internally it uses <code>canvas</code> for rendering and <code>base64</code> data URL for icon encoding.</p>\n\n<p>The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)</p>\n" }, { "answer_id": 52138377, "author": "Pepelegal", "author_id": 9542596, "author_profile": "https://Stackoverflow.com/users/9542596", "pm_score": 2, "selected": false, "text": "<p>There is a single line solution for those who use jQuery:</p>\n\n<pre><code>$(\"link[rel*='icon']\").prop(\"href\",'https://www.stackoverflow.com/favicon.ico');\n</code></pre>\n" }, { "answer_id": 53703704, "author": "max4ever", "author_id": 579646, "author_profile": "https://Stackoverflow.com/users/579646", "pm_score": 3, "selected": false, "text": "<p>Or if you want an emoticon :)</p>\n\n<pre><code>var canvas = document.createElement(\"canvas\");\ncanvas.height = 64;\ncanvas.width = 64;\n\nvar ctx = canvas.getContext(\"2d\");\nctx.font = \"64px serif\";\nctx.fillText(\"☠️\", 0, 64); \n\n$(\"link[rel*='icon']\").prop(\"href\", canvas.toDataURL());\n</code></pre>\n\n<p>Props to <a href=\"https://koddsson.com/posts/emoji-favicon/\" rel=\"noreferrer\">https://koddsson.com/posts/emoji-favicon/</a></p>\n" }, { "answer_id": 61786888, "author": "Ruskin", "author_id": 581414, "author_profile": "https://Stackoverflow.com/users/581414", "pm_score": 2, "selected": false, "text": "<p>I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it. </p>\n\n<p>Now that Chrome supports SVG favicons it makes it a whole lot easier.</p>\n\n<h2>Tampermonkey Script</h2>\n\n<p>Have a gander at <a href=\"https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f\" rel=\"nofollow noreferrer\">https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f</a> for a tampermonkey script that points to a demo site I chucked up at <a href=\"https://elliz.github.io/svg-favicon/\" rel=\"nofollow noreferrer\">https://elliz.github.io/svg-favicon/</a></p>\n\n<h2>Basic code</h2>\n\n<p>Adapted this from another answer ... could be improved but good enough for my needs.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>(function() {\n 'use strict';\n\n // play with https://codepen.io/elliz/full/ygvgay for getting it right\n // viewBox is required but does not need to be 16x16\n const svg = `\n &lt;svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\"&gt;\n &lt;circle cx=\"8\" cy=\"8\" r=\"7.2\" fill=\"gold\" stroke=\"#000\" stroke-width=\"1\" /&gt;\n &lt;circle cx=\"8\" cy=\"8\" r=\"3.1\" fill=\"#fff\" stroke=\"#000\" stroke-width=\"1\" /&gt;\n &lt;/svg&gt;\n `;\n\n var favicon_link_html = document.createElement('link');\n favicon_link_html.rel = 'icon';\n favicon_link_html.href = svgToDataUri(svg);\n favicon_link_html.type = 'image/svg+xml';\n\n try {\n let favicons = document.querySelectorAll('link[rel~=\"icon\"]');\n favicons.forEach(function(favicon) {\n favicon.parentNode.removeChild(favicon);\n });\n\n const head = document.getElementsByTagName('head')[0];\n head.insertBefore( favicon_link_html, head.firstChild );\n }\n catch(e) { }\n\n // functions -------------------------------\n function escapeRegExp(str) {\n return str.replace(/([.*+?^=!:${}()|\\[\\]\\/\\\\])/g, \"\\\\$1\");\n }\n\n function replaceAll(str, find, replace) {\n return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);\n }\n\n function svgToDataUri(svg) {\n // these may not all be needed - used to be for uri-encoded svg in old browsers\n var encoded = svg.replace(/\\s+/g, \" \")\n encoded = replaceAll(encoded, \"%\", \"%25\");\n encoded = replaceAll(encoded, \"&gt; &lt;\", \"&gt;&lt;\"); // normalise spaces elements\n encoded = replaceAll(encoded, \"; }\", \";}\"); // normalise spaces css\n encoded = replaceAll(encoded, \"&lt;\", \"%3c\");\n encoded = replaceAll(encoded, \"&gt;\", \"%3e\");\n encoded = replaceAll(encoded, \"\\\"\", \"'\"); // normalise quotes ... possible issues with quotes in &lt;text&gt;\n encoded = replaceAll(encoded, \"#\", \"%23\"); // needed for ie and firefox\n encoded = replaceAll(encoded, \"{\", \"%7b\");\n encoded = replaceAll(encoded, \"}\", \"%7d\");\n encoded = replaceAll(encoded, \"|\", \"%7c\");\n encoded = replaceAll(encoded, \"^\", \"%5e\");\n encoded = replaceAll(encoded, \"`\", \"%60\");\n encoded = replaceAll(encoded, \"@\", \"%40\");\n var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();\n return dataUri;\n }\n\n})();\n</code></pre>\n\n<p>Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.</p>\n" }, { "answer_id": 66503749, "author": "ubershmekel", "author_id": 177498, "author_profile": "https://Stackoverflow.com/users/177498", "pm_score": 4, "selected": false, "text": "<p>Here's a snippet to make the favicon be an emoji, or text. It works in the console when I'm at stackoverflow.</p>\n<pre><code>function changeFavicon(text) {\n const canvas = document.createElement('canvas');\n canvas.height = 64;\n canvas.width = 64;\n const ctx = canvas.getContext('2d');\n ctx.font = '64px serif';\n ctx.fillText(text, 0, 64);\n\n const link = document.createElement('link');\n const oldLinks = document.querySelectorAll('link[rel=&quot;shortcut icon&quot;]');\n oldLinks.forEach(e =&gt; e.parentNode.removeChild(e));\n link.id = 'dynamic-favicon';\n link.rel = 'shortcut icon';\n link.href = canvas.toDataURL();\n document.head.appendChild(link);\n}\n\nchangeFavicon('❤️');\n</code></pre>\n" }, { "answer_id": 68466511, "author": "yooneskh", "author_id": 5202815, "author_profile": "https://Stackoverflow.com/users/5202815", "pm_score": 2, "selected": false, "text": "<p>in most cases, favicon is declared like this.</p>\n<pre><code>&lt;link rel=&quot;icon&quot; href&quot;....&quot; /&gt;\n</code></pre>\n<p>This way you can attain reference to it with this.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const linkElement = document.querySelector('link[rel=icon]');\n</code></pre>\n<p>and you can change the picture with this</p>\n<pre><code>linkElement.href = 'url/to/any/picture/remote/or/relative';\n</code></pre>\n" }, { "answer_id": 70040223, "author": "Gonzalo Odiard", "author_id": 3969110, "author_profile": "https://Stackoverflow.com/users/3969110", "pm_score": 0, "selected": false, "text": "<p>Testing the proposed solutions on 2021 on Chrome, I found that some times the browser cache the favicon and do not show the change, even if the link was changed</p>\n<p>This code worked (similar to previous proposal but adds a random parameter to avoid caching)</p>\n<pre><code>let oldFavicon = document.getElementById('favicon')\nvar link = document.createElement('link')\nlink.id = 'favicon';\nlink.type = 'image/x-icon'\nlink.rel = 'icon';\nlink.href = new_favicon_url +'?=' + Math.random();\nif (oldFavicon) {\n document.head.removeChild(oldFavicon);\n}\ndocument.head.appendChild(link);\n</code></pre>\n<p>Copied from <a href=\"https://gist.github.com/mathiasbynens/428626#gistcomment-1809869\" rel=\"nofollow noreferrer\">https://gist.github.com/mathiasbynens/428626#gistcomment-1809869</a>\nin case that someone else have the same problem</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8114/" ]
I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before? I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?
Why not? ``` var link = document.querySelector("link[rel~='icon']"); if (!link) { link = document.createElement('link'); link.rel = 'icon'; document.getElementsByTagName('head')[0].appendChild(link); } link.href = 'https://stackoverflow.com/favicon.ico'; ```
260,915
<p>I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?</p> <p>For example:</p> <pre><code> typedef struct { char *str; } words; main() { words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in. } </code></pre> <p>Is this possible?</p> <hr> <p>I've researched this: <code>words* array = (words*)malloc(sizeof(words) * 100);</code></p> <p>I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as:</p> <pre><code> words* array = (words*)malloc(sizeof(words)); </code></pre> <p>However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment.</p> <hr> <p>I've made a little progress however:</p> <pre><code> typedef struct { char *str; } words; // Allocate first string. words x = (words) malloc(sizeof(words)); x[0].str = "john"; // Allocate second string. x=(words*) realloc(x, sizeof(words)); x[1].FirstName = "bob"; // printf second string. printf("%s", x[1].str); --&gt; This is working, it's printing out bob. free(x); // Free up memory. printf("%s", x[1].str); --&gt; Not working since its still printing out BOB even though I freed up memory. What is wrong? </code></pre> <p>I did some error checking and this is what I found. If after I free up memory for x I add the following:</p> <pre><code> x=NULL; </code></pre> <p>then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC??</p> <hr> <p>Thanks, I understand now due to:</p> <blockquote> <p>FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith</p> </blockquote> <h2>Update</h2> <p>I'm trying to modularize and put the creation of my array of structs in a function but nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work? My code is as follows:</p> <pre><code> # include &lt;stdio.h&gt; # include &lt;stdlib.h&gt; # include &lt;string.h&gt; # include &lt;ctype.h&gt; typedef struct { char *str1; char *str2; } words; void LoadData(words *, int *); main() { words *x; int num; LoadData(&amp;x, &amp;num); printf("%s %s", x[0].str1, x[0].str2); printf("%s %s", x[1].str1, x[1].str2); getch(); }// void LoadData(words *x, int * num) { x = (words*) malloc(sizeof(words)); x[0].str1 = "johnnie\0"; x[0].str2 = "krapson\0"; x = (words*) realloc(x, sizeof(words)*2); x[1].str1 = "bob\0"; x[1].str2 = "marley\0"; *num=*num+1; }// </code></pre> <p>This simple test code is crashing and I have no idea why. Where is the bug?</p>
[ { "answer_id": 260932, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 4, "selected": false, "text": "<p>If you want to dynamically allocate arrays, you can use <a href=\"http://en.wikipedia.org/wiki/Malloc\" rel=\"noreferrer\"><code>malloc</code></a> from <code>stdlib.h</code>.</p>\n\n<p>If you want to allocate an array of 100 elements using your <code>words</code> struct, try the following:</p>\n\n<pre><code>words* array = (words*)malloc(sizeof(words) * 100);\n</code></pre>\n\n<p>The size of the memory that you want to allocate is passed into <code>malloc</code> and then it will return a pointer of type <code>void</code> (<code>void*</code>). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is <code>words*</code>.</p>\n\n<p>The <code>sizeof</code> keyword is used here to find out the size of the <code>words</code> struct, then that size is multiplied by the number of elements you want to allocate.</p>\n\n<p>Once you are done, be sure to use <code>free()</code> to free up the heap memory you used in order to prevent <a href=\"http://en.wikipedia.org/wiki/Memory_leak\" rel=\"noreferrer\">memory leaks</a>:</p>\n\n<pre><code>free(array);\n</code></pre>\n\n<p>If you want to change the size of the allocated array, you can try to use <code>realloc</code> as others have mentioned, but keep in mind that if you do many <code>realloc</code>s you may end up <a href=\"http://en.wikipedia.org/wiki/Fragmentation_(computer)#External_fragmentation\" rel=\"noreferrer\">fragmenting the memory</a>. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many <code>realloc</code>s.</p>\n" }, { "answer_id": 260950, "author": "ob1", "author_id": 3961, "author_profile": "https://Stackoverflow.com/users/3961", "pm_score": 0, "selected": false, "text": "<p>If you want to grow the array dynamically, you should use malloc() to dynamically allocate some fixed amount of memory, and then use realloc() whenever you run out. A common technique is to use an exponential growth function such that you allocate some small fixed amount and then make the array grow by duplicating the allocated amount. </p>\n\n<p>Some example code would be:</p>\n\n<pre><code>size = 64; i = 0;\nx = malloc(sizeof(words)*size); /* enough space for 64 words */\nwhile (read_words()) {\n if (++i &gt; size) {\n size *= 2;\n x = realloc(sizeof(words) * size);\n }\n}\n/* done with x */\nfree(x);\n</code></pre>\n" }, { "answer_id": 260952, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>In C++, use a <a href=\"http://www.cplusplus.com/reference/stl/vector/\" rel=\"nofollow noreferrer\">vector</a>. It's like an array but you can easily add and remove elements and it will take care of allocating and deallocating memory for you.</p>\n\n<p>I know the title of the question says C, but you tagged your question with C and C++...</p>\n" }, { "answer_id": 260953, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 2, "selected": false, "text": "<p>Another option for you is a <a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"nofollow noreferrer\">linked list</a>. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.</p>\n" }, { "answer_id": 260981, "author": "Tom", "author_id": 8969, "author_profile": "https://Stackoverflow.com/users/8969", "pm_score": 5, "selected": false, "text": "<p>You've tagged this as C++ as well as C.</p>\n\n<p>If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;vector&gt;\n\ntypedef std::vector&lt;char*&gt; words;\n\nint main(int argc, char** argv) {\n\n words myWords;\n\n myWords.push_back(\"Hello\");\n myWords.push_back(\"World\");\n\n words::iterator iter;\n for (iter = myWords.begin(); iter != myWords.end(); ++iter) {\n printf(\"%s \", *iter);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ntypedef struct s_words {\n char* str;\n struct s_words* next;\n} words;\n\nwords* create_words(char* word) {\n words* newWords = malloc(sizeof(words));\n if (NULL != newWords){\n newWords-&gt;str = word;\n newWords-&gt;next = NULL;\n }\n return newWords;\n}\n\nvoid delete_words(words* oldWords) {\n if (NULL != oldWords-&gt;next) {\n delete_words(oldWords-&gt;next);\n }\n free(oldWords);\n}\n\nwords* add_word(words* wordList, char* word) {\n words* newWords = create_words(word);\n if (NULL != newWords) {\n newWords-&gt;next = wordList;\n }\n return newWords;\n}\n\nint main(int argc, char** argv) {\n\n words* myWords = create_words(\"Hello\");\n myWords = add_word(myWords, \"World\");\n\n words* iter;\n for (iter = myWords; NULL != iter; iter = iter-&gt;next) {\n printf(\"%s \", iter-&gt;str);\n }\n delete_words(myWords);\n return 0;\n}\n</code></pre>\n\n<p>Yikes, sorry for the worlds longest answer. So WRT to the \"don't want to use a linked list comment\":</p>\n\n<pre><code>#include &lt;stdio.h&gt; \n#include &lt;stdlib.h&gt;\n\ntypedef struct {\n char** words;\n size_t nWords;\n size_t size;\n size_t block_size;\n} word_list;\n\nword_list* create_word_list(size_t block_size) {\n word_list* pWordList = malloc(sizeof(word_list));\n if (NULL != pWordList) {\n pWordList-&gt;nWords = 0;\n pWordList-&gt;size = block_size;\n pWordList-&gt;block_size = block_size;\n pWordList-&gt;words = malloc(sizeof(char*)*block_size);\n if (NULL == pWordList-&gt;words) {\n free(pWordList);\n return NULL; \n }\n }\n return pWordList;\n}\n\nvoid delete_word_list(word_list* pWordList) {\n free(pWordList-&gt;words);\n free(pWordList);\n}\n\nint add_word_to_word_list(word_list* pWordList, char* word) {\n size_t nWords = pWordList-&gt;nWords;\n if (nWords &gt;= pWordList-&gt;size) {\n size_t newSize = pWordList-&gt;size + pWordList-&gt;block_size;\n void* newWords = realloc(pWordList-&gt;words, sizeof(char*)*newSize); \n if (NULL == newWords) {\n return 0;\n } else { \n pWordList-&gt;size = newSize;\n pWordList-&gt;words = (char**)newWords;\n }\n\n }\n\n pWordList-&gt;words[nWords] = word;\n ++pWordList-&gt;nWords;\n\n\n return 1;\n}\n\nchar** word_list_start(word_list* pWordList) {\n return pWordList-&gt;words;\n}\n\nchar** word_list_end(word_list* pWordList) {\n return &amp;pWordList-&gt;words[pWordList-&gt;nWords];\n}\n\nint main(int argc, char** argv) {\n\n word_list* myWords = create_word_list(2);\n add_word_to_word_list(myWords, \"Hello\");\n add_word_to_word_list(myWords, \"World\");\n add_word_to_word_list(myWords, \"Goodbye\");\n\n char** iter;\n for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) {\n printf(\"%s \", *iter);\n }\n\n delete_word_list(myWords);\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 261019, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 3, "selected": false, "text": "<p>This looks like an academic exercise which unfortunately makes it harder since you can't use C++. Basically you have to manage some of the overhead for the allocation and keep track how much memory has been allocated if you need to resize it later. This is where the C++ standard library shines.</p>\n\n<p>For your example, the following code allocates the memory and later resizes it:</p>\n\n<pre><code>// initial size\nint count = 100;\nwords *testWords = (words*) malloc(count * sizeof(words));\n// resize the array\ncount = 76;\ntestWords = (words*) realloc(testWords, count* sizeof(words));\n</code></pre>\n\n<p>Keep in mind, in your example you are just allocating a pointer to a char and you still need to allocate the string itself and more importantly to free it at the end. So this code allocates 100 pointers to char and then resizes it to 76, but does not allocate the strings themselves.</p>\n\n<p>I have a suspicion that you actually want to allocate the number of characters in a string which is very similar to the above, but change word to char.</p>\n\n<p>EDIT: Also keep in mind it makes <strong>a lot of sense</strong> to create functions to perform common tasks and enforce consistency so you don't copy code everywhere. For example, you might have a) allocate the struct, b) assign values to the struct, and c) free the struct. So you might have:</p>\n\n<pre><code>// Allocate a words struct\nwords* CreateWords(int size);\n// Assign a value\nvoid AssignWord(word* dest, char* str);\n// Clear a words structs (and possibly internal storage)\nvoid FreeWords(words* w);\n</code></pre>\n\n<p>EDIT: As far as resizing the structs, it is identical to resizing the char array. However the difference is if you make the struct array bigger, you should probably initialize the new array items to NULL. Likewise, if you make the struct array smaller, you need to cleanup before removing the items -- that is free items that have been allocated (and only the allocated items) before you resize the struct array. This is the primary reason I suggested creating helper functions to help manage this.</p>\n\n<pre><code>// Resize words (must know original and new size if shrinking\n// if you need to free internal storage first)\nvoid ResizeWords(words* w, size_t oldsize, size_t newsize);\n</code></pre>\n" }, { "answer_id": 266248, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Your code in the last update should not compile, much less run. You're passing &amp;x to LoadData. &amp;x has the type of **words, but LoadData expects words* . Of course it crashes when you call realloc on a pointer that's pointing into stack.</p>\n\n<p>The way to fix it is to change LoadData to accept words** . Thi sway, you can actually modify the pointer in main(). For example, realloc call would look like</p>\n\n<pre><code>*x = (words*) realloc(*x, sizeof(words)*2);\n</code></pre>\n\n<p>It's the same principlae as in \"num\" being int* rather than int.</p>\n\n<p>Besides this, you need to really figure out how the strings in words ere stored. Assigning a const string to char * (as in str2 = \"marley\\0\") is permitted, but it's rarely the right solution, even in C.</p>\n\n<p>Another point: non need to have \"marley\\0\" unless you really need two 0s at the end of string. Compiler adds 0 tho the end of every string literal.</p>\n" }, { "answer_id": 6686206, "author": "Adrian", "author_id": 843590, "author_profile": "https://Stackoverflow.com/users/843590", "pm_score": 0, "selected": false, "text": "<p>Here is how I would do it in C++</p>\n\n<pre><code>size_t size = 500;\nchar* dynamicAllocatedString = new char[ size ];\n</code></pre>\n\n<p>Use same principal for any struct or c++ class.</p>\n" }, { "answer_id": 8011025, "author": "zhanwu", "author_id": 244031, "author_profile": "https://Stackoverflow.com/users/244031", "pm_score": 1, "selected": false, "text": "<p>For the test code: if you want to modify a pointer in a function, you should pass a \"pointer to pointer\" to the function. Corrected code is as follows:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;ctype.h&gt;\n\ntypedef struct\n{\n char *str1;\n char *str2;\n} words;\n\nvoid LoadData(words**, int*);\n\nmain()\n{\n words **x;\n int num;\n\n LoadData(x, &amp;num);\n\n printf(\"%s %s\\n\", (*x[0]).str1, (*x[0]).str2);\n printf(\"%s %s\\n\", (*x[1]).str1, (*x[1]).str2);\n}\n\nvoid LoadData(words **x, int *num)\n{\n *x = (words*) malloc(sizeof(words));\n\n (*x[0]).str1 = \"johnnie\\0\";\n (*x[0]).str2 = \"krapson\\0\";\n\n *x = (words*) realloc(*x, sizeof(words) * 2);\n (*x[1]).str1 = \"bob\\0\";\n (*x[1]).str2 = \"marley\\0\";\n\n *num = *num + 1;\n}\n</code></pre>\n" }, { "answer_id": 50156730, "author": "Arul Girish", "author_id": 9735737, "author_profile": "https://Stackoverflow.com/users/9735737", "pm_score": 1, "selected": false, "text": "<p>Every coder need to simplify their code to make it easily understood....even for beginners.</p>\n\n<p>So <strong>array of structures using dynamically</strong> is easy, if you understand the concepts.</p>\n\n<pre><code>// Dynamically sized array of structures\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nstruct book \n{\n char name[20];\n int p;\n}; //Declaring book structure\n\nint main () \n{\n int n, i; \n\n struct book *b; // Initializing pointer to a structure\n scanf (\"%d\\n\", &amp;n);\n\n b = (struct book *) calloc (n, sizeof (struct book)); //Creating memory for array of structures dynamically\n\n for (i = 0; i &lt; n; i++)\n {\n scanf (\"%s %d\\n\", (b + i)-&gt;name, &amp;(b + i)-&gt;p); //Getting values for array of structures (no error check)\n } \n\n for (i = 0; i &lt; n; i++)\n {\n printf (\"%s %d\\t\", (b + i)-&gt;name, (b + i)-&gt;p); //Printing values in array of structures\n }\n\n scanf (\"%d\\n\", &amp;n); //Get array size to re-allocate \n b = (struct book *) realloc (b, n * sizeof (struct book)); //change the size of an array using realloc function\n printf (\"\\n\");\n\n for (i = 0; i &lt; n; i++)\n {\n printf (\"%s %d\\t\", (b + i)-&gt;name, (b + i)-&gt;p); //Printing values in array of structures\n }\n\n return 0;\n} \n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31274/" ]
I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger? For example: ``` typedef struct { char *str; } words; main() { words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in. } ``` Is this possible? --- I've researched this: `words* array = (words*)malloc(sizeof(words) * 100);` I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as: ``` words* array = (words*)malloc(sizeof(words)); ``` However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment. --- I've made a little progress however: ``` typedef struct { char *str; } words; // Allocate first string. words x = (words) malloc(sizeof(words)); x[0].str = "john"; // Allocate second string. x=(words*) realloc(x, sizeof(words)); x[1].FirstName = "bob"; // printf second string. printf("%s", x[1].str); --> This is working, it's printing out bob. free(x); // Free up memory. printf("%s", x[1].str); --> Not working since its still printing out BOB even though I freed up memory. What is wrong? ``` I did some error checking and this is what I found. If after I free up memory for x I add the following: ``` x=NULL; ``` then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC?? --- Thanks, I understand now due to: > > FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith > > > Update ------ I'm trying to modularize and put the creation of my array of structs in a function but nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work? My code is as follows: ``` # include <stdio.h> # include <stdlib.h> # include <string.h> # include <ctype.h> typedef struct { char *str1; char *str2; } words; void LoadData(words *, int *); main() { words *x; int num; LoadData(&x, &num); printf("%s %s", x[0].str1, x[0].str2); printf("%s %s", x[1].str1, x[1].str2); getch(); }// void LoadData(words *x, int * num) { x = (words*) malloc(sizeof(words)); x[0].str1 = "johnnie\0"; x[0].str2 = "krapson\0"; x = (words*) realloc(x, sizeof(words)*2); x[1].str1 = "bob\0"; x[1].str2 = "marley\0"; *num=*num+1; }// ``` This simple test code is crashing and I have no idea why. Where is the bug?
You've tagged this as C++ as well as C. If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects. ``` #include <stdio.h> #include <vector> typedef std::vector<char*> words; int main(int argc, char** argv) { words myWords; myWords.push_back("Hello"); myWords.push_back("World"); words::iterator iter; for (iter = myWords.begin(); iter != myWords.end(); ++iter) { printf("%s ", *iter); } return 0; } ``` If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily. ``` #include <stdio.h> #include <stdlib.h> typedef struct s_words { char* str; struct s_words* next; } words; words* create_words(char* word) { words* newWords = malloc(sizeof(words)); if (NULL != newWords){ newWords->str = word; newWords->next = NULL; } return newWords; } void delete_words(words* oldWords) { if (NULL != oldWords->next) { delete_words(oldWords->next); } free(oldWords); } words* add_word(words* wordList, char* word) { words* newWords = create_words(word); if (NULL != newWords) { newWords->next = wordList; } return newWords; } int main(int argc, char** argv) { words* myWords = create_words("Hello"); myWords = add_word(myWords, "World"); words* iter; for (iter = myWords; NULL != iter; iter = iter->next) { printf("%s ", iter->str); } delete_words(myWords); return 0; } ``` Yikes, sorry for the worlds longest answer. So WRT to the "don't want to use a linked list comment": ``` #include <stdio.h> #include <stdlib.h> typedef struct { char** words; size_t nWords; size_t size; size_t block_size; } word_list; word_list* create_word_list(size_t block_size) { word_list* pWordList = malloc(sizeof(word_list)); if (NULL != pWordList) { pWordList->nWords = 0; pWordList->size = block_size; pWordList->block_size = block_size; pWordList->words = malloc(sizeof(char*)*block_size); if (NULL == pWordList->words) { free(pWordList); return NULL; } } return pWordList; } void delete_word_list(word_list* pWordList) { free(pWordList->words); free(pWordList); } int add_word_to_word_list(word_list* pWordList, char* word) { size_t nWords = pWordList->nWords; if (nWords >= pWordList->size) { size_t newSize = pWordList->size + pWordList->block_size; void* newWords = realloc(pWordList->words, sizeof(char*)*newSize); if (NULL == newWords) { return 0; } else { pWordList->size = newSize; pWordList->words = (char**)newWords; } } pWordList->words[nWords] = word; ++pWordList->nWords; return 1; } char** word_list_start(word_list* pWordList) { return pWordList->words; } char** word_list_end(word_list* pWordList) { return &pWordList->words[pWordList->nWords]; } int main(int argc, char** argv) { word_list* myWords = create_word_list(2); add_word_to_word_list(myWords, "Hello"); add_word_to_word_list(myWords, "World"); add_word_to_word_list(myWords, "Goodbye"); char** iter; for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) { printf("%s ", *iter); } delete_word_list(myWords); return 0; } ```
260,945
<p>This should be easy, but I'm having a hard time finding the easiest solution.</p> <p>I need an <code>NSString</code> that is equal to another string concatenated with itself a given number of times.</p> <p>For a better explanation, consider the following python example:</p> <pre><code>&gt;&gt; original = "abc" "abc" &gt;&gt; times = 2 2 &gt;&gt; result = original * times "abcabc" </code></pre> <p>Any hints?</p> <hr> <p>EDIT:</p> <p>I was going to post a solution similar to the one by <a href="https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times#260969">Mike McMaster's answer</a>, after looking at this implementation from the OmniFrameworks:</p> <pre><code>// returns a string consisting of 'aLenght' spaces + (NSString *)spacesOfLength:(unsigned int)aLength; { static NSMutableString *spaces = nil; static NSLock *spacesLock; static unsigned int spacesLength; if (!spaces) { spaces = [@" " mutableCopy]; spacesLength = [spaces length]; spacesLock = [[NSLock alloc] init]; } if (spacesLength &lt; aLength) { [spacesLock lock]; while (spacesLength &lt; aLength) { [spaces appendString:spaces]; spacesLength += spacesLength; } [spacesLock unlock]; } return [spaces substringToIndex:aLength]; } </code></pre> <p>Code reproduced from the file:</p> <pre><code>Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m </code></pre> <p>on the OpenExtensions framework from the <a href="http://www.omnigroup.com/developer/" rel="noreferrer">Omni Frameworks</a> by <a href="http://www.omnigroup.com/" rel="noreferrer">The Omni Group</a>.</p>
[ { "answer_id": 260969, "author": "Mike McMaster", "author_id": 544, "author_profile": "https://Stackoverflow.com/users/544", "pm_score": 3, "selected": false, "text": "<pre><code>NSString *original = @\"abc\";\nint times = 2;\n\n// Capacity does not limit the length, it's just an initial capacity\nNSMutableString *result = [NSMutableString stringWithCapacity:[original length] * times]; \n\nint i;\nfor (i = 0; i &lt; times; i++)\n [result appendString:original];\n\nNSLog(@\"result: %@\", result); // prints \"abcabc\"\n</code></pre>\n" }, { "answer_id": 260979, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 1, "selected": false, "text": "<p>If you're using Cocoa in Python, then you can just do that, as PyObjC imbues <code>NSString</code> with all of the Python <code>unicode</code> class's abilities.</p>\n\n<p>Otherwise, there are two ways.</p>\n\n<p>One is to create an array with the same string in it <code>n</code> times, and use <code>componentsJoinedByString:</code>. Something like this:</p>\n\n<pre><code>NSMutableArray *repetitions = [NSMutableArray arrayWithCapacity:n];\nfor (NSUInteger i = 0UL; i &lt; n; ++i)\n [repetitions addObject:inputString];\noutputString = [repetitions componentsJoinedByString:@\"\"];\n</code></pre>\n\n<p>The other way would be to start with an empty <code>NSMutableString</code> and append the string to it <code>n</code> times, like this:</p>\n\n<pre><code>NSMutableString *temp = [NSMutableString stringWithCapacity:[inputString length] * n];\nfor (NSUInteger i = 0UL; i &lt; n; ++i)\n [temp appendString:inputString];\noutputString = [NSString stringWithString:temp];\n</code></pre>\n\n<p>You may be able to cut out the <code>stringWithString:</code> call if it's OK for you to return a mutable string here. Otherwise, you probably should return an immutable string, and the <code>stringWithString:</code> message here means you have two copies of the string in memory.</p>\n\n<p>Therefore, I recommend the <code>componentsJoinedByString:</code> solution.</p>\n\n<p>[Edit: Borrowed idea to use <code>…WithCapacity:</code> methods from <a href=\"https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times#260969\">Mike McMaster's answer</a>.]</p>\n" }, { "answer_id": 1181088, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>For performance, you could drop into C with something like this:</p>\n\n<pre><code>+ (NSString*)stringWithRepeatCharacter:(char)character times:(unsigned int)repetitions;\n{\n char repeatString[repetitions + 1];\n memset(repeatString, character, repetitions);\n\n // Set terminating null\n repeatString[repetitions] = 0;\n\n return [NSString stringWithCString:repeatString];\n}\n</code></pre>\n\n<p>This could be written as a category extension on the NSString class. There are probably some checks that should be thrown in there, but this is the straight forward gist of it.</p>\n" }, { "answer_id": 1181162, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The first method above is for a single character. This one is for a string of characters. It could be used for a single character too but has more overhead.</p>\n\n<pre><code>+ (NSString*)stringWithRepeatString:(char*)characters times:(unsigned int)repetitions;\n{\n unsigned int stringLength = strlen(characters);\n unsigned int repeatStringLength = stringLength * repetitions + 1;\n\n char repeatString[repeatStringLength];\n\n for (unsigned int i = 0; i &lt; repetitions; i++) {\n unsigned int pointerPosition = i * repetitions;\n memcpy(repeatString + pointerPosition, characters, stringLength); \n }\n\n // Set terminating null\n repeatString[repeatStringLength - 1] = 0;\n\n return [NSString stringWithCString:repeatString];\n}\n</code></pre>\n" }, { "answer_id": 4608137, "author": "tig", "author_id": 96823, "author_profile": "https://Stackoverflow.com/users/96823", "pm_score": 8, "selected": true, "text": "<p>There is a method called <code>stringByPaddingToLength:withString:startingAtIndex:</code>:</p>\n\n<pre><code>[@\"\" stringByPaddingToLength:100 withString: @\"abc\" startingAtIndex:0]\n</code></pre>\n\n<p>Note that if you want 3 abc's, than use 9 (<code>3 * [@\"abc\" length]</code>) or create category like this:</p>\n\n<pre><code>@interface NSString (Repeat)\n\n- (NSString *)repeatTimes:(NSUInteger)times;\n\n@end\n\n@implementation NSString (Repeat)\n\n- (NSString *)repeatTimes:(NSUInteger)times {\n return [@\"\" stringByPaddingToLength:times * [self length] withString:self startingAtIndex:0];\n}\n\n@end\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2954/" ]
This should be easy, but I'm having a hard time finding the easiest solution. I need an `NSString` that is equal to another string concatenated with itself a given number of times. For a better explanation, consider the following python example: ``` >> original = "abc" "abc" >> times = 2 2 >> result = original * times "abcabc" ``` Any hints? --- EDIT: I was going to post a solution similar to the one by [Mike McMaster's answer](https://stackoverflow.com/questions/260945/create-nsstring-by-repeating-another-string-a-given-number-of-times#260969), after looking at this implementation from the OmniFrameworks: ``` // returns a string consisting of 'aLenght' spaces + (NSString *)spacesOfLength:(unsigned int)aLength; { static NSMutableString *spaces = nil; static NSLock *spacesLock; static unsigned int spacesLength; if (!spaces) { spaces = [@" " mutableCopy]; spacesLength = [spaces length]; spacesLock = [[NSLock alloc] init]; } if (spacesLength < aLength) { [spacesLock lock]; while (spacesLength < aLength) { [spaces appendString:spaces]; spacesLength += spacesLength; } [spacesLock unlock]; } return [spaces substringToIndex:aLength]; } ``` Code reproduced from the file: ``` Frameworks/OmniFoundation/OpenStepExtensions.subproj/NSString-OFExtensions.m ``` on the OpenExtensions framework from the [Omni Frameworks](http://www.omnigroup.com/developer/) by [The Omni Group](http://www.omnigroup.com/).
There is a method called `stringByPaddingToLength:withString:startingAtIndex:`: ``` [@"" stringByPaddingToLength:100 withString: @"abc" startingAtIndex:0] ``` Note that if you want 3 abc's, than use 9 (`3 * [@"abc" length]`) or create category like this: ``` @interface NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times; @end @implementation NSString (Repeat) - (NSString *)repeatTimes:(NSUInteger)times { return [@"" stringByPaddingToLength:times * [self length] withString:self startingAtIndex:0]; } @end ```
260,962
<p>To trim the leading spaces we are using strmove. But we were advised to use strlmove instead of strmove. I have read and used strlcpy and strlcat. Whether strlmove does the similar functionality and what all are its advantages?</p> <p>Edit 1: Thank you Mike B and Chris Young. This is how we use strlcpy.</p> <pre><code>size_t strlcpy(char *dst, const char *src, size_t size) { strncpy(dst, src, size - 1); dst[size - 1] = '\0'; return(strlen(src)); } </code></pre> <p>So I was just thinking of using strlmove() also in the same way. I want to confirm whether any specifications is defined regarding the implementation of strlmove(). I know this is one of the best place i can ask.</p> <p>Edit 2: strlmove() is implemented the same way as strlcpy() and strlcat() using memmove().</p> <pre><code>size_t strlmove(char *dst, const char *src, size_t size) { //Error if the size is 0 //If src length is greater than size; // memmove(dst, src, size-1) and dst[size] = \0; //Otherwise // memmove(dst, src, length(src)); return source len; } </code></pre> <p>Appreciate the help and support provided.</p> <p>Thanks, Mathew Liju</p>
[ { "answer_id": 260972, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "<p>strmove, strlmove, strlcpy, strlcat are all <strong>not</strong> standard C functions, so I can't comment on what they do without knowing which specific non-standard library you're using. Standard C provides strcpy, strcat, strncat, strncpy, memmove, memcpy, etc.</p>\n\n<p>It makes sense to use strncpy over strcpy for safety if you don't know the source string will fit inside the destination buffer. However, strncpy has a major performance issue in that it <strong>always</strong> writes the amount of bytes specified for the size. That is:</p>\n\n<pre><code>char buf[4096];\nstrncpy(buf, \"Hello\", sizeof buf);\n</code></pre>\n\n<p>will write 'H', 'e', 'l', 'l', 'o' and fill the remaining 4091 bytes of buf with '\\0'. Another thing to be aware of with strncpy is that it will not null-terminate the string if the size parameter is smaller than the source string length plus its null. For example:</p>\n\n<pre><code>char buf[5];\nstrncpy(buf, \"Hello\", sizeof buf);\n</code></pre>\n\n<p>will write 'H', 'e', 'l', 'l', 'o' into buf and it will not be null-terminated.</p>\n" }, { "answer_id": 260998, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": true, "text": "<p>As <a href=\"https://stackoverflow.com/questions/260962/what-is-the-advantage-of-strlmove-vs-strmove-in-c#260972\">Chris Young mentions</a>, these routines are not standard (or as far as I known in wide, common use) so I can't be 100% certain with more specifics, but:</p>\n\n<p>Typically the <code>strl()</code> variations of <code>str()</code> routines take an additional parameter that indicates the size of the destination buffer. The routine guarantees that it will not write data past the end of the buffer (since it knows the size). Usually <code>strl()</code> functions will also guarantee that they will place a terminating null character at the end of the string or at the end of the buffer (potentially truncating any string created there) so that you are also guaranteed to have a terminated string that will be generally OK to pass to other <code>str()</code> functions. Note that if the length of the buffer is specified as 0 (zero) the function will <em>not</em> place a terminating null character (as there's no room in the buffer for anything).</p>\n\n<p>In my opinion, it's nearly always better to use a <code>strl()</code> (or <code>strn()</code>) function in preference to the corresponding <code>str()</code> routine to prevent buffer overruns.</p>\n" }, { "answer_id": 261174, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 1, "selected": false, "text": "<p>Quick Google search reveals that the only mentions of strlmove function is in stackoverflow :). So it's probably not very common function.<br>\nBut if we assume that this function is close by nature to <a href=\"http://www.manpagez.com/man/3/strlcpy/\" rel=\"nofollow noreferrer\">strlcpy</a>, this function is differ from <a href=\"http://sancho.ccd.uniroma2.it/cgi-bin/man/man2html?strmove+3\" rel=\"nofollow noreferrer\">strmove</a> by using size parameter to move limited amount of bytes and <strong>make the destination string NULL terminated</strong>. </p>\n" }, { "answer_id": 263125, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 0, "selected": false, "text": "<p>There is one big difference between strncpy and strlcpy at least in the version of Theo de Raadt, that you missed in your implementation. If the length of the given string is less than the buffer size, then strncpy pads the rest of the buffer with null bytes. This might be only a minor difference in many cases, but since many c programmer tend to use extra large buffers to be on the safe site, it can make a difference.\n<pre><code>\nstrncpy(buffer, \"bla\", 1024);\n</pre></code></p>\n\n<p>will write 1021 '\\0' into the buffer although one would be enough. strlcpy only writes one '\\0'.</p>\n" }, { "answer_id": 263680, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 0, "selected": false, "text": "<p>As Chris said, the functions you are using currently are non-std. ... even worse is that they are still highly inefficient and are still prone to errors. You chould be able to easily create a couple of APIs that use memcpy/memmove and take (char *)s which will work everywhere and likely be faster than the non-std. varients you are currently using.</p>\n\n<p>However if you want someone else to do the heavy lifting, and get safety/usability for free, you could look at something like <a href=\"http://www.and.org/ustr\" rel=\"nofollow noreferrer\">ustr</a> ... which is meant to be easy to integrate, is std. C, safe, fast, and can deal with constant/automatic/utf8/dynamic strings. There are also other options.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18657/" ]
To trim the leading spaces we are using strmove. But we were advised to use strlmove instead of strmove. I have read and used strlcpy and strlcat. Whether strlmove does the similar functionality and what all are its advantages? Edit 1: Thank you Mike B and Chris Young. This is how we use strlcpy. ``` size_t strlcpy(char *dst, const char *src, size_t size) { strncpy(dst, src, size - 1); dst[size - 1] = '\0'; return(strlen(src)); } ``` So I was just thinking of using strlmove() also in the same way. I want to confirm whether any specifications is defined regarding the implementation of strlmove(). I know this is one of the best place i can ask. Edit 2: strlmove() is implemented the same way as strlcpy() and strlcat() using memmove(). ``` size_t strlmove(char *dst, const char *src, size_t size) { //Error if the size is 0 //If src length is greater than size; // memmove(dst, src, size-1) and dst[size] = \0; //Otherwise // memmove(dst, src, length(src)); return source len; } ``` Appreciate the help and support provided. Thanks, Mathew Liju
As [Chris Young mentions](https://stackoverflow.com/questions/260962/what-is-the-advantage-of-strlmove-vs-strmove-in-c#260972), these routines are not standard (or as far as I known in wide, common use) so I can't be 100% certain with more specifics, but: Typically the `strl()` variations of `str()` routines take an additional parameter that indicates the size of the destination buffer. The routine guarantees that it will not write data past the end of the buffer (since it knows the size). Usually `strl()` functions will also guarantee that they will place a terminating null character at the end of the string or at the end of the buffer (potentially truncating any string created there) so that you are also guaranteed to have a terminated string that will be generally OK to pass to other `str()` functions. Note that if the length of the buffer is specified as 0 (zero) the function will *not* place a terminating null character (as there's no room in the buffer for anything). In my opinion, it's nearly always better to use a `strl()` (or `strn()`) function in preference to the corresponding `str()` routine to prevent buffer overruns.
260,986
<p>I have a text file which contains some data. I am trying to search for EA in <strong>ID column only</strong> and prints the whole row. But the code recognize all EA and prints all rows. What code I should add to satisfy the condition? Thanks Again:-)!</p> <p>DATA: <br> Name Age ID <br> ---------------------<br> KRISTE,22,<strong>EA</strong>2008<br> J<strong>EA</strong>N,21,ES4567<br> JAK,45,<strong>EA</strong>2008<br><br> The code prints:<br> KRISTE,22,<strong>EA</strong>2008<br> J<strong>EA</strong>N,21,ES4567<br> JAK,45,<strong>EA</strong>2008<br></p> <p>Desired output:<br> KRIS,22,<strong>EA</strong>2008<br> Kane,45,<strong>EA</strong>2008,<br></p> <pre><code>file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=&lt;F&gt;){ if ($line=~ m/$EA/i) { my @cells=($f1,$f2,$f3)= split ',',$line; print "&lt;TD&gt;f1&lt;/TD&gt;"; print "&lt;TD&gt;f2&lt;/TD&gt;"; print "&lt;TD&gt;f3&lt;/TD&gt;"; } </code></pre>
[ { "answer_id": 260995, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>You almost had it, I think this should work:</p>\n\n<pre><code>file='save.txt';\nopen(F,$file)||die(\"Could not open $file\");\n\nwhile ($line=&lt;F&gt;){\n my @cells=($f1,$f2,$f3)= split ',',$line;\n if ($f3=~ m/$EA/i) {\n print \"&lt;TD&gt;f1&lt;/TD&gt;\";\n print \"&lt;TD&gt;f2&lt;/TD&gt;\";\n print \"&lt;TD&gt;f3&lt;/TD&gt;\";\n }\n}\n</code></pre>\n\n<p>This splits the line into columns <em>first</em>, and then does the regex only on the third column.</p>\n\n<p>BTW your code may have other problems (for example those print statements don't look like they print the values of your variables) but I don't know perl very well so I only answered your main question...</p>\n" }, { "answer_id": 261141, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "<p>You should post the actual sample program you are using to illustrate the problem. Here's your cleansed program:</p>\n\n<pre><code>use strict;\nuse warnings;\n\nuse CGI;\n\nmy $EA = param('keyword');\n\nmy $file = 'save.txt';\nopen my $fh, \"&lt;\", $file or die \"Could not open $file: $!\";\n\nwhile( $line=&lt;$fh&gt; ) {\n if( $line=~ m/$EA/i ) {\n my( $f1, $f2, $f3 ) = split ',', $line;\n print \"&lt;TD&gt;$f1&lt;/TD&gt;\";\n print \"&lt;TD&gt;$f2&lt;/TD&gt;\";\n print \"&lt;TD&gt;$f3&lt;/TD&gt;\";\n }\n }\n</code></pre>\n\n<p>Here's a few things that can help you.</p>\n\n<ul>\n<li>Your variables need their sigils. They don't do anything without them.</li>\n<li>When you try to open a file and want to report an error, include the $! variable so you see what the error is.</li>\n<li>You can split directly to scalar variables. It's just a list assignment. You don't need the extra @cell variable.</li>\n<li>Give your statements some room to breathe by using some whitespace. It's free, after all.</li>\n</ul>\n" }, { "answer_id": 261171, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>A combination of brian's and Jeremy's code fixes all the problems:</p>\n\n<pre><code>use strict;\nuse warnings;\n\nmy $file = 'save.txt';\nopen my $fh, \"&lt;\", $file or die \"Could not open $file: $!\";\n\nwhile ($line = &lt;$fh&gt;)\n{\n my($f1, $f2, $f3) = split ',', $line;\n if ($f3 =~ m/EA/i)\n {\n print \"&lt;TD&gt;$f1&lt;/TD&gt;\";\n print \"&lt;TD&gt;$f2&lt;/TD&gt;\";\n print \"&lt;TD&gt;$f3&lt;/TD&gt;\";\n }\n}\n</code></pre>\n\n<p>Brian had generalized the match pattern with <code>use CGI;</code> and <code>my $EA = param('keyword');</code> but I undid that as I didn't see it as applicable to the question.</p>\n" }, { "answer_id": 262230, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 1, "selected": false, "text": "<p>Alternately, you could alter your regex to just match the third item in the list:</p>\n\n<pre><code>/[^,]*,[^,]*,.*EA/\n</code></pre>\n" }, { "answer_id": 262571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Your regex is incorrect for what you are trying to do. Ben's solution works, although there should also be a ^ at the start, which ensures that the regex will start matching from the start of the string:</p>\n\n<p>/^.<em>?,.</em>?,.*EA/</p>\n\n<p>Also, your code is kinda noisy, from a perl point of view. If you want to make your code easier to read, you can do this (I'm using Ben's regex):</p>\n\n<p><code>\n$f = 'save.txt';</p>\n\n<p>open( F, $file );</p>\n\n<p>@matches = grep { /^.<em>?,.</em>?,.*EA/ } &lt;F&gt;;\n</code></p>\n\n<p>Now @matches will hold all your matched records, you can do what you want with them.</p>\n" }, { "answer_id": 267771, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 2, "selected": false, "text": "<p>Rather than trying to do the CSV parsing yourself, use the excellent and efficient <a href=\"http://search.cpan.org/perldoc?Text::CSV_XS\" rel=\"nofollow noreferrer\">Text::CSV_XS</a>. This will handle escapes and quoting.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nuse Text::CSV_XS;\n\nmy $csv = Text::CSV_XS-&gt;new();\n\n# Skip to the data.\nwhile(&lt;DATA&gt;) {\n last if /^-{10,}$/;\n}\n\nwhile( my $row = $csv-&gt;getline(*DATA) ) {\n print \"@$row\\n\" if $row-&gt;[2] =~ /EA/;\n}\n\n\n__DATA__\nName Age ID\n---------------------\nKRISTE,22,EA2008\nJ**EA**N,21,ES4567\nJAK,45,EA2008\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/260986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
I have a text file which contains some data. I am trying to search for EA in **ID column only** and prints the whole row. But the code recognize all EA and prints all rows. What code I should add to satisfy the condition? Thanks Again:-)! DATA: Name Age ID --------------------- KRISTE,22,**EA**2008 J**EA**N,21,ES4567 JAK,45,**EA**2008 The code prints: KRISTE,22,**EA**2008 J**EA**N,21,ES4567 JAK,45,**EA**2008 Desired output: KRIS,22,**EA**2008 Kane,45,**EA**2008, ``` file='save.txt'; open(F,$file)||die("Could not open $file"); while ($line=<F>){ if ($line=~ m/$EA/i) { my @cells=($f1,$f2,$f3)= split ',',$line; print "<TD>f1</TD>"; print "<TD>f2</TD>"; print "<TD>f3</TD>"; } ```
You should post the actual sample program you are using to illustrate the problem. Here's your cleansed program: ``` use strict; use warnings; use CGI; my $EA = param('keyword'); my $file = 'save.txt'; open my $fh, "<", $file or die "Could not open $file: $!"; while( $line=<$fh> ) { if( $line=~ m/$EA/i ) { my( $f1, $f2, $f3 ) = split ',', $line; print "<TD>$f1</TD>"; print "<TD>$f2</TD>"; print "<TD>$f3</TD>"; } } ``` Here's a few things that can help you. * Your variables need their sigils. They don't do anything without them. * When you try to open a file and want to report an error, include the $! variable so you see what the error is. * You can split directly to scalar variables. It's just a list assignment. You don't need the extra @cell variable. * Give your statements some room to breathe by using some whitespace. It's free, after all.
261,004
<p>I've got an old classic ASP site that connects to a local sql server 2000 instance. We're moving the db to a new box, and the port is non standard for sql (out of my control). .NET connection strings handle the port number fine by adding it with ,1999 after the server name/IP. The classic ASP connection string isn't working with the same syntax. I checked connectionstrings.com and couldn't find one that worked.</p> <p>Current connection string (set to an Application variable in Global.asa):</p> <pre><code>Driver={SQL Server};Server=xxx.xxx.xxx.xxx;Database=dbname;Uid=dbuser;Pwd=dbpassword </code></pre> <p>I've installed the SQL Native Client and couldn't get that working either (still working on this)</p> <p>Any ideas?</p>
[ { "answer_id": 261026, "author": "jwalkerjr", "author_id": 689, "author_profile": "https://Stackoverflow.com/users/689", "pm_score": 0, "selected": false, "text": "<p>I think we need more information. What are you using to connect to the database? ODBC? OLE DB? Are you connecting through and ODBC DSN? Is the connection string in your ASP code, or is your data access via a VB or COM DLL?</p>\n" }, { "answer_id": 261077, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 0, "selected": false, "text": "<pre><code>cst = \"Provider=SQLOLEDB;\" &amp; _ \n \"Data Source=&lt;x.x.x.x&gt;,&lt;port number&gt;;\" &amp; _ \n \"Initial Catalog=&lt;dbname&gt;;\" &amp; _ \n \"Network=DBMSSOCN;\" &amp; _ \n \"User Id=&lt;uid&gt;;\" &amp; _ \n \"Password=&lt;pwd&gt;\" \n\n set conn = CreateObject(\"ADODB.Connection\") \n conn.open cst \n</code></pre>\n\n<p><a href=\"http://sqlserver2000.databases.aspfaq.com/how-do-i-connect-to-sql-server-on-a-port-other-than-1433.html\" rel=\"nofollow noreferrer\">More info</a></p>\n" }, { "answer_id": 269951, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": true, "text": "<p>The solution was installing the SQL Native Driver from MS, then updating the connection string to the following:</p>\n\n<pre><code>Driver={SQL Native Client};Server=xxx.xxx.xxx.xxx,port;Database=dbname;Uid=dbuser;Pwd=dbpassword\n</code></pre>\n\n<p>I originally couldn't get it working with the SQL Native Client because of a firewall issue that was later resolved.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
I've got an old classic ASP site that connects to a local sql server 2000 instance. We're moving the db to a new box, and the port is non standard for sql (out of my control). .NET connection strings handle the port number fine by adding it with ,1999 after the server name/IP. The classic ASP connection string isn't working with the same syntax. I checked connectionstrings.com and couldn't find one that worked. Current connection string (set to an Application variable in Global.asa): ``` Driver={SQL Server};Server=xxx.xxx.xxx.xxx;Database=dbname;Uid=dbuser;Pwd=dbpassword ``` I've installed the SQL Native Client and couldn't get that working either (still working on this) Any ideas?
The solution was installing the SQL Native Driver from MS, then updating the connection string to the following: ``` Driver={SQL Native Client};Server=xxx.xxx.xxx.xxx,port;Database=dbname;Uid=dbuser;Pwd=dbpassword ``` I originally couldn't get it working with the SQL Native Client because of a firewall issue that was later resolved.
261,045
<p>I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out.</p> <p>My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys.</p> <p>Another problem is that this code:</p> <pre><code>var m_dialogFrame = document.getElementById(m_dialogId); </code></pre> <p>Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to ___m_dialogBody5" I can fix it by adding</p> <pre><code> /** * @type Element */ </code></pre> <p>Before it, but that, also, will be messy.</p> <p>Also, both:</p> <pre><code>new XMLHttpRequest(); </code></pre> <p>And</p> <pre><code>new ActiveXObject("Microsoft.XMLHTTP"); </code></pre> <p>Get red squiggles saying "x cannot be resolved to a type"</p> <p>The last problem is with:</p> <p>if (m_options.width != "auto")</p> <p>Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String"</p> <p>How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.</p>
[ { "answer_id": 261760, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "<p>Unfortunately, you might just have to scrap the JavaScript validation.</p>\n\n<p>In my experience, the JavaScript tools which come bundled with Eclipse 3.4 have a hard time... well, <em>understanding</em> JavaScript at all, generating bogus warnings and errors as a result.</p>\n\n<p>For example, the common practice of using an <code>Object</code> as a poor man's namespace causes it to get completely lost. Here's <a href=\"http://www.jonathanbuchanan.plus.com/images/eclipsejs.png\" rel=\"nofollow noreferrer\">a screenshot of the kind of mess it makes</a> when trying to understand <a href=\"http://code.google.com/p/js-forms/source/browse/trunk/time.js\" rel=\"nofollow noreferrer\">this JavaScript file</a> - note the useless outline view and the spurious (and incorrect) warnings and errors (including not seeming to understand than <code>String.split</code> returns an <code>Array</code>).</p>\n" }, { "answer_id": 706930, "author": "user85835", "author_id": 85835, "author_profile": "https://Stackoverflow.com/users/85835", "pm_score": 1, "selected": false, "text": "<p>After hours of looking around I have found how to definetly remove JS validation.</p>\n\n<p>This means editing your .project file, so back it up before just in case.</p>\n\n<ul>\n<li>Close Eclipse</li>\n<li>Open your .project file</li>\n<li>look for the following line : &lt;nature&gt;org.eclipse.wst.jsdt.core.jsNature&lt;/nature&gt;</li>\n<li>delete it</li>\n<li>save your file and start Eclipse</li>\n</ul>\n\n<p>There no more red or yellow squibble all over the place... but no more js validation.</p>\n\n<p>If anyone knows how to do it properly without editing .project file please share.</p>\n" }, { "answer_id": 786432, "author": "Sorin Mocanu", "author_id": 63846, "author_profile": "https://Stackoverflow.com/users/63846", "pm_score": 2, "selected": false, "text": "<p>Apparently to fully disable the validation you should also disable \"Report problems as you type\" under JavaScript -> Editor.</p>\n" }, { "answer_id": 1256336, "author": "Krishna", "author_id": 89154, "author_profile": "https://Stackoverflow.com/users/89154", "pm_score": 4, "selected": true, "text": "<p>Looks like this problem is due to the default browser for Eclipse not having the required libraries.</p>\n\n<p>Try below steps to add the required library:\nProject -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library'</p>\n\n<p>This should resolve the issue. It did for me.</p>\n" }, { "answer_id": 2187619, "author": "cpg", "author_id": 264720, "author_profile": "https://Stackoverflow.com/users/264720", "pm_score": 2, "selected": false, "text": "<p>This is very painful. One way to solve the problem for me was to exclude all the js files from the build. Properties->javascript->Libraries->Source tab and exclude all the files that give you problems....its a pitty because I wanted some autocomplete.... : ( but need to finish the project for work....\nIf somebody has a solution it would be highly appreciated : ) </p>\n" }, { "answer_id": 4339597, "author": "Laurie", "author_id": 528558, "author_profile": "https://Stackoverflow.com/users/528558", "pm_score": 1, "selected": false, "text": "<p>I found that old validation errors will stick around in the problems view and highlighted in the files until after you tell it to validate again, so after saving your JSP validation preferences, right click on a project to validate everything in it; that will make the errors go away.</p>\n" }, { "answer_id": 9185345, "author": "Anders Eriksson", "author_id": 307901, "author_profile": "https://Stackoverflow.com/users/307901", "pm_score": 1, "selected": false, "text": "<p>The answer of user85835 helped me a bit but I also needed to follow these two extra steps. </p>\n\n<p>First in order to actually remove the warnings and errors and avoid having them recreated immediately do like this: </p>\n\n<ol>\n<li>Disable automatic immediate rebuild after clean which is done in the Clean... window.</li>\n<li>Clean project</li>\n</ol>\n\n<p>Then close Eclipse and remove the &lt;nature&gt;org.eclipse.wst.jsdt.core.jsNature&lt;/nature&gt; as user85835 describes.</p>\n\n<p>But before restarting Eclipse also do this second step. </p>\n\n<ol>\n<li>In your .project file look for a &lt;buildCommand&gt; XML block containing a &lt;name&gt;org.eclipse.wst.jsdt.core.javascriptValidator&lt;/name&gt;. </li>\n<li>If you find this delete this block too. </li>\n</ol>\n\n<p>Then save your .project file and start Eclipse again</p>\n\n<p>Restore clean and rebuild settings as you wish to have them. </p>\n\n<p>This worked for me.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
Looks like this problem is due to the default browser for Eclipse not having the required libraries. Try below steps to add the required library: Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library' This should resolve the issue. It did for me.
261,046
<p>I am maintaining a website with currently about 800 concurrent users. The business plan says that this number will be 10x higher in one year.</p> <p>This is my current configuration:</p> <pre><code>&lt;Connector port="8080" address="${jboss.bind.address}" maxThreads="500" maxHttpHeaderSize="8192" emptySessionPath="true" protocol="HTTP/1.1" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" /&gt; &lt;Connector port="8443" address="${jboss.bind.address}" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="500" minSpareThreads="5" maxSpareThreads="25" scheme="https" secure="true" clientAuth="false" keystoreFile="${jboss.server.home.dir}/conf/ks.p12" keystoreType="PKCS12" connectionTimeout="20000" keystorePass="pass" sslProtocol="TLS" acceptCount="100" /&gt; </code></pre> <p>The average used thread count is about 400 (for each http/https). But peaks really use 500 threads. I think I will get into trouble when I get 10x users :-)</p> <ul> <li>How can I tune this?</li> <li>Should I disable http keep alive? How can I configure keep-alive timeout?</li> <li>What values are good for acceptCount / maxThreads?</li> </ul>
[ { "answer_id": 261109, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 1, "selected": false, "text": "<p>You can tune this using <a href=\"http://jakarta.apache.org/jmeter/\" rel=\"nofollow noreferrer\">JMeter</a>. I think much depends on your specific hardware setup.\nA possible way to scale your site is to add machines. Check out the <a href=\"http://en.oreilly.com/velocity2008/public/content/home\" rel=\"nofollow noreferrer\">Velocity Conference</a>\n and the <a href=\"http://highscalability.com/\" rel=\"nofollow noreferrer\">High Scalability website</a>.</p>\n" }, { "answer_id": 261882, "author": "Yonatan Maman", "author_id": 20065, "author_profile": "https://Stackoverflow.com/users/20065", "pm_score": 2, "selected": false, "text": "<p>I think that putting tomcat in Apache Http server is much more robust and faster approach. here are the pros &amp; cons taken from <a href=\"http://wiki.apache.org/tomcat/FAQ/Connectors\" rel=\"nofollow noreferrer\">http://wiki.apache.org/tomcat/FAQ/Connectors</a></p>\n\n<p>Why should I integrate Apache with Tomcat? (or not)</p>\n\n<p>There are many reasons to integrate Tomcat with Apache. And there are reasons why it should not be done too. Needless to say, everyone will disagree with the opinions here. With the performance of Tomcat 5 and 6, performance reasons become harder to justify. So here are the issues to discuss in integrating vs not.</p>\n\n<ul>\n<li>Clustering. By using Apache as a front end you can let Apache act as a front door to your content to multiple Tomcat instances. If one of your Tomcats fails, Apache ignores it and your Sysadmin can sleep through the night. This point could be ignored if you use a hardware loadbalancer and Tomcat's clustering capabilities.</li>\n<li>Clustering/Security. You can also use Apache as a front door to different Tomcats for different URL namespaces (/app1/, /app2/, /app3/, or virtual hosts). The Tomcats can then be each in a protected area and from a security point of view, you only need to worry about the Apache server. Essentially, Apache becomes a smart proxy server.</li>\n<li>Security. This topic can sway one either way. Java has the security manager while Apache has a larger mindshare and more tricks with respect to security. I won't go into this in more detail, but let Google be your friend. Depending on your scenario, one might be better than the other. But also keep in mind, if you run Apache with Tomcat - you have two systems to defend, not one.</li>\n<li>Add-ons. Adding on CGI, perl, PHP is very natural to Apache. Its slower and more of a kludge for Tomcat. Apache also has hundreds of modules that can be plugged in at will. Tomcat can have this ability, but the code hasn't been written yet.</li>\n<li>Decorators! With Apache in front of Tomcat, you can perform any number of decorators that Tomcat doesn't support or doesn't have the immediate code support. For example, mod_headers, mod_rewrite, and mod_alias could be written for Tomcat, but why reinvent the wheel when Apache has done it so well?</li>\n<li><strong>Speed. Apache is faster at serving static content than Tomcat. But unless you have a high traffic site, this point is useless. But in some scenarios, tomcat can be faster than apache. So benchmark YOUR site.</strong></li>\n<li>Socket handling/system stability. Apache has better socket handling with respect to error conditions than Tomcat. The main reason is Tomcat must perform all its socket handling via the JVM which needs to be cross platform. The problem is socket optimization is a platform specific ordeal. Most of the time the java code is fine, but when you are also bombarded with dropped connections, invalid packets, invalid requests from invalid IP's, Apache does a better job at dropping these error conditions than JVM based program. (YMMV)</li>\n</ul>\n" }, { "answer_id": 262389, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>I'd also look into tuning the underlying JVM, not just tomcat- check out <a href=\"https://stackoverflow.com/questions/202502/\">this question</a> for some good tips, particularly around garbage collection and memory allocation. In my experience, JVM tuning is much more effective than tuning Tomcat's internals.</p>\n" }, { "answer_id": 15640822, "author": "shereifhawary", "author_id": 320364, "author_profile": "https://Stackoverflow.com/users/320364", "pm_score": 1, "selected": false, "text": "<p>hey you should have a look to </p>\n\n<p><a href=\"http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html#Production%20Configuration\" rel=\"nofollow\">http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html#Production Configuration</a></p>\n\n<p>you can set some configuration related to jsp compilation it should make the system faster.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2554/" ]
I am maintaining a website with currently about 800 concurrent users. The business plan says that this number will be 10x higher in one year. This is my current configuration: ``` <Connector port="8080" address="${jboss.bind.address}" maxThreads="500" maxHttpHeaderSize="8192" emptySessionPath="true" protocol="HTTP/1.1" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" /> <Connector port="8443" address="${jboss.bind.address}" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="500" minSpareThreads="5" maxSpareThreads="25" scheme="https" secure="true" clientAuth="false" keystoreFile="${jboss.server.home.dir}/conf/ks.p12" keystoreType="PKCS12" connectionTimeout="20000" keystorePass="pass" sslProtocol="TLS" acceptCount="100" /> ``` The average used thread count is about 400 (for each http/https). But peaks really use 500 threads. I think I will get into trouble when I get 10x users :-) * How can I tune this? * Should I disable http keep alive? How can I configure keep-alive timeout? * What values are good for acceptCount / maxThreads?
I think that putting tomcat in Apache Http server is much more robust and faster approach. here are the pros & cons taken from <http://wiki.apache.org/tomcat/FAQ/Connectors> Why should I integrate Apache with Tomcat? (or not) There are many reasons to integrate Tomcat with Apache. And there are reasons why it should not be done too. Needless to say, everyone will disagree with the opinions here. With the performance of Tomcat 5 and 6, performance reasons become harder to justify. So here are the issues to discuss in integrating vs not. * Clustering. By using Apache as a front end you can let Apache act as a front door to your content to multiple Tomcat instances. If one of your Tomcats fails, Apache ignores it and your Sysadmin can sleep through the night. This point could be ignored if you use a hardware loadbalancer and Tomcat's clustering capabilities. * Clustering/Security. You can also use Apache as a front door to different Tomcats for different URL namespaces (/app1/, /app2/, /app3/, or virtual hosts). The Tomcats can then be each in a protected area and from a security point of view, you only need to worry about the Apache server. Essentially, Apache becomes a smart proxy server. * Security. This topic can sway one either way. Java has the security manager while Apache has a larger mindshare and more tricks with respect to security. I won't go into this in more detail, but let Google be your friend. Depending on your scenario, one might be better than the other. But also keep in mind, if you run Apache with Tomcat - you have two systems to defend, not one. * Add-ons. Adding on CGI, perl, PHP is very natural to Apache. Its slower and more of a kludge for Tomcat. Apache also has hundreds of modules that can be plugged in at will. Tomcat can have this ability, but the code hasn't been written yet. * Decorators! With Apache in front of Tomcat, you can perform any number of decorators that Tomcat doesn't support or doesn't have the immediate code support. For example, mod\_headers, mod\_rewrite, and mod\_alias could be written for Tomcat, but why reinvent the wheel when Apache has done it so well? * **Speed. Apache is faster at serving static content than Tomcat. But unless you have a high traffic site, this point is useless. But in some scenarios, tomcat can be faster than apache. So benchmark YOUR site.** * Socket handling/system stability. Apache has better socket handling with respect to error conditions than Tomcat. The main reason is Tomcat must perform all its socket handling via the JVM which needs to be cross platform. The problem is socket optimization is a platform specific ordeal. Most of the time the java code is fine, but when you are also bombarded with dropped connections, invalid packets, invalid requests from invalid IP's, Apache does a better job at dropping these error conditions than JVM based program. (YMMV)
261,050
<p>I'm having an issue with a standard ASP.NET page that has a TextBox and a RequiredFieldValidator. The steps to reproduce are quite simple:</p> <ol> <li>Place a TextBox on a page</li> <li>Place a RequiredFieldValidator on the page</li> <li>Point the RequiredFieldValidator at the TextBox</li> <li>Run the app</li> <li>Tab away from the TextBox the RequiredFieldValidator does not show</li> <li>Enter text, then delete the text and THEN tab away, the RequiredFieldValidator does show</li> </ol> <p>The RequiredFieldValidator works fine in both cases after a postback, however it seems the client-side code isn't firing until something is entered into the textbox (and then deleted).</p> <p>Does anyone have a solution to this without hacking away at JavaScript myself?</p>
[ { "answer_id": 261082, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 2, "selected": false, "text": "<p>did you set the EnableClientScript attribute/property to true?\ndo you have a default value for the text box? if so you need to set the InitialValue property to that default value</p>\n" }, { "answer_id": 261100, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 3, "selected": true, "text": "<p>Is it possible this behavior is by design to suppress the appearance of validation controls until user input?</p>\n\n<p>Generally speaking, Validate() gets called whenever a control is clicked that has CausesValidation set to true, like a submit button. </p>\n\n<p>In any case, a poor mans work around, you <em>could</em> call the page Validate() function from the Load event handler. This will make things clearer to tab happy users that they need to enter something in. E.g.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Validate();\n}\n</code></pre>\n" }, { "answer_id": 261117, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "<p>A form can contain several validation groups. AFAIK validation is only triggered through a post-back, activating the validators of the corresponding validator group. Only after the post-back does the validator add its client-side Javascript validation code.</p>\n" }, { "answer_id": 261127, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 0, "selected": false, "text": "<p>Thats just how the validators work, they don't fire unless there was input to validate or there was a postback. You'll have to do the validation firing yourself if you want it to happen.</p>\n\n<p>I don't know the exact code you'll need but it'll have to do with handling onblur and overriding evaluation function:</p>\n\n<pre><code>function blurred(sender) {\n var validator = sender.Validators[0]\n validator.evaluationfunction(validator);\n}\n</code></pre>\n\n<p>and on the textbox:</p>\n\n<pre><code>&lt;asp:TextBox runat=\"server\" ID=\"txt\" onBlur=\"blurred(this)\"&gt;&lt;/asp:TextBox&gt;\n</code></pre>\n" }, { "answer_id": 261302, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 2, "selected": false, "text": "<p>You may be creating a usability issue here. If you validate mandatory fields on blur, the user will get a lot of \"Required Field\" errors just because he's tabbing through the fields.</p>\n" }, { "answer_id": 261450, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "<p>A follow-up to my previous answer:</p>\n\n<p>Validation occurs in the onchange event, rather than the onblur. onchange fires when the focus is lost AND the control value has changed.</p>\n\n<p>To trigger validation in the onblur event, I added the following code in the Page_Load():</p>\n\n<pre><code>ScriptManager.RegisterStartupScript(this, GetType(), \"js\" + myTextBox.ClientID,\n \"ValidatorHookupEvent(document.getElementById(\\\"\" + myTextBox.ClientID + \n \"\\\"), \\\"onblur\\\", \\\"ValidatorOnChange(event);\\\");\", true);\n</code></pre>\n\n<p>Works in ASP.Net 2.</p>\n" }, { "answer_id": 16025429, "author": "Faisal Salamah", "author_id": 2265247, "author_profile": "https://Stackoverflow.com/users/2265247", "pm_score": 0, "selected": false, "text": "<p>I had the same issue. Discovered that you need need to add some framework script references to your script manager. Make sure you have at least these script references withing \"script\" tags in your script manager.</p>\n\n<pre><code> &lt;asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" ValidateRequestMode=\"Enabled\" &gt;\n &lt;Scripts&gt;\n &lt;%--Framework Scripts--%&gt;\n &lt;%--&lt;asp:ScriptReference Name=\"MsAjaxBundle\" /&gt;--%&gt;\n &lt;asp:ScriptReference Name=\"jquery\" /&gt;\n &lt;asp:ScriptReference Name=\"jquery.ui.combined\" /&gt;\n &lt;asp:ScriptReference Name=\"WebForms.js\" Path=\"~/Scripts/WebForms/WebForms.js\" /&gt;\n &lt;asp:ScriptReference Name=\"WebUIValidation.js\" Path=\"~/Scripts/WebForms/WebUIValidation.js\" /&gt;\n &lt;asp:ScriptReference Name=\"WebFormsBundle\" /&gt;\n &lt;%--Site Scripts--%&gt;\n\n &lt;/Scripts&gt;\n &lt;/asp:ScriptManager&gt;\n</code></pre>\n\n<p>You can find those as well in the default master page created by .Net when you create a webforms application.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1462735/" ]
I'm having an issue with a standard ASP.NET page that has a TextBox and a RequiredFieldValidator. The steps to reproduce are quite simple: 1. Place a TextBox on a page 2. Place a RequiredFieldValidator on the page 3. Point the RequiredFieldValidator at the TextBox 4. Run the app 5. Tab away from the TextBox the RequiredFieldValidator does not show 6. Enter text, then delete the text and THEN tab away, the RequiredFieldValidator does show The RequiredFieldValidator works fine in both cases after a postback, however it seems the client-side code isn't firing until something is entered into the textbox (and then deleted). Does anyone have a solution to this without hacking away at JavaScript myself?
Is it possible this behavior is by design to suppress the appearance of validation controls until user input? Generally speaking, Validate() gets called whenever a control is clicked that has CausesValidation set to true, like a submit button. In any case, a poor mans work around, you *could* call the page Validate() function from the Load event handler. This will make things clearer to tab happy users that they need to enter something in. E.g. ``` protected void Page_Load(object sender, EventArgs e) { Validate(); } ```
261,062
<p>Although I grasp the concept of Bitwise Operators, I can't say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bitwise Operators.</p> <ul> <li>Do you use Bitwise Operators?</li> <li>Why do you use them?</li> <li>What are some example use cases?</li> </ul> <p>Please remember that this question is specifically intended for use of Bitwise Operators in web languages.</p>
[ { "answer_id": 261073, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>My main use for bitwise operators could be relevant anywhere - representing a set of flags. For instance, you might have an integer in the database representing a set of security permissions for a user, and in your web app you would have to check those before continuing.</p>\n\n<p>Those tend to only require <code>&amp;</code> and <code>|</code> - e.g.</p>\n\n<pre><code>if ((permissions &amp; Permission.CreateUser) != 0)\n{\n ...\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Permission requiredPermission = Permission.CreateUser\n | Permission.ChangePassword;\n</code></pre>\n\n<p>Bit <em>shifting</em> operators are less useful in \"business\" applications in my experience.</p>\n" }, { "answer_id": 261076, "author": "bmeck", "author_id": 12781, "author_profile": "https://Stackoverflow.com/users/12781", "pm_score": 1, "selected": false, "text": "<p>I use em every so often but never in places where I can avoid them. The most often I have used them are the following two situations.</p>\n\n<ol>\n<li>Encrypting form data from client using JavaScript when not over a secure connection, its not much but better than sending plain text.</li>\n<li>Streaming file structures (generally some binary file type) from PHP that are generated on the fly.</li>\n</ol>\n" }, { "answer_id": 261079, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<p>Generally, you don't need to concern about operations at the bit level. You can think in bytes, ints, doubles, and other higher level data types. But there are times when you'd like to be able to go to the level of an individual bit.</p>\n\n<p>One of the most common utilization cases of the bitwise operators are the <a href=\"http://www.shawnolson.net/a/601/setting-bits-and-flags-in-php.html\" rel=\"nofollow noreferrer\">flags</a> (php example). The <a href=\"http://www.php.net/language.operators.bitwise\" rel=\"nofollow noreferrer\">bitwise operators</a> are also used in binary file IO operations.</p>\n" }, { "answer_id": 261091, "author": "Henrik Paul", "author_id": 2238, "author_profile": "https://Stackoverflow.com/users/2238", "pm_score": 1, "selected": false, "text": "<p>On the off-topic side of things, in high-level languages, especially in parsed languages (such as PHP), bitwise operations are tons slower<sup>[citation needed]</sup> than the normal arithmetic. So, while Jon's permission checking might be ok from a performance standpoint, it's not very 'native' in the web domain.</p>\n" }, { "answer_id": 261094, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 3, "selected": false, "text": "<p>Besides from flags, there is not much reason to use bit-operations in scripting languages. \nBut once you delve into the lower levels of your stack, bit-operations become more and more critical.</p>\n" }, { "answer_id": 261227, "author": "tyler", "author_id": 25303, "author_profile": "https://Stackoverflow.com/users/25303", "pm_score": 6, "selected": false, "text": "<p>I'm going to be more explicit here because I think bitwise masks are a great tool that should be in any devs belt. I'm going to try to expand on the answers above. First, an example of using an integer to maintain state flags (common usage):</p>\n\n<pre><code>// These are my masks\nprivate static final int MASK_DID_HOMEWORK = 0x0001;\nprivate static final int MASK_ATE_DINNER = 0x0002;\nprivate static final int MASK_SLEPT_WELL = 0x0004; \n\n// This is my current state\nprivate int m_nCurState;\n</code></pre>\n\n<p>To <strong><em>set</em></strong> my state, I use the bitwise OR operator:</p>\n\n<pre><code>// Set state for'ate dinner' and 'slept well' to 'on'\nm_nCurState = m_nCurState | (MASK_ATE_DINNER | MASK_SLEPT_WELL);\n</code></pre>\n\n<p>Notice how I 'or' my current state in with the states that I want to turn 'on'. Who knows what my current state is and I don't want to blow it away. </p>\n\n<p>To <strong><em>unset</em></strong> my state, I use the bitwise AND operator with the complement operator:</p>\n\n<pre><code>// Turn off the 'ate dinner' flag\nm_nCurState = (m_nCurState &amp; ~MASK_ATE_DINNER);\n</code></pre>\n\n<p>To <strong><em>check</em></strong> my current state, I use the AND operator:</p>\n\n<pre><code>// Check if I did my homework\nif (0 != (m_nCurState &amp; MASK_DID_HOMEWORK)) {\n // yep\n} else { \n // nope...\n}\n</code></pre>\n\n<p>Why do I think this is interesting? Say I'm designing an interface that sets my state. I could write a method that accepts three booleans:</p>\n\n<pre><code>void setState( boolean bDidHomework, boolean bAteDinner, boolean bSleptWell);\n</code></pre>\n\n<p>Or, I could use a single number to represent all three states and pass a single value:</p>\n\n<pre><code>void setState( int nStateBits);\n</code></pre>\n\n<p>If you choose the second pattern you'll be very happy when decide to add another state - you won't have to break existing impls of your interface.</p>\n\n<p>My two cents.\nThanks.</p>\n" }, { "answer_id": 261925, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>For Java programmers the xor bitwise operator (^) provides a useful way to code an exclusive OR test between two booleans. Example:</p>\n\n<pre><code>boolean isFoo = ...\nboolean isBar = ...\n\nif (isFoo ^ isBar) {\n // Either isFoo is true or isBar is true, but not both.\n</code></pre>\n\n<p>Note: there's no actual bit manipulation going on here but it is a useful way to use the xor bitwise operator (in the web tier or anywhere else).</p>\n\n<p>(Same may apply to C#, since it's so similar to Java. Not sure, though.)</p>\n" }, { "answer_id": 655828, "author": "Jayrox", "author_id": 24802, "author_profile": "https://Stackoverflow.com/users/24802", "pm_score": 0, "selected": false, "text": "<p>The only time I have had to use them outside of authorizing access was for a project I was doing for a parser that took Color IDs assigned to ints</p>\n\n<p>i.e</p>\n\n<pre><code>$color_red= 1;\n$color_blue = 2;\n$color_yellow = 8;\n\n$color_purple = 3;\n$color_orange = 9;\n$color_green = 10;\n</code></pre>\n\n<p>then I was given a property</p>\n\n<pre><code>$can_collect_200_dollars = 10;\n</code></pre>\n\n<p>then used bitwise to compare the color given with the property</p>\n\n<pre><code>if($given_color &amp; $can_collect_200_dollars)\n{\n $yay_i_got_200_dollars = true;\n}else{\n $bummer_i_am_going_to_jail = true;\n}\n</code></pre>\n" }, { "answer_id": 1716580, "author": "user160820", "author_id": 160820, "author_profile": "https://Stackoverflow.com/users/160820", "pm_score": -1, "selected": false, "text": "<p>I think bitwise operators are very strong if used intelligently.</p>\n\n<p>Suppose you have a \"Online Store\". And some of your items fall in more that one Categories.</p>\n\n<p>Either you have to Create a Many-to-Many relation. Or you can give your Categories an extra Binary-ID and in your product just store the Bitwise combinition of Categories-IDs</p>\n\n<p>I think in few line I can't explain in detail. SORRY </p>\n" }, { "answer_id": 19968424, "author": "RestInPeace", "author_id": 1841956, "author_profile": "https://Stackoverflow.com/users/1841956", "pm_score": 3, "selected": false, "text": "<p>This question is already answered but I would like to share my experience with <code>&amp;</code>.</p>\n\n<p>I have used <code>&amp;</code> a short time ago to validate a signup form when I was doing an ASP.NET C# exercise where the short-circuited <code>&amp;&amp;</code> would not achieve a desired effect as easily. </p>\n\n<p>What I wanted to do was highlight all invalid fields in the form and show an error message label right beside each invalid field, and dehighlight all valid fields and remove the error messages from them.</p>\n\n<p>The code I used it was something like this:</p>\n\n<pre><code>protected void btnSubmitClicked(...) {\n username = txtUsername.Text;\n email = txtEmail.Text;\n pass = txtPassword.Text;\n if (isUsernameValid(username) &amp; isEmailValid(email) &amp; isPasswordValid(pass)) {\n // form is valid\n } else {\n // form is invalid\n }\n ...\n}\n\nprivate bool isPasswordValid(string password) {\n bool valid = true;\n string msg = \"\";\n if (password.length &lt; MIN_PASSWORD_SIZE) {\n valid = false;\n msg = \"Password must be at least \" + MIN_PASSWORD_SIZE + \" long.\";\n }\n\n highlightField(txtPassword, lblPassword, valid, msg);\n return valid;\n}\n\nprivate void highlightField(WebControl field, Label label, string valid, string msg) {\n if (isValid) {\n // de-highlight\n field.BorderColor = VALID_FIELD_COLOR;\n } else {\n // highlight the text field and focus on it\n field.BorderColor = INVALID_FIELD_COLOR;\n field.Focus();\n }\n\n label.Text = msg;\n}\n\n// and other similar functions for username and email\n</code></pre>\n\n<p>Were I to use <code>&amp;&amp;</code> instead of <code>&amp;</code>, the if-statement in <code>btnSubmitClicked</code> method would highlight only the very first invalid field, and all the other invalid fields after that would not be highlighted and its error message not shown because short-circuited <code>&amp;&amp;</code> would stop checking the condition after a false is encountered.</p>\n\n<p>There may be a better way to achieve the same thing, but I found <code>&amp;</code> useful at that time.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11568/" ]
Although I grasp the concept of Bitwise Operators, I can't say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bitwise Operators. * Do you use Bitwise Operators? * Why do you use them? * What are some example use cases? Please remember that this question is specifically intended for use of Bitwise Operators in web languages.
My main use for bitwise operators could be relevant anywhere - representing a set of flags. For instance, you might have an integer in the database representing a set of security permissions for a user, and in your web app you would have to check those before continuing. Those tend to only require `&` and `|` - e.g. ``` if ((permissions & Permission.CreateUser) != 0) { ... } ``` or ``` Permission requiredPermission = Permission.CreateUser | Permission.ChangePassword; ``` Bit *shifting* operators are less useful in "business" applications in my experience.
261,086
<p>I am using a fictional example for this. Say, I have a Widget class like:</p> <pre><code>abstract class Widget { Widget parent; } </code></pre> <p>Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular "type" of widget can be parent to a particular type of Widget.</p> <p>For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it.</p> <p>Precisely, what I would have liked to do is this:</p> <pre><code>// This does not works! class Widget&lt;PType&gt;: where PType: Widget { PType parent; } class WidgetParent&lt;Widget&gt; { public void Slap(); } class WidgetChild&lt;WidgetParent&gt; { } </code></pre> <p>So that when I want to access the parent of WidgetChild, instead of using it this way:</p> <pre><code>WidgetParent wp = wc.parent as WidgetParent; if(wp != null) { wp.Slap(); } else throw FakeParentException(); </code></pre> <p>I want to use it this way(if I could use generics):</p> <pre><code>wc.parent.Slap(); </code></pre>
[ { "answer_id": 261104, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "<p>I don't think there is a language mechanism that would allow you to do that.</p>\n\n<p>However, you might want to use a <strong><a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">Factory pattern</a> to separate the construction of the class from the class itself</strong>.</p>\n\n<p>Say, make a WidgetFactory class</p>\n\n<pre><code>class WidgetFactory\n{\n Widget CreateWidget()\n {\n return new Widget();\n }\n}\n</code></pre>\n\n<p>And for child classes, you'd make their factory as well. Say, a WidgetParentFactory or WidgetChildFactory or you could make a generic factory:</p>\n\n<pre><code>class WidgetFactory&lt;T&gt; where T : Widget\n{\n T CreateWidget()\n {\n return new T();\n }\n}\n</code></pre>\n\n<p>Then from the CreateWidget() method you could control class instantiation so that invalid child types can not be created.</p>\n\n<pre><code>class WidgetFactory&lt;T&gt; where T : Widget\n{\n T CreateWidget()\n {\n if (/*check the type T inheritance here*/)\n return new T();\n else\n throw new Exception(\"Invalid inheritance\");\n }\n}\n</code></pre>\n\n<p>This should do the trick for you.</p>\n\n<p>p.s. Would you care to elaborate on <em>why</em> you wanted to do this?</p>\n" }, { "answer_id": 261146, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>You should be able to use the code you've got by still having the non-generic class <code>Widget</code> and making <code>Widget&lt;T&gt;</code> derive from it:</p>\n\n<pre><code>public abstract class Widget\n{\n}\n\npublic abstract class Widget&lt;T&gt; : Widget where T : Widget\n{\n}\n</code></pre>\n\n<p>You then need to work out what belongs in the generic class and what belongs in the non-generic... from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!</p>\n" }, { "answer_id": 261176, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>You seem to be confusing type parameters and inheritance. This should work:</p>\n\n<pre><code>class Widget&lt;PType&gt; where PType :new()\n{\n public PType parent = new PType();\n}\n\nclass ParentType {}\n\nclass WidgetParent : Widget&lt;ParentType&gt; \n{ \n public void Slap() {Console.WriteLine(\"Slap\"); }\n}\n\nclass WidgetChild : Widget&lt;WidgetParent&gt;\n{\n}\npublic static void RunSnippet()\n{\n WidgetChild wc = new WidgetChild();\n wc.parent.Slap();\n}\n</code></pre>\n" }, { "answer_id": 261231, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>Use interfaces:</p>\n\n<pre><code>interface IContainerWidget { }\n\nclass Widget\n{\n private IContainerWidget Container;\n}\n\nclass ContainerWidget : Widget, IContainerWidget\n{\n}\n</code></pre>\n" }, { "answer_id": 269921, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>Here's my stab at organizing this.</p>\n\n<pre><code>public interface IWidget\n{\n void Behave();\n IWidget Parent { get; }\n}\n\npublic class AWidget : IWidget\n{\n IWidget IWidget.Parent { get { return this.Parent; } }\n void IWidget.Behave() { this.Slap(); }\n\n public BWidget Parent { get; set; }\n public void Slap() { Console.WriteLine(\"AWidget is slapped!\"); }\n}\n\npublic class BWidget : IWidget\n{\n IWidget IWidget.Parent { get { return this.Parent; } }\n void IWidget.Behave() { this.Pay(); }\n\n public AWidget Parent { get; set; }\n public void Pay() { Console.WriteLine(\"BWidget is paid!\"); }\n}\n\npublic class WidgetTester\n{\n public void AWidgetTestThroughIWidget()\n {\n IWidget myWidget = new AWidget() { Parent = new BWidget() };\n myWidget.Behave();\n myWidget.Parent.Behave();\n }\n public void AWidgetTest()\n {\n AWidget myWidget = new AWidget() { Parent = new BWidget() };\n myWidget.Slap();\n myWidget.Parent.Pay();\n }\n\n public void BWidgetTestThroughIWidget()\n {\n IWidget myOtherWidget = new BWidget() { Parent = new AWidget() };\n myOtherWidget.Behave();\n myOtherWidget.Parent.Behave();\n }\n\n public void BWidgetTest()\n {\n BWidget myOtherWidget = new BWidget() { Parent = new AWidget() };\n myOtherWidget.Pay();\n myOtherWidget.Parent.Slap();\n }\n}\n</code></pre>\n" }, { "answer_id": 428354, "author": "Tim Jarvis", "author_id": 53365, "author_profile": "https://Stackoverflow.com/users/53365", "pm_score": 0, "selected": false, "text": "<p>I had a similar issue and adapted it to suit this (hopefully)</p>\n\n<p><strong>Main Code</strong></p>\n\n<pre><code>public class Parent&lt;T&gt;\n where T : Child&lt;T&gt;\n{\n public Parent() { }\n\n\n public T Get()\n {\n return Activator.CreateInstance(typeof(T), new object[] { this }) as T;\n }\n}\n\npublic class Child&lt;T&gt;\n where T : Child&lt;T&gt;\n{\n Parent&lt;T&gt; _parent;\n\n public Parent&lt;T&gt; Parent { get { return _parent; } }\n\n public Child(Parent&lt;T&gt; parent)\n {\n _parent = parent;\n }\n}\n\n\npublic class ItemCollection : Parent&lt;Item&gt;\n{\n\n}\n\npublic class Item : Child&lt;Item&gt;\n{\n public Item(Parent&lt;Item&gt; parent)\n : base(parent)\n {\n }\n}\n</code></pre>\n\n<p><strong>Example :</strong></p>\n\n<pre><code>ItemCollection col = new ItemCollection();\nItem item = col.Get();\nitem.Parent.Slap();\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ]
I am using a fictional example for this. Say, I have a Widget class like: ``` abstract class Widget { Widget parent; } ``` Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular "type" of widget can be parent to a particular type of Widget. For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it. Precisely, what I would have liked to do is this: ``` // This does not works! class Widget<PType>: where PType: Widget { PType parent; } class WidgetParent<Widget> { public void Slap(); } class WidgetChild<WidgetParent> { } ``` So that when I want to access the parent of WidgetChild, instead of using it this way: ``` WidgetParent wp = wc.parent as WidgetParent; if(wp != null) { wp.Slap(); } else throw FakeParentException(); ``` I want to use it this way(if I could use generics): ``` wc.parent.Slap(); ```
You should be able to use the code you've got by still having the non-generic class `Widget` and making `Widget<T>` derive from it: ``` public abstract class Widget { } public abstract class Widget<T> : Widget where T : Widget { } ``` You then need to work out what belongs in the generic class and what belongs in the non-generic... from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!
261,089
<p>how is it advisable to control the cpu utilization during run time ?</p> <p>poll the cpu load and insert sleeps ?</p>
[ { "answer_id": 261123, "author": "artur02", "author_id": 13937, "author_profile": "https://Stackoverflow.com/users/13937", "pm_score": 2, "selected": false, "text": "<p>I'd recommend OS functionality. There are performance counters and WinAPI functions for this on Windows.</p>\n\n<p>Here is an example using <strong>performance counters</strong> from <a href=\"http://blogs.msdn.com/bclteam/archive/2006/06/06/619284.aspx\" rel=\"nofollow noreferrer\">BCL Team Blog</a>:</p>\n\n<pre><code>foreach (Process proc in Process.GetProcesses()) {\n using (PerformanceCounter pcProcess = new PerformanceCounter(\"Process\", \"% Processor Time\", proc.ProcessName)) {\n pcProcess.NextValue();\n System.Threading.Thread.Sleep(1000);\n Console.WriteLine(\"Process:{0} CPU% {1}\", proc.ProcessName, pcProcess.NextValue()); \n }\n}\n</code></pre>\n\n<p>This code makes the same <strong>with WMI</strong> from <a href=\"http://www.codeproject.com/KB/cs/perfgrid.aspx\" rel=\"nofollow noreferrer\">CodeProject</a>:</p>\n\n<pre><code>public string GetCPU()\n{\n decimal PercentProcessorTime=0;\n mObject_CPU.Get();\n\n ulong u_newCPU = \n (ulong)mObject_CPU.Properties[\"PercentProcessorTime\"].Value;\n ulong u_newNano = \n (ulong)mObject_CPU.Properties[\"TimeStamp_Sys100NS\"].Value;\n decimal d_newCPU = Convert.ToDecimal(u_newCPU);\n decimal d_newNano = Convert.ToDecimal(u_newNano);\n decimal d_oldCPU = Convert.ToDecimal(u_oldCPU);\n decimal d_oldNano = Convert.ToDecimal(u_oldNano);\n\n // Thanks to MSDN for giving me this formula !\n\n PercentProcessorTime = \n (1 - ((d_newCPU-d_oldCPU)/(d_newNano - d_oldNano)))*100m;\n\n // Save the values for the next run\n\n u_oldCPU = u_newCPU;\n u_oldNano = u_newNano;\n\n return PercentProcessorTime.ToString(\"N\",nfi);;\n}\n</code></pre>\n\n<p>So you can query these OS providers (or others for your OS) and sleep your thread if processor utilization is high.</p>\n" }, { "answer_id": 261158, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 0, "selected": false, "text": "<p>The easiest way would be to modify your main loop to either wait on input - the classic event driven model - or to periodically sleep for a short period of time.</p>\n\n<p>If putting the application to sleep I would only use a very short timeout, somewhere within 10-100ms range as any more and some user input would be delayed, and any less would involve a lot more OS level overhead in switching your application.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195/" ]
how is it advisable to control the cpu utilization during run time ? poll the cpu load and insert sleeps ?
I'd recommend OS functionality. There are performance counters and WinAPI functions for this on Windows. Here is an example using **performance counters** from [BCL Team Blog](http://blogs.msdn.com/bclteam/archive/2006/06/06/619284.aspx): ``` foreach (Process proc in Process.GetProcesses()) { using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName)) { pcProcess.NextValue(); System.Threading.Thread.Sleep(1000); Console.WriteLine("Process:{0} CPU% {1}", proc.ProcessName, pcProcess.NextValue()); } } ``` This code makes the same **with WMI** from [CodeProject](http://www.codeproject.com/KB/cs/perfgrid.aspx): ``` public string GetCPU() { decimal PercentProcessorTime=0; mObject_CPU.Get(); ulong u_newCPU = (ulong)mObject_CPU.Properties["PercentProcessorTime"].Value; ulong u_newNano = (ulong)mObject_CPU.Properties["TimeStamp_Sys100NS"].Value; decimal d_newCPU = Convert.ToDecimal(u_newCPU); decimal d_newNano = Convert.ToDecimal(u_newNano); decimal d_oldCPU = Convert.ToDecimal(u_oldCPU); decimal d_oldNano = Convert.ToDecimal(u_oldNano); // Thanks to MSDN for giving me this formula ! PercentProcessorTime = (1 - ((d_newCPU-d_oldCPU)/(d_newNano - d_oldNano)))*100m; // Save the values for the next run u_oldCPU = u_newCPU; u_oldNano = u_newNano; return PercentProcessorTime.ToString("N",nfi);; } ``` So you can query these OS providers (or others for your OS) and sleep your thread if processor utilization is high.
261,092
<p>What are all <a href="http://en.wikipedia.org/wiki/Hayes_command_set" rel="nofollow noreferrer">AT</a> commands required for <a href="http://en.wikipedia.org/wiki/General_Packet_Radio_Service" rel="nofollow noreferrer">GPRS</a> communication?</p>
[ { "answer_id": 261115, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>It depends quite a bit on:</p>\n\n<ul>\n<li>The modem</li>\n<li>How much of the modem's stack you plan on using</li>\n<li>The carrier you're using</li>\n</ul>\n\n<p>If you're using this on a computer and you have a modem configuration file (modem specific), and a carrier configuration or setup then you can intercept the serial commands and find out.</p>\n\n<p>Otherwise, try going to the modem manufacturer's website and find the AT command guide for your modem.</p>\n\n<p>Once you have the modem commands, setting up the connection requires several steps, including initiating the GSM connect, then a GPRS session with a server, and then the PPP session with your carrier's ISP equipement. You'll need several pieces of information from the carrier, which the AT command set will guide you towards.</p>\n\n<p>Your modem may also have a built in TCP/IP stack, in which case you also have AT commands to initiate the PPP session, and then TCP connections with internet servers.</p>\n\n<p>If you post the modem/carrier/goal/etc you might be able to get more specific help.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 261144, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>A more specific answer, if you're using a MultiTech Multimodem GPRS (or similar) and Tmobile's internet service (one of the higher tiers usually used with laptops). The uppercase names starting with \"M\" were the names of the states in the modem control state machine I was using. The data I was collecting was simple GPS strings, which were being stored by a PHP script on my server to be displayed here: <a href=\"http://www.ubasics.com/wmr/\" rel=\"nofollow noreferrer\">http://www.ubasics.com/wmr/</a> . A very basic tracking/telemetry application.</p>\n\n<p>Reset the modem:</p>\n\n<pre><code>MRESET:\nATZ\n</code></pre>\n\n<p>Attach to the provider's network:</p>\n\n<pre><code>MPROVIDERINIT:\nat+cgdcont=1,\"IP\",\"internet3.voicestream.com\",,0,0\n\nMIPINIT:\nat+wopen=1\n\nMPPPINIT:\nat#pppmode=1\n\nMCHECKPIN:\nat+cpin?\n\nMGSMREGISTER:\nat+creg=1\n</code></pre>\n\n<p>Attach to the providers GPRS network:</p>\n\n<pre><code>MGPRSREGISTER:\nat+cgreg=1\n\nMGPRSATTACH:\nat+cgatt=1\n\nMGPRSMODE:\nat#gprsmode=1\n</code></pre>\n\n<p>Attach to the provider's internet PPP server:</p>\n\n<pre><code>MSERVERINIT:\nAT#APNSERV=\"internet3.voicestream.com\"\n\nMUSERNAME:\nAT#APNUN=\"\"\n\nMPASSWORD:\nAT#APNPW=\"\"\n\nMSIGNAL:\nAT+CSQ\n\nMSTARTPPP:\nat#connectionstart\n</code></pre>\n\n<p>Attach the Modem's internal stack to an HTTP port:</p>\n\n<pre><code>MTCPSERVER:\nAT#TCPSERV=\"www.ubasics.com\"\n\nMTCPPORT:\nAT#TCPPORT=80\n\nMOPENSOCKET:\nat#otcp\n</code></pre>\n" }, { "answer_id": 261485, "author": "tonys", "author_id": 35439, "author_profile": "https://Stackoverflow.com/users/35439", "pm_score": 2, "selected": false, "text": "<p>As Adam said, the specific AT command set depends a little bit on your modem. The Siemens GSM modems support what seems to be a reasonably common subset though - there is a manual at:</p>\n\n<p><a href=\"http://www.automation.siemens.com/siplus/ftp/techndoku/TC65_atc_v02000.pdf\" rel=\"nofollow noreferrer\">http://www.automation.siemens.com/siplus/ftp/techndoku/TC65_atc_v02000.pdf</a></p>\n\n<p>which documents all the supported GSM commands in detail.</p>\n\n<p>(Google \"TC65 AT commands\" if the link is broken)</p>\n" }, { "answer_id": 742102, "author": "hlovdal", "author_id": 23118, "author_profile": "https://Stackoverflow.com/users/23118", "pm_score": 0, "selected": false, "text": "<p>Most of the mobile phone specific AT commands are standardised and specified in <a href=\"http://www.3gpp.org/ftp/Specs/html-info/27007.htm\" rel=\"nofollow noreferrer\">27.007</a> (SMS related commands are in <a href=\"http://www.3gpp.org/ftp/Specs/html-info/27005.htm\" rel=\"nofollow noreferrer\">27.005</a>). For Sony Ericsson phones there is a document <a href=\"http://developer.sonyericsson.com/getDocument.do?docId=65054\" rel=\"nofollow noreferrer\">Developers' Guidelines - AT Commands (5.50 MB)</a> available.</p>\n\n<p>Beware that GPRS AT commands are far from trivial. If your phone is correctly configured and all you want it to start a IP connection using the first defined internet account, you can run</p>\n\n<pre><code>ATD*98*1#\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ATD*99***1#\n</code></pre>\n\n<p>to start PPP negotiation (see \"Extension of ATD – Request GPRS service\" in the Sony Ericsson document).</p>\n" }, { "answer_id": 751675, "author": "Mauricio", "author_id": 84703, "author_profile": "https://Stackoverflow.com/users/84703", "pm_score": 1, "selected": false, "text": "<p>I am using a SIM340 GSM modem and a Ramtron 8051 compatible microcontroler.\nFollows my own sequence to connect to a remote server, using that configuration:</p>\n\n<p>ATE0 // echo off, optional, makes easier parsing SIM340 replies; if you are using a terminal program you dont want to deactivate echo.</p>\n\n<p>AT+CNMI=0,0,0,0,0 // do not issue messages when receiving new SMS; again, makes life easier for me if I dont have to check for unwanted replies.</p>\n\n<p>AT+CMGF=1 // SMS format: text</p>\n\n<p>AT+CIPFLP=0 // do not fix local port (according to SIM appnote this provides faster reconnection to server)</p>\n\n<p>AT+CIPMODE=1 // Transparent TCP mode : everything written to the GSM module is sent through TCP connection</p>\n\n<p>AT+CIPCSGP=1,\"gprs.personal.com\",\"gprs\",\"adgj\" //APN settings (APN, username, password)</p>\n\n<p>AT+CGDCONT=1,\"IP\",\"gprs.personal.com\" //type of connection</p>\n\n<p>AT+CIPCCFG=3,2,256,1</p>\n\n<p>AT+CIPSTART=\"TCP\",\"xxx.xxx.xxx.xxx\",\"82\" // connects to server on ip address xxx.xxx.xxx.xxx, port 82</p>\n\n<p>After issuing the last command, GSM module will reply with \"CONNECT OK\" if the connection attempt was succesful. \nFrom that moment on, every byte sent to the UART of the GSM will be sent to the server. \nTo go back to command mode, you can send the string \"+++\" (three plus signs) with no delay between them and with no byte before or after for at least 0.5s.</p>\n\n<p>If the connection to the server goes down for some reason you can reconnect using:</p>\n\n<p>AT+CIPSHUT // closes TCP connection</p>\n\n<p>AT+CIPSTART=\"TCP\",\"xxx.xxx.xxx.xxx\",\"82\" // re-issue the command for starting TCP connection</p>\n\n<p>Best regards.</p>\n" }, { "answer_id": 58624899, "author": "Stefan Ziegler", "author_id": 12297053, "author_profile": "https://Stackoverflow.com/users/12297053", "pm_score": 0, "selected": false, "text": "<p>Virtenio uses SIMCOM GPRS modems and if you have questions for such a modem, then you can ask me. I've developed the driver for Virtenio's <a href=\"https://www.virtenio.com/en/portfolio-items/preongate-gprs/\" rel=\"nofollow noreferrer\">GPRS Gateway</a> and I have knowledge here.</p>\n\n<p>Basically, you need at least the following commands for a GPRS connection:</p>\n\n<pre><code>AT+CGATT\nAT+CSTT\nAT+CIICR\nAT+CIFSR\nAT+CIPSTART\nAT+CIPSEND\nAT+CIPRXGET\nAT+CIPCLOSE\n</code></pre>\n\n<p>You also have to configure you modem first in order to get it to work properly, for instance to configure the data mode (textual or not) and some other things.</p>\n\n<p>Hope this helps you.</p>\n" }, { "answer_id": 71136856, "author": "Abdul Alim Shakir", "author_id": 8504033, "author_profile": "https://Stackoverflow.com/users/8504033", "pm_score": 0, "selected": false, "text": "<p>AT Commands for SIM900A</p>\n<p><strong>Parameters(AT+GSLP):</strong></p>\n<p>time: Time to sleep in milliseconds</p>\n<p>Example : <code>AT+GSLP=1500</code></p>\n<p><strong>Parameters(AT+CWMODE):</strong></p>\n<p>mode: An integer designating the mode of operation either 1, 2, or 3.</p>\n<p>1 = Station mode (client)</p>\n<p>2 = AP mode (host)</p>\n<p>3 = AP + Station mode</p>\n<p>Example : <code>AT+CWMODE=1</code></p>\n<p><strong>Parameters(AT+CIPMUX):</strong></p>\n<p>mode: An integer designating the mode of operation either 0 or 1</p>\n<p>0 = Single Connections</p>\n<p>1 = Multiple Connections</p>\n<p>Example : <code>AT+CIPMUX=0</code></p>\n<p><strong>Parameters(AT+CIPMODE):</strong></p>\n<p>mode: An integer designating the mode of operation either 0 or 1</p>\n<p>0 = Normal mode</p>\n<p>1 = unvarnished transmission mode</p>\n<p>Example : <code>AT+CIPMODE=0</code></p>\n<p><strong>Parameters(AT+CIPSTART):</strong></p>\n<p>type:String, “TCP” or “UDP”</p>\n<p>addr:String, remote IP</p>\n<p>port:String, remote port</p>\n<p>Example : <code>AT+CIPSTART = “TCP”,”182.65.89.118”, 8000</code></p>\n<p><strong>Parameters(AT+CIPSEND):</strong></p>\n<p>length: data length, MAX 2048 bytes</p>\n<p>Example : <code>AT+CIPSEND = 47</code></p>\n<p><em>Unvarnished Transmission Mode</em></p>\n<p>Wrap return “&gt;” after execute command. Enters unvarnished transmission, 20ms interval between each packet,maximum 2048 bytes per packet. When single packet containing “+++” is received, it returns to command mode.</p>\n<p><strong>Parameters(AT+CIPCLOSE):</strong></p>\n<p>Close TCP or UDP connection. For single connection mode.</p>\n<p>Example : <code>AT+CIPCLOSE</code></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What are all [AT](http://en.wikipedia.org/wiki/Hayes_command_set) commands required for [GPRS](http://en.wikipedia.org/wiki/General_Packet_Radio_Service) communication?
A more specific answer, if you're using a MultiTech Multimodem GPRS (or similar) and Tmobile's internet service (one of the higher tiers usually used with laptops). The uppercase names starting with "M" were the names of the states in the modem control state machine I was using. The data I was collecting was simple GPS strings, which were being stored by a PHP script on my server to be displayed here: <http://www.ubasics.com/wmr/> . A very basic tracking/telemetry application. Reset the modem: ``` MRESET: ATZ ``` Attach to the provider's network: ``` MPROVIDERINIT: at+cgdcont=1,"IP","internet3.voicestream.com",,0,0 MIPINIT: at+wopen=1 MPPPINIT: at#pppmode=1 MCHECKPIN: at+cpin? MGSMREGISTER: at+creg=1 ``` Attach to the providers GPRS network: ``` MGPRSREGISTER: at+cgreg=1 MGPRSATTACH: at+cgatt=1 MGPRSMODE: at#gprsmode=1 ``` Attach to the provider's internet PPP server: ``` MSERVERINIT: AT#APNSERV="internet3.voicestream.com" MUSERNAME: AT#APNUN="" MPASSWORD: AT#APNPW="" MSIGNAL: AT+CSQ MSTARTPPP: at#connectionstart ``` Attach the Modem's internal stack to an HTTP port: ``` MTCPSERVER: AT#TCPSERV="www.ubasics.com" MTCPPORT: AT#TCPPORT=80 MOPENSOCKET: at#otcp ```
261,125
<p>I launch a child process in Java as follows:</p> <pre><code>final String[] cmd = {"&lt;childProcessName&gt;"}; Process process = Runtime.getRuntime().exec(cmd); </code></pre> <p>It now runs in the background. All good and fine. </p> <p>If my program now crashes (it <em>is</em> still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies?</p> <p>If it helps, I'm using Mac OS X 10.5</p>
[ { "answer_id": 261133, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 3, "selected": false, "text": "<p>I worked it out myself already. I add a shutdown hook, as follows:</p>\n\n<pre><code>final String[] cmd = {\"&lt;childProcessName&gt;\"};\nfinal Process process = Runtime.getRuntime().exec(cmd);\nRunnable runnable = new Runnable() {\n public void run() {\n process.destroy();\n }\n};\nRuntime.getRuntime().addShutdownHook(new Thread(runnable));\n</code></pre>\n" }, { "answer_id": 261169, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>As you said, <a href=\"https://web.archive.org/web/20080310051714/http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2\" rel=\"nofollow noreferrer\">addShutdownHook</a> is the way to go.</p>\n<p>BUT:</p>\n<ul>\n<li><p>There's no real guarantee that your shutdown hooks are executed if the program terminates. Someone could kill the Java process and in that case your shutdown hook will not be executed. (as said in this <a href=\"https://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully\">SO question</a>)</p>\n</li>\n<li><p>some of the standard libraries have their own hooks which may run before yours.</p>\n</li>\n<li><p>beware of deadlocks.</p>\n</li>\n</ul>\n<p>Another possibility would be to <a href=\"http://wrapper.tanukisoftware.org/doc/english/index.html\" rel=\"nofollow noreferrer\">wrap your java program in a service</a>.</p>\n" }, { "answer_id": 62725766, "author": "Abhijith.M", "author_id": 10131853, "author_profile": "https://Stackoverflow.com/users/10131853", "pm_score": 1, "selected": false, "text": "<p>Adding shutdown hook is not a reliable method to kill the child processes. This is because Shutdown hook might not necessarily be executed when a force kill is performed from Task Manager.</p>\n<p>One approach would be that the child process can periodically monitor the PID of its parent. This way, Child process can exit itself when the parent exits.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
I launch a child process in Java as follows: ``` final String[] cmd = {"<childProcessName>"}; Process process = Runtime.getRuntime().exec(cmd); ``` It now runs in the background. All good and fine. If my program now crashes (it *is* still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies? If it helps, I'm using Mac OS X 10.5
As you said, [addShutdownHook](https://web.archive.org/web/20080310051714/http://www.onjava.com/pub/a/onjava/2003/03/26/shutdownhook.html?page=2) is the way to go. BUT: * There's no real guarantee that your shutdown hooks are executed if the program terminates. Someone could kill the Java process and in that case your shutdown hook will not be executed. (as said in this [SO question](https://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully)) * some of the standard libraries have their own hooks which may run before yours. * beware of deadlocks. Another possibility would be to [wrap your java program in a service](http://wrapper.tanukisoftware.org/doc/english/index.html).
261,190
<p>I am rendering a rails partial and I want to alternate the background color when it renders the partial. I know that is not super clear so here is an example of what I want to do:</p> Row One grey Background Row Two yellow background Row Three grey Background Row Four yellow background <ul> <li>sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear</li> </ul> <p>This is the view code that I am using </p> <pre><code>&lt;table&gt; &lt;%= render :partial =&gt; 'row' :collection =&gt; @rows %&gt; &lt;/table&gt; </code></pre> <p>the _row.html.erb partial looks like this</p> <pre><code>&lt;tr bgcolor="#AAAAAA"&gt; &lt;td&gt;&lt;%= row.name %&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>The problem is I do not know how to change the background color for every other row. Is there a way to do this?</p>
[ { "answer_id": 261204, "author": "Kristian", "author_id": 23246, "author_profile": "https://Stackoverflow.com/users/23246", "pm_score": 5, "selected": true, "text": "<p>You could use the Cycle helper. Something like this:</p>\n\n<pre><code>&lt;tr class=\"&lt;%= cycle(\"even\", \"odd\") %&gt;\"&gt;\n &lt;td&gt;&lt;%= row.name %&gt;&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>Or in your case use bgcolor instead, although i would recomend using css classes.</p>\n\n<p>You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and_more’). </p>\n\n<p>There is also: reset_cycle(‘cycle_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list.</p>\n\n<p>Check the rails <a href=\"http://apidock.com/rails/ActionView/Helpers/TextHelper/cycle\" rel=\"noreferrer\">documentation</a> for more examples.</p>\n" }, { "answer_id": 854437, "author": "didip", "author_id": 92666, "author_profile": "https://Stackoverflow.com/users/92666", "pm_score": 0, "selected": false, "text": "<p>Another idea, you can use javascript to change the element's style based on (total number of TD's % 2). </p>\n\n<p>That way all your visual stuff are contained in html/css/javascript layer. Then again, this technique does not work if javascript is disabled.</p>\n" }, { "answer_id": 14175375, "author": "Brendan", "author_id": 633523, "author_profile": "https://Stackoverflow.com/users/633523", "pm_score": 0, "selected": false, "text": "<p>There is one \"gotcha\" with cycle: If you should append to the string, the cycle breaks. For example,</p>\n\n<pre><code>cycle('odd', 'even') &lt;&lt; \" some other classes\"\n</code></pre>\n\n<p>will break the cycle. However, reversing the order or constructing a string works fine:</p>\n\n<pre><code>\"some other classes \" &lt;&lt; cycle('odd', 'even')\n\"#{cycle('odd', 'even')} some other classes\"\n</code></pre>\n\n<p>I've not (yet) delved into the source to see why this may be so. Also, I'm using Rails 3.2.x</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5004/" ]
I am rendering a rails partial and I want to alternate the background color when it renders the partial. I know that is not super clear so here is an example of what I want to do: Row One grey Background Row Two yellow background Row Three grey Background Row Four yellow background * sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear This is the view code that I am using ``` <table> <%= render :partial => 'row' :collection => @rows %> </table> ``` the \_row.html.erb partial looks like this ``` <tr bgcolor="#AAAAAA"> <td><%= row.name %></td> </tr> ``` The problem is I do not know how to change the background color for every other row. Is there a way to do this?
You could use the Cycle helper. Something like this: ``` <tr class="<%= cycle("even", "odd") %>"> <td><%= row.name %></td> </tr> ``` Or in your case use bgcolor instead, although i would recomend using css classes. You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and\_more’). There is also: reset\_cycle(‘cycle\_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list. Check the rails [documentation](http://apidock.com/rails/ActionView/Helpers/TextHelper/cycle) for more examples.
261,202
<p>I've written a little web site in my effort to learn vb.net and asp.net, fairly happy with it so rented some space and uploaded it, it was written using asp.net express edition 2008 and sql server express .... I've uploaded it and I've found that it was written in .NET 3.5 and my host only deals with 2.01 ... I've sorted most of that out, and trimmed my web.config file back to basics, but my forms based authentication isn't working </p> <pre><code>&lt;compilation debug="true" strict="false" explicit="true"&gt; &lt;/compilation&gt; &lt;authentication mode="Forms" /&gt; &lt;customErrors mode="Off"/&gt; &lt;/system.web&gt; </code></pre> <p>And it keeps reporting that the sql server does not support remote access ...... not sure what to do next, I don't have to write my own security routines do i ? I have a sql server back end</p> <p>Thanks for your time</p> <p>Chris</p>
[ { "answer_id": 261208, "author": "Yooakim", "author_id": 6536, "author_profile": "https://Stackoverflow.com/users/6536", "pm_score": 1, "selected": false, "text": "<p>If the probllem is that you can not access your SQL Server it may be that you are using a trusted connection to it?</p>\n\n<p>It is not likely to work if the website is on a ISP network and your SQL Server is on another network.</p>\n\n<p>What you then need to do is take a look at your connectionstring to change it so that you pass along the username/password in the connection string. NB: This is not optimal in terms of security but it is a way to access remot SQL Servers that are in antother domain.</p>\n\n<p>/joakim</p>\n" }, { "answer_id": 261590, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 2, "selected": true, "text": "<p>Are you using the SqlMembershipProvider to store your users in your database? Check your config file's section and make sure the connectionStringName refers to the name of your connection string.</p>\n" }, { "answer_id": 263709, "author": "spacemonkeys", "author_id": 32336, "author_profile": "https://Stackoverflow.com/users/32336", "pm_score": 0, "selected": false, "text": "<p>Cheers for your help people, changed my web.config to</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;configuration&gt;\n &lt;appSettings/&gt;\n &lt;connectionStrings&gt;\n &lt;add name=\"DatebaseConnectionString\" connectionString=\"ohh wouldn't you like to know\" /&gt;\n &lt;/connectionStrings&gt;\n &lt;system.web&gt;\n &lt;roleManager enabled=\"true\" /&gt;\n &lt;compilation debug=\"true\" strict=\"false\" explicit=\"true\"&gt;\n &lt;/compilation&gt;\n &lt;pages&gt;\n &lt;namespaces&gt;\n &lt;clear/&gt;\n &lt;add namespace=\"System\"/&gt;\n &lt;add namespace=\"System.Collections\"/&gt;\n &lt;add namespace=\"System.Collections.Generic\"/&gt;\n &lt;add namespace=\"System.Collections.Specialized\"/&gt;\n &lt;add namespace=\"System.Configuration\"/&gt;\n &lt;add namespace=\"System.Text\"/&gt;\n &lt;add namespace=\"System.Text.RegularExpressions\"/&gt;\n &lt;add namespace=\"System.Web\"/&gt;\n &lt;add namespace=\"System.Web.Caching\"/&gt;\n &lt;add namespace=\"System.Web.SessionState\"/&gt;\n &lt;add namespace=\"System.Web.Security\"/&gt;\n &lt;add namespace=\"System.Web.Profile\"/&gt;\n &lt;add namespace=\"System.Web.UI\"/&gt;\n &lt;add namespace=\"System.Web.UI.WebControls\"/&gt;\n &lt;add namespace=\"System.Web.UI.WebControls.WebParts\"/&gt;\n &lt;add namespace=\"System.Web.UI.HtmlControls\"/&gt;\n &lt;/namespaces&gt;\n &lt;/pages&gt;\n &lt;authentication mode=\"Forms\" /&gt;\n &lt;membership defaultProvider=\"SqlProvider\"&gt;\n &lt;providers&gt;\n &lt;add connectionStringName=\"DatebaseConnectionString\" applicationName=\"pedalpedalpuffpuff.com\"\n enablePasswordRetrieval=\"false\" enablePasswordReset=\"true\"\n requiresQuestionAndAnswer=\"true\" requiresUniqueEmail=\"true\"\n passwordFormat=\"Hashed\" maxInvalidPasswordAttempts=\"5\" passwordAttemptWindow=\"10\"\n name=\"SqlProvider\" type=\"System.Web.Security.SqlMembershipProvider\" /&gt;\n &lt;/providers&gt;\n &lt;/membership&gt;\n &lt;customErrors mode=\"Off\"/&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>And all worked fine</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32336/" ]
I've written a little web site in my effort to learn vb.net and asp.net, fairly happy with it so rented some space and uploaded it, it was written using asp.net express edition 2008 and sql server express .... I've uploaded it and I've found that it was written in .NET 3.5 and my host only deals with 2.01 ... I've sorted most of that out, and trimmed my web.config file back to basics, but my forms based authentication isn't working ``` <compilation debug="true" strict="false" explicit="true"> </compilation> <authentication mode="Forms" /> <customErrors mode="Off"/> </system.web> ``` And it keeps reporting that the sql server does not support remote access ...... not sure what to do next, I don't have to write my own security routines do i ? I have a sql server back end Thanks for your time Chris
Are you using the SqlMembershipProvider to store your users in your database? Check your config file's section and make sure the connectionStringName refers to the name of your connection string.
261,215
<p>I need to write the content of a map (key is ID of int, value is of self-defined struct) into a file, and load it from the file later on. Can I do it in MFC with CArchive?</p> <p>Thank you!</p>
[ { "answer_id": 261239, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 1, "selected": false, "text": "<p>I don't know much about MFC, but your problem is rather trivially solved using <a href=\"http://www.boost.org/doc/libs/1_35_0/libs/serialization/doc/index.html\" rel=\"nofollow noreferrer\">Boost.Serialization</a></p>\n\n<pre><code>struct MapData {\n int m_int;\n std::string m_str;\n\n private: \n friend class boost::serialization::access; \n\n template&lt;class Archive&gt; \n void serialize(Archive &amp;ar, const unsigned int version) \n { \n ar &amp; m_int; \n ar &amp; m_str; \n } \n};\n\nstd::map&lt; int, MapData &gt; theData;\n\ntemplate&lt;class Archive&gt;\nvoid serialize(Archive &amp; ar, std::map&lt; int, MapData &gt; &amp; data, const unsigned int version)\n{\n ar &amp; data;\n}\n</code></pre>\n\n<p>And then later were you want to do the real archiving:</p>\n\n<pre><code>std::ofstream ofs(\"filename\"); \nboost::archive::binary_oarchive oa(ofs); \noa &lt;&lt; theData; \n</code></pre>\n\n<p>That's it.</p>\n\n<p>(disclaimer: code simply typed in this box, not tested at all, typo's were intended ;)</p>\n" }, { "answer_id": 261303, "author": "Reunanen", "author_id": 19254, "author_profile": "https://Stackoverflow.com/users/19254", "pm_score": 3, "selected": false, "text": "<p>In MFC, I believe it's easiest to first serialize the size of the map, and then simply iterate through all the elements.</p>\n\n<p>You didn't specify if you use <code>std::map</code> or MFC's <code>CMap</code>, but a version based on <code>std::map</code> could look like this:</p>\n\n<pre><code>void MyClass::Serialize(CArchive&amp; archive)\n{\n CObject::Serialize(archive);\n if (archive.IsStoring()) {\n archive &lt;&lt; m_map.size(); // save element count\n std::map&lt;int, MapData&gt;::const_iterator iter = m_map.begin(), \n iterEnd = m_map.end();\n for (; iter != iterEnd; iter++) {\n archive &lt;&lt; iter-&gt;first &lt;&lt; iter-&gt;second;\n }\n }\n else {\n m_map.clear();\n size_t mapSize = 0;\n archive &gt;&gt; mapSize; // read element count\n for (size_t i = 0; i &lt; mapSize; ++i) {\n int key;\n MapData value;\n archive &gt;&gt; key;\n archive &gt;&gt; value;\n m_map[key] = value;\n }\n }\n}\n</code></pre>\n\n<p>If an error occurs when reading the archive, one of the streaming operations should throw an exception, which would then be caught by the framework on a higher level.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26404/" ]
I need to write the content of a map (key is ID of int, value is of self-defined struct) into a file, and load it from the file later on. Can I do it in MFC with CArchive? Thank you!
In MFC, I believe it's easiest to first serialize the size of the map, and then simply iterate through all the elements. You didn't specify if you use `std::map` or MFC's `CMap`, but a version based on `std::map` could look like this: ``` void MyClass::Serialize(CArchive& archive) { CObject::Serialize(archive); if (archive.IsStoring()) { archive << m_map.size(); // save element count std::map<int, MapData>::const_iterator iter = m_map.begin(), iterEnd = m_map.end(); for (; iter != iterEnd; iter++) { archive << iter->first << iter->second; } } else { m_map.clear(); size_t mapSize = 0; archive >> mapSize; // read element count for (size_t i = 0; i < mapSize; ++i) { int key; MapData value; archive >> key; archive >> value; m_map[key] = value; } } } ``` If an error occurs when reading the archive, one of the streaming operations should throw an exception, which would then be caught by the framework on a higher level.
261,219
<p>I'm having a bit of trouble trying to get class variables to work in javascript. </p> <p>I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables.</p> <p>This is why this bit of code confuses me.</p> <p>What is the correct way to implement class variables?</p> <pre><code>function classA() {}; classA.prototype.shared = 0; a = new classA; //print both values to make sure that they are the same classA.prototype.shared; a.shared; //increment class variable classA.prototype.shared++; //Verify that they are each 1 (Works) classA.prototype.shared; a.shared; //now increment the other reference a.shared++; //Verify that they are each 2 (Doesn't Work) classA.prototype.shared; a.shared; </code></pre> <p>UPDATE: So it seems that everyone is confirming the fact that by incrementing the instance's variable we don't affect the prototype. This is fine, this is what I have documented in my example, but doesn't this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance's var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object. </p> <p>I also understand that this isn't java/c++/ruby/python, it's a different language. I'm just curious as to why this behavior might be good. </p>
[ { "answer_id": 261241, "author": "Chei", "author_id": 11411, "author_profile": "https://Stackoverflow.com/users/11411", "pm_score": 1, "selected": false, "text": "<p>If you instantiate that class (<code>a = new classA</code>), then modifying that instance <code>a</code> won't change the base class itself. Instances of <code>classA</code> will inherit everything from <code>classA.prototype</code>, but that doesn't apply backwards, changing <code>a</code> won't change <code>classA</code>.<br>\nIf you have two instances like <code>a1 = new classA</code> and <code>a2 = new classA</code> then you can make changes to both <code>a1</code> and <code>a2</code> without effecting the other. Changing <code>classA.prototype</code> on the other hand will be visible in both of them.<br>\nThe variable <code>shared</code> of instance <code>a</code> will have the default value until it is given a new value. The default value is the value of <code>classA.prototype.shared</code>.</p>\n" }, { "answer_id": 261243, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 2, "selected": false, "text": "<p>You just put the member right on the \"class\" which in JavaScript is the function that constructs objects:</p>\n\n<pre><code>function ClassA(x) { this.x = x; }\nClassA.shared = \"\";\nClassA.prototype.foo = function() {\n return ClassA.shared + this.x;\n}\n\nvar inst1 = new ClassA(\"world\");\nvar inst2 = new ClassA(\"mars\");\n\nClassA.shared = \"Hello \";\nconsole.log(inst1.foo());\nconsole.log(inst2.foo());\nClassA.shared = \"Good bye \";\nconsole.log(inst1.foo());\nconsole.log(inst2.foo());\n</code></pre>\n" }, { "answer_id": 261356, "author": "Chei", "author_id": 11411, "author_profile": "https://Stackoverflow.com/users/11411", "pm_score": 3, "selected": false, "text": "<p>If you want to have a class variable, something like a static variable in Java, then you can declare a variable in the parent class, but then you shouldn't access it as a variable of the child objects. <a href=\"http://www.unix.com.ua/orelly/web/jscript/ch07_05.html\" rel=\"nofollow noreferrer\">This article</a> has a nice example of the class Circle having the variable <code>Circle.PI = 3.14</code> while all the instances of Circle access it as <code>Circle.PI</code> (instead of <code>c.PI</code>). </p>\n\n<p>So my answer is that if you want to have a class variable <code>shared</code> in <code>classA</code> then you shall declare the variable shared in <code>classA</code>, and later you should use <code>classA.shared</code> instead of <code>a.shared</code>. Changing <code>a.shared</code> will never result in <code>classA.shared</code> being changed.</p>\n" }, { "answer_id": 261568, "author": "Daniel Beardsley", "author_id": 13216, "author_profile": "https://Stackoverflow.com/users/13216", "pm_score": 4, "selected": false, "text": "<p><strong>Static (class level) variables can be done like this</strong>:</p>\n\n<pre><code>function classA(){\n //initialize\n}\n\nclassA.prototype.method1 = function(){\n //accessible from anywhere\n classA.static_var = 1;\n //accessible only from THIS object\n this.instance_var = 2;\n}\n\nclassA.static_var = 1; //This is the same variable that is accessed in method1()\n</code></pre>\n\n<p>Your output seems strange <strong>because of the way javascript handles prototypes</strong>. Calling any method / retreiving a variable of an instantiated object <strong>checks the instance first, THEN the prototype</strong>. i.e.</p>\n\n<pre><code>var a = new classA();\nclassA.prototype.stat = 1;\n\n// checks a.stat which is undefined, then checks classA.prototype.stat which has a value\nalert(a.stat); // (a.stat = undefined, a.prototype.stat = 1)\n\n// after this a.stat will not check the prototype because it is defined in the object.\na.stat = 5; // (a.stat = 5, a.prototype.stat = 1)\n\n// this is essentially a.stat = a.stat + 1;\na.stat++; // (a.stat = 6, a.prototype.stat = 1) \n</code></pre>\n" }, { "answer_id": 261639, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "<p>Incrementing the <code>shared</code> property via the instance makes it a property of that instance, which is why you're seeing this behaviour.</p>\n\n<p>Once you've done that, you'll never be accessing the prototype for that property through the instance, but its own property.</p>\n\n<pre><code>&gt;&gt;&gt; function ConstructorA() {};\n&gt;&gt;&gt; ConstructorA.prototype.shared = 0;\n&gt;&gt;&gt; var a = new ConstructorA();\n&gt;&gt;&gt; ConstructorA.prototype.shared++;\n&gt;&gt;&gt; a.shared\n1\n&gt;&gt;&gt; a.hasOwnProperty(\"shared\")\nfalse\n&gt;&gt;&gt; a.shared++;\n&gt;&gt;&gt; a.hasOwnProperty(\"shared\")\ntrue\n</code></pre>\n\n<p>This is why the correct solution is to use <code>ConstructorA.shared</code>, as suggested in many of the answers so far, and always access it through the constructor function, not an instance.</p>\n\n<p>It might help to consider that there's no such thing as a class in JavaScript. \"Instances\" created with the <code>new</code> operator are just objects which have been created by a particular constructor function and have a particular prototype chain. This is why <code>a.shared</code> won't be able to access <code>ConstructorA.shared</code> - property access involves looking at the object in question for the named property, and failing that, walking its prototype chain looking for the property, but the constructor function which created the object isn't part of the prototype chain.</p>\n" }, { "answer_id": 261779, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 0, "selected": false, "text": "<p>What you are defining is not a class variable, it is a default value for an instance variable.</p>\n\n<p>Class variables should be defined directly in the class, which means directly in the constrctor function.</p>\n\n<pre><code>function ClassA()\n{\n ClassA.countInstances = (ClassA.countInstances || 0) + 1;\n}\nvar a1 = new ClassA();\nalert(ClassA.countInstances);\nvar a2 = new ClassA();\nalert(ClassA.countInstances);\n</code></pre>\n\n<p>When you are declaring a variable in the prototype, this variable will be inherited by all instances as instance variables (just like methods) and will ve overriden if you change it in the instance (just like methods).</p>\n" }, { "answer_id": 261948, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 4, "selected": true, "text": "<pre><code>I assumed that since prototypes will be shared between objects then so will their variables.\n</code></pre>\n\n<p>They are, but this:</p>\n\n<pre><code>a.shared++\n</code></pre>\n\n<p>is not doing what you think it's doing. It's in fact (approximately) sugar syntax for:</p>\n\n<pre><code>(a.shared= a.shared+1)-1\n</code></pre>\n\n<p>(the -1 being to return the pre-increment value, not that you're actually using the retrun value, but still.)</p>\n\n<p>So this is actually doing an assigment to a.shared. When you assign to an instance member you are always writing to that instance's own members, <em>not</em> touching any members of any of its prototypes. It's the same as saying:</p>\n\n<pre><code>classA.prototype.shared= 1;\na.shared= 2;\n</code></pre>\n\n<p>So your new a.shared hides the prototype.shared without altering it. Other instances of classA would continue to show the prototype's value 1. If you deleted a.shared you would once again be able to see the prototype's variable that was hidden behind it.</p>\n" }, { "answer_id": 11888408, "author": "fijiaaron", "author_id": 12982, "author_profile": "https://Stackoverflow.com/users/12982", "pm_score": 1, "selected": false, "text": "<p>It's because prototypes are not class definitions. Prototypical variables are not static variables. Think of the word prototype. It's not a model used to build an object -- it is an example object to be duplicated.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28486/" ]
I'm having a bit of trouble trying to get class variables to work in javascript. I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables. This is why this bit of code confuses me. What is the correct way to implement class variables? ``` function classA() {}; classA.prototype.shared = 0; a = new classA; //print both values to make sure that they are the same classA.prototype.shared; a.shared; //increment class variable classA.prototype.shared++; //Verify that they are each 1 (Works) classA.prototype.shared; a.shared; //now increment the other reference a.shared++; //Verify that they are each 2 (Doesn't Work) classA.prototype.shared; a.shared; ``` UPDATE: So it seems that everyone is confirming the fact that by incrementing the instance's variable we don't affect the prototype. This is fine, this is what I have documented in my example, but doesn't this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance's var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object. I also understand that this isn't java/c++/ruby/python, it's a different language. I'm just curious as to why this behavior might be good.
``` I assumed that since prototypes will be shared between objects then so will their variables. ``` They are, but this: ``` a.shared++ ``` is not doing what you think it's doing. It's in fact (approximately) sugar syntax for: ``` (a.shared= a.shared+1)-1 ``` (the -1 being to return the pre-increment value, not that you're actually using the retrun value, but still.) So this is actually doing an assigment to a.shared. When you assign to an instance member you are always writing to that instance's own members, *not* touching any members of any of its prototypes. It's the same as saying: ``` classA.prototype.shared= 1; a.shared= 2; ``` So your new a.shared hides the prototype.shared without altering it. Other instances of classA would continue to show the prototype's value 1. If you deleted a.shared you would once again be able to see the prototype's variable that was hidden behind it.
261,234
<p>Let's say I have an array of lots of values (C++ syntax, sorry):</p> <pre><code>vector&lt;double&gt; x(100000); </code></pre> <p>This array is sorted such that <code>x[n] &gt; x[n-1]</code>.</p> <p>I would like a function to retrieve an array of all values in the range [a, b] (that's inclusive). Some interface like:</p> <pre><code>void subarray(const double a, const double b, vector&lt;double&gt; &amp;sub) { ... } </code></pre> <p>When this function completes, <code>sub</code> will contain the <code>n</code> values that fell in the range [a, b].</p> <p>Of course a linear search is easy:</p> <pre><code>void subarray(const double a, const double b, vector&lt;double&gt; &amp;sub) { for (size_t i = 0; i &lt; data.size(); i++) { if (a &lt;= data[i] &amp;&amp; data[i] &lt;= b) { sub.push_back(data[i]); } } } </code></pre> <p>However, because <code>data</code> is sorted, I should be able to do this much faster using a binary search. Who wants to take a stab at it? Any language is permitted!</p>
[ { "answer_id": 261245, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>You already appear to know that a binary search can be used to find the range, and implementations of those are easily found.</p>\n\n<p>Everything else is just getting trivial array manipulation.</p>\n" }, { "answer_id": 261250, "author": "Diomidis Spinellis", "author_id": 20520, "author_profile": "https://Stackoverflow.com/users/20520", "pm_score": 3, "selected": true, "text": "<p>What you're asking is a bit confusing regarding the the exact range properties and the types. However, you can tweak the following C++ code to suit your needs. The basic intuition is to use lower_bound and upper_bound to find the positions in the array that delineate the range you're looking for.</p>\n\n<pre><code>void subarray(const double a, const double b, vector &lt;double&gt; &amp;sub, vector &lt;int&gt; pn) {\n vector &lt;int&gt;::const_iterator begin, end;\n begin = lower_bound(pn.begin(), pn.end(), a);\n end = upper_bound(pn.begin(), pn.end(), b);\n sub.insert(sub.begin(), begin, end);\n}\n</code></pre>\n" }, { "answer_id": 261252, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "<p>The easy solution:</p>\n\n<ul>\n<li>use binary search to find the lowest a and the highest b</li>\n<li>allocate a new array</li>\n<li>copy the values </li>\n</ul>\n\n<p>Code is trivial as said before.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
Let's say I have an array of lots of values (C++ syntax, sorry): ``` vector<double> x(100000); ``` This array is sorted such that `x[n] > x[n-1]`. I would like a function to retrieve an array of all values in the range [a, b] (that's inclusive). Some interface like: ``` void subarray(const double a, const double b, vector<double> &sub) { ... } ``` When this function completes, `sub` will contain the `n` values that fell in the range [a, b]. Of course a linear search is easy: ``` void subarray(const double a, const double b, vector<double> &sub) { for (size_t i = 0; i < data.size(); i++) { if (a <= data[i] && data[i] <= b) { sub.push_back(data[i]); } } } ``` However, because `data` is sorted, I should be able to do this much faster using a binary search. Who wants to take a stab at it? Any language is permitted!
What you're asking is a bit confusing regarding the the exact range properties and the types. However, you can tweak the following C++ code to suit your needs. The basic intuition is to use lower\_bound and upper\_bound to find the positions in the array that delineate the range you're looking for. ``` void subarray(const double a, const double b, vector <double> &sub, vector <int> pn) { vector <int>::const_iterator begin, end; begin = lower_bound(pn.begin(), pn.end(), a); end = upper_bound(pn.begin(), pn.end(), b); sub.insert(sub.begin(), begin, end); } ```
261,237
<p>How do I create an Application Pool on IIS 6.0 using a PowerShell script?</p> <p>This is what I have come up with so far ...</p> <pre><code>$appPool = [wmiclass] "root\MicrosoftIISv2:IIsApplicationPool" </code></pre> <p>Thanks</p>
[ { "answer_id": 263843, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 4, "selected": true, "text": "<p>It isn't the most obvious process, but here is what worked for me..</p>\n\n<pre><code>$AppPoolSettings = [wmiclass]'root\\MicrosoftIISv2:IISApplicationPoolSetting'\n$NewPool = $AppPoolSettings.CreateInstance()\n$NewPool.Name = 'W3SVC/AppPools/MyAppPool'\n$Result = $NewPool.Put()\n</code></pre>\n\n<p>You might get an error with the call to Put(), but calling it a second (or third) time should make it work. This is due to an issue with PowerShell V1 and WMI.</p>\n" }, { "answer_id": 264404, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 3, "selected": false, "text": "<p>Thought I might share the script I came up with. Thanks to goes to Steven and leon.</p>\n\n<pre><code># Settings\n$newApplication = \"MaxSys.Services\"\n$poolUserName = \"BRISBANE\\svcMaxSysTest\"\n$poolPassword = \"ThisisforT3sting\"\n\n$newVDirName = \"W3SVC/1/ROOT/\" + $newApplication\n$newVDirPath = \"C:\\\" + $newApplication\n$newPoolName = $newApplication + \"Pool\"\n\n#Switch the Website to .NET 2.0\nC:\\windows\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe -sn W3SVC/\n\n# Create Application Pool\n$appPoolSettings = [wmiclass] \"root\\MicrosoftIISv2:IISApplicationPoolSetting\"\n$newPool = $appPoolSettings.CreateInstance()\n$newPool.Name = \"W3SVC/AppPools/\" + $newPoolName\n$newPool.PeriodicRestartTime = 0\n$newPool.IdleTimeout = 0\n$newPool.MaxProcesses = 2\n$newPool.WAMUsername = $poolUserName\n$newPool.WAMUserPass = $poolPassword\n$newPool.AppPoolIdentityType = 3\n$newPool.Put()\n# Do it again if it fails as there is a bug with Powershell/WMI\nif (!$?) \n{\n $newPool.Put() \n}\n\n# Create the virtual directory\nmkdir $newVDirPath\n\n$virtualDirSettings = [wmiclass] \"root\\MicrosoftIISv2:IIsWebVirtualDirSetting\"\n$newVDir = $virtualDirSettings.CreateInstance()\n$newVDir.Name = $newVDirName\n$newVDir.Path = $newVDirPath\n$newVDir.EnableDefaultDoc = $False\n$newVDir.Put()\n# Do it a few times if it fails as there is a bug with Powershell/WMI\nif (!$?) \n{\n $newVDir.Put() \n}\n\n# Create the application on the virtual directory\n$vdir = Get-WmiObject -namespace \"root\\MicrosoftIISv2\" -class \"IISWebVirtualDir\" -filter \"Name = '$newVDirName'\"\n$vdir.AppCreate3(2, $newPoolName)\n\n# Updated the Friendly Name of the application\n$newVDir.AppFriendlyName = $newApplication\n$newVDir.Put()\n</code></pre>\n" }, { "answer_id": 329952, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>All is well! I modified the code so there is an explicit call to the $newPool.Put() command after the initial error. Thanks for your help!</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784/" ]
How do I create an Application Pool on IIS 6.0 using a PowerShell script? This is what I have come up with so far ... ``` $appPool = [wmiclass] "root\MicrosoftIISv2:IIsApplicationPool" ``` Thanks
It isn't the most obvious process, but here is what worked for me.. ``` $AppPoolSettings = [wmiclass]'root\MicrosoftIISv2:IISApplicationPoolSetting' $NewPool = $AppPoolSettings.CreateInstance() $NewPool.Name = 'W3SVC/AppPools/MyAppPool' $Result = $NewPool.Put() ``` You might get an error with the call to Put(), but calling it a second (or third) time should make it work. This is due to an issue with PowerShell V1 and WMI.
261,271
<p>I'd like to compare two consecutive elements in a std::list while iterating through the list. What is the proper way to access element i+1 while my iterator is at element i? Thanks Cobe</p>
[ { "answer_id": 261277, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>Boost has a utility called <a href=\"http://www.boost.org/libs/utility/utility.htm\" rel=\"nofollow noreferrer\"><code>next</code></a> (and its inverse, <code>prior</code>) for just that purpose.</p>\n\n<pre><code>*itr == *next(itr)\n</code></pre>\n\n<p>Edit: But, if we step back to look at the forest, the <em>real</em> question is, why custom-write your <a href=\"http://en.cppreference.com/w/cpp/algorithm/adjacent_find\" rel=\"nofollow noreferrer\"><code>adjacent_find</code></a> function? (I recommend Nicola Bonelli's answer to be accepted.) That's part of the STL, and doesn't require using Boost, if your code doesn't use Boost (thanks to the commenters for pointing this out).</p>\n" }, { "answer_id": 261287, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "<p>The simplest way would be to hold two iterators (since you'll have to stop at the penultimate one anyway).</p>\n\n<pre><code>std::list&lt;int&gt;::const_iterator second = list.begin(),\n end = list.end();\n\nif ( second != end ) // Treat empty list\n for(std::list&lt;int&gt;::const_iterator first = second++; // Post-increment \n second != end; \n ++first, ++second)\n {\n //...\n }\n</code></pre>\n\n<p>Note that <code>first</code> is initialized with the <a href=\"http://cplus.about.com/od/glossar1/g/postincdefn.htm\" rel=\"nofollow noreferrer\">post-incrementation</a> of <code>second</code> so when the loop starts <code>first</code> is <code>list.begin()</code> and second is <code>list.begin()+1</code>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/261271/compare-two-consecutive-elements-in-stdlist#261277\">Chris Jester-Young points out</a> that boost has <code>next</code> and <code>prior</code> functions, although I am not familiar with these functions (for my sins) implementing them is trivial (especially considering that <code>list</code> has bidirectional iterators).</p>\n\n<pre><code>template &lt;class Iterator&gt;\nIterator next(Iterator i) // Call by value, original is not changed\n{ \n return ++i;\n}\n// Implementing prior is left as an exercise to the reader ;o) \n</code></pre>\n\n<p>My feeling is that use of <code>next</code> does not suite this problem as well as maintaining both iterators since you have to remember to make sure <code>next(i)</code> does not equal <code>end()</code> at every use.</p>\n\n<hr>\n\n<p><strong>Edits:</strong></p>\n\n<ul>\n<li>Fixed bug if the list is empty thanks to <a href=\"https://stackoverflow.com/users/20984\">Luc Touraille</a>'s comment.</li>\n<li>Add reference to <code>next</code> and why I think it doesn't fit this use-case.</li>\n</ul>\n" }, { "answer_id": 261413, "author": "Nicola Bonelli", "author_id": 19630, "author_profile": "https://Stackoverflow.com/users/19630", "pm_score": 4, "selected": false, "text": "<p>STL provide the adjacent_find() algorithm that can be used to find two consecutive equal elements. There is also a version with a custom predicate.</p>\n\n<p>These are the prototypes:</p>\n\n<pre><code>template &lt;class ForwardIterator&gt;\n ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last );\n\ntemplate &lt;class ForwardIterator, class BinaryPredicate&gt;\n ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last,\n BinaryPredicate pred );\n</code></pre>\n" }, { "answer_id": 261733, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "<p>List is a Reversible Container, so its iterators are Bidirectional Iterators, which is a model of Forward Iterator, which I'm pretty sure means you can do this (or something equivalent, if you're allergic to breaking out of the middle of a loop etc.):</p>\n\n<pre><code>if (!l.empty()) {\n for (list&lt;T&gt;::const_iterator i = l.begin();;) {\n const T &amp;a = *i;\n ++i;\n if (i == l.end()) break;\n do_comparison(a, *i);\n }\n}\n</code></pre>\n\n<p>You couldn't do that with an Input Iterator, because with those the values only \"exist\" as long as you have an iterator at them. But you can with a Forward Iterator.</p>\n" }, { "answer_id": 33833664, "author": "Joe", "author_id": 5587021, "author_profile": "https://Stackoverflow.com/users/5587021", "pm_score": 0, "selected": false, "text": "<pre><code>for (list&lt;int&gt;::iterator it = test.begin(); it!=test.end(); it++) {\n cout&lt;&lt;*it&lt;&lt;\":\\t\";\n list&lt;int&gt;::iterator copy = it;\n for( list&lt;int&gt;::iterator it2 = ++copy; it2!=test.end();it2++){\n cout&lt;&lt;*it2&lt;&lt;\"\\t\";\n }\n cout&lt;&lt;endl;\n }\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'd like to compare two consecutive elements in a std::list while iterating through the list. What is the proper way to access element i+1 while my iterator is at element i? Thanks Cobe
STL provide the adjacent\_find() algorithm that can be used to find two consecutive equal elements. There is also a version with a custom predicate. These are the prototypes: ``` template <class ForwardIterator> ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last ); template <class ForwardIterator, class BinaryPredicate> ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last, BinaryPredicate pred ); ```
261,296
<p>I have a batch file (in windows XP, with command extension activated) with the following line:</p> <pre><code>for /f %%s in ('type version.txt') do set VERSION=%%s </code></pre> <p>On some computer, it works just fine (as illustrated by <a href="https://stackoverflow.com/questions/130116/dos-batch-commands-to-read-first-line-from-text-file">this SO question</a>), but on other <strong>it kills cmd</strong> (the console window just closes)</p> <p>Why ?</p> <hr> <p>Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY_CURRENT_USER\Software\Microsoft\Command Processor...</p>
[ { "answer_id": 261299, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>I got a first empiric answer:</p>\n\n<pre><code>for /f %%s in (version.txt) do ...\n</code></pre>\n\n<p>works just fine, on every computer.</p>\n\n<p>It seems <code>for /f</code> works with a filename, not with any dos command like 'type filename'.</p>\n\n<p>However, it is not true for all my client's computer (on some, the 'type filename' works fine)</p>\n\n<p>If you want 15 (easy ?) points ;-), you can leave an answer to the question:<br>\n<strong>why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?</strong></p>\n\n<hr>\n\n<p>Edit: 3 years later(!), <a href=\"https://stackoverflow.com/users/385907/barlop\">barlop</a> faced a similar situation, detailed in the question \"<a href=\"https://stackoverflow.com/questions/7236499/for-f-closes-cmd-prompt-immediately\"><code>for /f</code> closes cmd prompt immediately?</a>\". His conclusion was:</p>\n\n<blockquote>\n <p><code>COMSPEC</code> did get listed when doing <code>SET</code>+<kbd>ENTER</kbd>.<br>\n So, I opened the environment variables window, and saw <code>COMSPEC</code> was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine. </p>\n</blockquote>\n\n<p>This <a href=\"http://ss64.org/viewtopic.php?id=504\" rel=\"nofollow noreferrer\">thread on ss64 forum</a>, mentioned by <a href=\"https://stackoverflow.com/users/297408/andriy-m\">Andriy M</a> in his answer to barlop's question, contains the details.</p>\n\n<blockquote>\n <p>The shelling out in the \"<code>for</code>\" loop to complete '<code>dir</code>' (or whatever command you've asked to complete) requires <code>ComSpec</code> to be set in order to reload the <code>cmd</code> window.</p>\n</blockquote>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\ComSpec=\n%SystemRoot%\\system32\\cmd.exe\n</code></pre>\n" }, { "answer_id": 262027, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 0, "selected": false, "text": "<p>Is it that the file doesn't have an extension and thus the cmd treats it like a directory that doesn't exist?</p>\n" }, { "answer_id": 262059, "author": "Craig Lebakken", "author_id": 33130, "author_profile": "https://Stackoverflow.com/users/33130", "pm_score": 0, "selected": false, "text": "<p>If command extensions are disabled, the (set) parameter to the for command must be a file.</p>\n\n<p>If command extensions are enabled, the (set) parameter to the for command may be a file, a string, or a command.</p>\n\n<p>Command extensions are disabled on the client's computer where the 'type filename' set fails.</p>\n\n<p>For infomation on enabling or disabling command extensions, type \"cmd /?\"</p>\n" }, { "answer_id": 262599, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 0, "selected": false, "text": "<p>Wait...could it be that you have the apostrophes around the file name?\nMS is saying that filenamesets get double-quotes and literal strings get apostrophes.</p>\n\n<pre><code>for /F [\"usebackqParsingKeywords\"] {%% | %}variable in (\"filenameset\") do command [CommandLineOptions]\n\nfor /F [\"usebackqParsingKeywords\"] {%% | %}variable in ('LiteralString') do command [CommandLineOptions]\n\nfor /F [\"usebackqParsingKeywords\"] {%% | %}variable in (`command`) do command [CommandLineOptions]\n</code></pre>\n\n<p>Unless of course you're doing this.</p>\n\n<blockquote>\n <p><em>You can use the for /F parsing logic\n on an immediate string, by wrapping\n the filenameset between the\n parentheses in single quotation marks\n (that is, 'filenameset'). Filenameset\n is treated as a single line of input\n from a file, and then it is parsed.</em></p>\n</blockquote>\n" }, { "answer_id": 271002, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 2, "selected": false, "text": "<p>Regarding the command extensions, there is the possibility CMD.EXE is called with /E:OFF so that command extensions are disabled (even though enabled in the registry). </p>\n\n<p>If using command extensions shell options in a script, it is HIGHLY suggested that you do the following trick at the beginning of your scripts.</p>\n\n<p>-- Information pasted from <a href=\"http://www.ss64.com/nt/setlocal.html\" rel=\"nofollow noreferrer\" title=\"http://www.ss64.com/nt/setlocal.html\">http://www.ss64.com/nt/setlocal.html</a></p>\n\n<blockquote>\n <p>SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments is given and one otherwise.</p>\n \n <p>You can use this in a batch file to determine if command extensions are available, using the following technique:</p>\n</blockquote>\n\n<pre><code>VERIFY errors 2&gt;nul\nSETLOCAL ENABLEEXTENSIONS\nIF ERRORLEVEL 1 echo Unable to enable extensions\n</code></pre>\n\n<blockquote>\n <p>This works because \"VERIFY errors\" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)</p>\n \n <p>If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them. </p>\n</blockquote>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
I have a batch file (in windows XP, with command extension activated) with the following line: ``` for /f %%s in ('type version.txt') do set VERSION=%%s ``` On some computer, it works just fine (as illustrated by [this SO question](https://stackoverflow.com/questions/130116/dos-batch-commands-to-read-first-line-from-text-file)), but on other **it kills cmd** (the console window just closes) Why ? --- Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY\_CURRENT\_USER\Software\Microsoft\Command Processor...
I got a first empiric answer: ``` for /f %%s in (version.txt) do ... ``` works just fine, on every computer. It seems `for /f` works with a filename, not with any dos command like 'type filename'. However, it is not true for all my client's computer (on some, the 'type filename' works fine) If you want 15 (easy ?) points ;-), you can leave an answer to the question: **why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?** --- Edit: 3 years later(!), [barlop](https://stackoverflow.com/users/385907/barlop) faced a similar situation, detailed in the question "[`for /f` closes cmd prompt immediately?](https://stackoverflow.com/questions/7236499/for-f-closes-cmd-prompt-immediately)". His conclusion was: > > `COMSPEC` did get listed when doing `SET`+`ENTER`. > > So, I opened the environment variables window, and saw `COMSPEC` was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine. > > > This [thread on ss64 forum](http://ss64.org/viewtopic.php?id=504), mentioned by [Andriy M](https://stackoverflow.com/users/297408/andriy-m) in his answer to barlop's question, contains the details. > > The shelling out in the "`for`" loop to complete '`dir`' (or whatever command you've asked to complete) requires `ComSpec` to be set in order to reload the `cmd` window. > > > ``` HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\ComSpec= %SystemRoot%\system32\cmd.exe ```
261,316
<p>I have created a report in MS Access report and write some VBA code to retrive data and show the report in MS-Word format. But while generate the report on runtime, the report first show or flash the report design view for few seconds and the report will get generated. </p> <p>I would like to find a solution to avoid this flashing of design view while generate the report. Is it possible in this MS-Access or VBA coding. ??</p> <p>I am posting the lines which i used to call the access report from access form code.</p> <p>DoCmd.OpenReport rst![Argument], acPreview</p> <p>this will generate the report but the design screen is flashing for few seconds while execution. </p> <p>And there is no VBA code has been written in the access report.</p> <p>The actual running is, i have prepare the data in a temp access table and generate the report from the table. </p> <p>The problem here is, while launching the report in preview mode the design screen of the report shows of some few seconds. This looks bad from the users side. </p>
[ { "answer_id": 261489, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>It seems you are opening the report in design view in order to change some property. It may be possible to avoid this, but you would need to post the code that opens the report to say for sure.</p>\n" }, { "answer_id": 262588, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "<p>How are you exporting the report to MS-Word? What's the code?</p>\n\n<p>Have you tried the same thing with a simple report (with a table data source) instead of using VBA code? Maybe the VBA is taking so long to run that it's holding the Report open in design mode long enough to be perceptible.</p>\n" }, { "answer_id": 271239, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 1, "selected": true, "text": "<p>What happens if you try this code:</p>\n\n<pre><code> Dim strReport As Report \n strReport = rst!Argument\n If SysCmd(acSysCmdGetObjectState, acReport, strReport) Then\n DoCmd.Close acReport, strReport\n End If\n DoCmd.OpenReport strReport, acPreview\n</code></pre>\n\n<p>What that code does is check to see if the report is already open in any view and then closes it if it is, then opens it. That insures that you're not in design view with the window hidden.</p>\n\n<p>And the code also avoids any possible ByRef reference problems that might be associated with passing a value from a recordset to the OpenReport command.</p>\n" }, { "answer_id": 648141, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have the same thing happen when I call a MS Access Report from a VB6 application. The reason it happens in my case is because I have a form set to appear at startup. If you don't have a startup form selected it should not become visible, therefore no flashing.</p>\n\n<p>Let me know if this helps.</p>\n\n<p>Mike</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18792/" ]
I have created a report in MS Access report and write some VBA code to retrive data and show the report in MS-Word format. But while generate the report on runtime, the report first show or flash the report design view for few seconds and the report will get generated. I would like to find a solution to avoid this flashing of design view while generate the report. Is it possible in this MS-Access or VBA coding. ?? I am posting the lines which i used to call the access report from access form code. DoCmd.OpenReport rst![Argument], acPreview this will generate the report but the design screen is flashing for few seconds while execution. And there is no VBA code has been written in the access report. The actual running is, i have prepare the data in a temp access table and generate the report from the table. The problem here is, while launching the report in preview mode the design screen of the report shows of some few seconds. This looks bad from the users side.
What happens if you try this code: ``` Dim strReport As Report strReport = rst!Argument If SysCmd(acSysCmdGetObjectState, acReport, strReport) Then DoCmd.Close acReport, strReport End If DoCmd.OpenReport strReport, acPreview ``` What that code does is check to see if the report is already open in any view and then closes it if it is, then opens it. That insures that you're not in design view with the window hidden. And the code also avoids any possible ByRef reference problems that might be associated with passing a value from a recordset to the OpenReport command.
261,336
<p>If I declare a temporary auto deleted character buffer using</p> <pre><code>std::auto_ptr&lt;char&gt; buffer(new char[n]); </code></pre> <p>then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.</p> <p>However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].</p> <p>What possibility is there that this mismatch might cause a memory leak?</p>
[ { "answer_id": 261352, "author": "Stephen Veiss", "author_id": 28097, "author_profile": "https://Stackoverflow.com/users/28097", "pm_score": 5, "selected": true, "text": "<p>The behaviour of calling delete on a pointer allocated with new[] is <a href=\"https://isocpp.org/wiki/faq/freestore-mgmt#delete-array\" rel=\"nofollow noreferrer\">undefined</a>. As you assumed, auto_ptr <a href=\"http://www.gotw.ca/conv/001.htm\" rel=\"nofollow noreferrer\">does call delete</a> when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.</p>\n\n<p>If you don't need to transfer the ownership of the pointer, Boost's <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/scoped_array.htm\" rel=\"nofollow noreferrer\">scoped_array</a> class might be what you're looking for.</p>\n" }, { "answer_id": 261353, "author": "nlativy", "author_id": 33635, "author_profile": "https://Stackoverflow.com/users/33635", "pm_score": 3, "selected": false, "text": "<p>That yields undefined behaviour (could be worse than memory leak, for instance heap corruption) try <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">boost's scoped_array or shared_array</a> instead.</p>\n" }, { "answer_id": 261355, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 3, "selected": false, "text": "<p>Calling delete on data allocated with new[] is undefined. This means that the compiler may generate code that may do anything. However in this case it probably works since there's no need to destruct the individual chars in the array, just the array itself.</p>\n\n<p>Still since this behavior is undefined, I would strongly recommend using <code>std::vector&lt;char&gt;</code> or <code>boost::scoped_array&lt;char&gt; / boost::shared_array&lt;char&gt;</code> instead. All are perfectly viable and superior options to using <code>std::auto_ptr&lt;&gt;</code> in this case. If you use <code>std::vector</code> you also have the possibility of dynamically grow the buffer if required.</p>\n" }, { "answer_id": 262779, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>I would use a vector of char as the buffer.</p>\n\n<pre><code>std::vector&lt;char&gt; buffer(size);\n\nread(input,&amp;buffer[0],size);\n</code></pre>\n\n<p>Basically you don't even want to call new if you don't need to.<br>\nA vector provides a run-time sized buffer that you can use just like an array (buffer).<br></p>\n\n<p>The best part is that the vector cleans up after itself and the standard guarantees that all element in the vector will be in contigious storage. Perfect for a buffer.</p>\n\n<p>Or more formaly the guarantee is:</p>\n\n<pre><code>(&amp;buffer[0]) + size == (&amp;buffer[size])\n</code></pre>\n" }, { "answer_id": 262814, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 3, "selected": false, "text": "<p>Is there a good reason not to use std::string? std::vector, as other have suggested? What you're doing is wrong, but without knowing what you're trying to do recommending something else is difficult.</p>\n" }, { "answer_id": 262930, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>This seems awful complex for a very simple solution. What's wrong with you using</p>\n\n<pre><code> char *c=new char[n] \n</code></pre>\n\n<p>here, and then deleting it?\nOr, if you need a bit more dynamic solution, </p>\n\n<pre><code>vector&lt;char&gt; c\n</code></pre>\n\n<p>Occam's Razor, man. :-)</p>\n" }, { "answer_id": 279032, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 2, "selected": false, "text": "<p>Yes, it is wrong. Wrap with a trivial wrapper.</p>\n\n<pre><code>typedef&lt; typename T_ &gt;\nstruct auto_vec{\n T_* t_;\n auto_vec( T_* t ): t_( t ) {}\n ~auto_vec() { delete[] t_; }\n T_* get() const { return t_; }\n T_* operator-&gt;() const { return get(); }\n T_&amp; operator*() const { return *get(); }\n /* you should also define operator=, reset and release, if you plan to use them */\n}\n\nauto_vec&lt;char&gt; buffer( new char[n] );\n</code></pre>\n" }, { "answer_id": 11514542, "author": "Daryn", "author_id": 135114, "author_profile": "https://Stackoverflow.com/users/135114", "pm_score": 2, "selected": false, "text": "<p>A few years have passed since the question was asked.</p>\n\n<p>But I hit this page from a search, so I figured I might as well note:\n<strong>std::unique_ptr</strong>, the C++11 replacement for auto_ptr, can handle deletion of objects created with new[].</p>\n\n<blockquote>\n <p>There are two versions of std::unique_ptr: 1) Manages the lifetime of\n a single object (e.g. allocated with new) <strong>2) Manages the lifetime of a\n dynamically-allocated array of objects (e.g. allocated with new[])</strong></p>\n</blockquote>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow\">cppreference unique_ptr</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259/" ]
If I declare a temporary auto deleted character buffer using ``` std::auto_ptr<char> buffer(new char[n]); ``` then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete. However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[]. What possibility is there that this mismatch might cause a memory leak?
The behaviour of calling delete on a pointer allocated with new[] is [undefined](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array). As you assumed, auto\_ptr [does call delete](http://www.gotw.ca/conv/001.htm) when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible. If you don't need to transfer the ownership of the pointer, Boost's [scoped\_array](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/scoped_array.htm) class might be what you're looking for.
261,338
<p>Talking from a 'best practice' point of view, what do you think is the best way to insert HTML using PHP. For the moment I use one of the following methods (mostly the latter), but I'm curious to know which you think is best.</p> <pre><code>&lt;?php if($a){ ?&gt; [SOME MARKUP] &lt;?php } else{ ?&gt; [SOME OTHER MARKUP] &lt;?php } ?&gt; </code></pre> <p>Opposed to:</p> <pre><code>&lt;?php unset($out); if($a) $out = '[SOME MARKUP]'; else $out = '[OTHER MARKUP]'; print $out; ?&gt; </code></pre>
[ { "answer_id": 261341, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 3, "selected": false, "text": "<p>The most important consideration is keeping the logic separate from the presentation - less coupling will make future changes to both much more straightforward.</p>\n\n<p>You might even want to consider using some sort of templating system like <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">smarty</a>.</p>\n" }, { "answer_id": 261343, "author": "Jeremy Weathers", "author_id": 8794, "author_profile": "https://Stackoverflow.com/users/8794", "pm_score": 1, "selected": false, "text": "<p>Neither. Use <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a>. By separating your internal logic from the display logic you will build code that is much simpler to maintain. (Don't take the path of PHPLib's old template system that tried to completely separate PHP and HTML - it requires display logic to be intermingled with your core business logic and is very messy.) If you absolutely must generate HTML snippets in your PHP code, use your 2nd method, but pass the variable to Smarty.</p>\n" }, { "answer_id": 261363, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "<p>It is better to completely seperate your logic (PHP code) from the presentation (HTML), by using a template engine. </p>\n\n<p>It is fast and easy to insert PHP into HTML, but it gets messy very fast, and is very difficult to maintain. It is a <em>very</em> quick and <em>very</em> dirty approach...</p>\n\n<p>As for which of all the template engines available in PHP is better, see these questions for example:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/163834/php-templates-with-php\">PHP templates - with PHP</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/210507/safe-php-template-engines\">Safe PHP Template Engines</a></li>\n</ul>\n" }, { "answer_id": 261384, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "<p>If a template engine seems to much of a hassle you can make your own poor man's template engine. This example should definately be improved and is not suitable for all tasks, but for smaller sites might be suitable. Just to get you an idea:</p>\n\n<p>template.inc:</p>\n\n<pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;%title%&lt;/title&gt;&lt;/head&gt;&lt;body&gt;\n%mainbody%\nBla bla bla &lt;a href=\"%linkurl%\"&gt;%linkname%&lt;/a&gt;.\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>index.php:</p>\n\n<pre><code>&lt;?php\n$title = getTitle();\n$mainbody = getMainBody();\n$linkurl = getLinkUrl();\n$linkname = getLinkName();\n$search = array(\"/%title%/\", \"/%mainbody%/\", \"/%linkurl%/\", \"/%linkname%/\");\n$replace = array($title, $mainbody, $linkurl, $linkname);\n$template = file_get_contents(\"template.inc\");\nprint preg_replace($search, $replace, $template);\n?&gt;\n</code></pre>\n" }, { "answer_id": 261385, "author": "monzee", "author_id": 31003, "author_profile": "https://Stackoverflow.com/users/31003", "pm_score": 2, "selected": false, "text": "<p>For a very simple case like this, it is fine to use PHP as a template. However, if you go beyond simple logic (and you most likely will), it is a good idea to use template engines.</p>\n\n<p>In Zend Framework, which uses PHP view scripts by default, the recommended way to do this would be like this:</p>\n\n<pre><code>&lt;?php if ($a) : ?&gt;\n [MARKUP HERE]\n&lt;?php else : ?&gt;\n [SOME MORE MARKUP]\n&lt;?php endif ?&gt;\n</code></pre>\n\n<p>The more verbose syntax makes it a lot easier to match conditional blocks in a glance than using braces.</p>\n" }, { "answer_id": 261402, "author": "markus", "author_id": 11995, "author_profile": "https://Stackoverflow.com/users/11995", "pm_score": 1, "selected": false, "text": "<p>Smarty is ok, if you're not using a framework or when you're using a framework which doesn't have it's own templating system.</p>\n\n<p>Otherwise most PHP frameworks and younger generation CMS have their own templating system. </p>\n\n<p>In general the idea of a templating system is to have files which contain almost only HTML (View/Template File) and files which contain only data or business logics (Model or Controller Files).</p>\n\n<p>A Template File can look something like this (example from SilverStripe):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n &lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"&gt;\n &lt;head&gt;\n &lt;% base_tag %&gt;\n $MetaTags\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"tutorial/css/layout.css\" /&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"Main\"&gt;\n &lt;ul id=\"Menu1\"&gt;\n &lt;% control Menu(1) %&gt;\n &lt;li class=\"$LinkingMode\"&gt;\n &lt;a href=\"$Link\" title=\"Go to the &amp;quot;{$Title}&amp;quot; page\"&gt;$MenuTitle&lt;/a&gt;\n &lt;/li&gt;\n &lt;% end_control %&gt;\n &lt;/ul&gt;\n &lt;div id=\"Header\"&gt;\n &lt;h1&gt;$Title&lt;/h1&gt;\n &lt;/div&gt;\n &lt;div id=\"ContentContainer\"&gt;\n $Layout\n &lt;/div&gt;\n &lt;div id=\"Footer\"&gt;\n &lt;span&gt;Some Text&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>You can see that there are only a few non-HTML code pieces inserted in the places where data will be inserted before the page is sent to the client.</p>\n\n<p>Your code can then (simplified) rather look something like:</p>\n\n<pre><code>&lt;?php\n unset($out);\n if($a) $out = '[SOME CONTENT TO INSERT INTO THE TEMPLATE]';\n else $out = '[SOME ALTERNATIVE CONTENT]';\n templateInsert($out);\n?&gt;\n</code></pre>\n\n<p>The great thing about it: Your HTML can be seen as such and changed as such, your designer can make sense of it and doesn't have to look through your code trying to get the bits and pieces together from different places without any chance to view what she's doing. You on the other hand can make changes in the logic without worries about how it will look on the page. You'll most probably also make less mistakes because your code will be compact and therfore readable.</p>\n" }, { "answer_id": 261416, "author": "adnam", "author_id": 27886, "author_profile": "https://Stackoverflow.com/users/27886", "pm_score": 0, "selected": false, "text": "<p>Do NOT use smarty - PHP is a templating system in itself. Consider using this syntax:</p>\n\n<pre><code>&lt;?php if($a):?&gt;\n[SOME MARKUP]\n&lt;?php else: ?&gt;\n[SOME OTHER MARKUP]\n&lt;? endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 261549, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 6, "selected": true, "text": "<p>If you are going to do things that way, you want to separate your logic and design, true. </p>\n\n<p>But you don't need to use Smarty to do this. </p>\n\n<p>Priority is about mindset. I have seen people do shocking things in Smarty, and it eventually turns into people developing sites <strong>in</strong> Smarty, and then some bright spark will decide they need to write a template engine in Smarty (Never underestimate the potential of a dumb idea).</p>\n\n<p>If you break your code into two parts and force yourself to adhere to a standard, then you'll get much better performance.</p>\n\n<p>PageLogic.php </p>\n\n<pre><code>&lt;?php \n\n $pageData = (object)(array()); // Handy trick I learnt. \n\n /* Logic Goes here */\n\n\n $pageData-&gt;foo = SomeValue; \n\n ob_start(); \n require(\"layout.php\"); \n ob_end_flush();\n</code></pre>\n\n<p>Layout.php </p>\n\n<pre><code> &lt;html&gt;\n &lt;!-- etc --&gt;\n &lt;?php for ( $i = 1; $i &lt; 10; $i++ ){ ?&gt;\n &lt;?php echo $pageData-&gt;foo[$i]; ?&gt;\n &lt;?php } ?&gt;\n &lt;!-- etc --&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>PHP Was written as a templating engine, so you at least should <em>try</em> to use it for its designed task before assessing whether or not you need to delve into Smarty. </p>\n\n<hr>\n\n<p>Moreover, if you decide to use a templating engine, try get one that escapes HTML by <strong>default</strong> and you \"opt out\" instead of \"opt in.\" You'll save yourself a lot of XSS headaches. Smarty is weak in this respect, and because of this, there are a lot of content-naïve templates written in it.</p>\n\n<pre><code>{if $cond}\n {$dangerous_value}\n{else}\n {$equally_dangerous_value}\n{/if}\n</code></pre>\n\n<p>Is generally how Smarty templates go. The problem is $dangerous_value can be arbitrary HTML and this just leads to even <strong>more</strong> bad coding practices with untraceable spaghetti code everywhere.</p>\n\n<p>Any template language you consider <strong>should</strong> cater to this concern. e.g.: </p>\n\n<pre><code>{$code_gets_escaped} \n{{$code_gets_escaped_as_a_uri}}\n{{{$dangerous_bare_code}}}\n</code></pre>\n\n<p>This way, your potential doorways for exploitation are easily discernible in the template, as opposed to the doorway to exploitation being the <strong>DEFAULT</strong> behaviour. </p>\n" }, { "answer_id": 261604, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 4, "selected": false, "text": "<p>-1 for the typical hysterical ‘use [my favourite templating system] instead!’ posts. Every PHP post, even if the native PHP answer is a one-liner, always degenerates into this, just as every one-liner JavaScript question ends up full of ‘use [my favourite framework] instead!’. It's embarrassing.</p>\n\n<p>Seriously, we <em>know</em> about separating business logic and presentation concerns. You can do that — or <em>not</em> do that — in any templating system, whether PHP, Smarty or something completely different. No templating system magically separates your concerns without a bunch of thinking.</p>\n\n<p>(In fact a templating system that is too restrictive can end up with you having to write auxiliary code that is purely presentational, cluttering up your business logic with presentational concerns. This is not a win!)</p>\n\n<p>To answer the question that was asked, the first example is OK, but very difficult to read due to the bad indentation. See monzee's example for a more readable way; you can use the : notation or {}s, whichever you prefer, but the important thing for readability is to keep your HTML and PHP as a single, ‘well-formed’ indented hierarchy.</p>\n\n<p>And a final plea: remember htmlspecialchars(). Every time plain text needs to go in to a web page, this <em>must</em> be used, or it's XSS all over the floor. I know this question isn't directly related to that, but every time we post example code including &lt; ?php echo($title) ?> or a framework equivalent without the escaping, we're encouraging the continuation of the security disaster area that most PHP apps have become.</p>\n" }, { "answer_id": 332721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Something I wish I'd known when I first started doing PHP: Keep your heavy-lifting program code as far away from your HTML output as possible. That way they both stay in large, fairly contiguous, readable chunks.</p>\n\n<p>The best way I've found of doing this is to make a static HTML file <em>first</em>, maybe with some fake data so I can poke around and get the design right, then write PHP code to get the dynamic part of the output and glue them both together (how you do that part is up to you - you could do it with Smarty like others are suggesting).</p>\n" }, { "answer_id": 603396, "author": "PartialOrder", "author_id": 49529, "author_profile": "https://Stackoverflow.com/users/49529", "pm_score": 1, "selected": false, "text": "<p>If you <em>must</em> do it either way use the curly braces. Don't echo HTML with PHP.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ]
Talking from a 'best practice' point of view, what do you think is the best way to insert HTML using PHP. For the moment I use one of the following methods (mostly the latter), but I'm curious to know which you think is best. ``` <?php if($a){ ?> [SOME MARKUP] <?php } else{ ?> [SOME OTHER MARKUP] <?php } ?> ``` Opposed to: ``` <?php unset($out); if($a) $out = '[SOME MARKUP]'; else $out = '[OTHER MARKUP]'; print $out; ?> ```
If you are going to do things that way, you want to separate your logic and design, true. But you don't need to use Smarty to do this. Priority is about mindset. I have seen people do shocking things in Smarty, and it eventually turns into people developing sites **in** Smarty, and then some bright spark will decide they need to write a template engine in Smarty (Never underestimate the potential of a dumb idea). If you break your code into two parts and force yourself to adhere to a standard, then you'll get much better performance. PageLogic.php ``` <?php $pageData = (object)(array()); // Handy trick I learnt. /* Logic Goes here */ $pageData->foo = SomeValue; ob_start(); require("layout.php"); ob_end_flush(); ``` Layout.php ``` <html> <!-- etc --> <?php for ( $i = 1; $i < 10; $i++ ){ ?> <?php echo $pageData->foo[$i]; ?> <?php } ?> <!-- etc --> </html> ``` PHP Was written as a templating engine, so you at least should *try* to use it for its designed task before assessing whether or not you need to delve into Smarty. --- Moreover, if you decide to use a templating engine, try get one that escapes HTML by **default** and you "opt out" instead of "opt in." You'll save yourself a lot of XSS headaches. Smarty is weak in this respect, and because of this, there are a lot of content-naïve templates written in it. ``` {if $cond} {$dangerous_value} {else} {$equally_dangerous_value} {/if} ``` Is generally how Smarty templates go. The problem is $dangerous\_value can be arbitrary HTML and this just leads to even **more** bad coding practices with untraceable spaghetti code everywhere. Any template language you consider **should** cater to this concern. e.g.: ``` {$code_gets_escaped} {{$code_gets_escaped_as_a_uri}} {{{$dangerous_bare_code}}} ``` This way, your potential doorways for exploitation are easily discernible in the template, as opposed to the doorway to exploitation being the **DEFAULT** behaviour.
261,345
<p>How do I get the complete request URL (including query string) in my controller? Is it a matter of concatenating my URL and form parameters or is there a better way.</p> <p>I checked <a href="https://stackoverflow.com/questions/40680/how-do-i-get-the-full-url-of-the-page-i-am-on-in-c">this</a> question, but it seems not to be applicable to MVC. </p> <p>Correct me if I'm wrong.</p> <p>Some more detailed information:</p> <p>My call to my <code>SearchController.AdvancedSearch()</code> originates from a form with about 15 optional parameters. Because of the number of parameters and no possible way (I think) to have optional parameters passed in a clean way, I went for a catchall string that is handled in the controller.</p> <p>Now I want my controller to store its call in a breadcrumb component so that when the crumb is clicked the exact same result can be fetched (with all, but not more, of the arguments included). To do this I need the entire request.URL, <em>including the querystring</em>.</p> <p>In <code>Request.RawURL</code>, <code>request.URL</code> etc this query string is not included. In fact currently I do a plain function.</p> <pre><code>String.Format("{0}/{1}", request.Url, request.form) </code></pre> <p>This gives me some weird results (like submit button values etc), but it works. If there are suggestions on how to make this less of an ugly hack, please do tell.</p> <p>I know where to find the current request, but I can't seem to find a raw URL anywhere though. They are all deprived from the querystring and I need that bit too.</p> <p>My controller updates a collection of URLs in my <code>BreadCrumb</code> component. Therefore it needs the request URL. How do you suggest I take on this problem?</p>
[ { "answer_id": 261411, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 2, "selected": false, "text": "<p>You can get at the current Request object by using:</p>\n\n<pre><code>HttpContext.Current.Request\n</code></pre>\n\n<p>However, I've gotta ask -- why do you want the request URL? By doing this, you've made your controller dependent on the Request object, which will make your unit tests much harder to write.</p>\n" }, { "answer_id": 261818, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 5, "selected": false, "text": "<pre><code>HttpContext.Current.Request.RawUrl\nHttpContext.Current.Request.QueryString\n</code></pre>\n\n<p>As far as your second question. Instead of tracking the url's, query string info, etc, that your user has gone to. Track the controllers and actions called. That would remove the need for the Request object entirely.</p>\n" }, { "answer_id": 263872, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>Within the controller, you can access <code>Request.RawUrl</code>.</p>\n" }, { "answer_id": 6557831, "author": "Serhiy", "author_id": 246719, "author_profile": "https://Stackoverflow.com/users/246719", "pm_score": 7, "selected": true, "text": "<p>You can use <a href=\"https://msdn.microsoft.com/en-us/library/system.uri.pathandquery(v=vs.110).aspx\" rel=\"noreferrer\"><code>Request.Url.PathAndQuery</code></a>.</p>\n\n<p>MVC5: use <strong>Request.RequestUri.PathAndQuery</strong></p>\n" }, { "answer_id": 26827583, "author": "Dino Liu", "author_id": 3986569, "author_profile": "https://Stackoverflow.com/users/3986569", "pm_score": 2, "selected": false, "text": "<pre><code>Request.RawUrl\n</code></pre>\n\n<p>Use this property is return the all url.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
How do I get the complete request URL (including query string) in my controller? Is it a matter of concatenating my URL and form parameters or is there a better way. I checked [this](https://stackoverflow.com/questions/40680/how-do-i-get-the-full-url-of-the-page-i-am-on-in-c) question, but it seems not to be applicable to MVC. Correct me if I'm wrong. Some more detailed information: My call to my `SearchController.AdvancedSearch()` originates from a form with about 15 optional parameters. Because of the number of parameters and no possible way (I think) to have optional parameters passed in a clean way, I went for a catchall string that is handled in the controller. Now I want my controller to store its call in a breadcrumb component so that when the crumb is clicked the exact same result can be fetched (with all, but not more, of the arguments included). To do this I need the entire request.URL, *including the querystring*. In `Request.RawURL`, `request.URL` etc this query string is not included. In fact currently I do a plain function. ``` String.Format("{0}/{1}", request.Url, request.form) ``` This gives me some weird results (like submit button values etc), but it works. If there are suggestions on how to make this less of an ugly hack, please do tell. I know where to find the current request, but I can't seem to find a raw URL anywhere though. They are all deprived from the querystring and I need that bit too. My controller updates a collection of URLs in my `BreadCrumb` component. Therefore it needs the request URL. How do you suggest I take on this problem?
You can use [`Request.Url.PathAndQuery`](https://msdn.microsoft.com/en-us/library/system.uri.pathandquery(v=vs.110).aspx). MVC5: use **Request.RequestUri.PathAndQuery**
261,348
<p>I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?</p>
[ { "answer_id": 261349, "author": "Jens Bannmann", "author_id": 7641, "author_profile": "https://Stackoverflow.com/users/7641", "pm_score": 7, "selected": true, "text": "<p>The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:</p>\n\n<pre><code>import javax.annotation.Resource;\nimport javax.servlet.ServletContext;\nimport javax.xml.ws.WebServiceContext;\nimport javax.xml.ws.handler.MessageContext;\n\n...\n\n@Resource\nprivate WebServiceContext context;\n</code></pre>\n\n<p>Then, you can access the servlet context using:</p>\n\n<pre><code>ServletContext servletContext =\n (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);\n</code></pre>\n" }, { "answer_id": 35776676, "author": "Mirko Cianfarani", "author_id": 1461682, "author_profile": "https://Stackoverflow.com/users/1461682", "pm_score": 2, "selected": false, "text": "<p>If you use Maven add this dependency!!!</p>\n\n<pre><code> &lt;dependency&gt;\n &lt;groupId&gt;javax.servlet&lt;/groupId&gt;\n &lt;artifactId&gt;servlet-api&lt;/artifactId&gt;\n &lt;version&gt;2.4&lt;/version&gt;\n &lt;scope&gt;provided&lt;/scope&gt;\n &lt;/dependency&gt;\n</code></pre>\n\n<p>So I solved for avoid conflict error for get ServletContext\n<a href=\"https://rishisoftwareblog.wordpress.com/2013/02/06/using-a-servlet-config-file-with-a-cxf-jax-rs-web-service/\" rel=\"nofollow\">INFO :</a></p>\n\n<p>And in class method I use </p>\n\n<pre><code>@WebService(endpointInterface = \"choice.HelloWorld\")\npublic class HelloWorldImpl implements HelloWorld {\n @Resource\n private WebServiceContext context;\n public String sayHi(String text) {\n HttpServletRequest request =(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);\n System.out.println(request.getContextPath());\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7641/" ]
I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?
The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service: ``` import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; ... @Resource private WebServiceContext context; ``` Then, you can access the servlet context using: ``` ServletContext servletContext = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT); ```
261,351
<p>I have a web page <code>x.php</code> (in a password protected area of my web site) which has a form and a button which uses the <code>POST</code> method to send the form data and opens <code>x.php#abc</code>. This works pretty well.</p> <p>However, if the users decides to navigate back in Internet Explorer 7, all the fields in the original <code>x.php</code> get cleared and everything must be typed in again. I cannot save the posted information in a session and I am trying to understand how I can get IE7 to behave the way I want.</p> <p>I've searched the web and found answers which suggest that the HTTP header should contain explicit caching information. Currently, I've tried this :</p> <pre><code>session_name("FOO"); session_start(); header("Pragma: public"); header("Expires: Fri, 7 Nov 2008 23:00:00 GMT"); header("Cache-Control: public, max-age=3600, must-revalidate"); header("Last-Modified: Thu, 30 Oct 2008 17:00:00 GMT"); </code></pre> <p>and variations thereof. Without success. Looking at the returned headers with a tool such as <a href="http://www.wireshark.org/" rel="noreferrer">WireShark</a> shows me that Apache is indeed honouring my headers.</p> <p>So my question is: what am I doing wrong?</p>
[ { "answer_id": 261403, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 2, "selected": false, "text": "<p>Firefox does this kind of caching. As I understand your question, you want IE7 to behave the way Firefox does. I think that's not possible.</p>\n\n<p>Firefox and IE7 differ on the way they interpret the back button.</p>\n\n<p>Firefox will display the DOM tree of the previous page as it was last displayed before the page was left. That is, all the form data will still be contained in the form's input field. But you won't see an <code>onload</code> event upon hitting the back button.</p>\n\n<p>IE7 will render the page again based upon the response it receives from the server. Thus the form is emtpy (unless there were default values sent by the server originally), but you'll see an <code>onload</code> event.</p>\n" }, { "answer_id": 261494, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>I poked around and this is quite a hard problem. Its also a major pain in the ass for Dynamically modified content. You visit the page, javascript augments it with your instruction, you go to the next page, and come back, and javascript has forgotten. And there's no way to simply update the page server-side, because the page comes out of cache. </p>\n\n<p>So I devised a back-button-cache-breaker. </p>\n\n<p>Its evil and bad-for-the-web, but it makes it able for pages to behave how people expect them to behave instead of magically warping all over the place. </p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;//&lt;!-- &lt;![CDATA[\n(function(){\n if( document.location.hash === \"\" )\n {\n document.location.hash=\"_\";\n }\n else\n {\n var l = document.location;\n var myurl = ( l.protocol + \"//\" + l.hostname + l.pathname + l.search); \n document.location = myurl;\n }\n})();\n//]]&gt; --&gt;&lt;/script&gt;\n</code></pre>\n\n<p>This will do a bit of magic in that it detects whether or not the page you are /currently/ viewing was loaded from cache or not. </p>\n\n<p>if you're there the first time, it will detect \"no hash\" , and add \"<code>#_</code>\" to the page url. \nif you're there for the >1st time ( ie: not a direct link to the page ), the page already has the #_ on it, so it removes it and in the process of removing it, triggers a page reload. </p>\n" }, { "answer_id": 261558, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 5, "selected": true, "text": "<p>IE <em>will</em> retain form contents on a back button click automatically, as long as:</p>\n\n<ul>\n<li>you haven't broken cacheing with a no-cache pragma or similar</li>\n<li>the form fields in question weren't dynamically created by script</li>\n</ul>\n\n<p>You seem to have the cacheing in hand, so I'm guessing the latter may apply. (As mkoeller says, Firefox avoids this problem if the page is in the last few back clicks by keeping the page itself alive for longer than it's on the screen. However this is optional, and Firefox will revert to the same behaviour as IE and other browsers once you've browsed a few pages ahead and it has expired the old one.)</p>\n\n<p>If you're creating your own form fields from script onload, then the browser has no way of knowing that the new input control is ‘the same’ as the old instance, so it can't fill it in with the previously-submitted value. In this case if you want it to play well with the back button you have to start storing data on the client.</p>\n\n<p>Then you have to use some sort of state-keying so that each set of data is tied to exactly one instance of the page, otherwise going through multiple instances of the same form or having two browsers tabs open on the form at once will severely confuse your script.</p>\n\n<p>And <em>then</em> you are starting to collect a lot of data if they're big forms, and if the client-side storage mechanism you're using is cookies you can start to lose data, as well as sending a load of unnecessary state nonsense with every HTTP request. Other client-side storage mechanisms are available but they're browser-specific.</p>\n\n<p>In short: doing dynamically-generated forms nicely is a huge pain and it's probably best avoided if you can. Having a hidden form on the page that a script makes visible, thus allowing browsers to do their field-remembering-magic instead of giving you the task, is typically much easier.</p>\n" }, { "answer_id": 261678, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 2, "selected": false, "text": "<p>You could use autocomplete=\"off\" in your fields. \nThis way the values won't be cached by the browser so the values won't be filled in the form when the user clicks the back button.</p>\n" }, { "answer_id": 262062, "author": "Pierre Arnaud", "author_id": 4597, "author_profile": "https://Stackoverflow.com/users/4597", "pm_score": 2, "selected": false, "text": "<p>While trying to further narrow down the problem, I've found the cause of my problem. I was using URLs which were being rewritten by Apache (i.e. I always accessed my page as <code>http://foo.com/page</code> which is mapped by Apache to <code>http://foo.com/page.htm</code>). Using the <em>real</em> URLs solved the problem and made IE7 happy, as long as I specify the proper HTTP header (<code>Cache-Control</code>, <code>Expires</code>, etc.).</p>\n\n<p>Here is what I do in the PHP code to output headers which seem to make all browsers happy with the cache:</p>\n\n<pre><code>function emitConditionalGet($timestamp)\n{\n // See also http://www.mnot.net/cache_docs/\n // and code sample http://simonwillison.net/2003/Apr/23/conditionalGet/\n\n $gmdate_exp = gmdate('D, d M Y H:i:s', time() + 1) . ' GMT';\n $last_modified = gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';\n $etag = '\"'.md5($last_modified).'\"';\n\n // If the client provided any of the if-modified-since or if-none-match\n // infos, take them into account:\n\n $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])\n ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false;\n $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH'])\n ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false;\n\n if (!$if_modified_since &amp;&amp; !$if_none_match)\n {\n return; // the client does not cache anything\n }\n\n if ($if_none_match &amp;&amp; $if_none_match != $etag)\n {\n return; // ETag mismatch: the page changed!\n }\n if ($if_modified_since &amp;&amp; $if_modified_since != $last_modified)\n {\n return; // if-modified-since mismatch: the page changed!\n }\n\n // Nothing changed since last time client visited this page.\n\n header(\"HTTP/1.0 304 Not Modified\");\n header(\"Last-Modified: $last_modified\");\n header(\"ETag: $etag\");\n header(\"Cache-Control: private, max-age=1, must-revalidate\");\n header(\"Expires: $gmdate_exp\");\n header(\"Pragma: private, cache\");\n header(\"Content-Type: text/html; charset=utf-8\");\n exit;\n}\n\nfunction emitDefaultHeaders($timestamp)\n{\n $gmdate_exp = gmdate('D, d M Y H:i:s', time() + 1) . ' GMT';\n $last_modified = gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';\n $etag = '\"'.md5($last_modified).'\"';\n\n header(\"Last-Modified: $last_modified\");\n header(\"ETag: $etag\");\n header(\"Cache-Control: private, max-age=1, must-revalidate\");\n header(\"Expires: $gmdate_exp\");\n header(\"Pragma: private, cache\");\n header(\"Content-Type: text/html; charset=utf-8\");\n}\n\nfunction getTimestamp()\n{\n // Find out when this page's contents last changed; in a static system,\n // this would be the file time of the backing HTML/PHP page. Add your\n // own logic here:\n return filemtime($SCRIPT_FILENAME);\n}\n\n// ...\n\n$timestamp = getTimestamp();\nemitConditionalGet($timestamp);\nemitDefaultHeaders($timestamp); //previously, this variable was mistyped as \"$timestaml\"\n</code></pre>\n" }, { "answer_id": 56979332, "author": "MeSo2", "author_id": 6500909, "author_profile": "https://Stackoverflow.com/users/6500909", "pm_score": 2, "selected": false, "text": "<p>This is an old post, and much has changed since. None the less, I had this very problem with one of my forms (but with Chrome acting up.) It would clear all the info if going back. I found the workaround by total coincidence and needed to share it here, just because it was so odd. Probably it is not the very best place to post this, but here we go.</p>\n\n<p>This is what I had (a stripped down version and not working.) </p>\n\n<pre><code>&lt;table&gt;\n &lt;form&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type=\"number\" value=\"0\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/form&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>And this fixed it (now working.) Moving the <code>&lt;form&gt;</code> tag outside of the <code>&lt;table&gt;</code> and the <code>&lt;tr&gt;</code> tag.</p>\n\n<pre><code>&lt;form&gt;\n&lt;table&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;input type=\"number\" value=\"0\"&gt;&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n&lt;/form&gt;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
I have a web page `x.php` (in a password protected area of my web site) which has a form and a button which uses the `POST` method to send the form data and opens `x.php#abc`. This works pretty well. However, if the users decides to navigate back in Internet Explorer 7, all the fields in the original `x.php` get cleared and everything must be typed in again. I cannot save the posted information in a session and I am trying to understand how I can get IE7 to behave the way I want. I've searched the web and found answers which suggest that the HTTP header should contain explicit caching information. Currently, I've tried this : ``` session_name("FOO"); session_start(); header("Pragma: public"); header("Expires: Fri, 7 Nov 2008 23:00:00 GMT"); header("Cache-Control: public, max-age=3600, must-revalidate"); header("Last-Modified: Thu, 30 Oct 2008 17:00:00 GMT"); ``` and variations thereof. Without success. Looking at the returned headers with a tool such as [WireShark](http://www.wireshark.org/) shows me that Apache is indeed honouring my headers. So my question is: what am I doing wrong?
IE *will* retain form contents on a back button click automatically, as long as: * you haven't broken cacheing with a no-cache pragma or similar * the form fields in question weren't dynamically created by script You seem to have the cacheing in hand, so I'm guessing the latter may apply. (As mkoeller says, Firefox avoids this problem if the page is in the last few back clicks by keeping the page itself alive for longer than it's on the screen. However this is optional, and Firefox will revert to the same behaviour as IE and other browsers once you've browsed a few pages ahead and it has expired the old one.) If you're creating your own form fields from script onload, then the browser has no way of knowing that the new input control is ‘the same’ as the old instance, so it can't fill it in with the previously-submitted value. In this case if you want it to play well with the back button you have to start storing data on the client. Then you have to use some sort of state-keying so that each set of data is tied to exactly one instance of the page, otherwise going through multiple instances of the same form or having two browsers tabs open on the form at once will severely confuse your script. And *then* you are starting to collect a lot of data if they're big forms, and if the client-side storage mechanism you're using is cookies you can start to lose data, as well as sending a load of unnecessary state nonsense with every HTTP request. Other client-side storage mechanisms are available but they're browser-specific. In short: doing dynamically-generated forms nicely is a huge pain and it's probably best avoided if you can. Having a hidden form on the page that a script makes visible, thus allowing browsers to do their field-remembering-magic instead of giving you the task, is typically much easier.
261,362
<p>I've got an HTML "select" element which I'm updating dynamically with code something like this:</p> <pre><code>var selector = document.getElementById('selectorId'); for (var i = 0; i &lt; data.length; ++i) { var opt = document.createElement('option'); opt.value = data[i].id; opt.text = data[i].name; selector.appendChild(opt); } </code></pre> <p>Works fine in Firefox, but IE7 doesn't resize the list box to fit the new data. If the list box is initially empty (which it is in my case), you can hardly see any of the options I've added. Is there a better way to do this? Or a way to patch it up to work in IE?</p>
[ { "answer_id": 261390, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": -1, "selected": false, "text": "<p>You could try replacing the entire select element from generated html code, or as a hack removing the element from the DOM and readding it.</p>\n" }, { "answer_id": 261409, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>Set the <code>innerHTML</code> property of the option objects, instead of their <code>text</code>.</p>\n\n<pre><code>var selector = document.getElementById('selectorId'); \nfor (var i = 0; i &lt; data.length; ++i)\n{\n var opt = document.createElement('option');\n opt.value = data[i].id;\n opt.innerHTML = data[i].name;\n selector.appendChild(opt);\n}\n</code></pre>\n\n<p>Works on IE6, just tested. Does not break on FF3, so I guess this is it.</p>\n\n<p><em>(I chose \"innerHTML\" because this works across browsers. To set the literal text, you have to use \"innerText\" on IE, and \"textContent\" on FF, and you probably have to test it elsewhere as well. As long as there are no special characters (&amp;, &lt;, &gt;) in the \"name\" properties, \"innerHTML\" will be enough.)</em></p>\n" }, { "answer_id": 261469, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 2, "selected": false, "text": "<p>You don't need to manipulate DOM for this. Try this instead</p>\n\n<pre><code>var selector = document.getElementById('selectorId'); \nfor (var i = 0; i &lt; data.length; ++i) {\n selector.options[selector.options.length] = new Option(data[i].name, data[i].id);\n}\n</code></pre>\n" }, { "answer_id": 261563, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<p>Set the width of the select box explicitly, using eg. a CSS ‘width’ style, instead of letting the browser guess the width from its contents.</p>\n" }, { "answer_id": 9234333, "author": "David Gimeno i Ayuso", "author_id": 1202887, "author_profile": "https://Stackoverflow.com/users/1202887", "pm_score": 2, "selected": false, "text": "<p>After adding the option element, force <code>select.style.width</code> to <code>auto</code>, even if it is already <code>auto</code>. </p>\n\n<p>If this doesn't work, clear <code>select.style.width</code> to <code>\"\"</code> and then restore <code>select.style.width</code> to <code>auto</code> again. </p>\n\n<p>That makes Internet Explorer recalculate the optimal width of <code>select</code> elements.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3974/" ]
I've got an HTML "select" element which I'm updating dynamically with code something like this: ``` var selector = document.getElementById('selectorId'); for (var i = 0; i < data.length; ++i) { var opt = document.createElement('option'); opt.value = data[i].id; opt.text = data[i].name; selector.appendChild(opt); } ``` Works fine in Firefox, but IE7 doesn't resize the list box to fit the new data. If the list box is initially empty (which it is in my case), you can hardly see any of the options I've added. Is there a better way to do this? Or a way to patch it up to work in IE?
Set the `innerHTML` property of the option objects, instead of their `text`. ``` var selector = document.getElementById('selectorId'); for (var i = 0; i < data.length; ++i) { var opt = document.createElement('option'); opt.value = data[i].id; opt.innerHTML = data[i].name; selector.appendChild(opt); } ``` Works on IE6, just tested. Does not break on FF3, so I guess this is it. *(I chose "innerHTML" because this works across browsers. To set the literal text, you have to use "innerText" on IE, and "textContent" on FF, and you probably have to test it elsewhere as well. As long as there are no special characters (&, <, >) in the "name" properties, "innerHTML" will be enough.)*
261,368
<p>How do you calculate the number of <code>&lt;td&gt;</code> elements in a particular <code>&lt;tr&gt;</code>?</p> <p>I didn't specify id or name to access directly, we have to use the <code>document.getElementsByTagName</code> concept.</p>
[ { "answer_id": 261383, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 4, "selected": true, "text": "<p>You can use something like the following:</p>\n\n<pre><code>var rowIndex = 0; // rowindex, in this case the first row of your table\nvar table = document.getElementById('mytable'); // table to perform search on\nvar row = table.getElementsByTagName('tr')[rowIndex];\nvar cells = row.getElementsByTagName('td');\nvar cellCount = cells.length;\nalert(cellCount); // will return the number of cells in the row\n</code></pre>\n" }, { "answer_id": 261391, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 1, "selected": false, "text": "<p>Something like</p>\n\n<pre><code>var tot = 0;\nvar trs = document.getElementsByTagName(\"tr\");\nfor (i = 0; i &lt; trs.length; i++) {\n tds = trs[i].getElementsByTagName(\"td\");\n tot += tds.length;\n}\n</code></pre>\n\n<p>At the end, <code>tot</code> hold the total number of all td elements \"sons\" of tr elements.</p>\n" }, { "answer_id": 261397, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 2, "selected": false, "text": "<p>document.getElementsByTagName returns an array of elements, so you should be able to do something like this:</p>\n\n<pre><code>var totals = new Array();\n\nvar tbl = document.getElementById('yourTableId');\nvar rows = tbl.getElementsByTagName('tr');\nfor (var i = 0; i &lt; rows.length; i++) {\n totals.push(rows[i].getElementsByTagName('td').length;\n}\n\n...\n\n// total cells in row 1\ntotals[0];\n// in row 2\ntotals[1];\n// etc.\n</code></pre>\n" }, { "answer_id": 261399, "author": "philnash", "author_id": 28376, "author_profile": "https://Stackoverflow.com/users/28376", "pm_score": 1, "selected": false, "text": "<pre><code>var trs = document.getElementsByTagName('tr');\nfor(var i=0;i&lt;trs.length;i++){\n alert(\"Number of tds in row '+(i+1)+' is ' + tr[i].getElementsByTagName('td').length);\n}\n</code></pre>\n\n<p>will alert the number of &lt;td&gt;s in each &lt;tr&gt; on the page.</p>\n" }, { "answer_id": 261459, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>If you use the <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> library, it should be as simple as this.</p>\n\n<pre><code>$(\"table tr:eq(0) &gt; td\").length\n</code></pre>\n\n<p>You can use anything as a selector as you would CSS3</p>\n\n<pre><code>$(\"#mytableid tr\").eq(0).children(\"td\").length \n</code></pre>\n\n<p>Would be another way to do it. </p>\n" }, { "answer_id": 261532, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<pre><code>tr.cells.length\n</code></pre>\n\n<p>Is an easier way to spell it.</p>\n" }, { "answer_id": 262698, "author": "user34280", "author_id": 34280, "author_profile": "https://Stackoverflow.com/users/34280", "pm_score": 2, "selected": false, "text": "<p>bobince has the correct answer. I tried to give him some love, but I am new with a 0 rep. </p>\n\n<p>tr.cells.length is the quickest way to get what you want.</p>\n\n<p>Now, the assumption is that you already have a reference to the tr. If you don't, at some point you have to have a reference to the table. In the DOM, the table element has an array (actually an HTMLCollection) called rows. </p>\n\n<pre><code>table.rows[r].cells[c]\n</code></pre>\n\n<p>will give you the address of any cell where r = the index of the row and c = the index of the cell within that row.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you calculate the number of `<td>` elements in a particular `<tr>`? I didn't specify id or name to access directly, we have to use the `document.getElementsByTagName` concept.
You can use something like the following: ``` var rowIndex = 0; // rowindex, in this case the first row of your table var table = document.getElementById('mytable'); // table to perform search on var row = table.getElementsByTagName('tr')[rowIndex]; var cells = row.getElementsByTagName('td'); var cellCount = cells.length; alert(cellCount); // will return the number of cells in the row ```
261,374
<p>What is the most efficient way to enumerate every cell in every sheet in a workbook?</p> <p>The method below seems to work reasonably for a workbook with ~130,000 cells. On my machine it took ~26 seconds to open the file and ~5 seconds to enumerate the cells . However I'm no Excel expert and wanted to validate this code snippet with the wider community.</p> <pre><code>DateTime timer = DateTime.Now; Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application(); try { exampleFile = new FileInfo(Path.Combine(System.Environment.CurrentDirectory, "Large.xlsx")); excelApplication.Workbooks.Open(exampleFile.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing); Console.WriteLine(string.Format("Took {0} seconds to open file", (DateTime.Now - timer).Seconds.ToString())); timer = DateTime.Now; foreach(Workbook workbook in excelApplication.Workbooks) { foreach(Worksheet sheet in workbook.Sheets) { int i = 0, iRowMax, iColMax; string data = String.Empty; Object[,] rangeData = (System.Object[,]) sheet.UsedRange.Cells.get_Value(missing); if (rangeData != null) { iRowMax = rangeData.GetUpperBound(0); iColMax = rangeData.GetUpperBound(1); for (int iRow = 1; iRow &lt; iRowMax; iRow++) { for(int iCol = 1; iCol &lt; iColMax; iCol++) { data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty; if (i % 100 == 0) { Console.WriteLine(String.Format("Processed {0} cells.", i)); } i++; } } } } workbook.Close(false, missing, missing); } Console.WriteLine(string.Format("Took {0} seconds to parse file", (DateTime.Now - timer).Seconds.ToString())); } finally { excelApplication.Workbooks.Close(); excelApplication.Quit(); } </code></pre> <p><strong>Edit</strong>:</p> <p>Worth stating that I want to use PIA and interop in order to access properties of excel workbooks that are not exposed by API's that work directly with the Excel file.</p>
[ { "answer_id": 261412, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 3, "selected": true, "text": "<p>Excel PIA Interop is really slow when you are doing things cell by cell.</p>\n\n<p>You should select the range you want to extract, like you did with the <code>Worksheet.UsedRange</code> property and then read the value of the whole range in one step, by invoking <code>get_Value()</code> (or just simply by reading the <code>Value</code> or <code>Value2</code> property, I can't remember which one) on it.</p>\n\n<p>This will yield an <code>object[,]</code>, that is, a two dimensional array, which can be easily enumerated and is quick to be read.</p>\n\n<p><strong>EDIT</strong>: I just read your actual code and realized that it actually does what I proposed. Shame on me for not reading the question properly before answering. In that case, you cannot make it much faster. Excel PIA Interop is slow. If you need a quicker solution you will have to either migrate jExcelApi from Java to C# (not a terribly hard thing to do) or use some commercial component. I suggest to avoid the OLEDB interface at all costs, in order to keep your sanity.</p>\n\n<p>Unrelated, but helpful tip: You should use the ?? operator. It is really handy. Instead of</p>\n\n<pre><code>data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty;\n</code></pre>\n\n<p>you could just write</p>\n\n<pre><code>data = Convert.ToString(rangeData[iRow, iCol]) ?? string.Empty;\n</code></pre>\n\n<p>In that case, even String.Empty is not necessary since <a href=\"http://msdn.microsoft.com/en-us/library/astxcyeh.aspx\" rel=\"nofollow noreferrer\">Convert.ToString(object)</a> converts <code>null</code> to an empty string anyway.</p>\n" }, { "answer_id": 261482, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>I think, this is the most efficient way, how do it with PIA.\nMaybe will littlebit faster using \"foreach\" insted of \"for\", but it will not dramatic change.</p>\n\n<p>If is efficiency your primary goal, you should work with excel files directly - without excel application.</p>\n" }, { "answer_id": 261521, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>There is an open source implementation of an Excel reader and writer called <a href=\"http://sourceforge.net/projects/koogra/\" rel=\"nofollow noreferrer\">Koogra</a>. It allows you to read in the excel file and modify it using pure managed code. \nThis would probably be much faster than the code you are using now.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5182/" ]
What is the most efficient way to enumerate every cell in every sheet in a workbook? The method below seems to work reasonably for a workbook with ~130,000 cells. On my machine it took ~26 seconds to open the file and ~5 seconds to enumerate the cells . However I'm no Excel expert and wanted to validate this code snippet with the wider community. ``` DateTime timer = DateTime.Now; Microsoft.Office.Interop.Excel.Application excelApplication = new Microsoft.Office.Interop.Excel.Application(); try { exampleFile = new FileInfo(Path.Combine(System.Environment.CurrentDirectory, "Large.xlsx")); excelApplication.Workbooks.Open(exampleFile.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing); Console.WriteLine(string.Format("Took {0} seconds to open file", (DateTime.Now - timer).Seconds.ToString())); timer = DateTime.Now; foreach(Workbook workbook in excelApplication.Workbooks) { foreach(Worksheet sheet in workbook.Sheets) { int i = 0, iRowMax, iColMax; string data = String.Empty; Object[,] rangeData = (System.Object[,]) sheet.UsedRange.Cells.get_Value(missing); if (rangeData != null) { iRowMax = rangeData.GetUpperBound(0); iColMax = rangeData.GetUpperBound(1); for (int iRow = 1; iRow < iRowMax; iRow++) { for(int iCol = 1; iCol < iColMax; iCol++) { data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty; if (i % 100 == 0) { Console.WriteLine(String.Format("Processed {0} cells.", i)); } i++; } } } } workbook.Close(false, missing, missing); } Console.WriteLine(string.Format("Took {0} seconds to parse file", (DateTime.Now - timer).Seconds.ToString())); } finally { excelApplication.Workbooks.Close(); excelApplication.Quit(); } ``` **Edit**: Worth stating that I want to use PIA and interop in order to access properties of excel workbooks that are not exposed by API's that work directly with the Excel file.
Excel PIA Interop is really slow when you are doing things cell by cell. You should select the range you want to extract, like you did with the `Worksheet.UsedRange` property and then read the value of the whole range in one step, by invoking `get_Value()` (or just simply by reading the `Value` or `Value2` property, I can't remember which one) on it. This will yield an `object[,]`, that is, a two dimensional array, which can be easily enumerated and is quick to be read. **EDIT**: I just read your actual code and realized that it actually does what I proposed. Shame on me for not reading the question properly before answering. In that case, you cannot make it much faster. Excel PIA Interop is slow. If you need a quicker solution you will have to either migrate jExcelApi from Java to C# (not a terribly hard thing to do) or use some commercial component. I suggest to avoid the OLEDB interface at all costs, in order to keep your sanity. Unrelated, but helpful tip: You should use the ?? operator. It is really handy. Instead of ``` data = rangeData[iRow, iCol] != null ? rangeData[iRow, iCol].ToString() : string.Empty; ``` you could just write ``` data = Convert.ToString(rangeData[iRow, iCol]) ?? string.Empty; ``` In that case, even String.Empty is not necessary since [Convert.ToString(object)](http://msdn.microsoft.com/en-us/library/astxcyeh.aspx) converts `null` to an empty string anyway.
261,375
<p>No doubt I'm missing something really simple here but I just can't see the problem with this query which is producing the following error:</p> <pre><code>SQL query: INSERT INTO ads( ad_id, author, ad_date, category, title, description, condition, price, fullname, telephone, email, status, photo, photothumb ) VALUES ( NULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', '' ); MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ad_id', 'author', 'ad_date', 'category', 'title', 'description', 'condition', '' at line 1 </code></pre> <p>Can someone with a fresh pair of eyes spot the problem?</p> <p>Thanks, Al. </p>
[ { "answer_id": 261380, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 3, "selected": true, "text": "<p>Shouldn't you use back ticks instead of single quotes in column names?</p>\n\n<pre><code>INSERT INTO ads( `ad_id`, `author`, `ad_date`, `category`, `title`, `description`, `condition`, `price`, `fullname`, `telephone`, `email`, `status`, `photo`, `photothumb` )\nVALUES (\nNULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', ''\n);\n</code></pre>\n" }, { "answer_id": 261381, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 1, "selected": false, "text": "<p>Single quotes are used for string literals. In MySQL, by default, double quotes are also used for string literals although this is incompatible with standard SQL and you should stick to single quotes in your code.</p>\n\n<p>For column names, you normally wouldn't quote them at all. If you need to - and you don't for any of yours - then quote them with a backquote (`), or set it to strict ANSI compatible mode (ANSI_QUOTES) and use double quotes.</p>\n" }, { "answer_id": 261426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It might be that CONDITION is a mysql keyword, and not allowed as column name.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/declare-conditions.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/declare-conditions.html</a></p>\n\n<p>You definitely do not need the ' or `</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34019/" ]
No doubt I'm missing something really simple here but I just can't see the problem with this query which is producing the following error: ``` SQL query: INSERT INTO ads( ad_id, author, ad_date, category, title, description, condition, price, fullname, telephone, email, status, photo, photothumb ) VALUES ( NULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', '' ); MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ad_id', 'author', 'ad_date', 'category', 'title', 'description', 'condition', '' at line 1 ``` Can someone with a fresh pair of eyes spot the problem? Thanks, Al.
Shouldn't you use back ticks instead of single quotes in column names? ``` INSERT INTO ads( `ad_id`, `author`, `ad_date`, `category`, `title`, `description`, `condition`, `price`, `fullname`, `telephone`, `email`, `status`, `photo`, `photothumb` ) VALUES ( NULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', '' ); ```
261,377
<p>I apologize in advance for the long post...</p> <p>I used to be able to build our VC++ solutions (we're on VS 2008) when we listed the STLPort include and library directories under VS Menu > Tools > Options > VC++ Directories > Directories for Include and Library files. However, we wanted to transition to a build process that totally relies on .vcproj and .sln files. These can be checked into source control unlike VS Options which have to be configured on each development PC separately. We handled the transition for most libraries by adding the Include directories to each Project's Property Pages > Configuration Properties > C/C++ > General > Additional Include Directories, and Library directories to Linker > General > Additional Library Directories.</p> <p>Unfortunately, this approach doesn't work for STLPort. We get LNK2019 and LNK2001 errors during linking:</p> <pre><code>Error 1 error LNK2019: unresolved external symbol "public: virtual bool __thiscall MyClass::myFunction(class stlp_std::basic_istream&lt;char,class stlp_std::char_traits&lt;char&gt; &gt; &amp;,class MyOtherClass &amp;,class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; &amp;)const " (?myFunction@MyClass@@UBE_NAAV?$basic_istream@DV?$char_traits@D@stlp_std@@@stlp_std@@AAVSbprobScenarioData@@AAV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@3@@Z) referenced in function _main MyLibrary.obj Error 5 error LNK2001: unresolved external symbol "public: static void __cdecl MyClass::myFunction(class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; const &amp;,class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; const &amp;,class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; const &amp;,class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; const &amp;,long,enum MyClass::MessageType,int,class stlp_std::basic_string&lt;char,class stlp_std::char_traits&lt;char&gt;,class stlp_std::allocator&lt;char&gt; &gt; const &amp;)" (?myFunction@MyClass@@SAXABV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@stlp_std@@000JW4MessageType@1@H0@Z) MyLibrary.lib </code></pre> <p>This happens while linking and executable project to dependencies which are library projects. Curiously, this does not happen while linking the library projects themselves. Any ideas?</p>
[ { "answer_id": 261951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is a link error. It doesn't have to do with your include paths.</p>\n\n<p>You either forgot to add MyClass.cpp to your project, or forgot to define those two functions.</p>\n\n<p>The reason the error doesn't happen when \"linking\" library projects is that library projects are not linked. They are simply a bunch of OBJs that are put together by the LIB program into a library file.</p>\n" }, { "answer_id": 267614, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>Add the library name to the list of additional libraries to link. Sorry I'm not in front of a recent version of VS to know exactly where it goes.</p>\n" }, { "answer_id": 293044, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 1, "selected": false, "text": "<p>These link errors suggest that certain classes in <em>your</em> application either haven't been compiled using STLPort or have been omitted from the build. They do not suggest that you aren't linking against STLport.</p>\n\n<p>My guesses would be that:</p>\n\n<ul>\n<li>The build settings for MyClass somehow overwrite the project-wide setting for the include path and thus MyClass is being built using the default C++ STL implementation and not STLport. This should be easy to check - run dumpbin against the object file and check the functions in there reference the standard library in the stlp_* namespace or not. If not, it's likely that the compiler is not picking up the correct include path. I'd also have a look at the command line that the IDE is calling the compiler with. These can be viewed via the C/C++ Configuration properties as well.</li>\n<li>As other posters also mentioned, there is a chance that MyClass isn't being built, but that should be very easy to check.</li>\n</ul>\n" }, { "answer_id": 309128, "author": "rep_movsd", "author_id": 20392, "author_profile": "https://Stackoverflow.com/users/20392", "pm_score": 1, "selected": false, "text": "<p>You have to configure STL port to use the native IOStreams implementation.</p>\n\n<p>Also is there any specific reason you use STLPort? The default STL implementation is recommended unless you are trying to make a cross platform application - even then its not really needed in most cases.</p>\n" }, { "answer_id": 399288, "author": "SunriseProgrammer", "author_id": 10677, "author_profile": "https://Stackoverflow.com/users/10677", "pm_score": 3, "selected": true, "text": "<p>Raymond Chen recently talked about this at <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/12/29/9255240.aspx\" rel=\"nofollow noreferrer\">The Old New Thing</a>-- one cause of these problems is that the library was compiled with one set of switches, but your app is using a different set. What you have to do is:</p>\n\n<p>Get the exact symbol that the linker is looking for. It will be a horrible mangled name. \nUse a hex editor (IIRC, Visual Studio will do this) to look at the .lib file you're linking to. \nFind the symbol that's almost the thing the linker is looking for, but not quite. \nGiven the differences in the symbols, try to figure out what command line switches will help. \nGood luck -- for people who aren't used to this sort of problem, the solution can take days to figure out (!)</p>\n" }, { "answer_id": 687185, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 3, "selected": false, "text": "<p>As mentioned in other answers, this is a linker error and likely the result of the library and the application being compiled with different options. There are a few solutions on tracking this down already (one of them as the chosen answer, currently). These solutions <strong><em>will</em></strong> work. However, there are a few tools that will <strong>make your search much much easier</strong>.</p>\n\n<p>For starters, understanding decorated names will help. Within all that garbage, you will recognise some things: The <strong>name of your function</strong>, <strong>namespaces</strong>, some <strong>class types</strong> you are using. All of those characters around them mean something to the compiler, but you don't need the compiler to tell you what they are.</p>\n\n<blockquote>\n <h2>Enter undname.exe:</h2>\n \n <hr>\n \n <em>undname.exe &lt;decoratedname&gt;</em>\n \n <ul>\n <li>is a simple command line program that is in your VS bin directory. </li>\n <li>takes the decorated name as it's first argument. </li>\n <li>outputs a human readable format of the symbol.</li>\n </ul>\n</blockquote>\n\n<p>Armed with that knowledge, you can now move on to finding a reasonable candidate for the mis-created symbol.</p>\n\n<p>First off, you could edit your libraries in a hex editor, as suggested elsewhere. However, there is a much easier way to find the symbols.</p>\n\n<blockquote>\n <h2>Enter dumpbin.exe:</h2>\n \n <hr>\n \n <em>dumpbin.exe &lt;switches&gt; &lt;library name&gt;</em>\n \n <ul>\n <li>is a simple command line program that is in your VS bin directory.</li>\n <li>takes a set of switches and a library to apply them to.</li>\n <li>outputs information from the library</li>\n </ul>\n</blockquote>\n\n<p>The switch you will be interested in for your question is <em>/linkermember</em>. There are many other switches that can get you very interesting information, but this one will list out all the symbols in the library.</p>\n\n<p>At this point, a little commandline savvy will serve you well. Tools like <em>grep</em> can really shorten your work-cycle, but you can get by with redirecting to a file and using notepad or the like.</p>\n\n<p>Since I don't have your code or library, I'll contrive an example from TinyXML.</p>\n\n<p>Assuming your error message was this:</p>\n\n<pre><code>Error 1 error LNK2019: unresolved external symbol \"public: unsigned char __cdecl TiXmlComment::Accept(bool,class TiXmlVisitor *) \" (?Accept@TiXmlComment@@ZBE_NPAVTiXmlVisitor@@@Z) referenced in function _main MyLibrary.obj \n</code></pre>\n\n<p>Having determined this is a function in the TinyXML, I can start looking for the mismatched symbol. I'll start by dumping the linkermembers of the library. (Notice the switch is singular, this always gets me when I type it from memory!)</p>\n\n<pre><code>\n>dumpbin /linkermember tinyxml.lib\nMicrosoft (R) COFF/PE Dumper Version 8.00.50727.762\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n\nDump of file tinyxml.lib\n\nFile Type: LIBRARY\n\nArchive member name at 8: /\n4992E7BC time/date Wed Feb 11 08:59:08 2009\n uid\n gid\n 0 mode\n B402 size\ncorrect header end\n\n 859 public symbols\n\n 16292 ??$_Allocate@D@std@@YAPADIPAD@Z\n 16292 ??$_Char_traits_cat@U?$char_traits@D@std@@@std@@YA?AU_Secure_char_traits_tag@0@XZ\n 16292 ??$copy_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDI@Z\n 16292 ??$copy_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDIU_Secure_char_traits_tag@1@@Z\n 16292 ??$move_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDI@Z\n 16292 ??$move_s@U?$char_traits@D@std@@@_Traits_helper@std@@YAPADPADIPBDIU_Secure_char_traits_tag@1@@Z\n 16292 ??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z\n 16292 ??0?$_String_val@DV?$allocator@D@std@@@std@@IAE@V?$allocator@D@1@@Z\n 16292 ??0?$_String_val@DV?$allocator@D@std@@@std@@QAE@ABV01@@Z\n\n</code></pre>\n\n<p>This is obviously too much to read, but we don't have to, we know what we're looking for, so we'll just look for it.</p>\n\n<pre><code>\n>dumpbin /linkermember tinyxml.lib | grep Accept\n 529AE ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z\n 529AE ?Accept@TiXmlDeclaration@@UBE_NPAVTiXmlVisitor@@@Z\n 529AE ?Accept@TiXmlDocument@@UBE_NPAVTiXmlVisitor@@@Z\n 529AE ?Accept@TiXmlElement@@UBE_NPAVTiXmlVisitor@@@Z\n 529AE ?Accept@TiXmlText@@UBE_NPAVTiXmlVisitor@@@Z\n 529AE ?Accept@TiXmlUnknown@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlDeclaration@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlDocument@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlElement@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlText@@UBE_NPAVTiXmlVisitor@@@Z\n 3 ?Accept@TiXmlUnknown@@UBE_NPAVTiXmlVisitor@@@Z\n</code></pre>\n\n<p>That's much easier to read. Looking at our error, we're looking for the Accept Function of TiXmlComment. We could grep the output additionally for that name, if we had lots of matches (like looking at the size function in the stl!), but in this case, we can pick it out of the list. Here is where we turn to undname:</p>\n\n<pre><code>\n>undname ?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z\nMicrosoft (R) C++ Name Undecorator\nCopyright (C) Microsoft Corporation. All rights reserved.\n\nUndecoration of :- \"?Accept@TiXmlComment@@UBE_NPAVTiXmlVisitor@@@Z\"\nis :- \"public: virtual bool __thiscall TiXmlComment::Accept(class TiXmlVisitor *)const \"\n</code></pre>\n\n<p>So, in this example, our application is looking for a function which returns an <strong>unsigned char</strong>, but the library has a function returning a <strong>bool</strong>.</p>\n\n<p>This is a contrived example, but it illustrates the technique to use to track down your issue. You are probably looking for a typedef type which is set differently based on your options.</p>\n\n<p>The problem where I ran into this was with <strong>time_t</strong>. In some libraries I was using, the <strong>time_t</strong> used a 32-bit type as part of it's internal representation. This library was generated with an older compiler, where that was the default. In VS 2005, the <strong>time_t</strong> uses a 64-bit type by default. I had to add the preprocessor define <strong>_USE_32BIT_TIME_T</strong> to get it to compile. I tracked this issue down precisely as I have described.</p>\n\n<p>I hope this helps someone solve this issue!</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15515/" ]
I apologize in advance for the long post... I used to be able to build our VC++ solutions (we're on VS 2008) when we listed the STLPort include and library directories under VS Menu > Tools > Options > VC++ Directories > Directories for Include and Library files. However, we wanted to transition to a build process that totally relies on .vcproj and .sln files. These can be checked into source control unlike VS Options which have to be configured on each development PC separately. We handled the transition for most libraries by adding the Include directories to each Project's Property Pages > Configuration Properties > C/C++ > General > Additional Include Directories, and Library directories to Linker > General > Additional Library Directories. Unfortunately, this approach doesn't work for STLPort. We get LNK2019 and LNK2001 errors during linking: ``` Error 1 error LNK2019: unresolved external symbol "public: virtual bool __thiscall MyClass::myFunction(class stlp_std::basic_istream<char,class stlp_std::char_traits<char> > &,class MyOtherClass &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > &)const " (?myFunction@MyClass@@UBE_NAAV?$basic_istream@DV?$char_traits@D@stlp_std@@@stlp_std@@AAVSbprobScenarioData@@AAV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@3@@Z) referenced in function _main MyLibrary.obj Error 5 error LNK2001: unresolved external symbol "public: static void __cdecl MyClass::myFunction(class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,long,enum MyClass::MessageType,int,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &)" (?myFunction@MyClass@@SAXABV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@stlp_std@@000JW4MessageType@1@H0@Z) MyLibrary.lib ``` This happens while linking and executable project to dependencies which are library projects. Curiously, this does not happen while linking the library projects themselves. Any ideas?
Raymond Chen recently talked about this at [The Old New Thing](http://blogs.msdn.com/oldnewthing/archive/2008/12/29/9255240.aspx)-- one cause of these problems is that the library was compiled with one set of switches, but your app is using a different set. What you have to do is: Get the exact symbol that the linker is looking for. It will be a horrible mangled name. Use a hex editor (IIRC, Visual Studio will do this) to look at the .lib file you're linking to. Find the symbol that's almost the thing the linker is looking for, but not quite. Given the differences in the symbols, try to figure out what command line switches will help. Good luck -- for people who aren't used to this sort of problem, the solution can take days to figure out (!)
261,386
<p>I'm new to Flex, and I'm trying to write a simple application. I have a file with an image and I want to display this image on a Graphics. How do I do this? I tried [Embed]-ding it and adding as a child to the component owning the Graphics', but I'm getting a "Type Coercion failed: cannot convert ... to mx.core.IUIComponent" error.</p>
[ { "answer_id": 261768, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 4, "selected": true, "text": "<p>Off the top of my head I can think of two things that might help you (depending on what it is exactly that you're trying to achieve):</p>\n\n<p>If you just want to display an image you've embedded, you can add an <a href=\"http://livedocs.adobe.com/flex/3/langref/mx/controls/Image.html\" rel=\"noreferrer\">Image</a> component to the stage and set the value of its <code>source</code> as the graphical asset (<code>Class</code>) that you're embedding:</p>\n\n<pre><code>[Bindable]\n[Embed(source=\"assets/image.png\")]\nprivate var MyGfx:Class;\n\nmyImage.source = MyGfx;\n</code></pre>\n\n<p>If you actually want to <em>draw</em> a bitmap onto a <code>Graphics</code> object, you can do this with the <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#beginBitmapFill()\" rel=\"noreferrer\">beginBitmapFill()</a> method:</p>\n\n<pre><code>[Bindable]\n[Embed(source=\"assets/image.png\")]\nprivate var MyGfx:Class;\n\nvar myBitmap:BitmapData = new MyGfx().bitmapData;\nmyGraphics.beginBitmapFill(myBitmap);\nmyGraphics.endFill();\n</code></pre>\n\n<p>You might find the <a href=\"http://www.adobe.com/devnet/flex/quickstart/\" rel=\"noreferrer\">Flex Quick Starts</a> articles on Adobe's site useful, especially the <a href=\"http://www.adobe.com/devnet/flex/quickstart/embedding_assets/\" rel=\"noreferrer\">\"Embedding Assets\"</a> section.</p>\n" }, { "answer_id": 261981, "author": "RickDT", "author_id": 5421, "author_profile": "https://Stackoverflow.com/users/5421", "pm_score": 0, "selected": false, "text": "<p>You can also add a regular AS3 displayobject to a Flex component by adding it to the rawChildren collection (myComponent.rawChildren.addChild(myPNG)), but that's a bit of a hack. </p>\n\n<p>If you're trying to do this via myDisplayObject.graphics, please post some sample source.</p>\n" }, { "answer_id": 264170, "author": "Ben Throop", "author_id": 27899, "author_profile": "https://Stackoverflow.com/users/27899", "pm_score": 0, "selected": false, "text": "<p>Since you're a beginner, here's an easy way.</p>\n\n<p>In your application, switch to Design View. </p>\n\n<p>Drag an Image Component from the Component Panel onto the main Application Canvas. </p>\n\n<p>Size the Image on the Canvas and leave it selected. On the right hand side, in the properties panel, click the Folder button on the \"Source\" field. </p>\n\n<p>Choose your image. If you place the image in your project's folder, it will be included in your build folder.</p>\n\n<p>Then take a look at the source view. You will see MXML code that reflects what you've done. You can change this by hand as well. The source=\"blah.png\" part can also be pointed to a remote URL.</p>\n" }, { "answer_id": 3517107, "author": "KateA", "author_id": 279793, "author_profile": "https://Stackoverflow.com/users/279793", "pm_score": 0, "selected": false, "text": "<p>ok there is an other way to do it \nyou can follow <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#includeExamplesSummary\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#includeExamplesSummary</a>\nand use beginBitmapFill () method see example very usefull !</p>\n" }, { "answer_id": 5192958, "author": "Levon", "author_id": 58038, "author_profile": "https://Stackoverflow.com/users/58038", "pm_score": 3, "selected": false, "text": "<p>The accepted answer is incomplete because without a call to <code>drawRect()</code> nothing will be drawn. I have implemented it this way and it works. Notice that I added a matrix translation, otherwise images would have to be drawn either at 0,0 or would be clipped incorrectly.</p>\n\n<pre><code>[Embed(source='assets/land-field.png')] \nprivate var ImgField:Class; \nprivate var field:BitmapData = new ImgField().bitmapData;\n\npublic static function drawImage(g:Graphics, image:BitmapData, x:int, y:int):void {\n var mtx:Matrix = new Matrix();\n mtx.translate(x, y);\n g.beginBitmapFill(image, mtx, false, false);\n g.drawRect(x, y, image.width, image.height);\n g.endFill();\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6533/" ]
I'm new to Flex, and I'm trying to write a simple application. I have a file with an image and I want to display this image on a Graphics. How do I do this? I tried [Embed]-ding it and adding as a child to the component owning the Graphics', but I'm getting a "Type Coercion failed: cannot convert ... to mx.core.IUIComponent" error.
Off the top of my head I can think of two things that might help you (depending on what it is exactly that you're trying to achieve): If you just want to display an image you've embedded, you can add an [Image](http://livedocs.adobe.com/flex/3/langref/mx/controls/Image.html) component to the stage and set the value of its `source` as the graphical asset (`Class`) that you're embedding: ``` [Bindable] [Embed(source="assets/image.png")] private var MyGfx:Class; myImage.source = MyGfx; ``` If you actually want to *draw* a bitmap onto a `Graphics` object, you can do this with the [beginBitmapFill()](http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#beginBitmapFill()) method: ``` [Bindable] [Embed(source="assets/image.png")] private var MyGfx:Class; var myBitmap:BitmapData = new MyGfx().bitmapData; myGraphics.beginBitmapFill(myBitmap); myGraphics.endFill(); ``` You might find the [Flex Quick Starts](http://www.adobe.com/devnet/flex/quickstart/) articles on Adobe's site useful, especially the ["Embedding Assets"](http://www.adobe.com/devnet/flex/quickstart/embedding_assets/) section.
261,387
<p>I've noticed in many places in Java (C# included), that many "getter" methods are prefixed with "get" while many other aren't. I never noticed any kind of pattern Sun seems to be following. What are some guidelines or rules for using "get" in getter method names?</p>
[ { "answer_id": 261396, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 2, "selected": false, "text": "<p>\"get\" and \"set\" prefix pair in Java is used originally as a convention to denote java bean. Later, it become just an encapsulation convention, since Java, unlike C# doesn't have proper properties.</p>\n" }, { "answer_id": 261410, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "<p>Java doesn't (yet) support properties. Getters and setters are a bodge to get around this. Other languages - including C# - support properties and you should use these instead. This isn't just a \"best practice\" thing either: serialization in C# will rely on properties, not getters &amp; setters, so not using properties could lead to all sorts of problems in the future if you need to serialize your classes.</p>\n\n<p>The advantage to properties is that they make the code more readable. Something like</p>\n\n<pre><code>obj.setX(10);\n</code></pre>\n\n<p>in Java, becomes</p>\n\n<pre><code>obj.X = 10;\n</code></pre>\n\n<p>Yet behind the scenes, X is a method, rather than being a variable and so can perform dirty input checking etc.</p>\n" }, { "answer_id": 261425, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>It certainly used to be the case that APIs often exposed read-only properties without the <code>get</code> prefix: <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html#length()\" rel=\"nofollow noreferrer\"><code>String.length()</code></a> and even the newer <a href=\"http://java.sun.com/javase/6/docs/api/java/nio/Buffer.html#capacity()\" rel=\"nofollow noreferrer\"><code>Buffer.capacity()</code></a> being reasonable examples.</p>\n\n<p>The upside of this is that there's less fluff involved. The downside is that anything which tries to determine properties automatically based on the conventions won't discover them. Personally I <em>tend</em> to err on the side of including the prefix.</p>\n\n<p>Of course, in C# it's mostly irrelevant as there are \"real\" properties anyway :)</p>\n" }, { "answer_id": 261435, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "<p>Objective C 2.0 also uses properties, using the same dot syntax.</p>\n\n<p>Prior to that, it used a slightly different naming scheme for getters and setters (which, naturally, can still be used with properties, or for plain old attributes).</p>\n\n<pre><code>value = [obj attr];\n\n[obj setAttr:value];\n\n[obj getAttr:&amp;value];\n</code></pre>\n\n<p>That is, get is used in a different way. It doesn't return a value, but stores the result in the passed in variable.</p>\n\n<p>The typical getter has the same name as the attribute, the setter is the attribute prefixed by set (as per Java's convention). These conventions are used by the KVO (Key-Value Observation) system, so should be adhered to.</p>\n" }, { "answer_id": 261481, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 4, "selected": true, "text": "<p>It comes down to semantics. Yes, C# has \"properties\" which give you a get/set 'method' stub... but functions (...\"methods\"...) in the .NET Framework that start with \"Get\" is supposed to clue the developer into the fact that some operation is happening for the sole purpose of getting some results.</p>\n\n<p>You may think that's odd and say \"why not just use the return type to clue people in?\", and the answer is simple. Think of the following methods:</p>\n\n<pre><code>public Person CreatePerson(string firstName, string lastName) {...}\n</code></pre>\n\n<p>Just by that method's name, you can probably figure that there will be database activity involved, and then a newly created \"person\" will be returned.</p>\n\n<p>but, what about this:</p>\n\n<pre><code>public Person GetPerson(string firstName, string lastName) {...}\n</code></pre>\n\n<p>Just by <em>that</em> method's name, you can probably assume that a 100% \"Safe\" retrieval of a person from a database is being done.</p>\n\n<p>You would never call the \"CreatePerson\" multiple times... but you <em>should</em> feel safe to call \"GetPerson\" all the time. (it should not affect the 'state' of the application).</p>\n" }, { "answer_id": 261504, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 2, "selected": false, "text": "<p>The best practice in <strong>Java</strong> is to use the get and set prefixes for properties. </p>\n\n<p>Frameworks, tag libraries, etc will look for methods with those prefixes and use them as properties.</p>\n\n<p>So, if you have a java class like this...</p>\n\n<pre><code>public class User{\n private String name;\n public String getName(){ return name;}\n public void setName(String name){ this.name = name; }\n}\n</code></pre>\n\n<p>.. with struts-tags (or any other ognl based tag library) you will access the name property with <code>user.name</code>.</p>\n\n<p>The Spring framework also uses this convention in the xml configuration files.</p>\n" }, { "answer_id": 281142, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 1, "selected": false, "text": "<p>It depends. It is often redundant information, even in languages without properties.</p>\n\n<p>In C++, instead of a getAttr()/setAttr() pair, it is common to provide two overloads of an Attr() function:\nvoid Attr(Foo f); // The setter\nFoo Attr(); // The getter</p>\n\n<p>In Java, it is common practice to prefix get/set.\nI'll have to say the best practice is to go with what's standard in your language. In Java, people expect to see get/set prefixes, so omitting them might confuse people, even though they're not strictly necessary.</p>\n" }, { "answer_id": 377917, "author": "Yang Meyer", "author_id": 45018, "author_profile": "https://Stackoverflow.com/users/45018", "pm_score": 1, "selected": false, "text": "<p>Just a short addendum: Another convention is for getters of Boolean fields to be prefixed with \"is\" instead of \"get\", e.g. <code>bool isEnabled() { return enabled; }</code></p>\n" }, { "answer_id": 10568713, "author": "mikera", "author_id": 214010, "author_profile": "https://Stackoverflow.com/users/214010", "pm_score": 3, "selected": false, "text": "<p>I personally like the following rule:</p>\n\n<ul>\n<li>Use the <code>get</code> prefix whenever the value is directly modifiable with a corresponding <code>set</code> method</li>\n<li>Drop the <code>get</code> prefix in situations where the value is something you can't set directly as a property (i.e. there is no equivalent setXXX method)</li>\n</ul>\n\n<p>The rationale for the second case is that if the value isn't really a user-settable \"property\" as such, then it shouldn't need a get/set pair of methods. An implication is that if this convention is followed and you see a getXXX method, you can assume the existence of a setXXX method as well.</p>\n\n<p>Examples:</p>\n\n<ul>\n<li><code>String.length()</code> - since strings are immutable, length is a read-only value</li>\n<li><code>ArrayList.size()</code> - size changes when elements are added or removed, but you can't set it directly</li>\n</ul>\n" }, { "answer_id": 68985870, "author": "Michal M", "author_id": 1050787, "author_profile": "https://Stackoverflow.com/users/1050787", "pm_score": 0, "selected": false, "text": "<p>13 years later, I believe this question deserves a revisit. Surely, over the time there were a lot of stackoverflow Q&amp;A-s (even some good answers here), articles and blog posts that amounted to the same conclusion, but finally, I think, we get a rather straightforward answer from Brian Goetz himself:</p>\n<blockquote>\n<p>“The JavaBeans naming convention* is a little bit of an unfortunate story,” he continues. “It’s a terrible convention for general-purpose development. It was a fairly well-targeted convention for naming visual components in a visual editor, where you were dragging and dropping buttons and labels and things like that onto a canvas, and you had property sheets that you could edit about foreground color and fonts and what have you, which could be discovered reflectively.”</p>\n<p>Goetz explains that the naming convention was great way building those UI components—which turns out to not have been a key Java use-case. “And yet, somehow, we continued with that naming convention, even though it’s such a poor match for most business domain objects.”</p>\n</blockquote>\n<p>– <a href=\"https://blogs.oracle.com/javamagazine/java-architects-loom-panama-valhalla#anchor_4\" rel=\"nofollow noreferrer\">https://blogs.oracle.com/javamagazine/java-architects-loom-panama-valhalla#anchor_4</a></p>\n<p><code>*</code> – basically, the <code>getX</code>/<code>setX</code> convention in question</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30323/" ]
I've noticed in many places in Java (C# included), that many "getter" methods are prefixed with "get" while many other aren't. I never noticed any kind of pattern Sun seems to be following. What are some guidelines or rules for using "get" in getter method names?
It comes down to semantics. Yes, C# has "properties" which give you a get/set 'method' stub... but functions (..."methods"...) in the .NET Framework that start with "Get" is supposed to clue the developer into the fact that some operation is happening for the sole purpose of getting some results. You may think that's odd and say "why not just use the return type to clue people in?", and the answer is simple. Think of the following methods: ``` public Person CreatePerson(string firstName, string lastName) {...} ``` Just by that method's name, you can probably figure that there will be database activity involved, and then a newly created "person" will be returned. but, what about this: ``` public Person GetPerson(string firstName, string lastName) {...} ``` Just by *that* method's name, you can probably assume that a 100% "Safe" retrieval of a person from a database is being done. You would never call the "CreatePerson" multiple times... but you *should* feel safe to call "GetPerson" all the time. (it should not affect the 'state' of the application).
261,407
<p>Currently I have a structure like this:</p> <pre><code>A | +--B | +--C </code></pre> <p>It's mapped with one table per subclass using joined tables. For historic reasons I also use a discriminator, so the current situation is as described in <a href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/inheritance.html#inheritance-tablepersubclass-discriminator" rel="noreferrer">Section 9.1.3 of the Hibernate manual</a>.</p> <p><strong>Question:</strong> How do I extend the mapping for a structure like this:</p> <pre><code>A | +--B | | | D | +--C </code></pre> <p>Can I <code>&lt;subclass&gt;</code> a <code>&lt;subclass&gt;</code> in the hibernate mapping? What <code>&lt;key&gt;</code>s do I need?</p>
[ { "answer_id": 262654, "author": "shyam", "author_id": 7616, "author_profile": "https://Stackoverflow.com/users/7616", "pm_score": 4, "selected": true, "text": "<p><strong><em>not tested</em></strong> but, according to the link you posted if you are using hibernate3</p>\n\n<pre><code>&lt;hibernate-mapping&gt;\n &lt;class name=\"A\" table=\"A\"&gt;\n &lt;id name=\"id\" type=\"long\" column=\"a_id\"&gt;\n &lt;generator class=\"native\"/&gt;\n &lt;/id&gt;\n &lt;discriminator column=\"discriminator_col\" type=\"string\"/&gt;\n &lt;property name=\"\" type=\"\"/&gt;\n &lt;!-- ... --&gt;\n &lt;/class&gt;\n &lt;subclass name=\"B\" extends=\"A\" discriminator-value=\"B\"&gt;\n &lt;!-- ... --&gt;\n &lt;/subclass&gt;\n &lt;subclass name=\"D\" extends=\"B\" discriminator-value=\"D\"&gt;\n &lt;!-- ... --&gt;\n &lt;/subclass&gt;\n &lt;subclass name=\"C\" extends=\"A\" discriminator-value=\"C\"&gt;\n &lt;!-- ... --&gt;\n &lt;/subclass&gt;\n&lt;/hibernate-mapping&gt;\n</code></pre>\n" }, { "answer_id": 47792576, "author": "KayV", "author_id": 3956731, "author_profile": "https://Stackoverflow.com/users/3956731", "pm_score": 0, "selected": false, "text": "<p>Using Annotations, it can be done as follows:</p>\n\n<pre><code>@Entity\n@Inheritance(strategy = InheritanceType.JOINED)\n@DiscriminatorColumn(name=\"LoanType\",discriminatorType=\"String\")\n@Table(name = \"A\")\npublic class A implements Serializable{\n}\n\n@Entity\n@Table(name= \"B\")\n@PrimaryKeyJoinColumn(name = \"B_ID\", referencedColumnName =\"A_ID\")\npublic class B extends A{\n}\n\n\n@Entity\n@Table(name= \"C\")\n@PrimaryKeyJoinColumn(name = \"C_ID\", referencedColumnName = \"B_ID\")\npublic class C extends B{}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29549/" ]
Currently I have a structure like this: ``` A | +--B | +--C ``` It's mapped with one table per subclass using joined tables. For historic reasons I also use a discriminator, so the current situation is as described in [Section 9.1.3 of the Hibernate manual](http://www.hibernate.org/hib_docs/v3/reference/en-US/html/inheritance.html#inheritance-tablepersubclass-discriminator). **Question:** How do I extend the mapping for a structure like this: ``` A | +--B | | | D | +--C ``` Can I `<subclass>` a `<subclass>` in the hibernate mapping? What `<key>`s do I need?
***not tested*** but, according to the link you posted if you are using hibernate3 ``` <hibernate-mapping> <class name="A" table="A"> <id name="id" type="long" column="a_id"> <generator class="native"/> </id> <discriminator column="discriminator_col" type="string"/> <property name="" type=""/> <!-- ... --> </class> <subclass name="B" extends="A" discriminator-value="B"> <!-- ... --> </subclass> <subclass name="D" extends="B" discriminator-value="D"> <!-- ... --> </subclass> <subclass name="C" extends="A" discriminator-value="C"> <!-- ... --> </subclass> </hibernate-mapping> ```
261,431
<p>I have a variable </p> <pre><code>unsigned char* data = MyFunction(); </code></pre> <p>how to find the length of data?</p>
[ { "answer_id": 261437, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 3, "selected": false, "text": "<p>Assuming its a <code>string</code></p>\n\n<pre><code>length = strlen( char* );\n</code></pre>\n\n<p>but it doesn't seem to be...so there isn't a way <em>without</em> having the function return the length.</p>\n" }, { "answer_id": 261451, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 3, "selected": false, "text": "<p>You will have to pass the length of the data back from <code>MyFunction</code>. Also, make sure you know who allocates the memory and who has to deallocate it. There are various patterns for this. Quite often I have seen:</p>\n\n<pre><code>int MyFunction(unsigned char* data, size_t* datalen)\n</code></pre>\n\n<p>You then allocate data and pass datalen in. The result (int) should then indicate if your buffer (data) was long enough...</p>\n" }, { "answer_id": 261508, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As said before strlen only works in strings NULL-terminated so the first 0 ('\\0' character) will mark the end of the string. You are better of doing someting like this:</p>\n\n<pre><code>unsigned int size;\nunsigned char* data = MyFunction(&amp;size);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>unsigned char* data;\nunsigned int size = MyFunction(data);\n</code></pre>\n" }, { "answer_id": 261514, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "<p>Now this is really not that hard. You got a pointer to the first character to the string. You need to increment this pointer until you reach a character with null value. You then substract the final pointer from the original pointer and voila you have the string length.</p>\n\n<pre><code>int strlen(unsigned char *string_start)\n{\n /* Initialize a unsigned char pointer here */\n /* A loop that starts at string_start and\n * is increment by one until it's value is zero,\n *e.g. while(*s!=0) or just simply while(*s) */\n /* Return the difference of the incremented pointer and the original pointer */\n}\n</code></pre>\n" }, { "answer_id": 261877, "author": "plan9assembler", "author_id": 1710672, "author_profile": "https://Stackoverflow.com/users/1710672", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt; \nint lengthOfU(unsigned char * str)\n{\n int i = 0;\n\n while(*(str++)){\n i++;\n if(i == INT_MAX)\n return -1;\n }\n\n return i;\n}\n</code></pre>\n\n<p>HTH</p>\n" }, { "answer_id": 263718, "author": "Larry Gritz", "author_id": 3832, "author_profile": "https://Stackoverflow.com/users/3832", "pm_score": 1, "selected": false, "text": "<p>The original question did not say that the data returned is a null-terminated string. If not, there's no way to know how big the data is. If it's a string, use strlen or write your own. The only reason not to use strlen is if this is a homework problem, so I'm not going to spell it out for you.</p>\n" }, { "answer_id": 2019859, "author": "mch", "author_id": 245461, "author_profile": "https://Stackoverflow.com/users/245461", "pm_score": 2, "selected": false, "text": "<p>There is no way to find the size of (<code>unsigned char *)</code> if it is not null terminated.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a variable ``` unsigned char* data = MyFunction(); ``` how to find the length of data?
Assuming its a `string` ``` length = strlen( char* ); ``` but it doesn't seem to be...so there isn't a way *without* having the function return the length.
261,449
<p>I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.</p> <p>I've found a <a href="https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server">previous question on the subject</a>, but it deals with stored procedures, which I'm not using. I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).</p> <p>I guess my general idea is this:</p> <pre><code>If the row is found update else insert </code></pre> <p>As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT? Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?</p>
[ { "answer_id": 261466, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": true, "text": "<p>The most efficient way is to do the <code>UPDATE</code>, then do an <code>INSERT</code> if <code>@@rowcount</code> is zero, <a href=\"https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server#108416\">as explained in this previous answer</a>.</p>\n" }, { "answer_id": 261703, "author": "MrFox", "author_id": 32726, "author_profile": "https://Stackoverflow.com/users/32726", "pm_score": 0, "selected": false, "text": "<p>(First of all - I would not try to avoid stored procedures, if there is no strong reason. The give a good benefit in most cases.)</p>\n\n<p><strong>You could do it this way:</strong></p>\n\n<ul>\n<li>create a (temporary) table</li>\n<li>fill in your rows</li>\n<li>run a INTERSECT that identifies the extisting rows</li>\n<li>update your table with them</li>\n<li>run a EXCEPT that identifies the new rows</li>\n<li>run an insert with these elements</li>\n<li>drop/clear your (temporary) table</li>\n</ul>\n\n<p>This will probably run faster, if you are inserting/updating large amounts of rows.</p>\n" }, { "answer_id": 261722, "author": "Craig Norton", "author_id": 24804, "author_profile": "https://Stackoverflow.com/users/24804", "pm_score": -1, "selected": false, "text": "<p>If you are always going to:<br>\n* Count the rows<br>\n* Insert / Update based on the result<p>\nWhy not instead:<br>\n* Delete row<br>\n* Insert row<p></p>\n\n<p>Same result and neater.<br>\nAs far as I know when you Update a row - SQLServer does a Delete / Insert anyway (where it exists)</p>\n" }, { "answer_id": 261746, "author": "Eric Sabine", "author_id": 1493157, "author_profile": "https://Stackoverflow.com/users/1493157", "pm_score": 0, "selected": false, "text": "<p>Completely understand that your post was titled \"SQL Server 2005\" but just wanted to throw out something to look forward to if/when you upgrade to SQL 2008. Microsoft has added a new MERGE statement which will give you the ability to code one DML statement that does both the update and insert. It's pretty cool. I've yet to compare performance and I/Os but it's just great to have another tool in your toolbox. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30023/" ]
I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there. I've found a [previous question on the subject](https://stackoverflow.com/questions/13540/insert-update-stored-proc-on-sql-server), but it deals with stored procedures, which I'm not using. I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005). I guess my general idea is this: ``` If the row is found update else insert ``` As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT? Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?
The most efficient way is to do the `UPDATE`, then do an `INSERT` if `@@rowcount` is zero, [as explained in this previous answer](https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server#108416).
261,455
<p>After reading a couple of answers and comments on some SQL questions here, and also hearing that a friend of mine works at a place which has a policy which bans them, I'm wondering if there's anything wrong with using backticks around field names in MySQL.</p> <p>That is:</p> <pre><code>SELECT `id`, `name`, `anotherfield` ... -- vs -- SELECT id, name, anotherfield ... </code></pre>
[ { "answer_id": 261467, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "<p>Well, as far as I know, the whole purpose of using backticks is so you can use names that coincide with reserved keywords. So, if the name isn't colliding with a reserved keyword, I don't see any reason to use backticks. But, that's no reason to ban them, either.</p>\n" }, { "answer_id": 261471, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "<p>To me it makes a lot of sense to use them at all times when dealing with field names.</p>\n\n<ul>\n<li>Firstly, once you get into the habit, it doesn't hurt to just hit the backtick key. </li>\n<li>Secondly, to me, it makes it easier to see what exactly are the fields in your query, and what are keywords or methods.</li>\n<li>Lastly, it allows you to use whatever field name you wish when designing your table. Sometimes it makes a lot of sense to name a field \"key\", \"order\", or \"values\"... all of which require backticks when referring to them.</li>\n</ul>\n" }, { "answer_id": 261475, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 6, "selected": false, "text": "<p>The only problem with backticks is that they are not ANSI-SQL compliant, e.g. they don't work in SQL Server.</p>\n\n<p>If there is a chance you would have to port your SQL to another database, use double quotes.</p>\n" }, { "answer_id": 261476, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 8, "selected": true, "text": "<p>Using backticks permits you to use alternative characters. In query writing it's not such a problem, but if one assumes you can just use backticks, I would assume it lets you get away with ridiculous stuff like</p>\n\n<pre><code>SELECT `id`, `my name`, `another field` , `field,with,comma` \n</code></pre>\n\n<p>Which does of course generate badly named tables. </p>\n\n<p>If you're just being concise I don't see a problem with it, \nyou'll note if you run your query as such</p>\n\n<pre><code>EXPLAIN EXTENDED Select foo,bar,baz \n</code></pre>\n\n<p>The generated warning that comes back will have back-ticks <strong>and</strong> fully qualified table names. So if you're using query generation features and automated re-writing of queries, backticks would make anything parsing your code less confused. </p>\n\n<p>I think however, instead of mandating whether or not you can use backticks, they should have a standard for names. It solves more 'real' problems. </p>\n" }, { "answer_id": 261480, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "<p>Backticks aren't part of standard ANSI SQL. From <a href=\"http://dev.mysql.com/doc/refman/5.0/en/identifiers.html\" rel=\"noreferrer\">the mysql manual</a>:</p>\n\n<blockquote>\n <p>If the ANSI_QUOTES SQL mode is\n enabled, it is also allowable to quote\n identifiers within double quotes</p>\n</blockquote>\n\n<p>So if you use backticks and then decide to move away from MySQL, you have a problem (although you probably have a lot bigger problems as well)</p>\n" }, { "answer_id": 261484, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 3, "selected": false, "text": "<p>There isn't anything wrong if you keep using MYSQL, except maybe the visual fuziness of the queries. But they do allow the use of reserved keywords or embedded spaces as table and column names. This is a no-no with most database engines and will prevent any migration at a later time.</p>\n\n<p>As for easy reading, many people use caps for SQL keywords, eg.</p>\n\n<pre><code>SELECT some_fied, some_other_field FROM whatever WHERE id IS NULL;\n</code></pre>\n" }, { "answer_id": 3604070, "author": "EllisGL", "author_id": 344028, "author_profile": "https://Stackoverflow.com/users/344028", "pm_score": 2, "selected": false, "text": "<p>It's a lot easier to search your code-base for something in backticks. Say you have a table named <code>event</code>. <code>grep -r \"event\" *</code> might return hundreds of results. <code>grep -r \"\\`event\\`\" *</code> will return anything probably referencing your database. </p>\n" }, { "answer_id": 12769711, "author": "Federico", "author_id": 1666955, "author_profile": "https://Stackoverflow.com/users/1666955", "pm_score": 3, "selected": false, "text": "<p>If you ask to me, backticks should always be used. But there are some reasons why a team may prefer not to use them.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Using them, there are no reserved words or forbidden chars.</li>\n<li>In some cases, you get more descriptive error messages.</li>\n<li>If you avoid bad practices you don't care, but... in real word, sometimes they are a decent way to avoid SQL injections.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>They are not standard and usually not portable. However, as long as you don't use a backtick as part of an identifier (which is the worst practice I am able to imagine), you can port your query by automatically removing backticks.</li>\n<li>If some of your query come from Access, they may quote table names with \" (and maybe you can't remove all the \" blindly). However, mixtures of backticks and double quotes are allowed.</li>\n<li>Some stupid software or function filters your queries, and has problems with backticks. However, they are part of ASCII so this means that your software/function is very bad.</li>\n</ul>\n" }, { "answer_id": 29532205, "author": "ysrtymz", "author_id": 3711199, "author_profile": "https://Stackoverflow.com/users/3711199", "pm_score": 0, "selected": false, "text": "<p>if you are using some field names as default mysql or mssql values for example \"status\", you have to use backticks ( \"select <code>status</code> from table_name\" or \"select id from table_name where <code>status</code>=1\" ).\nbecause mysql returns errors or doesnt work the query.</p>\n" }, { "answer_id": 45838759, "author": "Sonpal singh Sengar", "author_id": 5413872, "author_profile": "https://Stackoverflow.com/users/5413872", "pm_score": 2, "selected": false, "text": "<p>Simple Thing about backtick <strong>``</strong> is use for denote identifier like database_name, table_name etc, and single quote <strong>''</strong>, double quote <strong>\"\"</strong> for string literals, whereas \"\" use for print value as it is and '' print the value variable hold or in another case print the text his have.</p>\n\n<pre><code>i.e 1.-&gt; use `model`; \n here `model` is database name not conflict with reserve keyword 'model'\n2- $age = 27;\ninsert into `tbl_people`(`name`,`age`,`address`) values ('Ashoka','$age',\"Delhi\");\n\nhere i used both quote for all type of requirement. If anything not clear let me know..\n</code></pre>\n" }, { "answer_id": 54352150, "author": "Command", "author_id": 10449301, "author_profile": "https://Stackoverflow.com/users/10449301", "pm_score": -1, "selected": false, "text": "<p>The main use of backticks (`) in SQL is to use them in situations where you are going to call them again in upcoming clauses. In every other time it is recommended to use double quotes(\"\"). </p>\n\n<p>For example</p>\n\n<pre><code>SELECT CONCAT(Name, ' in ', city, ', ', statecode) AS `Publisher and Location`,\n COUNT(ISBN) AS \"# Books\",\n MAX(LENGTH(title)) AS \"Longest Title\",\n MIN(LENGTH(title)) AS \"Shortest Title\"\nFROM Publisher JOIN Book\nON Publisher.PublisherID = Book.PublisherID WHERE INSTR(name, 'read')&gt;0\nGROUP BY `Publisher and Location`\nHAVING COUNT(ISBN) &gt; 1;\n</code></pre>\n\n<p>In the above statement do you see how <code>Publisher and Location</code> is used again in <code>GROUP BY</code> clause.</p>\n\n<p>Instead of using </p>\n\n<blockquote>\n <p>GROUP BY Name, city, statecode</p>\n</blockquote>\n\n<p>I just used</p>\n\n<blockquote>\n <p>GROUP BY <code>Publisher and Location</code></p>\n</blockquote>\n\n<p>Only when such situations arise, it is useful to use backticks. In all other times using double quotes is recommended.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
After reading a couple of answers and comments on some SQL questions here, and also hearing that a friend of mine works at a place which has a policy which bans them, I'm wondering if there's anything wrong with using backticks around field names in MySQL. That is: ``` SELECT `id`, `name`, `anotherfield` ... -- vs -- SELECT id, name, anotherfield ... ```
Using backticks permits you to use alternative characters. In query writing it's not such a problem, but if one assumes you can just use backticks, I would assume it lets you get away with ridiculous stuff like ``` SELECT `id`, `my name`, `another field` , `field,with,comma` ``` Which does of course generate badly named tables. If you're just being concise I don't see a problem with it, you'll note if you run your query as such ``` EXPLAIN EXTENDED Select foo,bar,baz ``` The generated warning that comes back will have back-ticks **and** fully qualified table names. So if you're using query generation features and automated re-writing of queries, backticks would make anything parsing your code less confused. I think however, instead of mandating whether or not you can use backticks, they should have a standard for names. It solves more 'real' problems.
261,463
<p>We have a couple of web servers using load balancer. Machines are running IIS6 on port 81. Externally, site is accessable using port 80. External name and name of the machine are different.</p> <p>We're getting </p> <pre><code>System.ServiceModel.EndpointNotFoundException: The message with To '&lt;url&gt;' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree. </code></pre> <p>Relevant part of web.config is:</p> <pre><code> &lt;endpoint binding="ws2007HttpBinding" bindingConfiguration="MyServiceBinding" contract="MyService.IMyService" listenUriMode="Explicit" /&gt; </code></pre> <p>We tried adding listenUri, but that didn't solve our problems.</p> <p>Any ideas?</p>
[ { "answer_id": 261498, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>What is the specific load balancer? Using an F5 BIG-IP we got it working fairly easily, but we were using the same port and (relative) uri on the nlb as individual machines (so we can treat an individual machine the same as the farm if we choose). Obviously each machine has a different name, but this setup also allows you to test individual servers by spoofing the host - for example, by editing your HOSTS file to point [your farm name] to [test server IP].</p>\n\n<p>The biggest pain we had was SSL; using TransportWithMessageCredential security, WCF refuses inbound http connections - so we had to set up the nlb to re-encrypt between the nlb and the server node - but not a biggie.</p>\n\n<p>The only other issue we had was with hosting WCF inside IIS, and WCF not being able to correctly identify the intended site (although IIS was fine) over http (but fine over https). To fix this I wrote a custom factory that simply ignored http completely (only listened on https) - which ties in neatly with the TransportWithMessageCredential requirements anyway, so I wasn't bothered by this.</p>\n\n<p>I wonder if you wouldn't get more joy by hosting on a standard port but as a different site (IP/host-header/etc).</p>\n" }, { "answer_id": 482995, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 4, "selected": true, "text": "<pre><code>[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]\n</code></pre>\n\n<p>Putting this attribute on service solves the problem.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28912/" ]
We have a couple of web servers using load balancer. Machines are running IIS6 on port 81. Externally, site is accessable using port 80. External name and name of the machine are different. We're getting ``` System.ServiceModel.EndpointNotFoundException: The message with To '<url>' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree. ``` Relevant part of web.config is: ``` <endpoint binding="ws2007HttpBinding" bindingConfiguration="MyServiceBinding" contract="MyService.IMyService" listenUriMode="Explicit" /> ``` We tried adding listenUri, but that didn't solve our problems. Any ideas?
``` [ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)] ``` Putting this attribute on service solves the problem.
261,512
<p>I'm currently working with Db2 Enterprise Server V 8.2 with FixPak 10</p> <p>And I want to retrieve list of all the open active connections with an instance.</p> <p>In Oracle there is a utility program called &quot;Top Session&quot; which does the similar task. Is there any equivalent in DB2?</p>
[ { "answer_id": 261578, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": false, "text": "<p>The command you seek is:</p>\n\n<pre><code>LIST APPLICATIONS\n</code></pre>\n\n<p>In the DB2 Command Center there is a tool which list the applications and displays them in a human friendly format as well.</p>\n" }, { "answer_id": 265776, "author": "Fuangwith S.", "author_id": 24550, "author_profile": "https://Stackoverflow.com/users/24550", "pm_score": 3, "selected": false, "text": "<p>CLP:</p>\n\n<pre><code>db2 list applications\n</code></pre>\n\n<p>QUERY:</p>\n\n<pre><code>SELECT * FROM SYSIBM.APPLICATIONS\nSELECT * FROM SYSIBM.SESSION\n</code></pre>\n" }, { "answer_id": 391667, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>To get more detailed information from list applications:</p>\n\n<pre><code>db2 list applications for database {dbName} show detail\n</code></pre>\n\n<p>For applications with lots of active connections it is useful to pipe the results to <code>grep</code> to find only the threads currently executing or locked. </p>\n\n<pre><code>db2 list applications for database {dbName} show detail | grep -i \"executing\"\n</code></pre>\n\n<p>and</p>\n\n<pre><code>db2 list applications for database {dbName} show detail | grep -i \"lock\"\n</code></pre>\n" }, { "answer_id": 62642694, "author": "Amrith Raj Herle", "author_id": 5227954, "author_profile": "https://Stackoverflow.com/users/5227954", "pm_score": 2, "selected": false, "text": "<p>Maybe you are searching for below query.</p>\n<pre><code>SELECT\n AUTHID,\n APPL_NAME,\n CLIENT_NNAME,\n AGENT_ID,\n APPL_ID,\n APPL_STATUS\nFROM\n SYSIBMADM.APPLICATIONS\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34058/" ]
I'm currently working with Db2 Enterprise Server V 8.2 with FixPak 10 And I want to retrieve list of all the open active connections with an instance. In Oracle there is a utility program called "Top Session" which does the similar task. Is there any equivalent in DB2?
CLP: ``` db2 list applications ``` QUERY: ``` SELECT * FROM SYSIBM.APPLICATIONS SELECT * FROM SYSIBM.SESSION ```
261,515
<p>I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g.</p> <p>Störung%20.doc would be renamed to St_rung_20.doc</p> <p>In order of preference:</p> <ol> <li>A Windiws batch file</li> <li>A Windows script file to run with cscript (vbs)</li> <li>A third party piece of software that can be run from the command-line (i.e. no user interaction required)</li> <li>Another language script file, for which I'd have to install an additional script engine</li> </ol> <p>Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.</p>
[ { "answer_id": 261552, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<p>Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue <code>chcp 65001</code> to set cmd.exe to Unicode beforehand and try again.</p>\n\n<p>If that fails, the following VBScript would do it:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nDim fso: Set fso = CreateObject(\"Scripting.FileSystemObject\")\nDim invalidChars: Set invalidChars = New RegExp\n\n' put all characters that you want to strip inside the brackets\ninvalidChars.Pattern = \"[äöüß&amp;%]\"\ninvalidChars.IgnoreCase = True\ninvalidChars.Global = True\n\nIf WScript.Arguments.Unnamed.Count = 0 Then\n WScript.Echo \"Please give folder name as argument 1.\"\n WScript.Quit 1\nEnd If\n\nRecurse fso.GetFolder(WScript.Arguments.Unnamed(0))\n\nSub Recurse(f)\n Dim item\n\n For Each item In f.SubFolders\n Recurse item\n Sanitize item\n Next\n For Each item In f.Files\n Sanitize item\n Next\nEnd Sub\n\nSub Sanitize(folderOrFile)\n Dim newName: newName = invalidChars.Replace(folderOrFile.Name, \"_\")\n If folderOrFile.Name = newName Then Exit Sub\n WScript.Echo folderOrFile.Name, \" -&gt; \", newName\n folderOrFile.Name = newName \nEnd Sub\n</code></pre>\n\n<p>call it like this:</p>\n\n<pre><code>cscript replace.vbs \"c:\\path\\to\\my\\files\"\n</code></pre>\n\n<p>You can also drag&amp;drop a folder onto it in Windows Explorer.</p>\n" }, { "answer_id": 261553, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://www.robvanderwoude.com/bht.html\" rel=\"nofollow noreferrer\">http://www.robvanderwoude.com/bht.html</a>:</p>\n\n<p>use NT's SET's string substitution to replace or remove characters anywhere in a string: </p>\n\n<pre><code>SET STRING=[ABCDEFG]\nSET STRING=%STRING:[=%\nSET STRING=%STRING:]=%\nECHO String: %STRING%\n\nwill display \nString: ABCDEFG\n\nSET STRING=[ABCDEFG]\nSET STRING=%STRING:[=(%\nSET STRING=%STRING:]=)%\nECHO String: %STRING%\n\nwill display \nString: (ABCDEFG)\n\nSET STRING=[ABCDEFG]\nSET STRING=%STRING:~1,7%\nECHO String: %STRING%\n\nwill display \nString: ABCDEFG\n</code></pre>\n\n<p>If you use this attempt, you will have to process each character you want to replace (e.g. Ä,Ö,Ü,ä,ö,ü,ß, but also á,à,é,è...) seperately.</p>\n" }, { "answer_id": 268812, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 3, "selected": true, "text": "<p>Thanks to Tomalak who actually pointed me in the right direction. Thought I'd post here for completeness.</p>\n\n<p>The problem seems to be that the codepage used by GPG is fixed (Latin I) independent of the codepage configured in the console. But once he pointed this out, I figured out how to workaraound this.</p>\n\n<p>The trick is to change the codepage before generating the file list. This will actually make the filelist appear to be incorrect when viewed in the console. However, when passed to GPG, it works fine. GPG accepts the files and spits out the encrytped files with correct filenames.</p>\n\n<p>The batch file looks something like this:</p>\n\n<pre><code>chcp 1252\ndir /b /s /a-d MyFolder &gt;filelist.txt\ngpg -r [email protected] --encrypt-files &lt;filelist.txt\n</code></pre>\n" }, { "answer_id": 2428894, "author": "Etienne URBAH", "author_id": 291920, "author_profile": "https://Stackoverflow.com/users/291920", "pm_score": 2, "selected": false, "text": "<p>Following 'RenameFilesWithAccentedAndDiacriticalLatinChars.pl' PERL script renames files with accented and diacritical Latin characters :</p>\n\n<ul>\n<li>This PERL script starts from the folder given in parameter, or else from\nthe current folder.</li>\n<li>It recursively searches for files with characters belonging to 80 - FF of\nCP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters)\nor Latin characters having diacritical marks.</li>\n<li>It calculates new file names by removing the accents and diacritical marks\nonly from Latin characters (For example, Été --&gt; Ete).</li>\n<li>It displays all proposed renaming and perhaps conflicts, and asks the user\nfor global approval.</li>\n<li>If the user has approved, it renames all files having no conflict.</li>\n</ul>\n\n<p>Option '--batch' avoids interactive questions. Use with care.</p>\n\n<p>Option '--' avoids the next parameter to be interpreted as option.</p>\n\n<p><strong>Special Warning</strong> :</p>\n\n<ul>\n<li>This script was originally encoded in UTF-8, and should stay so.</li>\n<li>This script may rename a lot of files.</li>\n<li>Files names are theoretically all encoded only with UTF-8. But some file\nnames may be found to contain also some characters having legacy encoding.</li>\n<li>The author has applied efforts for consistency checks, robustness, conflict\ndetection and use of appropriate encoding.\nSo this script should only rename files by removing accents and diacritical\nmarks from Latin characters.</li>\n<li>But this script has been tested only under a limited number of OS\n(Windows, Mac OS X, Linux) and a limited number of terminal encodings\n(CP 850, ISO-8859-1, UTF-8).</li>\n<li>So, under weird circumstances, this script could rename many files with\nrandom names.</li>\n<li>Therefore, this script should be used with care, and modified with extreme\ncare (beware encoding of internal strings, inputs, outputs and commands)</li>\n</ul>\n\n<pre><code>#!/usr/bin/perl -w\n#=============================================================================\n#\n# Copyright 2010 Etienne URBAH\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details at\n# http://www.gnu.org/licenses/gpl.html\n#\n# For usage and SPECIAL WARNING, see the 'Help' section below.\n#\n#=============================================================================\nuse 5.008_000; # For correct Unicode support\nuse warnings;\nuse strict;\nuse Encode;\n\n$| = 1; # Autoflush STDOUT\n\n#-----------------------------------------------------------------------------\n# Function ucRemoveEolUnderscoreDash :\n# Set Uppercase, remove End of line, Underscores and Dashes\n#-----------------------------------------------------------------------------\nsub ucRemoveEolUnderscoreDash\n{\n local $_ = uc($_[0]);\n chomp;\n tr/_\\-//d;\n $_;\n}\n\n#-----------------------------------------------------------------------------\n# Constants\n#-----------------------------------------------------------------------------\nmy $Encoding_Western = 'ISO-8859-1';\nmy $Encoding_Central = 'ISO-8859-2';\nmy $Encoding_Baltic = 'ISO-8859-4';\nmy $Encoding_Turkish = 'ISO-8859-9';\nmy $Encoding_W_Euro = 'ISO-8859-15';\nmy $Code_Page_OldWest = 850;\nmy $Code_Page_Central = 1250;\nmy $Code_Page_Western = 1252;\nmy $Code_Page_Turkish = 1254;\nmy $Code_Page_Baltic = 1257;\nmy $Code_Page_UTF8 = 65001;\n\nmy $HighBitSetChars = pack('C*', 0x80..0xFF);\n\nmy %SuperEncodings =\n ( &amp;ucRemoveEolUnderscoreDash($Encoding_Western), 'cp'.$Code_Page_Western,\n &amp;ucRemoveEolUnderscoreDash($Encoding_Central), 'cp'.$Code_Page_Central,\n &amp;ucRemoveEolUnderscoreDash($Encoding_Baltic), 'cp'.$Code_Page_Baltic,\n &amp;ucRemoveEolUnderscoreDash($Encoding_Turkish), 'cp'.$Code_Page_Turkish,\n &amp;ucRemoveEolUnderscoreDash($Encoding_W_Euro), 'cp'.$Code_Page_Western,\n &amp;ucRemoveEolUnderscoreDash('cp'.$Code_Page_OldWest),\n 'cp'.$Code_Page_Western );\n\nmy %EncodingNames = ( 'cp'.$Code_Page_Central, 'Central European',\n 'cp'.$Code_Page_Western, 'Western European',\n 'cp'.$Code_Page_Turkish, ' Turkish ',\n 'cp'.$Code_Page_Baltic, ' Baltic ' );\n\nmy %NonAccenChars = ( \n #--------------------------------#\n'cp'.$Code_Page_Central, # Central European (cp1250) #\n #--------------------------------#\n #€_‚_„…†‡_‰Š‹ŚŤŽŹ_‘’“”•–—_™š›śťžź#\n 'E_,_,.++_%S_STZZ_````.--_Ts_stzz'.\n\n # ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľż#\n '_``LoAlS`CS_--RZ`+,l`uP.,as_L~lz'.\n\n #ŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢß#\n 'RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTS'.\n\n #ŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙#\n 'raaaalccceeeeiiddnnoooo%ruuuuyt`',\n\n #--------------------------------#\n'cp'.$Code_Page_Western, # Western European (cp1252) #\n #--------------------------------#\n #€_‚ƒ„…†‡ˆ‰Š‹Œ_Ž__‘’“”•–—˜™š›œ_žŸ#\n 'E_,f,.++^%S_O_Z__````.--~Ts_o_zY'.\n\n # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿#\n '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'.\n\n #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞß#\n 'AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTS'.\n\n #àáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ#\n 'aaaaaaaceeeeiiiidnooooo%ouuuuyty',\n\n #--------------------------------#\n'cp'.$Code_Page_Turkish, # Turkish (cp1254) #\n #--------------------------------#\n #€_‚ƒ„…†‡ˆ‰Š‹Œ____‘’“”•–—˜™š›œ__Ÿ#\n 'E_,f,.++^%S_O____````.--~Ts_o__Y'.\n\n # ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿#\n '_!cLoYlS`Ca_--R-`+23`uP.,10_qh3_'.\n\n #ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞß#\n 'AAAAAAACEEEEIIIIGNOOOOOxOUUUUISS'.\n\n #àáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ#\n 'aaaaaaaceeeeiiiignooooo%ouuuuisy',\n\n #--------------------------------#\n'cp'.$Code_Page_Baltic, # Baltic (cp1257) #\n #--------------------------------#\n #€_‚_„…†‡_‰_‹_¨ˇ¸_‘’“”•–—_™_›_¯˛_#\n 'E_,_,.++_%___``,_````.--_T___-,_'.\n\n # �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æ#\n '__cLo_lSOCR_--RA`+23`uP.o1r_qh3a'.\n\n #ĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽß#\n 'AIACAAEECEZEGKILSNNOOOOxULSUUZZS'.\n\n #ąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙#\n 'aiacaaeecezegkilsnnoooo%ulsuuzz`' );\n\nmy %AccentedChars;\nmy $AccentedChars = '';\nmy $NonAccenChars = '';\nfor ( $Code_Page_Central, $Code_Page_Western,\n $Code_Page_Turkish, $Code_Page_Baltic )\n {\n $AccentedChars{'cp'.$_} = decode('cp'.$_, $HighBitSetChars);\n $AccentedChars .= $AccentedChars{'cp'.$_};\n $NonAccenChars .= $NonAccenChars{'cp'.$_};\n }\n#print \"\\n\", length($NonAccenChars), ' ', $NonAccenChars,\"\\n\";\n#print \"\\n\", length($AccentedChars), ' ', $AccentedChars,\"\\n\";\n\nmy $QuotedMetaNonAccenChars = quotemeta($NonAccenChars);\n\nmy $DiacriticalChars = '';\nfor ( 0x0300..0x036F, 0x1DC0..0x1DFF )\n { $DiacriticalChars .= chr($_) }\n\n#-----------------------------------------------------------------------------\n# Parse options and parameters\n#-----------------------------------------------------------------------------\nmy $b_Help = 0;\nmy $b_Interactive = 1;\nmy $b_UTF8 = 0;\nmy $b_Parameter = 0;\nmy $Folder;\n\nfor ( @ARGV )\n{\n if ( lc($_) eq '--' )\n { $b_Parameter = 1 }\n elsif ( (not $b_Parameter) and (lc($_) eq '--batch') )\n { $b_Interactive = 0 }\n elsif ( (not $b_Parameter) and (lc($_) eq '--utf8') )\n { $b_UTF8 = 1 }\n elsif ( $b_Parameter or (substr($_, 0, 1) ne '-') )\n {\n if ( defined($Folder) )\n { die \"$0 accepts only 1 parameter\\n\" }\n else\n { $Folder = $_ }\n }\n else\n { $b_Help = 1 }\n}\n\n#-----------------------------------------------------------------------------\n# Help\n#-----------------------------------------------------------------------------\nif ( $b_Help )\n {\n die &lt;&lt; \"END_OF_HELP\"\n\n$0 [--help] [--batch] [--] [folder]\n\nThis script renames files with accented and diacritical Latin characters :\n\n- This PERL script starts from the folder given in parameter, or else from\n the current folder.\n- It recursively searches for files with characters belonging to 80 - FF of\n CP 1250, CP 1252, CP 1254 and CP 1257 (mostly accented Latin characters)\n or Latin characters having diacritical marks.\n- It calculates new file names by removing the accents and diacritical marks\n only from Latin characters (For example, Été --&gt; Ete).\n- It displays all proposed renaming and perhaps conflicts, and asks the user\n for global approval.\n- If the user has approved, it renames all files having no conflict.\n\nOption '--batch' avoids interactive questions. Use with care.\n\nOption '--' avoids the next parameter to be interpreted as option.\n\nSPECIAL WARNING :\n- This script was originally encoded in UTF-8, and should stay so.\n- This script may rename a lot of files.\n- Files names are theoretically all encoded only with UTF-8. But some file\n names may be found to contain also some characters having legacy encoding.\n- The author has applied efforts for consistency checks, robustness, conflict\n detection and use of appropriate encoding.\n So this script should only rename files by removing accents and diacritical\n marks from Latin characters.\n- But this script has been tested only under a limited number of OS\n (Windows, Mac OS X, Linux) and a limited number of terminal encodings\n (CP 850, ISO-8859-1, UTF-8).\n- So, under weird circumstances, this script could rename many files with\n random names.\n- Therefore, this script should be used with care, and modified with extreme\n care (beware encoding of internal strings, inputs, outputs and commands)\nEND_OF_HELP\n }\n\n#-----------------------------------------------------------------------------\n# If requested, change current folder\n#-----------------------------------------------------------------------------\nif ( defined($Folder) )\n { chdir($Folder) or die \"Can NOT set '$Folder' as current folder\\n\" }\n\n#-----------------------------------------------------------------------------\n# Following instruction is MANDATORY.\n# The return value should be non-zero, but on some systems it is zero.\n#-----------------------------------------------------------------------------\nutf8::decode($AccentedChars);\n# or die \"$0: '\\$AccentedChars' should be UTF-8 but is NOT.\\n\";\n\n#-----------------------------------------------------------------------------\n# Check consistency on 'tr'\n#-----------------------------------------------------------------------------\n$_ = $AccentedChars;\neval \"tr/$AccentedChars/$QuotedMetaNonAccenChars/\";\nif ( $@ ) { warn $@ }\nif ( $@ or ($_ ne $NonAccenChars) )\n { die \"$0: Consistency check on 'tr' FAILED :\\n\\n\",\n \"Translated Accented Chars : \", length($_), ' : ', $_, \"\\n\\n\",\n \" Non Accented Chars : \", length($NonAccenChars), ' : ',\n $NonAccenChars, \"\\n\" }\n\n#-----------------------------------------------------------------------------\n# Constants depending on the OS\n#-----------------------------------------------------------------------------\nmy $b_Windows = ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') );\n\nmy ($Q, $sep, $sep2, $HOME, $Find, @List, $cwd, @Move);\n\nif ( $b_Windows )\n {\n $Q = '\"';\n $sep = '\\\\';\n $sep2 = '\\\\\\\\';\n $HOME = $ENV{'USERPROFILE'};\n $Find = 'dir /b /s';\n @List = ( ( (`ver 2&gt;&amp;1` =~ m/version\\s+([0-9]+)/i) and ($1 &gt;= 6) ) ?\n ('icacls') :\n ( 'cacls') );\n $cwd = `cd`; chomp $cwd; $cwd = quotemeta($cwd);\n @Move = ('move');\n }\nelse\n {\n $Q = \"'\";\n $sep = '/';\n $sep2 = '/';\n $HOME = $ENV{'HOME'};\n $Find = 'find .';\n @List = ('ls', '-d', '--');\n @Move = ('mv', '--');\n if ( -w '/bin' ) { die \"$0: For safety reasons, \",\n \"usage is BLOCKED to administrators.\\n\"}\n }\n\nmy $Encoding;\nmy $ucEncoding;\nmy $InputPipe = '-|'; # Used as global variable\n\n#-----------------------------------------------------------------------------\n# Under Windows, associate input and output encodings to code pages :\n# - Get the original code page,\n# - If it is not UTF-8, try to set it to UTF-8,\n# - Define the input encoding as the one associated to the ACTIVE code page,\n# - If STDOUT is the console, encode output for the ORIGINAL code page.\n#-----------------------------------------------------------------------------\nmy $Code_Page_Original;\nmy $Code_Page_Active;\n\nif ( $b_Windows )\n {\n #-----------------------------------------------------------------------\n # Get the original code page\n #-----------------------------------------------------------------------\n $_ = `chcp`;\n m/([0-9]+)$/ or die \"Non numeric Windows code page : \", $_;\n $Code_Page_Original = $1;\n print 'Windows Original Code Page = ', $Code_Page_Original,\n ( $Code_Page_Original == $Code_Page_UTF8 ?\n ' = UTF-8, display is perhaps correct with a true type font.' :\n '' ), \"\\n\\n\";\n $Code_Page_Active = $Code_Page_Original ;\n\n #-----------------------------------------------------------------------\n # The input encoding must be the same as the ACTIVE code page\n #-----------------------------------------------------------------------\n $Encoding = ( $Code_Page_Active == $Code_Page_UTF8 ?\n 'utf8' :\n 'cp'.$Code_Page_Active ) ;\n $InputPipe .= \":encoding($Encoding)\";\n print \"InputPipe = '$InputPipe'\\n\\n\";\n\n #-----------------------------------------------------------------------\n # If STDOUT is the console, output encoding must be the same as the\n # ORIGINAL code page\n #-----------------------------------------------------------------------\n if ( $Code_Page_Original != $Code_Page_UTF8 )\n {\n no warnings 'unopened';\n @_ = stat(STDOUT);\n use warnings;\n if ( scalar(@_) and ($_[0] == 1) )\n { binmode(STDOUT, \":encoding(cp$Code_Page_Original)\") }\n else\n { binmode(STDOUT, \":encoding($Encoding)\") }\n }\n }\n\n#-----------------------------------------------------------------------------\n# Under *nix, if the 'LANG' environment variable contains an encoding,\n# verify that this encoding is supported by the OS and by PERL.\n#-----------------------------------------------------------------------------\nelsif ( defined($ENV{'LANG'}) and ($ENV{'LANG'} =~ m/\\.([^\\@]+)$/i) )\n {\n $Encoding = $1;\n\n my $Kernel = `uname -s`;\n chomp $Kernel;\n my $ucEncoding = &amp;ucRemoveEolUnderscoreDash($Encoding);\n if ( (lc($Kernel) ne 'darwin') and not grep {$_ eq $ucEncoding}\n ( map { ($_, &amp;ucRemoveEolUnderscoreDash($_)) }\n `locale -m` ) )\n { die \"Encoding = '$Encoding' or '$ucEncoding' NOT supported \".\n \"by the OS\\n\" }\n\n my $ucLocale = &amp;ucRemoveEolUnderscoreDash($ENV{'LANG'});\n if ( not grep {$_ eq $ucLocale}\n ( map { ($_, &amp;ucRemoveEolUnderscoreDash($_)) }\n `locale -a` ) )\n { die \"Locale = '$ENV{LANG}' or '$ucLocale' NOT supported \".\n \"by the OS\\n\" }\n\n if ( not defined(Encode::find_encoding($Encoding)) )\n { die \"Encoding = '$Encoding' or '$ucEncoding' NOT supported \".\n \"by PERL\\n\" }\n\n print \"Encoding = '$Encoding' is supported by the OS and PERL\\n\\n\";\n binmode(STDOUT, \":encoding($Encoding)\");\n }\n\n#-----------------------------------------------------------------------------\n# Check consistency between parameter of 'echo' and output of 'echo'\n#-----------------------------------------------------------------------------\nundef $_;\nif ( defined($Encoding) )\n {\n $ucEncoding = &amp;ucRemoveEolUnderscoreDash($Encoding);\n if ( defined($SuperEncodings{$ucEncoding}) )\n { $_ = substr($AccentedChars{$SuperEncodings{$ucEncoding}},\n 0x20, 0x60) }\n elsif ( defined($AccentedChars{$Encoding}) )\n { $_ = $AccentedChars{$Encoding} }\n elsif ( $Encoding =~ m/^utf-?8$/i )\n { $_ = $AccentedChars }\n }\nif ( not defined($_) ) # Chosen chars are same in 4 code pages\n { $_ = decode('cp'.$Code_Page_Central,\n pack('C*', 0xC9, 0xD3, 0xD7, 0xDC, # ÉÓ×Ü\n 0xE9, 0xF3, 0xF7, 0xFC)) } # éó÷ü\n#print $_, \" (Parameter)\\n\\n\";\n#system 'echo', $_;\nutf8::decode($_);\n#print \"\\n\", $_, \" (Parameter after utf8::decode)\\n\\n\";\nmy @EchoCommand = ( $b_Windows ?\n \"echo $_\" :\n ('echo', $_) );\n#system @EchoCommand;\n\nopen(ECHO, $InputPipe, @EchoCommand) or die 'echo $_: ', $!;\nmy $Output = join('', &lt;ECHO&gt;);\nclose(ECHO);\nchomp $Output;\n#print \"\\n\", $Output, \" (Output of 'echo')\\n\";\nutf8::decode($Output);\n#print \"\\n\", $Output, \" (Output of 'echo' after utf8::decode)\\n\\n\";\n\nif ( $Output ne $_ )\n {\n warn \"$0: Consistency check between parameter \",\n \"of 'echo' and output of 'echo' FAILED :\\n\\n\",\n \"Parameter of 'echo' : \", length($_), ' : ', $_, \"\\n\\n\",\n \" Output of 'echo' : \", length($Output), ' : ', $Output, \"\\n\";\n exit 1;\n }\n\n#-----------------------------------------------------------------------------\n# Print the translation table\n#-----------------------------------------------------------------------------\nif ( defined($Encoding) )\n{\n undef $_;\n $ucEncoding = &amp;ucRemoveEolUnderscoreDash($Encoding);\n if ( defined($SuperEncodings{$ucEncoding}) )\n {\n $_ = $SuperEncodings{$ucEncoding};\n print \"--------- $EncodingNames{$_} ---------\\n\",\n ' ', substr($AccentedChars{$_}, 0x20, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x20, 0x20), \"\\n\\n\",\n ' ', substr($AccentedChars{$_}, 0x40, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x40, 0x20), \"\\n\\n\",\n ' ', substr($AccentedChars{$_}, 0x60, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x60, 0x20), \"\\n\\n\" }\n else\n {\n for ( 'cp'.$Code_Page_Central, 'cp'.$Code_Page_Western,\n 'cp'.$Code_Page_Turkish, 'cp'.$Code_Page_Baltic )\n {\n if ( ('cp'.$Encoding eq $_) or ($Encoding =~ m/^utf-?8$/i) )\n { print \"--------- $EncodingNames{$_} ---------\\n\",\n ' ', substr($AccentedChars{$_}, 0, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0, 0x20), \"\\n\\n\",\n ' ', substr($AccentedChars{$_}, 0x20, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x20, 0x20), \"\\n\\n\",\n ' ', substr($AccentedChars{$_}, 0x40, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x40, 0x20), \"\\n\\n\",\n ' ', substr($AccentedChars{$_}, 0x60, 0x20), \"\\n\",\n '--&gt; ', substr($NonAccenChars{$_}, 0x60, 0x20), \"\\n\\n\" }\n }\n }\n}\n\n#-----------------------------------------------------------------------------\n# Completely optional :\n# Inside the Unison file, find the accented file names to ignore\n#-----------------------------------------------------------------------------\nmy $UnisonFile = $HOME.$sep.'.unison'.$sep.'common.unison';\nmy @Ignores;\n\nif ( open(UnisonFile, '&lt;', $UnisonFile) )\n {\n print \"\\nUnison File '\", $UnisonFile, \"'\\n\";\n while ( &lt;UnisonFile&gt; )\n {\n if ( m/^\\s*ignore\\s*=\\s*Name\\s*(.+)/ )\n {\n $_ = $1 ;\n if ( m/[$AccentedChars]/ )\n { push(@Ignores, $_) }\n }\n }\n close(UnisonFile);\n }\nprint map(\" Ignore: \".$_.\"\\n\", @Ignores);\n\n#-----------------------------------------------------------------------------\n# Function OutputAndErrorFromCommand :\n#\n# Execute the command given as array in parameter, and return STDOUT + STDERR\n#\n# Reads global variable $InputPipe\n#-----------------------------------------------------------------------------\nsub OutputAndErrorFromCommand\n{\n local $_;\n my @Command = @_; # Protects content of @_ from any modification\n #---------------------------------------------------------------------------\n # Under Windows, fork fails, so :\n # - Enclose into double quotes parameters containing blanks or simple\n # quotes,\n # - Use piped open with redirection of STDERR.\n #---------------------------------------------------------------------------\n if ( defined($ENV{'OS'}) and ($ENV{'OS'} eq 'Windows_NT') )\n {\n for ( @Command )\n { s/^((-|.*(\\s|')).*)$/$Q$1$Q/ }\n my $Command = join(' ', @Command);\n #print \"\\n\", $Command;\n open(COMMAND, $InputPipe, \"$Command 2&gt;&amp;1\") or die '$Command: ', $!;\n }\n #---------------------------------------------------------------------------\n # Under Unix, quoting is too difficult, but fork succeeds\n #---------------------------------------------------------------------------\n else\n {\n my $pid = open(COMMAND, $InputPipe);\n defined($pid) or die \"Can't fork: $!\";\n if ( $pid == 0 ) # Child process\n {\n open STDERR, '&gt;&amp;=STDOUT';\n exec @Command; # Returns only on failure\n die \"Can't @Command\";\n }\n }\n $_ = join('', &lt;COMMAND&gt;); # Child's STDOUT + STDERR\n close COMMAND;\n chomp;\n utf8::decode($_);\n $_;\n}\n\n#-----------------------------------------------------------------------------\n# Find recursively all files inside the current folder.\n# Verify accessibility of files with accented names.\n# Calculate non-accented file names from accented file names.\n# Build the list of duplicates.\n#-----------------------------------------------------------------------------\nmy %Olds; # $Olds{$New} = [ $Old1, $Old2, ... ]\nmy $Old;\nmy $Dir;\nmy $Command;\nmy $ErrorMessage;\nmy $New;\nmy %News;\n\nprint \"\\n\\nFiles with accented name and the corresponding non-accented name \",\n \":\\n\";\n\nopen(FIND, $InputPipe, $Find) or die $Find, ': ', $!;\n\nFILE:\nwhile ( &lt;FIND&gt; )\n{\n chomp;\n #---------------------------------------------------------------------------\n # If the file path contains UTF-8, following instruction is MANDATORY.\n # If the file path does NOT contain UTF-8, it should NOT hurt.\n #---------------------------------------------------------------------------\n utf8::decode($_);\n\n if ( $b_Windows )\n { s/^$cwd$sep2// }\n else\n { s/^\\.$sep2// }\n\n #---------------------------------------------------------------------------\n # From now on : $_ = Dir/OldFilename\n #---------------------------------------------------------------------------\n push(@{$Olds{$_}}, $_);\n\n if ( m/([^$sep2]+)$/ and\n ($1 =~ m/[$AccentedChars]|([\\ -\\~][$DiacriticalChars])/) )\n {\n if ( $b_Windows and m/$Q/ )\n {\n print \"\\n $Q$_$Q\\n*** contains quotes.\\n\";\n next;\n }\n for my $Ignore ( @Ignores )\n {\n if ( m/$Ignore$/ )\n { next FILE }\n }\n $Old = $_ ;\n m/^(.*$sep2)?([^$sep2]+)$/;\n $Dir = ( defined($1) ? $1 : '');\n $_ = $2;\n\n #---------------------------------------------------------------------\n # From now on : $Old = Dir/OldFilename\n # $_ = OldFilename\n #---------------------------------------------------------------------\n print \"\\n $Q$Old$Q\\n\";\n $ErrorMessage = &amp;OutputAndErrorFromCommand(@List, $Old);\n if ( $? != 0 )\n { print \"*** $ErrorMessage\\n\" }\n else\n {\n #---------------------------------------------------------------\n # Change accented Latin chars to non-accented chars.\n # Remove all diacritical marks after Latin chars.\n #---------------------------------------------------------------\n eval \"tr/$AccentedChars/$QuotedMetaNonAccenChars/\";\n s/([\\ -\\~])[$DiacriticalChars]+/$1/g;\n #---------------------------------------------------------------\n # From now on : $Old = Dir/OldFilename\n # $_ = NewFilename\n #---------------------------------------------------------------\n if ( $@ )\n { warn $@ }\n else\n {\n $New = $Dir.$_;\n if ( $b_Windows or (not utf8::is_utf8($Dir)) ) # Weird\n { utf8::decode($New) } # but necessary\n $News{$Old} = $New;\n push(@{$Olds{$New}}, $Old);\n }\n print \"--&gt; $Q$Dir$_$Q\\n\";\n }\n }\n}\n\nclose(FIND);\n\n#-----------------------------------------------------------------------------\n# Print list of duplicate non-accented file names\n#-----------------------------------------------------------------------------\nmy $b_NoDuplicate = 1;\n\nfor my $New ( sort keys %Olds )\n{\n if ( scalar(@{$Olds{$New}}) &gt; 1 )\n {\n if ( $b_NoDuplicate )\n {\n print \"\\n\\nFollowing files would have same non-accented name \",\n \":\\n\";\n $b_NoDuplicate = 0;\n }\n print \"\\n\", map(' '.$_.\"\\n\", @{$Olds{$New}}), '--&gt; ', $New, \"\\n\";\n for ( @{$Olds{$New}} )\n { delete $News{$_} };\n }\n}\n\n#-----------------------------------------------------------------------------\n# If there are NO file to rename, then exit\n#-----------------------------------------------------------------------------\nmy $Number = scalar(keys %News);\n\nprint \"\\n\\n\";\nif ( $Number &lt; 1 )\n {\n print \"There are NO file to rename\\n\";\n exit;\n }\n\n#-----------------------------------------------------------------------------\n# Ask the user for global approval of renaming\n#-----------------------------------------------------------------------------\nif ( $b_Interactive )\n {\n print \"In order to really rename the \", $Number,\n \" files which can safely be renamed, type 'rename' : \";\n $_ = &lt;STDIN&gt;;\n sleep 1; # Gives time to PERL to handle interrupts\n if ( not m/^rename$/i )\n { exit 1 }\n }\nelse\n { print $Number, \" files will be renamed\\n\\n\" }\n\n#-----------------------------------------------------------------------------\n# Rename accented file names sorted descending by name size\n#-----------------------------------------------------------------------------\n$Number = 0;\nmy $Move = join(' ', @Move);\n\nfor ( sort {length($b) &lt;=&gt; length($a)} keys %News )\n{\n $ErrorMessage = &amp;OutputAndErrorFromCommand(@Move, $_, $News{$_});\n if ( $? == 0 )\n { $Number++ }\n else\n { print \"\\n$Move $Q$_$Q\\n\", (' ' x length($Move)),\n \" $Q$News{$_}$Q\\n\", ('*' x length($Move)), \" $ErrorMessage\\n\" }\n}\nprint \"\\n$Number files have been successfully renamed\\n\";\n\n__END__\n\n</code></pre>\n" }, { "answer_id": 2470001, "author": "Manolo", "author_id": 296527, "author_profile": "https://Stackoverflow.com/users/296527", "pm_score": 0, "selected": false, "text": "<p>I'm using this batch to rename folders and seems to work fine so far...\nIn my case codepage is 1252, yours might be different.</p>\n\n<pre><code>mode con codepage select=1252\n@echo off\nSetlocal enabledelayedexpansion\n::folder only (/D option)\nfor /R /D %%d in (*) do (\n\nset an=%%~nd\nset bn=!an:.=_!\nset cn=!bn:-=_!\nset dn=!cn: =_!\nset en=!dn:Á=A!\nset fn=!en:É=E!\nset gn=!fn:Í=I!\nset hn=!gn:Ó=O!\nset in=!hn:Ú=U!\nset jn=!in:Ü=U!\nset kn=!jn:á=a!\nset ln=!kn:é=e!\nset mn=!ln:í=i!\nset nn=!mn:ó=o!\nset on=!nn:ú=u!\nset pn=!on:ü=u!\nset qn=!pn:Ñ=N!\nset zn=!on:ñ=n!\n\nset ax=%%~xd\nset bx=!ax:.=_!\nset cx=!bx:-=_!\nset dx=!cx: =_!\nset bx=!ax:.=_!\nset cx=!bx:-=_!\nset dx=!cx: =_!\nset ex=!dx:Á=A!\nset fx=!ex:É=E!\nset gx=!fx:Í=I!\nset hx=!gx:Ó=O!\nset ix=!hx:Ú=U!\nset jx=!ix:Ü=U!\nset kx=!jx:á=a!\nset lx=!kx:é=e!\nset mx=!lx:í=i!\nset nx=!mx:ó=o!\nset ox=!nx:ú=u!\nset px=!ox:ü=u!\nset qx=!px:Ñ=N!\nset zx=!ox:ñ=n!\n\n\nif [!an!]==[] (set zn=)\nif [!ax!]==[] (set zx=)\n\nset newname=!zn!!zx!\n\nif /i not [%%~nd%%~xd]==[!newname!] rename \"%%d\" !newname!\n\n)\n\nendlocal\n\npause\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9625/" ]
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g. Störung%20.doc would be renamed to St\_rung\_20.doc In order of preference: 1. A Windiws batch file 2. A Windows script file to run with cscript (vbs) 3. A third party piece of software that can be run from the command-line (i.e. no user interaction required) 4. Another language script file, for which I'd have to install an additional script engine Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.
Thanks to Tomalak who actually pointed me in the right direction. Thought I'd post here for completeness. The problem seems to be that the codepage used by GPG is fixed (Latin I) independent of the codepage configured in the console. But once he pointed this out, I figured out how to workaraound this. The trick is to change the codepage before generating the file list. This will actually make the filelist appear to be incorrect when viewed in the console. However, when passed to GPG, it works fine. GPG accepts the files and spits out the encrytped files with correct filenames. The batch file looks something like this: ``` chcp 1252 dir /b /s /a-d MyFolder >filelist.txt gpg -r [email protected] --encrypt-files <filelist.txt ```
261,518
<p>Here's the situation:</p> <p>I have one VS2005 solution with two projects: MyDll (DLL), MyDllUnitTest (console EXE).</p> <p>In MyDll I have a class called MyClass which is internal to the DLL and should not be exported. I want to test it in MyDllUnitTest, so I added a test suite class called MyClassTest, where I create instances of MyClass and test them.</p> <p>My question: how can I link the object file of MyClass, created by building MyDll, to the MyDllUnitTest EXE? I don't want to build MyClass in MyDllUnitTest and I don't want to export the class.</p> <p>I tried using the same <em>Intermediate Directory</em> for both projects (so object files are in the same directory) and using the References feature of VS2005 (right click project --> References --> Add New Reference...), but it didn't work - I still get a linking error (LNK2001).</p> <p><strong>Edit:</strong> I don't want to have the same source file in two projects - consider the face that I have many MyClass/MyClassTest, which means I have to duplicate each MyClass to a different project. I know it is possible to use the same object file in two projects, I've seen it done before but forgot how.</p> <p><strong>Edit:</strong> I've decided to put the files in both projects, so they are compiled twice. It turns out the "Reference" feature works automatically - but only for static lib projects.</p>
[ { "answer_id": 261579, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 3, "selected": true, "text": "<p>I don't understand why you don't want to build it in your dll project. As long as both projects are using the same source file, they will both generate the same object file (assuming compiler options are set the same way).</p>\n\n<p>If you want to test the dll without exporting the class itself (I presume this is because exporting classes in a dll is usually a bad idea), consider exporting a \"factory\" function from the dll. It would have a signature like:</p>\n\n<pre><code>extern \"C\" MyClass *CreateMyClass();\n</code></pre>\n\n<p>This function would create an object of MyClass and return a pointer to it. Your unit test can then do whatever it needs with the returned class object.</p>\n" }, { "answer_id": 261707, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 0, "selected": false, "text": "<p>I think you also need to explicitly add the .obj file to your list of additional dependencies in your project linker settings.</p>\n" }, { "answer_id": 263688, "author": "user32378", "author_id": 32378, "author_profile": "https://Stackoverflow.com/users/32378", "pm_score": 1, "selected": false, "text": "<p>Here is an alternative approach to achieve what your trying to do BUT I believe that it will meet your requirements...</p>\n\n<p>Use the InternalsVisibleToAttribute attribute on the assembly that contains the classes you want to test. Then if you reference this assembly you'll be able to test the class even though to other assemblies these types are \"invisible\". Magic! </p>\n\n<p>Here is the MSDN reference of the attribute to use ...</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx</a></p>\n" }, { "answer_id": 8541963, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>you could also try to use a command that generates a .lib with all the objects.</p>\n\n<p>Like in the answer from: <a href=\"https://stackoverflow.com/questions/8541727/visual-c-link-generated-objs-from-referenced-project/\">Visual C++ link generated objs from referenced project</a></p>\n" }, { "answer_id": 11831619, "author": "Paul Becherer", "author_id": 1579618, "author_profile": "https://Stackoverflow.com/users/1579618", "pm_score": 1, "selected": false, "text": "<p>What I do here is making an extra 'filter' \"Object Files\" in the testing project, alongside the \"Header Files\" and \"Source Files\", and putting all the necessary .obj files in there (which is easier if they've already been generated, by the way). This seems to work fine here. We also use that for unit testing here, and in some places for not having to compile the same source file twice when using it for two different DLLs.</p>\n\n<p>One reason we're doing it this way is that we use CMake to generate our project files, and so cannot use all of the internal Visual Studio 'magic'.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33982/" ]
Here's the situation: I have one VS2005 solution with two projects: MyDll (DLL), MyDllUnitTest (console EXE). In MyDll I have a class called MyClass which is internal to the DLL and should not be exported. I want to test it in MyDllUnitTest, so I added a test suite class called MyClassTest, where I create instances of MyClass and test them. My question: how can I link the object file of MyClass, created by building MyDll, to the MyDllUnitTest EXE? I don't want to build MyClass in MyDllUnitTest and I don't want to export the class. I tried using the same *Intermediate Directory* for both projects (so object files are in the same directory) and using the References feature of VS2005 (right click project --> References --> Add New Reference...), but it didn't work - I still get a linking error (LNK2001). **Edit:** I don't want to have the same source file in two projects - consider the face that I have many MyClass/MyClassTest, which means I have to duplicate each MyClass to a different project. I know it is possible to use the same object file in two projects, I've seen it done before but forgot how. **Edit:** I've decided to put the files in both projects, so they are compiled twice. It turns out the "Reference" feature works automatically - but only for static lib projects.
I don't understand why you don't want to build it in your dll project. As long as both projects are using the same source file, they will both generate the same object file (assuming compiler options are set the same way). If you want to test the dll without exporting the class itself (I presume this is because exporting classes in a dll is usually a bad idea), consider exporting a "factory" function from the dll. It would have a signature like: ``` extern "C" MyClass *CreateMyClass(); ``` This function would create an object of MyClass and return a pointer to it. Your unit test can then do whatever it needs with the returned class object.
261,525
<p>We're using Perforce and Visual Studio. Whenever we create a branch, some projects will not be bound to source control unless we use "Open from Source Control", but other projects work regardless. From my investigations, I know some of the things involved:</p> <p>In our .csproj files, there are these settings:</p> <ul> <li>&lt;SccProjectName></li> <li>&lt;SccLocalPath></li> <li>&lt;SccAuxPath></li> <li>&lt;SccProvider></li> </ul> <p>Sometimes they are all set to "SAK", sometimes not. It seems things are more likely to work if these say "SAK".</p> <p>In our .sln file, there are settings for many of the projects:</p> <ul> <li>SccLocalPath#</li> <li>SccProjectFilePathRelativizedFromConnection#</li> <li>SccProjectUniqueName#</li> </ul> <p>(The # is a number that identifies each project.) SccLocalPath is a path relative to the solution file. Often it is ".", sometimes it is the folder that the project is in, and sometimes it is ".." or "..\..", and it seems to be bad for it to point to a folder above the solution folder. The relativized one is a path <em>from</em> that folder to the project file. It will be missing entirely if SccLocalPath points to the project's folder. If the SccLocalPath has ".." in it, this path might include folder names that are not the same between branches, which I think causes problems.</p> <p>So, to finally get to the specifics I'd like to know:</p> <ul> <li>What happens when you do "Change source control" and bind projects? How does Visual Studio decide what to put in the project and solution files?</li> <li>What happens when you do "Open from source control"?</li> <li>What's this "connection" folder that SccLocalPath and SccProjectFilePathRelativizedFromConnection refer to? How does Visual Studio/Perforce pick it?</li> <li>Is there some recommended way to make the source control bindings continue to work even when you create a new branch of the solution?</li> </ul> <hr> <p><em>Added June 2012:</em> I don't use Perforce any more, so I can't vouch for it, but have a look at <a href="https://stackoverflow.com/a/11148342/2283">KCD's answer</a> below. Apparently there's <a href="http://forums.perforce.com/index.php?/topic/1585-new-perforce-plugin-for-visual-studio-20121-beta-available-now/" rel="nofollow noreferrer">a new P4 VS plugin</a> under development. Hopefully it should clear up all this mess!</p>
[ { "answer_id": 268578, "author": "Thomas L Holaday", "author_id": 29403, "author_profile": "https://Stackoverflow.com/users/29403", "pm_score": 1, "selected": false, "text": "<p>I can answer the last one.</p>\n\n<p>In order to get source control bindings to work even when you create a new branch, follow a strict hierarchical structure:</p>\n\n<pre><code>/Solution\n /library1\n /library2\n /product1\n /product2\n /subsolution\n /sublibrary1\n /subproduct1\n</code></pre>\n\n<p>Each file must be in exactly one .vcproj. You can have multiple .vcproj in the same directory, but if they share files, the shared files must go into their own .vcproj.</p>\n\n<p>If you are relentless in this, all the Scc stuff will be relative-path, so a new branch will work (because it only changes the topmost directory).</p>\n" }, { "answer_id": 271228, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 2, "selected": false, "text": "<p>Very poorly. I know that is not the answer to your questions that you were looking for (in the future, perhaps you could narrow the focus?), but source control integration with Visual Studio just sucks. The reason being that they all have to use Microsoft's terrible SCC interface. It's pathetic! They put source control information in the project files! Why would they do that?</p>\n\n<p>Just abandon the Visual Studio integration and use the Perforce client. It's not that much extra work. You can't spare 30 seconds per day to switch over to the Perforce client and check in/out the files out from there?</p>\n" }, { "answer_id": 322397, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 2, "selected": false, "text": "<p>Support for renaming a file or moving it to a new folder directory is <em>terrible</em> and painful if using the Visual Studio P4 plug-in integration. No built-in feature exists that alerts P4 to renaming the file or that it has been moved.</p>\n\n<p>The issue is that renaming a file requires not just updating the associated VS project file but Perforce needs to be informed as well of the change if you want to maintain proper revision history.</p>\n\n<p>Currently, I do not see a way to do both in a single operation if using the VS integration. Instead, you have to:</p>\n\n<ol>\n<li>rename/move the file from within the Perforce client </li>\n<li>delete the old filename reference in the project file within VS</li>\n<li>add the new filename reference in the project file within VS</li>\n<li>submit your changes </li>\n</ol>\n\n<p>If you use a continuous integration build process and you submit changes at any point prior to the last step, you are guaranteed to have a broken build.</p>\n\n<p>The problem magnifies significantly the more files that require renaming or moving. This is not a smooth process whatsoever.</p>\n" }, { "answer_id": 529538, "author": "Milan Gardian", "author_id": 23843, "author_profile": "https://Stackoverflow.com/users/23843", "pm_score": 8, "selected": true, "text": "<h1>Introduction</h1>\n\n<p>I would disagree with the claim that Perforce integration in Visual Studio is \"terrible\". Rather, I'd define it as \"out of the box experience is less than optimal\" :-). The following sections discuss my understanding of the integration and recommendations for project/solution setup.</p>\n\n<p>If you're not interested in the details of how the source control integration works you can skip to the end of this answer where I summarize answers to Weeble's question.</p>\n\n<p><em>Disclaimer</em>: The following sections are just educated guesses based on my empirical experience, however I've used the technique over many years in many projects (each project having multiple experimental/trunk/maintenance/release branches, sometimes even multiple solution files, without issues). The disadvantage is that you have to <em>manually</em> update the project files - but the 2 minute investment is amortized over the lifetime of a project pretty nicely IMHO :-).</p>\n\n<h1>Solution vs. Project</h1>\n\n<p>Visual Studio uses source control binding information from both solution file and each project file during the initial solution loading. This binding information is then stored in <strong>name.suo</strong> file (assuming we're using <strong>name.sln</strong> as solution) - note that <strong>suo</strong> files are marked with <strong>hidden</strong> flag so they won't be visible in file explorer (unless you override the \"Hidden files and folders\" option).</p>\n\n<p>The easiest way to re-bind to source control provider if anything goes wrong is to delete the appropriate <strong>suo</strong> file and reopen solution. After suo file has been created, changes to &lt;Scc*&gt; elements have no effect.</p>\n\n<p>If during the initial solution opening there is a discrepancy between the binding information stored in solution file and information stored in project file, Visual Studio will attempt to fix this (sometimes it will even prompt for your decision to choose whether the information in solution or the information in project should be used as a \"master\" to resolve the discrepancy):</p>\n\n<p><img src=\"https://i.stack.imgur.com/AUf7n.png\" alt=\"alt text\"></p>\n\n<p>Why is Visual Studio violating DRY (Don't Repeat Yourself) principle? I have no idea. I presume this has historic reasons and is tightly coupled to the needs of that nightmare called Visual Source Safe :-).</p>\n\n<h1>How to set it up \"correctly\"?</h1>\n\n<p>When adding either new or existing solutions/projects to Perforce, I <strong>always</strong> start by creating a blank solution (see the \"Source-controlling a blank solution\" section). I then add projects to this blank solution, one after another. The steps differ slightly based on whether the project being added already exists (see the \"Source-controlling existing (unbound) projects\" and \"Source-controlling existing (bound) projects\" sections) or I need to create a new one (see the \"Source-controlling new projects\" section).</p>\n\n<h1>Source-controlling a blank solution</h1>\n\n<p>To add a new blank solution to source control, do the following:</p>\n\n<ol>\n<li>Start Visual Studio, \"New\" -> \"Project...\" -> \"Other project types\" -> \"Blank solution\"; fill in solution name and location, \"OK\" button</li>\n<li>\"File\" -> \"Source Control\" -> \"Add Solution to Source Control...\"</li>\n<li>In the connection dialog enter appropriate P4 server port, client and user (note that view of the selected client must include the location that you picked in step 1)</li>\n<li>\"View\" -> \"Pending Checkins\" -> \"Check In\" -> in the submit dialog instead of hitting the \"Submit\" button, use \"Cancel\". <br/>\n<strong>Reason</strong>: The \"Check In\" action will create a new file, \"name.vssscc\", then add both \"name.sln\" and \"name.vssscc\" to Perforce's default changelist; by cancelling the submit dialog we will keep the \"add\" operation pending and will be able to edit the files before submitting to P4</li>\n<li>Close Visual Studio</li>\n<li><p>Open the name.sln file in your favourite editor (notepad, if you're really desperate :-) ) and add two new lines (<strong>SccProjectName0</strong> and <strong>SccProvider0</strong>) - the blank solution file should now have a source control section as follows:</p>\n\n<pre><code>GlobalSection(SourceCodeControl) = preSolution\n SccNumberOfProjects = 1\n SccLocalPath0 = .\n SccProjectName0 = Tutorial\n SccProvider0 = MSSCCI:Perforce\\u0020SCM\nEndGlobalSection\n</code></pre>\n\n<p>The values should be chosen as follows:</p>\n\n<ul>\n<li><strong>SccProjectName0</strong>: an arbitrary string that will be displayed in \"Change Source Control\" dialog as \"Server Binding\". This name is used to determine what projects/solution files can share the same source control connection. I recommend not using space for this name as escaping rules for spaces are different in solution and project files.</li>\n<li><strong>SccProvider0</strong>: hard-coded value \"MSSCCI:Perforce\\u0020SCM\".</li>\n</ul></li>\n<li>Submit the two pending files using the Perforce client of your choice (p4.exe, P4Win, P4V)</li>\n</ol>\n\n<p>You can now test the bindings:</p>\n\n<ol>\n<li>Make sure Visual Studio is closed </li>\n<li>Delete **all* files except the name.sln (especially the name.suo)</li>\n<li>Open Visual Studio and use it to open name.sln</li>\n<li>A connection dialog should appear, use appropriate port/client/user and click OK</li>\n<li>Solution explorer should now display the solution node with a padlock overlay icon:\n<img src=\"https://i.stack.imgur.com/KmfTd.png\" alt=\"Source-controlled blank solution\"></li>\n<li>You can now verify source control status of the solution by using \"File\" -> \"Source Control\" -> \"Change Source Control...\":\n<img src=\"https://i.stack.imgur.com/DLvQY.png\" alt=\"Source control status of blank solution\">\nNote: The column \"Server Binding\" is showing the value we chose for \"SccProjectName0\".</li>\n</ol>\n\n<h1>Source-controlling new projects</h1>\n\n<p>If you're creating a brand-new project and would like to immediately start tracking it in a Perforce depot, follow these steps:</p>\n\n<ol>\n<li>Open the source-controlled solution in Visual Studio</li>\n<li>\"File\" -> \"Add\" -> \"New Project...\" - pick the project type you're adding, name and location (location should be a subdirectory of the directory where the solution file is stored)</li>\n<li>\"File\" -> \"Save All\" (this will commit all in-memory changes to solution file and the newly created project file to the disk)</li>\n<li><p>Manually edit the project file you just created using an editor of your choice (come on, notepad AGAIN? ;-) ). Add the following property elements into a PropertyGroup (any property group):</p>\n\n<pre><code>&lt;PropertyGroup&gt;\n ...\n &lt;SccProjectName&gt;Tutorial&lt;/SccProjectName&gt;\n &lt;SccLocalPath&gt;..\\..&lt;/SccLocalPath&gt;\n &lt;SccProvider&gt;MSSCCI:Perforce SCM&lt;/SccProvider&gt;\n ...\n&lt;/PropertyGroup&gt;\n</code></pre>\n\n<p>The values should be chosen as follows:</p>\n\n<ul>\n<li><strong>SccProjectName</strong> - this is the value that is displayed in \"Change Source Control\" dialog as \"Server Binding\"; should be the same as the value you used for SccProjectName0 in blank solution; if not the same, solution and this project won't be able to share the same source control provider connection</li>\n<li><strong>SccLocalPath</strong> - relative path to the reference directory (displayed in \"Change Source Control\" dialog as \"Local binding\"); because I recommend using the solution directory as the reference directory, this is in effect relative path from directory containing project file to directory containing solution file (my example is storing projects in \"(solutionDir)/Source/ProjectName/projectName.csproj\", thus the relative path is \"two levels up\")</li>\n<li><strong>SccProvider</strong> - hard-coded value \"MSSCCI:Perforce SCM\"; this is used to determine what SCCAPI provider are the Scc* binding values valid for</li>\n</ul></li>\n<li><p>Switch back to Visual Studio; it should automatically detect that the project file has been updated externally and offer to reload it (if not, unload and reload the project manually)</p></li>\n<li>\"View\" -> \"Pending Checkins\"</li>\n<li>\"Check In\" -> I recommend right-clicking on (solutionName).vssscc file and selecting \"Revert if unchanged\" (even though Visual Studio opens it for edit, it remains unchanged); provide description and submit the change</li>\n</ol>\n\n<p>To verify that the newly added project is bound properly, you can follow these steps:</p>\n\n<ol>\n<li>Make sure Visual Studio is closed</li>\n<li>Delete (solutionName).suo file as well as MSSCCPRJ.SCC (in solution directory)</li>\n<li>Open Visual Studio and use it to open (solutionName).sln</li>\n<li>A connection dialog should appear, use appropriate port/client/user and click OK</li>\n<li>Solution explorer should now display the project node with a padlock overlay icon:\n<img src=\"https://i.stack.imgur.com/vyRH4.png\" alt=\"Source-controlled projects\"></li>\n<li><p>You can now verify source control status of the solution by using \"File\" -> \"Source Control\" -> \"Change Source Control...\":\n<img src=\"https://i.stack.imgur.com/3V33X.png\" alt=\"Status of source-controlled projects\"></p>\n\n<p>One thing to note about this status screenshot is that when I selected the solution row, all the remaining rows were \"selected\" as well (blue highlight). This is because all those entries have the same \"Server Binding\" + \"Local Binding\" and thus share the same source-control-provider (P4) connection.</p>\n\n<p>Also note that \"Relative Path\" for both projects has two levels, and are relative to the same \"Local Binding\" - the directory where solution file resides.</p></li>\n</ol>\n\n<h1>Source-controlling existing (unbound) projects</h1>\n\n<p>If you have existing projects that have not yet been used in any other Perforce solution, follow these steps to add them to Perforce (i.e. importing projects that have not been source-controlled before (Internet downloads etc.) or were using a different source control provider (Visual Source Safe, etc.).</p>\n\n<ol>\n<li>Copy the project into appropriate location</li>\n<li>Clean-up existing source control bindings (if any):\n\n<ul>\n<li>Remove existing project-file bindings, i.e. all properties starting with \"Scc\"</li>\n<li>Delete file (projectName).vspscc in the same directory as the project file (if any)</li>\n</ul></li>\n<li>Open the source-controlled solution in Visual Studio</li>\n<li>\"File\" -> \"Add\" -> \"Existing project...\" - browse to the project (the copy you created in step 1)</li>\n<li>\"File\" -> \"Save All\" (this will commit all in-memory changes to solution file)</li>\n<li>Follow the steps 4-7 from \"Source-controlling new projects\" (i.e. you will now add \"Scc*\" property elements into a <strong>PropertyGroup</strong>)</li>\n</ol>\n\n<p>Verification steps are exactly the same as in \"Source-controlling new projects\" section.</p>\n\n<h1>Source-controlling existing (bound) projects</h1>\n\n<p>If you have projects that have already been bound to Perforce using the technique discussed here and you want to use them in a different solution (new branch, alternative solution reusing the project, etc) use the following steps:</p>\n\n<ol>\n<li>Integrate the project into desired location</li>\n<li>Open the source-controlled solution in Visual Studio</li>\n<li>\"File\" -> \"Add\" -> \"Existing project...\" - browse to the project created in step 1 via integration</li>\n<li>\"View\" -> \"Pending Checkins\" -> \"Check In\" - add description and submit</li>\n</ol>\n\n<h1>Summary</h1>\n\n<ul>\n<li>Source control binding information is stored in both solution and projects, must be in sync (if not, Visual Studio will attempt to fix any discrepancies)</li>\n<li>I always treat project files as the primary source of binding information and solution files as throwaway files that can be recreated easily by first source-controlling a blank solution and then adding desired projects</li>\n<li>Solution file should always have valid <strong>SccProvider0</strong> and <strong>SccProjectName0</strong> values (have to be added manually with new versions of P4SCC plugins)</li>\n<li>Project files should always have valid <strong>SccProjectName</strong> (preferrably same as <strong>SccProjectName0</strong>), <strong>SccLocalPath</strong> and <strong>SccProvider</strong> values (also have to be edited manually as the P4SCC defaults are no good)</li>\n</ul>\n\n<p>I'm also including answers to your original questions:</p>\n\n<blockquote>\n <p>What happens when you do \"Change source control\" and bind projects? How does Visual Studio decide what to put in the project and solution files?</p>\n</blockquote>\n\n<p>This updates \"Scc*\" elements in a project file you're rebinding; the solution file is then updated as well so that it is in sync with the project file bindings</p>\n\n<blockquote>\n <p>What happens when you do \"Open from source control\"?</p>\n</blockquote>\n\n<p>Allows you to pick solution that you'd like to open. Afterwards all the projects included in the solution are automatically synced to head. I find this feature not very useful in Perforce world where you have to create a client anyway and the chances are you're syncing this client from a P4V/P4Win/P4 instead of relying on Visual Studio. This was kind-of useful in Visual Source Safe world where there was no concept of views and you were defining where a repository goes on checkout time.</p>\n\n<blockquote>\n <p>What's this \"connection\" folder that SccLocalPath and SccProjectFilePathRelativizedFromConnection refer to? How does Visual Studio/Perforce pick it?</p>\n</blockquote>\n\n<p>This is Visual Studio's bookkeeping. It is determined based on bindings in each project file (I guess in theory if a project file loses binding information for some reason, it could be reconstructed from the solution information...)</p>\n\n<blockquote>\n <p>Is there some recommended way to make the source control bindings continue to work even when you create a new branch of the solution?</p>\n</blockquote>\n\n<p>I hope the sections above give you some idea of a way that is working very well for me :-).</p>\n" }, { "answer_id": 2481213, "author": "Tim Sparkles", "author_id": 92333, "author_profile": "https://Stackoverflow.com/users/92333", "pm_score": 5, "selected": false, "text": "<p>Milan's post is well-researched and well-written, but its length demonstrates beyond a shadow of a doubt that the P4SCC model is broken. Storing source control binding info inside the project &amp; solution files is ridiculous. Enforcing (via sccprojectname) that a project be part of only one solution is equally ridiculous.</p>\n\n<p>Additionally, P4SCC has a tremendous performance cost in a large solution, as it retrieves info from source control for each file at startup, and maintains that state in memory throughout the development session. It creates extra cruft in the form of information-free .vsscc &amp; vssscc files to support some SCC feature that (AFAICT) Perforce does not use. </p>\n\n<p>The ideal Perforce integration looks like:</p>\n\n<ul>\n<li>If I create a new solution, project, or project item, run 'p4 add'.</li>\n<li>If I change a file, run 'p4 edit'.</li>\n<li>Some toolbar/context menu integration for revision history, revision graph, timelapse/blame, and 'show in P4 gui'.</li>\n<li>(nice to have) If I rename a file that exists in the depot, run 'p4 integrate' and 'p4 delete'. If I rename a file opened for add, run 'p4 revert' and 'p4 add'.</li>\n<li>That's all</li>\n</ul>\n\n<p>We have moved completely away from P4SCC and its bizarre requirements and burdens. Instead we use <a href=\"http://code.google.com/p/niftyplugins/\" rel=\"noreferrer\">NiftyPerforce</a>. There are some bugs, but we find working around these bugs to be much less frustrating than working around the design defects in the Perforce&lt;->VSSCC model.</p>\n" }, { "answer_id": 5184384, "author": "Dave Andersen", "author_id": 116311, "author_profile": "https://Stackoverflow.com/users/116311", "pm_score": 2, "selected": false, "text": "<p>After experimenting with Milan Gardian's very informative answer, I think I can provide a simpler solution to get it working pretty well.</p>\n\n<p>As Weeble mentioned, the SAK values work fine when everything else is set up correctly, and they are often the default values (but I think it depends on which project type it is). If they do not show up in your project, just paste in this property group.</p>\n\n<pre><code>&lt;PropertyGroup&gt;\n &lt;SccProjectName&gt;SAK&lt;/SccProjectName&gt;\n &lt;SccProvider&gt;SAK&lt;/SccProvider&gt;\n &lt;SccAuxPath&gt;SAK&lt;/SccAuxPath&gt;\n &lt;SccLocalPath&gt;SAK&lt;/SccLocalPath&gt;\n&lt;/PropertyGroup&gt;\n</code></pre>\n\n<p>Add these two lines to the *.sln in the SourceCodeControl GlobalSection. As long as the project files have SAK values, they should inherit the names from the solution.</p>\n\n<pre><code>SccProjectName0 = Perforce\\u0020Project\nSccProvider0 = MSSCCI:Perforce\\u0020SCM\n</code></pre>\n\n<p>No *.vssscc, *.vspscc, or *.SCC files need to be checked in (though they will be generated when the solution is opened).</p>\n" }, { "answer_id": 6592823, "author": "Zoner", "author_id": 804455, "author_profile": "https://Stackoverflow.com/users/804455", "pm_score": 3, "selected": false, "text": "<p>Using Perforce with Visual Studio can be simplified by using the P4CONFIG environment variable.</p>\n\n<p>Basically you go into Visual Studio, Tools -> Options -> Source Control -> Plug-in Settings, Advanced button. This will bring up a Perforce configuration dialog specific to the SCC integration. Switch to the Connection tab, and check the radio button titled 'Bind the workspace that matches your Perforce environment settings'. This will tell perforce to prefer using P4CONFIG environment variable for determining the environment you are under. This same dialog exists in P4V under Edit -> Preferences, but only affects p4v's behavior.</p>\n\n<p>How you setup the P4CONFIG environment variable is up to you to some degree. I like having them be named the same everywhere so I set a system-wide environment variable P4CONFIG to look for a file named p4config.cfg. This file is just an ini style file, where you can assign other variables such as P4USER, P4CLIENT, P4HOST etc. Perforce will search for this file in the current directory and all parent directories until it encounters one. Basically you put this file in the root most directory of your where your clientspec is mapped to on your hard drive, and leave it alone.</p>\n\n<p>This approach greatly reduces the amount of 'correctness' that the SCC configuration needs in visual studio in order to function. (SAK bindings work fine etc.)</p>\n\n<p>If after syncing your code from perforce for the first time or to a totaly clean directory structure, and getting a dialog complaining about perforce wanting to either temporarily work offline or remove bindings, there is still some editing you need to do. Primarily the .sln file itself needs to be modified so it knows the sln has SCC bindings for itself . This is done by making sure the following fields are placed right after SccNumberOfProjects in the .sln file.</p>\n\n<pre><code>SccProjectName0 = Perforce\\u0020Project\nSccProvider0 = MSSCCI:Perforce\\u0020SCM\n</code></pre>\n\n<p>All of the individual projects should work fine with default 'SAK bindings' provided you are using the P4CONFIG approach. Fixing this should allow Perforce to work from a clean sync perfectly, and also eliminate the generation of MSSCCPRJ.SCC cruft in each of the project directories.</p>\n" }, { "answer_id": 11148342, "author": "KCD", "author_id": 516748, "author_profile": "https://Stackoverflow.com/users/516748", "pm_score": 3, "selected": false, "text": "<p>Just to keep this current - the P4VS plugin has been rewritten circa 2012</p>\n\n<blockquote>\n <p>Now you can perform all of your daily \n interaction with Perforce naturally, like checking in code and viewing file history, \n directly from the IDE. </p>\n \n <p>If you’re a power user looking for a bit more, P4VS won’t disappoint.\n P4VS is fully compatible with Perforce Streams, and the Stream Graph\n is accessible from the IDE, along with Time-lapse View and Revision \n Graph. If you are responsible for branch management, you can merge \n from P4VS as well.</p>\n \n <p>And, if you work remotely or want to do a little private branching, \n P4Sandbox can be configured through P4VS.</p>\n</blockquote>\n\n<ul>\n<li><a href=\"http://www.perforce.com/product/components/visual-studio-plug-in\" rel=\"nofollow noreferrer\">P4VS page on perforce.com</a></li>\n<li><a href=\"http://www.perforce.com/documentation/multimedia-library/webinar/best-tools-2012-increase-productivity-visual-studio-perforce\" rel=\"nofollow noreferrer\">Webinar</a> on how to use it</li>\n</ul>\n" }, { "answer_id": 17050066, "author": "Mr Twister", "author_id": 2475558, "author_profile": "https://Stackoverflow.com/users/2475558", "pm_score": -1, "selected": false, "text": "<p>This is not a Perforce issue, it is a Visual Studio issue. The ridiculous requirement that source files be modified to allow Visual Studio to understand that there is an SCM tool in use is idiotic.</p>\n\n<p>The simple answer is 'stop using the Visual Studio source control integration'. It just plain sucks. Even with TFS it just plain sucks.</p>\n\n<p>If you want to be able to check out from within Visual Studio, just create a custom tool. A simple call to 'p4 edit' with the appropriate VS variable is all you need. Want to revert a file? Same idea...call p4 revert with the appropriate variable. Done.</p>\n\n<p>Use p4v to manage your source control needs (submissions, history, diffs, etc.) Visual Studio rocks as a source editor. It sucks as an SCM interface.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2283/" ]
We're using Perforce and Visual Studio. Whenever we create a branch, some projects will not be bound to source control unless we use "Open from Source Control", but other projects work regardless. From my investigations, I know some of the things involved: In our .csproj files, there are these settings: * <SccProjectName> * <SccLocalPath> * <SccAuxPath> * <SccProvider> Sometimes they are all set to "SAK", sometimes not. It seems things are more likely to work if these say "SAK". In our .sln file, there are settings for many of the projects: * SccLocalPath# * SccProjectFilePathRelativizedFromConnection# * SccProjectUniqueName# (The # is a number that identifies each project.) SccLocalPath is a path relative to the solution file. Often it is ".", sometimes it is the folder that the project is in, and sometimes it is ".." or "..\..", and it seems to be bad for it to point to a folder above the solution folder. The relativized one is a path *from* that folder to the project file. It will be missing entirely if SccLocalPath points to the project's folder. If the SccLocalPath has ".." in it, this path might include folder names that are not the same between branches, which I think causes problems. So, to finally get to the specifics I'd like to know: * What happens when you do "Change source control" and bind projects? How does Visual Studio decide what to put in the project and solution files? * What happens when you do "Open from source control"? * What's this "connection" folder that SccLocalPath and SccProjectFilePathRelativizedFromConnection refer to? How does Visual Studio/Perforce pick it? * Is there some recommended way to make the source control bindings continue to work even when you create a new branch of the solution? --- *Added June 2012:* I don't use Perforce any more, so I can't vouch for it, but have a look at [KCD's answer](https://stackoverflow.com/a/11148342/2283) below. Apparently there's [a new P4 VS plugin](http://forums.perforce.com/index.php?/topic/1585-new-perforce-plugin-for-visual-studio-20121-beta-available-now/) under development. Hopefully it should clear up all this mess!
Introduction ============ I would disagree with the claim that Perforce integration in Visual Studio is "terrible". Rather, I'd define it as "out of the box experience is less than optimal" :-). The following sections discuss my understanding of the integration and recommendations for project/solution setup. If you're not interested in the details of how the source control integration works you can skip to the end of this answer where I summarize answers to Weeble's question. *Disclaimer*: The following sections are just educated guesses based on my empirical experience, however I've used the technique over many years in many projects (each project having multiple experimental/trunk/maintenance/release branches, sometimes even multiple solution files, without issues). The disadvantage is that you have to *manually* update the project files - but the 2 minute investment is amortized over the lifetime of a project pretty nicely IMHO :-). Solution vs. Project ==================== Visual Studio uses source control binding information from both solution file and each project file during the initial solution loading. This binding information is then stored in **name.suo** file (assuming we're using **name.sln** as solution) - note that **suo** files are marked with **hidden** flag so they won't be visible in file explorer (unless you override the "Hidden files and folders" option). The easiest way to re-bind to source control provider if anything goes wrong is to delete the appropriate **suo** file and reopen solution. After suo file has been created, changes to <Scc\*> elements have no effect. If during the initial solution opening there is a discrepancy between the binding information stored in solution file and information stored in project file, Visual Studio will attempt to fix this (sometimes it will even prompt for your decision to choose whether the information in solution or the information in project should be used as a "master" to resolve the discrepancy): ![alt text](https://i.stack.imgur.com/AUf7n.png) Why is Visual Studio violating DRY (Don't Repeat Yourself) principle? I have no idea. I presume this has historic reasons and is tightly coupled to the needs of that nightmare called Visual Source Safe :-). How to set it up "correctly"? ============================= When adding either new or existing solutions/projects to Perforce, I **always** start by creating a blank solution (see the "Source-controlling a blank solution" section). I then add projects to this blank solution, one after another. The steps differ slightly based on whether the project being added already exists (see the "Source-controlling existing (unbound) projects" and "Source-controlling existing (bound) projects" sections) or I need to create a new one (see the "Source-controlling new projects" section). Source-controlling a blank solution =================================== To add a new blank solution to source control, do the following: 1. Start Visual Studio, "New" -> "Project..." -> "Other project types" -> "Blank solution"; fill in solution name and location, "OK" button 2. "File" -> "Source Control" -> "Add Solution to Source Control..." 3. In the connection dialog enter appropriate P4 server port, client and user (note that view of the selected client must include the location that you picked in step 1) 4. "View" -> "Pending Checkins" -> "Check In" -> in the submit dialog instead of hitting the "Submit" button, use "Cancel". **Reason**: The "Check In" action will create a new file, "name.vssscc", then add both "name.sln" and "name.vssscc" to Perforce's default changelist; by cancelling the submit dialog we will keep the "add" operation pending and will be able to edit the files before submitting to P4 5. Close Visual Studio 6. Open the name.sln file in your favourite editor (notepad, if you're really desperate :-) ) and add two new lines (**SccProjectName0** and **SccProvider0**) - the blank solution file should now have a source control section as follows: ``` GlobalSection(SourceCodeControl) = preSolution SccNumberOfProjects = 1 SccLocalPath0 = . SccProjectName0 = Tutorial SccProvider0 = MSSCCI:Perforce\u0020SCM EndGlobalSection ``` The values should be chosen as follows: * **SccProjectName0**: an arbitrary string that will be displayed in "Change Source Control" dialog as "Server Binding". This name is used to determine what projects/solution files can share the same source control connection. I recommend not using space for this name as escaping rules for spaces are different in solution and project files. * **SccProvider0**: hard-coded value "MSSCCI:Perforce\u0020SCM". 7. Submit the two pending files using the Perforce client of your choice (p4.exe, P4Win, P4V) You can now test the bindings: 1. Make sure Visual Studio is closed 2. Delete \*\*all\* files except the name.sln (especially the name.suo) 3. Open Visual Studio and use it to open name.sln 4. A connection dialog should appear, use appropriate port/client/user and click OK 5. Solution explorer should now display the solution node with a padlock overlay icon: ![Source-controlled blank solution](https://i.stack.imgur.com/KmfTd.png) 6. You can now verify source control status of the solution by using "File" -> "Source Control" -> "Change Source Control...": ![Source control status of blank solution](https://i.stack.imgur.com/DLvQY.png) Note: The column "Server Binding" is showing the value we chose for "SccProjectName0". Source-controlling new projects =============================== If you're creating a brand-new project and would like to immediately start tracking it in a Perforce depot, follow these steps: 1. Open the source-controlled solution in Visual Studio 2. "File" -> "Add" -> "New Project..." - pick the project type you're adding, name and location (location should be a subdirectory of the directory where the solution file is stored) 3. "File" -> "Save All" (this will commit all in-memory changes to solution file and the newly created project file to the disk) 4. Manually edit the project file you just created using an editor of your choice (come on, notepad AGAIN? ;-) ). Add the following property elements into a PropertyGroup (any property group): ``` <PropertyGroup> ... <SccProjectName>Tutorial</SccProjectName> <SccLocalPath>..\..</SccLocalPath> <SccProvider>MSSCCI:Perforce SCM</SccProvider> ... </PropertyGroup> ``` The values should be chosen as follows: * **SccProjectName** - this is the value that is displayed in "Change Source Control" dialog as "Server Binding"; should be the same as the value you used for SccProjectName0 in blank solution; if not the same, solution and this project won't be able to share the same source control provider connection * **SccLocalPath** - relative path to the reference directory (displayed in "Change Source Control" dialog as "Local binding"); because I recommend using the solution directory as the reference directory, this is in effect relative path from directory containing project file to directory containing solution file (my example is storing projects in "(solutionDir)/Source/ProjectName/projectName.csproj", thus the relative path is "two levels up") * **SccProvider** - hard-coded value "MSSCCI:Perforce SCM"; this is used to determine what SCCAPI provider are the Scc\* binding values valid for 5. Switch back to Visual Studio; it should automatically detect that the project file has been updated externally and offer to reload it (if not, unload and reload the project manually) 6. "View" -> "Pending Checkins" 7. "Check In" -> I recommend right-clicking on (solutionName).vssscc file and selecting "Revert if unchanged" (even though Visual Studio opens it for edit, it remains unchanged); provide description and submit the change To verify that the newly added project is bound properly, you can follow these steps: 1. Make sure Visual Studio is closed 2. Delete (solutionName).suo file as well as MSSCCPRJ.SCC (in solution directory) 3. Open Visual Studio and use it to open (solutionName).sln 4. A connection dialog should appear, use appropriate port/client/user and click OK 5. Solution explorer should now display the project node with a padlock overlay icon: ![Source-controlled projects](https://i.stack.imgur.com/vyRH4.png) 6. You can now verify source control status of the solution by using "File" -> "Source Control" -> "Change Source Control...": ![Status of source-controlled projects](https://i.stack.imgur.com/3V33X.png) One thing to note about this status screenshot is that when I selected the solution row, all the remaining rows were "selected" as well (blue highlight). This is because all those entries have the same "Server Binding" + "Local Binding" and thus share the same source-control-provider (P4) connection. Also note that "Relative Path" for both projects has two levels, and are relative to the same "Local Binding" - the directory where solution file resides. Source-controlling existing (unbound) projects ============================================== If you have existing projects that have not yet been used in any other Perforce solution, follow these steps to add them to Perforce (i.e. importing projects that have not been source-controlled before (Internet downloads etc.) or were using a different source control provider (Visual Source Safe, etc.). 1. Copy the project into appropriate location 2. Clean-up existing source control bindings (if any): * Remove existing project-file bindings, i.e. all properties starting with "Scc" * Delete file (projectName).vspscc in the same directory as the project file (if any) 3. Open the source-controlled solution in Visual Studio 4. "File" -> "Add" -> "Existing project..." - browse to the project (the copy you created in step 1) 5. "File" -> "Save All" (this will commit all in-memory changes to solution file) 6. Follow the steps 4-7 from "Source-controlling new projects" (i.e. you will now add "Scc\*" property elements into a **PropertyGroup**) Verification steps are exactly the same as in "Source-controlling new projects" section. Source-controlling existing (bound) projects ============================================ If you have projects that have already been bound to Perforce using the technique discussed here and you want to use them in a different solution (new branch, alternative solution reusing the project, etc) use the following steps: 1. Integrate the project into desired location 2. Open the source-controlled solution in Visual Studio 3. "File" -> "Add" -> "Existing project..." - browse to the project created in step 1 via integration 4. "View" -> "Pending Checkins" -> "Check In" - add description and submit Summary ======= * Source control binding information is stored in both solution and projects, must be in sync (if not, Visual Studio will attempt to fix any discrepancies) * I always treat project files as the primary source of binding information and solution files as throwaway files that can be recreated easily by first source-controlling a blank solution and then adding desired projects * Solution file should always have valid **SccProvider0** and **SccProjectName0** values (have to be added manually with new versions of P4SCC plugins) * Project files should always have valid **SccProjectName** (preferrably same as **SccProjectName0**), **SccLocalPath** and **SccProvider** values (also have to be edited manually as the P4SCC defaults are no good) I'm also including answers to your original questions: > > What happens when you do "Change source control" and bind projects? How does Visual Studio decide what to put in the project and solution files? > > > This updates "Scc\*" elements in a project file you're rebinding; the solution file is then updated as well so that it is in sync with the project file bindings > > What happens when you do "Open from source control"? > > > Allows you to pick solution that you'd like to open. Afterwards all the projects included in the solution are automatically synced to head. I find this feature not very useful in Perforce world where you have to create a client anyway and the chances are you're syncing this client from a P4V/P4Win/P4 instead of relying on Visual Studio. This was kind-of useful in Visual Source Safe world where there was no concept of views and you were defining where a repository goes on checkout time. > > What's this "connection" folder that SccLocalPath and SccProjectFilePathRelativizedFromConnection refer to? How does Visual Studio/Perforce pick it? > > > This is Visual Studio's bookkeeping. It is determined based on bindings in each project file (I guess in theory if a project file loses binding information for some reason, it could be reconstructed from the solution information...) > > Is there some recommended way to make the source control bindings continue to work even when you create a new branch of the solution? > > > I hope the sections above give you some idea of a way that is working very well for me :-).
261,536
<p>I'm getting the following error when my win32 (c#) app is calling web services.</p> <pre><code>The request failed with HTTP status 504: Gateway timeout server response timeout. </code></pre> <p>I understand 'I think' that this is because the upstream request does not get a response in a timely fashion.</p> <p>But my question is this? How do I change the <strong>app.config</strong> settings in my win32 application to allow more time to process its data. I assume I require these changes to be made on my app settings as the webservices and IIS hosting the ws are setup with extended times.</p> <p>Look forward to a response and thank you in advance.</p>
[ { "answer_id": 261562, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 5, "selected": false, "text": "<p>CheckUpDown has <a href=\"http://www.checkupdown.com/status/E504.html\" rel=\"noreferrer\">a nice explanation of the 504 error</a>:</p>\n<blockquote>\n<p>A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.</p>\n<p>This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.</p>\n<p>This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.</p>\n</blockquote>\n" }, { "answer_id": 8494758, "author": "james.garriss", "author_id": 584674, "author_profile": "https://Stackoverflow.com/users/584674", "pm_score": 6, "selected": false, "text": "<p>You can't. The problem is not that your app is impatient and timing out; the problem is that an intermediate proxy is impatient and timing out. \"The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI.\" (<a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5</a>) It most likely indicates that the origin server is having some sort of issue, so it's not responding quickly to the forwarded request.</p>\n\n<p>Possible solutions, none of which are likely to make you happy:</p>\n\n<ul>\n<li>Increase timeout value of the proxy (if it's under your control)</li>\n<li>Make your request to a different server (if there's another server with the same data)</li>\n<li>Make your request differently (if possible) such that you are requesting less data at a time</li>\n<li>Try again once the server is not having issues</li>\n</ul>\n" }, { "answer_id": 35071350, "author": "dynamiclynk", "author_id": 1427166, "author_profile": "https://Stackoverflow.com/users/1427166", "pm_score": 1, "selected": false, "text": "<p>If your using ASP.Net 5 (now known as ASP.Net Core v1) ensure in your project.json \"commands\" section for each site you are hosting that the Kestrel proxy listening port differs between sites, otherwise one site will work but the other will return a 504 gateway timeout.</p>\n\n<pre><code> \"commands\": {\n \"web\": \"Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5090\"\n },\n</code></pre>\n" }, { "answer_id": 36895709, "author": "prashant", "author_id": 1440298, "author_profile": "https://Stackoverflow.com/users/1440298", "pm_score": 1, "selected": false, "text": "<p>One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast. </p>\n" }, { "answer_id": 37295368, "author": "Henrik Wang", "author_id": 6349991, "author_profile": "https://Stackoverflow.com/users/6349991", "pm_score": 2, "selected": false, "text": "<p>Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat). </p>\n\n<p>If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B.\nIt happens.</p>\n\n<p>for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.</p>\n" }, { "answer_id": 49990202, "author": "LarsWA", "author_id": 278170, "author_profile": "https://Stackoverflow.com/users/278170", "pm_score": 0, "selected": false, "text": "<p>I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...</p>\n\n<p>I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. \nOne of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.</p>\n\n<p>In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)</p>\n\n<p>This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server. </p>\n\n<p>After removing the spn and allowing the call to fall back to NTLM, it works fine.</p>\n\n<p>As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26098/" ]
I'm getting the following error when my win32 (c#) app is calling web services. ``` The request failed with HTTP status 504: Gateway timeout server response timeout. ``` I understand 'I think' that this is because the upstream request does not get a response in a timely fashion. But my question is this? How do I change the **app.config** settings in my win32 application to allow more time to process its data. I assume I require these changes to be made on my app settings as the webservices and IIS hosting the ws are setup with extended times. Look forward to a response and thank you in advance.
You can't. The problem is not that your app is impatient and timing out; the problem is that an intermediate proxy is impatient and timing out. "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI." (<http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5>) It most likely indicates that the origin server is having some sort of issue, so it's not responding quickly to the forwarded request. Possible solutions, none of which are likely to make you happy: * Increase timeout value of the proxy (if it's under your control) * Make your request to a different server (if there's another server with the same data) * Make your request differently (if possible) such that you are requesting less data at a time * Try again once the server is not having issues
261,539
<p>I've got a WCF service that uses a LinqToSql DataContext to fetch some information out of a database. The return type of the operation is IEnumerable<code>&lt;DomainObject</code>>, and I have a helper method that converts from the Table-derived LINQ object to a WCF data contract like so:</p> <pre><code>[OperationContract] public IEnumerable&lt;DomainObjectDTO&gt; RetrieveDomainObjects() { var context = CreateDataContext(); return from domainObject in context.DomainObjects select ConvertDomainObject(domainObject); } private DomainObjectDTO ConvertDomainObject(DomainObject obj) { // etc... } </code></pre> <p>This code exhibits a strange behaviour if I pass an invalid connection string to the DataContext. Being unable to find the correct database, presumably the above code throws a SqlException when enumerating the IEnumerable<code>&lt;DomainObjectDTO</code>> when serialization is happening. However, when I run this code in my debugger, I see no first-chance exception on the server side at all! I told the debugger in the Exceptions tab to break on all thrown CLR exceptions, and it simply doesn't. I also don't see the characteristic "First chance exception" message in the Output window.</p> <p>On the client side, I get a CommunicationException with an error message along the lines of "The socket connection terminated unexpectedly". None of the inner exceptions provides any hint as to the underlying cause of the problem.</p> <p>The only way I could figure this out was to rewrite the LINQ code in such a way that the query expression is evaluated inside of the OperationContract method. Incidentally, I get the same result if there is a permissions problem, or if I wrap the DataContext in a using statement, so this is not just isolated to SqlExceptions.</p> <p>Disregarding the inadvisability of making the return type an IEnumerable<code>&lt;T</code>> and only enumerating the query somewhere in the depths of the serializer, is WCF suppressing or somehow preventing exceptions from being thrown in this case? And if so, why?</p>
[ { "answer_id": 261555, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "<p>Did you configure your \"<a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.includeexceptiondetailinfaults.aspx\" rel=\"nofollow noreferrer\">IncludeExceptionDetailInFaults</a>\" settings? (it defaults to 'false' for security purposes).</p>\n" }, { "answer_id": 261556, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>WCF is a curious beast that lives slightly outside of regular IIS; it may be that the standard debugging gets glitchy. However, you could try <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicedebugbehavior.includeexceptiondetailinfaults.aspx\" rel=\"nofollow noreferrer\">enabling debug exceptions</a>, and/or implementing (and configuring) your own <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx\" rel=\"nofollow noreferrer\"><code>IErrorHandler</code></a> to log the issues.</p>\n\n<p>Another option: is there perhaps an iterator block (<code>yield return</code>) somewhere in the mix here? <em>Nothing</em> in an iterator block is evaluated until the enumerator is iterated, which can lead to some odd looking issues with data that should have been validated earlier. In the case above, this isn't an issue (no <code>yield return</code>), but it is one to watch.</p>\n\n<p>For example, the following is <em>very</em> different:</p>\n\n<pre><code>var context = CreateDataContext();\nvar query = from domainObject in context.DomainObjects\n select ConvertDomainObject(domainObject);\nforeach(var item in query) { yield return item; }\n</code></pre>\n" }, { "answer_id": 261587, "author": "Darren", "author_id": 6065, "author_profile": "https://Stackoverflow.com/users/6065", "pm_score": 1, "selected": false, "text": "<p>WCF does seem, at least in my experience, to do some magic with exceptions. I'm really not sure what it does with exceptions but I've found that if the FaultContract attribute is used to specify exceptions that the contract could throw, it'll at least give a bit more information to the client about the why the error occurred.</p>\n\n<p>We would also catch any exceptions and re throw them as FaultExceptions, something like:</p>\n\n<pre><code>try\n{\n DoSomething();\n}\ncatch ( Exception ex )\n{ \n throw new FaultException&lt;CustomException&gt;( new CustomException( ex ), ex.Message );\n}\n</code></pre>\n\n<p>Where custom exception is specified in the fault contract. This seems to give a bit more information to the client about the exception. So I suspect if you add SQLException as part of the FaultContract then it'll get sent to the client.</p>\n" }, { "answer_id": 262335, "author": "kelsmj", "author_id": 17001, "author_profile": "https://Stackoverflow.com/users/17001", "pm_score": 0, "selected": false, "text": "<p>Try putting the following in the App.config for your client and service:</p>\n\n<pre><code>&lt;system.diagnostics&gt;\n&lt;sources&gt;\n &lt;source name=\"System.ServiceModel\" switchValue=\"Verbose,ActivityTracing\"\n propagateActivity=\"true\"&gt;\n &lt;listeners&gt;\n &lt;add type=\"System.Diagnostics.DefaultTraceListener\" name=\"Default\"&gt;\n &lt;filter type=\"\" /&gt;\n &lt;/add&gt;\n &lt;add name=\"NewListener\"&gt;\n &lt;filter type=\"\" /&gt;\n &lt;/add&gt;\n &lt;/listeners&gt;\n &lt;/source&gt;\n&lt;/sources&gt;\n&lt;sharedListeners&gt;\n &lt;add initializeData=\"C:\\App_tracelog.svclog\"\n type=\"System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\n name=\"NewListener\" traceOutputOptions=\"LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack\"&gt;\n &lt;filter type=\"\" /&gt;\n &lt;/add&gt;\n&lt;/sharedListeners&gt;\n</code></pre>\n\n<p>\nThen load both the resulting log files in the Service Trace Viewer that comes with the Windows SDK. You will be able to see the actual exception thrown that way.</p>\n\n<p>Links: <a href=\"http://msdn.microsoft.com/en-us/library/aa751795.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa751795.aspx</a> </p>\n" }, { "answer_id": 4799428, "author": "Tim Lovell-Smith", "author_id": 234288, "author_profile": "https://Stackoverflow.com/users/234288", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>is WCF suppressing or somehow preventing exceptions from being thrown in this case? And if so, why?</p>\n</blockquote>\n\n<p>I don't know much about WCF but it doesn't sound very likely to me.</p>\n\n<p>The special thing about first-chance exception is that it goes directly to the debugger and the debugger gets the chance to see it <em>before</em> the exception is actually raised - hence the words 'first chance' - the debugger has the 'first chance' to handle the exception. How could anything bypass it? It would have to be some way of stopping the exception being raised completely. (Is there security or reliability features in CLR that can do this?).</p>\n\n<p>The best alternative explanation I can propose is that something goes wrong in advance of the point where you expect the SqlException to be thrown. I would try also looking at unmanaged exceptions, not just managed exceptions, in case it is a case of e.g. something goes wrong in unmanaged serialization code trying to use the managed IEnumerable, or some CLR bug...</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32539/" ]
I've got a WCF service that uses a LinqToSql DataContext to fetch some information out of a database. The return type of the operation is IEnumerable`<DomainObject`>, and I have a helper method that converts from the Table-derived LINQ object to a WCF data contract like so: ``` [OperationContract] public IEnumerable<DomainObjectDTO> RetrieveDomainObjects() { var context = CreateDataContext(); return from domainObject in context.DomainObjects select ConvertDomainObject(domainObject); } private DomainObjectDTO ConvertDomainObject(DomainObject obj) { // etc... } ``` This code exhibits a strange behaviour if I pass an invalid connection string to the DataContext. Being unable to find the correct database, presumably the above code throws a SqlException when enumerating the IEnumerable`<DomainObjectDTO`> when serialization is happening. However, when I run this code in my debugger, I see no first-chance exception on the server side at all! I told the debugger in the Exceptions tab to break on all thrown CLR exceptions, and it simply doesn't. I also don't see the characteristic "First chance exception" message in the Output window. On the client side, I get a CommunicationException with an error message along the lines of "The socket connection terminated unexpectedly". None of the inner exceptions provides any hint as to the underlying cause of the problem. The only way I could figure this out was to rewrite the LINQ code in such a way that the query expression is evaluated inside of the OperationContract method. Incidentally, I get the same result if there is a permissions problem, or if I wrap the DataContext in a using statement, so this is not just isolated to SqlExceptions. Disregarding the inadvisability of making the return type an IEnumerable`<T`> and only enumerating the query somewhere in the depths of the serializer, is WCF suppressing or somehow preventing exceptions from being thrown in this case? And if so, why?
WCF does seem, at least in my experience, to do some magic with exceptions. I'm really not sure what it does with exceptions but I've found that if the FaultContract attribute is used to specify exceptions that the contract could throw, it'll at least give a bit more information to the client about the why the error occurred. We would also catch any exceptions and re throw them as FaultExceptions, something like: ``` try { DoSomething(); } catch ( Exception ex ) { throw new FaultException<CustomException>( new CustomException( ex ), ex.Message ); } ``` Where custom exception is specified in the fault contract. This seems to give a bit more information to the client about the exception. So I suspect if you add SQLException as part of the FaultContract then it'll get sent to the client.
261,543
<p>Is there a way to drop a validation that was set in Rails plugin (or included module)? Let's say I have some model with module included in it:</p> <pre><code>class User &lt; ActiveRecord::Base include SomeModuleWithValidations # How to cancel validates_presence_of :something here? end module SomeModuleWithValidations def self.included(base) base.class_eval do validates_presence_of :something end end end </code></pre> <p>My only idea so far was to do something like:</p> <pre><code>validates_presence_of :something, :if =&gt; Proc.new{1==2} </code></pre> <p>which would work, I think, but it isn't particulary pretty.</p>
[ { "answer_id": 261713, "author": "Kristian", "author_id": 23246, "author_profile": "https://Stackoverflow.com/users/23246", "pm_score": 1, "selected": false, "text": "<p>You could overload the validates_precense_of in the class. Something like:</p>\n\n<pre><code>def self.validates_presence_of(*args)\n return if args.first == :foo\n super\nend\n</code></pre>\n\n<p>Or if you have validates_presence_of :foo you could do:</p>\n\n<pre><code>def foo\n self[:foo] || \"\"\nend\n</code></pre>\n\n<p>However, none of those solutions are very nice. It would most likely be easier to just uncomment it in the module, or redefine it to no-op in just that module.</p>\n" }, { "answer_id": 1537048, "author": "Milan Novota", "author_id": 26123, "author_profile": "https://Stackoverflow.com/users/26123", "pm_score": 1, "selected": true, "text": "<p>See <a href=\"http://casperfabricius.com/site/2008/12/06/removing-rails-validations-with-metaprogramming/\" rel=\"nofollow noreferrer\">http://casperfabricius.com/site/2008/12/06/removing-rails-validations-with-metaprogramming/</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26123/" ]
Is there a way to drop a validation that was set in Rails plugin (or included module)? Let's say I have some model with module included in it: ``` class User < ActiveRecord::Base include SomeModuleWithValidations # How to cancel validates_presence_of :something here? end module SomeModuleWithValidations def self.included(base) base.class_eval do validates_presence_of :something end end end ``` My only idea so far was to do something like: ``` validates_presence_of :something, :if => Proc.new{1==2} ``` which would work, I think, but it isn't particulary pretty.
See <http://casperfabricius.com/site/2008/12/06/removing-rails-validations-with-metaprogramming/>
261,547
<p>This query is related to <a href="https://stackoverflow.com/questions/259850/javascript-multiple-client-side-validations-on-same-event">this</a> one I asked yesterday. I have a radio button list on my asp.net page defined as follows: </p> <pre><code>&lt;asp:RadioButtonList ID="rdlSortBy" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" AutoPostBack="True" &gt; &lt;asp:ListItem Selected="True"&gt;Name&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;Staff No&lt;/asp:ListItem&gt; &lt;/asp:RadioButtonList&gt; </code></pre> <p>On the client-side, am doing the following validations:</p> <pre><code>rdlSortBy.Attributes("onclick") = "javascript:return prepareSave() &amp;&amp; prepareSearch();" </code></pre> <p>The problem is that the Javascript validation runs as expected. A message is displayed and I expect to remain on the page until user has saved the changes, instead the page is posted back and effectively I am loosing unsaved changes.</p> <p>What could be going wrong?</p>
[ { "answer_id": 261632, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 1, "selected": false, "text": "<p>The <code>OnClick</code> code you are using to \"validate\" is being run and then the code which posts the form back which the control itself injects is being run.</p>\n\n<p>You need to intercept that PostBack process and stop it before it posts the form client-side. The best way to do this would be with a <code>CustomValidator</code> and specifically the \"ClientValidationFunction\" property. This will allow your JavaScript to signal that the post back should not occur due to a validation error.</p>\n" }, { "answer_id": 271713, "author": "Julius A", "author_id": 13370, "author_profile": "https://Stackoverflow.com/users/13370", "pm_score": 3, "selected": true, "text": "<p>I fixed this, the problem was that I was attaching the \"onclick\" of the RadioButtonList instead on the individual radio buttons.</p>\n\n<p>This is the fix:</p>\n\n<pre><code>rdlSortBy.Items(0).Attributes(\"onclick\") = \"javascript:return isDirtied() &amp;&amp; prepareSearch();\"\n rdlSortBy.Items(1).Attributes(\"onclick\") = \"javascript:return isDirtied() &amp;&amp; prepareSearch();\"\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13370/" ]
This query is related to [this](https://stackoverflow.com/questions/259850/javascript-multiple-client-side-validations-on-same-event) one I asked yesterday. I have a radio button list on my asp.net page defined as follows: ``` <asp:RadioButtonList ID="rdlSortBy" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" AutoPostBack="True" > <asp:ListItem Selected="True">Name</asp:ListItem> <asp:ListItem>Staff No</asp:ListItem> </asp:RadioButtonList> ``` On the client-side, am doing the following validations: ``` rdlSortBy.Attributes("onclick") = "javascript:return prepareSave() && prepareSearch();" ``` The problem is that the Javascript validation runs as expected. A message is displayed and I expect to remain on the page until user has saved the changes, instead the page is posted back and effectively I am loosing unsaved changes. What could be going wrong?
I fixed this, the problem was that I was attaching the "onclick" of the RadioButtonList instead on the individual radio buttons. This is the fix: ``` rdlSortBy.Items(0).Attributes("onclick") = "javascript:return isDirtied() && prepareSearch();" rdlSortBy.Items(1).Attributes("onclick") = "javascript:return isDirtied() && prepareSearch();" ```
261,559
<p>I was wondering how to make a toolbar in MFC that used 24bit or 256 colour bitmaps rather than the horrible 16 colour ones.</p> <p>Can anyone point me in the direction of some simple code?</p> <p>Thanks</p>
[ { "answer_id": 261589, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 5, "selected": true, "text": "<p>The reason this happens is that the MFC CToolbar class uses an image list internally that is initialised to use 16 colours only. The solution is to create our own image list and tell the toolbar to use that instead. I know this will work for 256-colours, but I haven't tested it with higher bit-depths:</p>\n\n<p>First, load a 256-colour bitmap from a resource:</p>\n\n<pre><code>HBITMAP hBitmap = (HBITMAP) ::LoadImage(AfxGetInstanceHandle(),\n MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_BITMAP,\n 0,0, LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS);\nCBitmap bm;\nbm.Attach(hBitmap);\n</code></pre>\n\n<p>Next, create a 256-colour image list and add our bitmap to it:</p>\n\n<pre><code>CImageList m_imagelist.Create(20, 20, ILC_COLOR8, 4, 4);\nm_imagelist.Add(&amp;bm, (CBitmap*) NULL);\n</code></pre>\n\n<p>Finally, we need to tell the toolbar to use the new image list:</p>\n\n<pre><code>m_toolbar.GetToolBarCtrl().SetImageList(&amp;m_imagelist);\n</code></pre>\n\n<p>It's also possible that the new MFC version in VS2008 may have solved this problem as I know that many of the UI elements have been updated. I haven't actually tried using it yet so I can't be certain.</p>\n" }, { "answer_id": 1640564, "author": "Victor", "author_id": 198494, "author_profile": "https://Stackoverflow.com/users/198494", "pm_score": 0, "selected": false, "text": "<p>The solution worked Flawless, you only need to fix it a little:</p>\n\n<pre><code>CImageList m_imagelist;\nm_imagelist.Create(20, 20, ILC_COLOR8, 4, 4); \nm_imagelist.Add(&amp;bm, (CBitmap*) NULL); \n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
I was wondering how to make a toolbar in MFC that used 24bit or 256 colour bitmaps rather than the horrible 16 colour ones. Can anyone point me in the direction of some simple code? Thanks
The reason this happens is that the MFC CToolbar class uses an image list internally that is initialised to use 16 colours only. The solution is to create our own image list and tell the toolbar to use that instead. I know this will work for 256-colours, but I haven't tested it with higher bit-depths: First, load a 256-colour bitmap from a resource: ``` HBITMAP hBitmap = (HBITMAP) ::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_BITMAP, 0,0, LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS); CBitmap bm; bm.Attach(hBitmap); ``` Next, create a 256-colour image list and add our bitmap to it: ``` CImageList m_imagelist.Create(20, 20, ILC_COLOR8, 4, 4); m_imagelist.Add(&bm, (CBitmap*) NULL); ``` Finally, we need to tell the toolbar to use the new image list: ``` m_toolbar.GetToolBarCtrl().SetImageList(&m_imagelist); ``` It's also possible that the new MFC version in VS2008 may have solved this problem as I know that many of the UI elements have been updated. I haven't actually tried using it yet so I can't be certain.
261,572
<p>I am building a FAQ module for my site and I want to be able to control single elements on the page even though they all have the same class. I believe this comes under siblings which I am not yet familiar with.</p> <p>Basically I want the user to be able to click the question div and then when they click it the answer div within the same div as the question div is set to show (if that makes sense!). Any help would be greatly appreciated.</p> <pre><code>&lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; &lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; &lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 261596, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 3, "selected": true, "text": "<p>If I understand your question correctly, you should \nStart by setting all answers as hidden in the css:\n.answer {display:none;}</p>\n\n<p>Then you can use jquery to show the correct answer to the clicked questions : </p>\n\n<pre><code>$(document).ready ( function () {\n $('.question').click(function() {\n $(this).next('.answer').show();\n });\n});\n</code></pre>\n\n<p>Edit: you can also use .toggle() instead of .show() to show/hide.</p>\n" }, { "answer_id": 261597, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 0, "selected": false, "text": "<p>You should probably check out this <a href=\"https://stackoverflow.com/questions/233936/jquery-swapping-elements\">question</a> where something similar is done.</p>\n\n<p>Basically, you first need to setup ID's for your elements so that you can identify single elements within the set classes.</p>\n\n<p>You could then add a click event handler which would set the selected item and show the appropriate answer.</p>\n\n<p>You can see the syntax for grabbing siblings in the <a href=\"http://docs.jquery.com/Traversing/siblings\" rel=\"nofollow noreferrer\">documentation here</a>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
I am building a FAQ module for my site and I want to be able to control single elements on the page even though they all have the same class. I believe this comes under siblings which I am not yet familiar with. Basically I want the user to be able to click the question div and then when they click it the answer div within the same div as the question div is set to show (if that makes sense!). Any help would be greatly appreciated. ``` <div class="set"> <div class="question">What is the airspeed velocity of an unladen swallow?</div> <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div> </div> <div class="set"> <div class="question">What is the airspeed velocity of an unladen swallow?</div> <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div> </div> <div class="set"> <div class="question">What is the airspeed velocity of an unladen swallow?</div> <div class="answer">Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. </div> </div> ```
If I understand your question correctly, you should Start by setting all answers as hidden in the css: .answer {display:none;} Then you can use jquery to show the correct answer to the clicked questions : ``` $(document).ready ( function () { $('.question').click(function() { $(this).next('.answer').show(); }); }); ``` Edit: you can also use .toggle() instead of .show() to show/hide.
261,580
<p>This declaration causes an overflow in VBA:</p> <pre><code>Const OVERFLOWS As Long = 10 * 60 * 60 </code></pre> <p>whereas setting the value directly is fine:</p> <pre><code>Const COMPILES_OK As Long = 36000 </code></pre> <p>How do you persuade VBA to treat literal integers as longs?</p> <p>Thanks</p>
[ { "answer_id": 261615, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 5, "selected": true, "text": "<p>Add the <code>long</code> suffix <code>&amp;</code> to at least one number:</p>\n\n<pre><code>Const OVERFLOWS As Long = 10&amp; * 60 * 60\n</code></pre>\n\n<p>Note that using the <code>CLNG</code> function to convert the values to <code>long</code> will not work, because VBA does not allow assigning the return value of a function to a constant.</p>\n" }, { "answer_id": 261627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The type character can also be appended to literals : Const OVERFLOWS As Long = (10&amp; * 60 * 60)\n(one is suffucient actually because of the way the VBA engine evaluates the expression).</p>\n" }, { "answer_id": 261652, "author": "mjwills", "author_id": 34092, "author_profile": "https://Stackoverflow.com/users/34092", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://support.microsoft.com/kb/191713\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/191713</a> is a nice summary of the type declaration characters available in VBA / VB4-6.</p>\n" }, { "answer_id": 261680, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 2, "selected": false, "text": "<p>For those who find the &amp; symbol a bit esoteric, an alternative is to use the CLNG function which converts a number to long</p>\n\n<pre><code>Const OVERFLOWS As Long = CLNG(10) * 60 * 60\n</code></pre>\n\n<p>you could then do a similar thing for a Single constant</p>\n\n<pre><code>Const OVERFLOWS As Single = CSNG(10) * 60 * 60\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1518/" ]
This declaration causes an overflow in VBA: ``` Const OVERFLOWS As Long = 10 * 60 * 60 ``` whereas setting the value directly is fine: ``` Const COMPILES_OK As Long = 36000 ``` How do you persuade VBA to treat literal integers as longs? Thanks
Add the `long` suffix `&` to at least one number: ``` Const OVERFLOWS As Long = 10& * 60 * 60 ``` Note that using the `CLNG` function to convert the values to `long` will not work, because VBA does not allow assigning the return value of a function to a constant.
261,599
<p>This code always works, even in different browsers:</p> <pre><code>function fooCheck() { alert(internalFoo()); // We are using internalFoo() here... return internalFoo(); // And here, even though it has not been defined... function internalFoo() { return true; } //...until here! } fooCheck(); </code></pre> <p>I could not find a single reference to why it should work, though. I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.</p> <p>Could someone please enlighten me?</p>
[ { "answer_id": 261605, "author": "RailsSon", "author_id": 30786, "author_profile": "https://Stackoverflow.com/users/30786", "pm_score": 2, "selected": false, "text": "<p>I have only used JavaScript a little. I am not sure if this will help, but it looks very similar to what you are talking about and may give some insight:</p>\n\n<p><a href=\"http://www.dustindiaz.com/javascript-function-declaration-ambiguity/\" rel=\"nofollow noreferrer\">http://www.dustindiaz.com/javascript-function-declaration-ambiguity/</a></p>\n" }, { "answer_id": 261613, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 3, "selected": false, "text": "<p>Some languages have the requirement that identifiers have to be defined before use. A reason for this is that the compiler uses a single pass on the sourcecode. </p>\n\n<p>But if there are multiple passes (or some checks are postponed) you can perfectly live without that requirement.\nIn this case, the code is probably first read (and interpreted) and then the links are set. </p>\n" }, { "answer_id": 261626, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 1, "selected": false, "text": "<p>The body of the function \"internalFoo\" needs to go somewhere at parsing time, so when the code is read (a.k.a parsing) by the JS interpreter, the data structure for the function is created and the name is assigned.</p>\n\n<p>Only later, then the code is run, JavaScript actually tries to find out if \"internalFoo\" exists and what it is and whether it can be called, etc.</p>\n" }, { "answer_id": 261640, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 4, "selected": false, "text": "<p>The browser reads your HTML from beginning to end and can execute it as it is read and parsed into executable chunks (variable declarations, function definitions, etc.) But at any point can only use what's been defined in the script before that point.</p>\n\n<p>This is different from other programming contexts that process (compile) all your source code, perhaps link it together with any libraries you need to resolve references, and construct an executable module, at which point execution begins.</p>\n\n<p>Your code can refer to named objects (variables, other functions, etc.) that are defined further along, but you can't execute referring code until all the pieces are available.</p>\n\n<p>As you become familiar with JavaScript, you will become intimately aware of your need to write things in the proper sequence.</p>\n\n<p>Revision: To confirm the accepted answer (above), use Firebug to step though the script section of a web page. You'll see it skip from function to function, visiting only the first line, before it actually executes any code.</p>\n" }, { "answer_id": 261682, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 9, "selected": true, "text": "<p>The <code>function</code> declaration is magic and causes its identifier to be bound before anything in its code-block* is executed.</p>\n\n<p>This differs from an assignment with a <code>function</code> expression, which is evaluated in normal top-down order.</p>\n\n<p>If you changed the example to say:</p>\n\n<pre><code>var internalFoo = function() { return true; };\n</code></pre>\n\n<p>it would stop working.</p>\n\n<p>The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.</p>\n\n<p>This is documented in the <a href=\"https://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">ECMAScript standard</a>, section <strong>10.1.3</strong>. Unfortunately ECMA-262 is not a very readable document even by standards-standards!</p>\n\n<p>*: the containing function, block, module or script.</p>\n" }, { "answer_id": 262643, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": -1, "selected": false, "text": "<p>For the same reason the following will always put <code>foo</code> in the global namespace:</p>\n\n<pre><code>if (test condition) {\n var foo;\n}\n</code></pre>\n" }, { "answer_id": 42266568, "author": "Negin", "author_id": 5611484, "author_profile": "https://Stackoverflow.com/users/5611484", "pm_score": 6, "selected": false, "text": "<p>It is called HOISTING - Invoking (calling) a function before it has been defined.</p>\n\n<p>Two different types of function that I want to write about are:</p>\n\n<p>Expression Functions &amp; Declaration Functions</p>\n\n<ol>\n<li><p>Expression Functions:</p>\n\n<p>Function expressions can be stored in a variable so they do not need function names. They will also be named as an anonymous function (a function without a name).</p>\n\n<p>To invoke (call) these functions they always need a <strong><em>variable name</em></strong>. This kind of function won't work if it is called before it has been defined which means Hoisting is not happening here. We must always define the expression function first and then invoke it.</p>\n\n<pre><code>let lastName = function (family) {\n console.log(\"My last name is \" + family);\n};\nlet x = lastName(\"Lopez\");\n</code></pre>\n\n<p>This is how you can write it in ECMAScript&nbsp;6:</p>\n\n<pre><code>lastName = (family) =&gt; console.log(\"My last name is \" + family);\n\nx = lastName(\"Lopez\");\n</code></pre></li>\n<li><p>Declaration Functions:</p>\n\n<p>Functions declared with the following syntax are not executed immediately. They are \"saved for later use\" and will be executed later, when they are invoked (called upon). This type of function works if you call it BEFORE or AFTER where is has been defined. If you call a declaration function before it has been defined Hoisting works properly.</p>\n\n<pre><code>function Name(name) {\n console.log(\"My cat's name is \" + name);\n}\nName(\"Chloe\");\n</code></pre>\n\n<p>Hoisting example:</p>\n\n<pre><code>Name(\"Chloe\");\nfunction Name(name) {\n console.log(\"My cat's name is \" + name);\n}\n</code></pre></li>\n</ol>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21648/" ]
This code always works, even in different browsers: ``` function fooCheck() { alert(internalFoo()); // We are using internalFoo() here... return internalFoo(); // And here, even though it has not been defined... function internalFoo() { return true; } //...until here! } fooCheck(); ``` I could not find a single reference to why it should work, though. I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter. Could someone please enlighten me?
The `function` declaration is magic and causes its identifier to be bound before anything in its code-block\* is executed. This differs from an assignment with a `function` expression, which is evaluated in normal top-down order. If you changed the example to say: ``` var internalFoo = function() { return true; }; ``` it would stop working. The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases. This is documented in the [ECMAScript standard](https://www.ecma-international.org/publications/standards/Ecma-262.htm), section **10.1.3**. Unfortunately ECMA-262 is not a very readable document even by standards-standards! \*: the containing function, block, module or script.
261,622
<p>Is it possible to replace the standard broken image via CSS or using another technique? All my images are the same size and my have transparency.</p> <p>I've tried to wrap all images with a div's background:</p> <pre><code>&lt;div class="no_broken"&gt; &lt;img src="http://www.web.com/found.gif"/&gt; &lt;/div&gt; &lt;div class="no_broken"&gt; &lt;img src="http://www.web.com/notfound.gif"/&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>div.no_broken { background-image: url(standard.gif); } div.no_broken, div.no_broken img { width: 32px; height: 32px; display: block; } </code></pre> <p>But this will display two images on top of each other if the IMG is transparent.</p>
[ { "answer_id": 261635, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 0, "selected": false, "text": "<p>As far as I know, there is no CSS property that controls the display of broken images. Maybe there are browser-specific properties? You may have to resort to Javascript to iterate the images on the page, and replace their src if they are broken.</p>\n" }, { "answer_id": 261641, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 1, "selected": false, "text": "<p>I don't what technology you are using but in ASP.net there is something called control adapters.</p>\n\n<p>I have used this to capture the PreRender of all images and replace the imageurl if the imageurl is not complete.</p>\n\n<p>I don't know if this relates at all to your situation and certainly will not work when there is a path but not image at the path.</p>\n" }, { "answer_id": 261651, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 7, "selected": true, "text": "<p>This works without CSS:</p>\n\n<pre><code>&lt;img src=\"some.jpg\" onerror=\"this.src='alternative.jpg';\"&gt;\n</code></pre>\n\n<p>It seems to even work when Javascript is disabled.</p>\n" }, { "answer_id": 22946052, "author": "broox", "author_id": 446604, "author_profile": "https://Stackoverflow.com/users/446604", "pm_score": 3, "selected": false, "text": "<p>If you'd like to add some javascript into the mix, this should work well with jQuery to detect image errors and add some sort of error state CSS class to the broken images.</p>\n\n<pre><code>$(document).ready(function () {\n $('.no_broken img').error(function () {\n $(this).addClass('broken');\n });\n});\n</code></pre>\n\n<p>And then in your CSS you could have something like</p>\n\n<pre><code>div.no_broken, div.no_broken img { \n width: 32px; \n height: 32px; \n display: block; \n}\n\ndiv.no_broken img.broken {\n background-image: url(standard.gif);\n content:\"\";\n}\n</code></pre>\n" }, { "answer_id": 31027662, "author": "Dave Sumter", "author_id": 706866, "author_profile": "https://Stackoverflow.com/users/706866", "pm_score": 2, "selected": false, "text": "<p>Thought I'd package the comment from <strong>kmoser</strong> into an answer. Clearing the onerror handler is a good idea as loops are possible.</p>\n\n<p>Javascript</p>\n\n<pre><code>function epic(c) {\n c.onerror='';\n c.src='alternative.jpg';\n};\n</code></pre>\n\n<p>HTML</p>\n\n<pre><code>&lt;img src='some.jpg' onerror='epic(this)'&gt;\n</code></pre>\n\n<p>We drop this epic function into all our image tags now on <a href=\"http://twiends.com\" rel=\"nofollow\">twiends</a>, as we pull in loads of social profile images that all expire at some point in the future.</p>\n" }, { "answer_id": 52968407, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "<p>Yes, you can replace an image with CSS, using a trick of pseudo selectors.</p>\n\n<p>Basically, <code>::before</code> and <code>::after</code> only apply when the image fails to load. You can use absolute positioning to place the CSS pseudo element over the broken image placeholder:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {\r\n position: relative;\r\n width: 200px;\r\n height: 200px;\r\n display: inline-block;\r\n vertical-align: text-bottom;\r\n}\r\n\r\n img::before {\r\n content: 'fall back';\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n bottom: 0;\r\n right: 0;\r\n line-height: 200px;\r\n background-color: #fd0;\r\n color: currentColor;\r\n text-align: center;\r\n border-radius: 2px;\r\n display: block;\r\n width: 200px;\r\n height: 200px;\r\n overflow: hidden;\r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;img src=\"not-found\"&gt;\r\n&lt;img src=\"https://via.placeholder.com/200\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This snippet works with no JS at all, but only works in newer browsers.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28150/" ]
Is it possible to replace the standard broken image via CSS or using another technique? All my images are the same size and my have transparency. I've tried to wrap all images with a div's background: ``` <div class="no_broken"> <img src="http://www.web.com/found.gif"/> </div> <div class="no_broken"> <img src="http://www.web.com/notfound.gif"/> </div> ``` CSS: ``` div.no_broken { background-image: url(standard.gif); } div.no_broken, div.no_broken img { width: 32px; height: 32px; display: block; } ``` But this will display two images on top of each other if the IMG is transparent.
This works without CSS: ``` <img src="some.jpg" onerror="this.src='alternative.jpg';"> ``` It seems to even work when Javascript is disabled.
261,655
<p>I have a list of tuples like this:</p> <pre><code>[ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] </code></pre> <p>I want to iterate through this keying by the first item, so, for example, I could print something like this:</p> <pre><code>a 1 2 3 b 1 2 c 1 </code></pre> <p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...</p>
[ { "answer_id": 261665, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 7, "selected": true, "text": "<pre><code>l = [\n('a', 1),\n('a', 2),\n('a', 3),\n('b', 1),\n('b', 2),\n('c', 1),\n]\n\nd = {}\nfor x, y in l:\n d.setdefault(x, []).append(y)\nprint d\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}\n</code></pre>\n" }, { "answer_id": 261677, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 5, "selected": false, "text": "<p>Slightly simpler...</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\n\nfq = defaultdict(list)\nfor n, v in myList:\n fq[n].append(v)\n \nprint(fq) # defaultdict(&lt;type 'list'&gt;, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})\n</code></pre>\n" }, { "answer_id": 261766, "author": "user7461", "author_id": 7461, "author_profile": "https://Stackoverflow.com/users/7461", "pm_score": 4, "selected": false, "text": "<p>A solution using groupby</p>\n<pre><code>from itertools import groupby\nl = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),]\n[(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])]\n</code></pre>\n<p>Output:</p>\n<pre><code>[('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])]\n</code></pre>\n<p><code>groupby(l, lambda x:x[0])</code> gives you an iterator that contains</p>\n<pre><code>['a', [('a', 1), ...], c, [('c', 1)], ...]\n</code></pre>\n" }, { "answer_id": 262530, "author": "lacker", "author_id": 2652, "author_profile": "https://Stackoverflow.com/users/2652", "pm_score": 2, "selected": false, "text": "<p>I would just do the basic</p>\n\n<pre>\nanswer = {}\nfor key, value in list_of_tuples:\n if key in answer:\n answer[key].append(value)\n else:\n answer[key] = [value]\n</pre>\n\n<p>If it's this short, why use anything complicated. Of course if you don't mind using setdefault that's okay too.</p>\n" }, { "answer_id": 1694768, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "<h3>Print list of tuples grouping by the first item</h3>\n\n<p>This answer is based on <a href=\"https://stackoverflow.com/questions/261655/converting-a-list-of-tuples-into-a-dict-in-python/261766#261766\">the @gommen one</a>.</p>\n\n<pre><code>#!/usr/bin/env python\n\nfrom itertools import groupby\nfrom operator import itemgetter\n\nL = [\n('a', 1),\n('a', 2),\n('a', 3),\n('b', 1),\n('b', 2),\n('c', 1),\n]\n\nkey = itemgetter(0)\nL.sort(key=key) #NOTE: use `L.sort()` if you'd like second items to be sorted too\nfor k, group in groupby(L, key=key):\n print k, ' '.join(str(item[1]) for item in group)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>a 1 2 3\nb 1 2\nc 1\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
I have a list of tuples like this: ``` [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] ``` I want to iterate through this keying by the first item, so, for example, I could print something like this: ``` a 1 2 3 b 1 2 c 1 ``` How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...
``` l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] d = {} for x, y in l: d.setdefault(x, []).append(y) print d ``` produces: ``` {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]} ```
261,660
<p>I have a <code>TreeView</code> windows forms control with an <code>ImageList</code>, and I want some of the nodes to display images, but the others to not have images.</p> <p>I <em>don't</em> want a blank space where the image should be. I <em>don't</em> want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?</p>
[ { "answer_id": 262396, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 4, "selected": true, "text": "<p>I tried this once and I don't think it is possible.</p>\n\n<p>If you try to set both <code>ImageKey</code> and <code>ImageIndex</code> to \"not set\" values the control just defaults <code>ImageIndex</code> to 0. The following code:</p>\n\n<pre><code>treeView.ImageKey = \"Value\";\nDebug.WriteLine(treeView.ImageIndex);\ntreeView.ImageKey = null;\nDebug.WriteLine(treeView.ImageIndex);\ntreeView.ImageIndex = -1;\nDebug.WriteLine(treeView.ImageIndex);\n</code></pre>\n\n<p>Produces output:</p>\n\n<pre><code>-1\n0\n0\n</code></pre>\n\n<p>This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.</p>\n" }, { "answer_id": 1009477, "author": "John Fischer", "author_id": 99573, "author_profile": "https://Stackoverflow.com/users/99573", "pm_score": 4, "selected": false, "text": "<p>You need to set <code>ImageIndex</code> and <code>SelectedImageIndex</code> to a number that is higher than the number of values in your <code>ImageList</code>. For example, if you create this node and add it to your <code>TreeView</code>:</p>\n\n<pre><code>TreeNode node1 = new TreeNode(string.Empty, 12, 12); // imageList1.Count = 5\n</code></pre>\n\n<p>you will have an invisible <code>TreeNode</code> inserted into your <code>TreeView</code>. I changed the background color of my <code>TreeView</code> and it was still invisible.</p>\n\n<p>(I googled this for some time, and I eventually found the answer here: <a href=\"http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html</a>)</p>\n" }, { "answer_id": 14668991, "author": "user1887120", "author_id": 1887120, "author_profile": "https://Stackoverflow.com/users/1887120", "pm_score": 2, "selected": false, "text": "<p><strong>This will draw the <code>TreeNode</code> text where the image should have been, getting rid of the white space.</strong></p>\n\n<p>You'll need to set the <code>TreeView</code>'s <code>DrawMode</code> property to <code>OwnerDrawText</code>. You can find the <code>DrawMode</code> property in the properties panel.</p>\n\n<p>Next when you add a node, set it's <code>ImageIndex</code> and <code>SelectedImageIndex</code> greater than the value of your <code>yourImageListName.Images.Count</code> value. This is so no image will be drawn, but there will still be that white space you don't want.</p>\n\n<p>Now to get rid the white space. Add a handle for the treeviews <code>DrawNode</code> event. This can be done by going to the treeviews property panel and clicking the Icon in the panel that looks like a lighting bolt, then scroll till you see the text <code>DrawNode</code>, double click it.</p>\n\n<p>Now you just copy and paste this into the created method</p>\n\n<pre><code>if (e.Node.ImageIndex &gt;= e.Node.TreeView.ImageList.Images.Count) // if there is no image\n{\n int imagewidths = e.Node.TreeView.ImageList.ImageSize.Width;\n int textheight = TextRenderer.MeasureText(e.Node.Text, e.Node.NodeFont).Height;\n int x = e.Node.Bounds.Left - 3 - imagewidths / 2;\n int y = (e.Bounds.Top + e.Bounds.Bottom) / 2+1;\n\n Point point = new Point(x - imagewidths/2, y - textheight/2); // the new location for the text to be drawn\n\n TextRenderer.DrawText(e.Graphics, e.Node.Text, e.Node.NodeFont, point, e.Node.ForeColor);\n}\nelse // drawn at the default location\n TextRenderer.DrawText(e.Graphics, e.Node.Text, e.Node.TreeView.Font, e.Bounds, e.Node.ForeColor);\n</code></pre>\n" }, { "answer_id": 20616195, "author": "MtnManChris", "author_id": 2133578, "author_profile": "https://Stackoverflow.com/users/2133578", "pm_score": 4, "selected": false, "text": "<p>What I have chosen to do is to use an image of dots for those <code>TreeView</code> nodes that are not supposed to have an image.</p>\n\n<p><img src=\"https://i.stack.imgur.com/5UT6j.png\" alt=\"TreeNode with image dots\"></p>\n\n<p>I add this image as the last image in the list, and if the item is not supposed to have an image I set it to <code>ImageList.Images.Count-1</code></p>\n" }, { "answer_id": 31326820, "author": "Rogerio Souza", "author_id": 2820012, "author_profile": "https://Stackoverflow.com/users/2820012", "pm_score": 0, "selected": false, "text": "<p>Hei bro, i found a way.\nSet the first image as an empty image, like this...</p>\n\n<pre><code>TreeView treeView = new TreeView();\ntreeView.ImageList.Images.Add(new Bitmap(1,1));\n</code></pre>\n\n<p>So, the index 0 is an empty image.\nI hope this helps</p>\n" }, { "answer_id": 31507872, "author": "Aussie Ash", "author_id": 2614736, "author_profile": "https://Stackoverflow.com/users/2614736", "pm_score": 4, "selected": false, "text": "<p>I found that using StateImageList on the TreeView instead of ImageList will only show the image when StateImageIndex on the TreeNode is equal or greater than 0</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/261660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I have a `TreeView` windows forms control with an `ImageList`, and I want some of the nodes to display images, but the others to not have images. I *don't* want a blank space where the image should be. I *don't* want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?
I tried this once and I don't think it is possible. If you try to set both `ImageKey` and `ImageIndex` to "not set" values the control just defaults `ImageIndex` to 0. The following code: ``` treeView.ImageKey = "Value"; Debug.WriteLine(treeView.ImageIndex); treeView.ImageKey = null; Debug.WriteLine(treeView.ImageIndex); treeView.ImageIndex = -1; Debug.WriteLine(treeView.ImageIndex); ``` Produces output: ``` -1 0 0 ``` This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.