qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
217,955
<p>What's the best way (or tool) on the Windows (Vista) command line to get size and modification time for a file on a remote webserver, without downloading it?</p>
[ { "answer_id": 217971, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "Invoke-WebRequest -Method Head" }, { "answer_id": 217972, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "HEAD /resource HTTP/1.1\nHost: www.example.com\n" }, { "answer_id": 3355936, "author": "David Bell", "author_id": 404869, "author_profile": "https://Stackoverflow.com/users/404869", "pm_score": 3, "selected": false, "text": "wget --server-response -O /dev/null http://....\n" }, { "answer_id": 5633024, "author": "Laurence", "author_id": 703738, "author_profile": "https://Stackoverflow.com/users/703738", "pm_score": 3, "selected": false, "text": "TELNET server_name 80\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29549/" ]
217,957
<p>How do I print debug messages in the Google Chrome JavaScript Console?</p> <p>Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the <strong>print</strong> command in JavaScript Debugger will not work here. In the JavaScript Console, <code>print()</code> will send the parameter to the printer.</p>
[ { "answer_id": 2757552, "author": "Delan Azabani", "author_id": 330644, "author_profile": "https://Stackoverflow.com/users/330644", "pm_score": 7, "selected": false, "text": "if (!window.console) console = {};\nconsole.log = console.log || function(){};\nconsole.warn = console.warn || function(){};\nconsole.error = console.error || function(){};\nconsole.info = console.info || function(){};\n" }, { "answer_id": 3727132, "author": "Vegar", "author_id": 449548, "author_profile": "https://Stackoverflow.com/users/449548", "pm_score": 4, "selected": false, "text": "console.log" }, { "answer_id": 4190924, "author": "Bruce", "author_id": 505323, "author_profile": "https://Stackoverflow.com/users/505323", "pm_score": 3, "selected": false, "text": "localConsole.debug.call()" }, { "answer_id": 6086498, "author": "Tarek Saied", "author_id": 554019, "author_profile": "https://Stackoverflow.com/users/554019", "pm_score": 4, "selected": false, "text": "function log(message){\n if (typeof console == \"object\") {\n console.log(message);\n }\n}\n" }, { "answer_id": 7726194, "author": "cwd", "author_id": 288032, "author_profile": "https://Stackoverflow.com/users/288032", "pm_score": 3, "selected": false, "text": "// Use a less-common namespace than just 'log'\nfunction myLog(msg)\n{\n // Attempt to send a message to the console\n try\n {\n console.log(msg);\n }\n // Fail gracefully if it does not exist\n catch(e){}\n}\n" }, { "answer_id": 11167099, "author": "stryker", "author_id": 1460052, "author_profile": "https://Stackoverflow.com/users/1460052", "pm_score": 2, "selected": false, "text": "console.log()" }, { "answer_id": 12580824, "author": "Tim Büthe", "author_id": 60518, "author_profile": "https://Stackoverflow.com/users/60518", "pm_score": 4, "selected": false, "text": "console.js" }, { "answer_id": 17016305, "author": "kodybrown", "author_id": 139793, "author_profile": "https://Stackoverflow.com/users/139793", "pm_score": 2, "selected": false, "text": "// Console extensions...\n(function() {\n var __localhost = (document.location.host === \"localhost\"),\n __allow_examine = true;\n\n if (!console) {\n console = {};\n }\n\n console.__log = console.log;\n console.log = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__log === \"function\") {\n console.__log(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__info = console.info;\n console.info = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__info === \"function\") {\n console.__info(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__warn = console.warn;\n console.warn = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__warn === \"function\") {\n console.__warn(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__error = console.error;\n console.error = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__error === \"function\") {\n console.__error(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg);\n }\n }\n };\n\n console.__group = console.group;\n console.group = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__group === \"function\") {\n console.__group(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(\"group:\\r\\n\" + msg + \"{\");\n }\n }\n };\n\n console.__groupEnd = console.groupEnd;\n console.groupEnd = function() {\n if (__localhost) {\n if (typeof console !== \"undefined\" && typeof console.__groupEnd === \"function\") {\n console.__groupEnd(arguments);\n } else {\n var i, msg = \"\";\n for (i = 0; i < arguments.length; ++i) {\n msg += arguments[i] + \"\\r\\n\";\n }\n alert(msg + \"\\r\\n}\");\n }\n }\n };\n\n /// <summary>\n /// Clever way to leave hundreds of debug output messages in the code,\n /// but not see _everything_ when you only want to see _some_ of the\n /// debugging messages.\n /// </summary>\n /// <remarks>\n /// To enable __examine_() statements for sections/groups of code, type the\n /// following in your browser's console:\n /// top.__examine_ABC = true;\n /// This will enable only the console.examine(\"ABC\", ... ) statements\n /// in the code.\n /// </remarks>\n console.examine = function() {\n if (!__allow_examine) {\n return;\n }\n if (arguments.length > 0) {\n var obj = top[\"__examine_\" + arguments[0]];\n if (obj && obj === true) {\n console.log(arguments.splice(0, 1));\n }\n }\n };\n})();\n" }, { "answer_id": 17153511, "author": "dbrin", "author_id": 834424, "author_profile": "https://Stackoverflow.com/users/834424", "pm_score": 2, "selected": false, "text": "/* Console shim */\n(function () {\n var f = function () {};\n if (!window.console) {\n window.console = {\n log:f, info:f, warn:f, debug:f, error:f\n };\n }\n}());\n" }, { "answer_id": 19511951, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 6, "selected": false, "text": "console.log(\"this is %o, event is %o, host is %s\", this, e, location.host);\n" }, { "answer_id": 23763171, "author": "vogomatix", "author_id": 1421665, "author_profile": "https://Stackoverflow.com/users/1421665", "pm_score": 1, "selected": false, "text": "if (!window.console) console = {};\nconsole.log = console.log || function(){};\nconsole.warn = console.warn || console.log; // defaults to log\nconsole.error = console.error || console.log; // defaults to log\nconsole.info = console.info || console.log; // defaults to log\n" }, { "answer_id": 35357664, "author": "Nicholas Smith", "author_id": 5488863, "author_profile": "https://Stackoverflow.com/users/5488863", "pm_score": 2, "selected": false, "text": "console.debug(\"\");\n" }, { "answer_id": 65906785, "author": "Daniel", "author_id": 303914, "author_profile": "https://Stackoverflow.com/users/303914", "pm_score": 0, "selected": false, "text": "console.group(\"Main\");\nconsole.group(\"Feature 1\");\nconsole.log(\"Enabled:\", true);\nconsole.log(\"Public:\", true);\nconsole.groupEnd();\nconsole.group(\"Feature 2\");\nconsole.log(\"Enabled:\", false);\nconsole.warn(\"Error: Requires auth\");\nconsole.groupEnd();\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
217,960
<p>How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:</p> <pre>http://site/catalogue/BrowseByStyleLevel/1</pre> <p>The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.</p> <p>For example, these two URLs will take you to the same place:</p> <blockquote> <p><a href="https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages">https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages</a></p> <p><a href="https://stackoverflow.com/questions/119323/">https://stackoverflow.com/questions/119323/</a></p> </blockquote> <p><strong>EDIT:</strong> The friendly part of the url is referred to as a <em>slug</em>.</p>
[ { "answer_id": 217991, "author": "Moran Helman", "author_id": 1409636, "author_profile": "https://Stackoverflow.com/users/1409636", "pm_score": 1, "selected": false, "text": " routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\"} \n // Parameter defaults )\n" }, { "answer_id": 218373, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 7, "selected": true, "text": "routes.MapRoute( \"Default\", // Route name\n \"{controller}/{action}/{id}/{ignoreThisBit}\", \n new { controller = \"Home\", \n action = \"Index\", \n id = \"\",\n ignoreThisBit = \"\"} // Parameter defaults )\n" }, { "answer_id": 6866064, "author": "Hamid Tavakoli", "author_id": 602165, "author_profile": "https://Stackoverflow.com/users/602165", "pm_score": 2, "selected": false, "text": "routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\",\n action = \"Index\",\n id = UrlParameter.Optional\n } // Parameter defaults\n);\nroutes.MapRoute(\"Place\", \"{controller}/{action}/{id}/{slug}\", new { controller = \"Place\", action = \"Details\", id = UrlParameter.Optional,slug=\"\" });\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]
217,961
<p>Is there a way to Deserialize Expressions in C#, I would like to store Expressions in a Database and load them at run time.</p>
[ { "answer_id": 3682878, "author": "Jonathan Parker", "author_id": 4504, "author_profile": "https://Stackoverflow.com/users/4504", "pm_score": 2, "selected": false, "text": "IQuerayble<T>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ]
217,964
<p>I need to migrate Access databases to SQL Server 2005. Since this needs to be done from within a setup so that a customers' installation is transparently migrated to SQL Server 2005, I wonder if it is possible to automate the SSMA toolkit from Microsoft.</p>
[ { "answer_id": 3682878, "author": "Jonathan Parker", "author_id": 4504, "author_profile": "https://Stackoverflow.com/users/4504", "pm_score": 2, "selected": false, "text": "IQuerayble<T>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23369/" ]
217,968
<p>I am using a satellite assembly to hold all the localization resources in a C# application.</p> <p>What I need to do is create a menu in the GUI with all the available languages that exists for the application. Is there any way to get information dynamically?</p>
[ { "answer_id": 1083120, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 3, "selected": true, "text": "public static string[] GetInstalledCultures()\n{\n List<string> cultures = new List<string>();\n foreach (string file in Directory.GetFiles(HttpContext.Current.Server.MapPath(\"/App_GlobalResources\"), \\\\Change folder to search in if needed.\n \"*.resx\", SearchOption.TopDirectoryOnly))\n {\n string name = file.Split('\\\\').Last();\n name = name.Split('.')[1];\n\n cultures.Add(name != \"resx\" ? name : \"auto\"); \\\\Change \"auto\" to something else like \"en-US\" if needed.\n }\n return cultures.ToArray();\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/66654/" ]
217,969
<p>I was trying to test code using com class to display Word files but I cannot seem to get the answer and still searching. I get errors and sometimes, programs do not display anything at all. Please give me some ideas. I'm working with PHP 4.</p>
[ { "answer_id": 217981, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 0, "selected": false, "text": "<object>" }, { "answer_id": 56308332, "author": "user11555821", "author_id": 11555821, "author_profile": "https://Stackoverflow.com/users/11555821", "pm_score": 0, "selected": false, "text": "<head><title>snook.ca load document</title>\n\n<script language=\"JavaScript\">\n\n<!--//\n\nfunction loadworddoc(){\n\n // creates the word object\n\n var doc = new ActiveXObject(\"Word.Application\"); \n\n // doesn't display Word window\n\n doc.Visible=false; \n\n // specify path to document\n\n doc.Documents.Open(document.all.hello.value); \n\n\n\n //copy the content from my word document and throw it into my variable\n\n var txt;\n\n txt = doc.Documents(document.all.hello.value).Content;\n\n //document.all.myarea.value = txt;\n\n document.all.tbContentElement.DOM.body.innerHTML = txt;\n\n // quit word (very important or you'll quickly chew up memory!)\n\n doc.quit(0); \n\n }\n\n //-->\n\n </script>\n\n</head>\n\n<body>\n\n <p><input type=button onClick=\"loadworddoc();\" value=\"Load\">\n\n <p><input type=file name=hello>\n\n <p><textarea name=myarea cols=50 rows=5>nothing here yet</textarea>\n\n <object ID=\"tbContentElement\" CLASS=\"tbContentElement\" \n\n CLASSID=\"clsid:2D360201-FFF5-11D1-8D03-00A0C959BC0A\" VIEWASTEXT\n\n width=\"450\" height=\"300\">\n\n <param name=Scrollbars value=true></object>\n\n</body>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
217,977
<p>I have an XML reader on this XML string:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;story id="1224488641nL21535800" date="20 Oct 2008" time="07:44"&gt; &lt;title&gt;PRESS DIGEST - PORTUGAL - Oct 20&lt;/title&gt; &lt;text&gt; &lt;p&gt; LISBON, Oct 20 (Reuters) - Following are some of the main stories in Portuguese newspapers on Monday. Reuters has not verified these stories and does not vouch for their accuracy. &lt;/p&gt; &lt;p&gt;More HTML stuff here&lt;/p&gt; &lt;/text&gt; &lt;/story&gt; </code></pre> <p>I created an XSD and a corresponding class for deserialization.</p> <pre><code>[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public class story { [System.Xml.Serialization.XmlAttributeAttribute()] public string id; [System.Xml.Serialization.XmlAttributeAttribute()] public string date; [System.Xml.Serialization.XmlAttributeAttribute()] public string time; public string title; public string text; } </code></pre> <p>I then create an instance of the class using the <code>Deserialize</code> method of XmlSerializer.</p> <pre><code>XmlSerializer ser = new XmlSerializer(typeof(story)); return (story)ser.Deserialize(xr); </code></pre> <p>Now, the <code>text</code> member of <code>story</code> is always null. How do I change my <code>story</code> class so that the XML is parsed as expected?</p> <p><strong>EDIT:</strong> </p> <p>Using an XmlText does not work and I have no control over the XML I'm parsing.</p>
[ { "answer_id": 218049, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "// ...\n[XmlElement(\"HACK - this should never match anything\")]\npublic string text;\n// ...\n" }, { "answer_id": 218231, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 1, "selected": false, "text": "<text>\n <p>blah</p>\n <p>blib</p>\n</text>\n" }, { "answer_id": 218468, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 1, "selected": false, "text": "IXmlSerializable" }, { "answer_id": 12065068, "author": "techSage", "author_id": 229011, "author_profile": "https://Stackoverflow.com/users/229011", "pm_score": 0, "selected": false, "text": "<p>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
217,980
<p>In the documentation of hardware that allows us to control it via UDP/IP, I found the following fragment:</p> <blockquote> <p>In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data, BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.</p> </blockquote> <p>I am wondering how this translates to C#? Do I have to convert stuff before sending it over? For example, if I want to send over a 32 bit integer, or a 4 character string?</p>
[ { "answer_id": 217987, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "bool le = BitConverter.IsLittleEndian;\n" }, { "answer_id": 218004, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": false, "text": "htons" }, { "answer_id": 218015, "author": "Jan Bannister", "author_id": 460845, "author_profile": "https://Stackoverflow.com/users/460845", "pm_score": 6, "selected": false, "text": "IPAddress.NetworkToHostOrder(...)\n" }, { "answer_id": 13287344, "author": "mafu", "author_id": 39590, "author_profile": "https://Stackoverflow.com/users/39590", "pm_score": 0, "selected": false, "text": "private static byte[] NetworkToHostOrder (byte[] array, int offset, int length)\n{\n return array.Skip (offset).Take (length).Reverse ().ToArray ();\n}\n\nint foo = BitConverter.ToInt64 (NetworkToHostOrder (queue, 14, 8), 0);\n" }, { "answer_id": 32511009, "author": "Marko Samirić", "author_id": 5322807, "author_profile": "https://Stackoverflow.com/users/5322807", "pm_score": 1, "selected": false, "text": " private UInt16 swapOctetsUInt16(UInt16 toSwap)\n {\n Int32 tmp = 0;\n tmp = toSwap >> 8;\n tmp = tmp | ((toSwap & 0xff) << 8);\n return (UInt16) tmp;\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
218,003
<p>I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string?</p> <p>e.g.</p> <pre><code>CString strIn = "Test number 1"; CString strQuery = "num"; bool fRet = SomeFn(strIn, StrQuery); if( fRet == true ) { // Ok strQuery was found in strIn ... </code></pre> <p>I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net)</p> <p>Thanks!</p>
[ { "answer_id": 218014, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 5, "selected": true, "text": "CString strIn = \"test number 1\";\nint index = strIn.Find(\"num\");\nif (index != -1)\n // ok, found\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
218,023
<p>I have committed, and pushed, several patches: A1-->A2-->A3-->A4 (HEAD)</p> <p>Everyone's pulled these changesets into their local copy.</p> <p>Now we want to "roll back" to A2, and continue developing from there - essentially throwing away A3 and A4. What's the best way to do this?</p>
[ { "answer_id": 218050, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 3, "selected": false, "text": "git-revert" }, { "answer_id": 221137, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 6, "selected": false, "text": "git checkout A2 -- . \ngit commit -m 'going back to A2'\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
218,024
<p>I have a question with fluent interfaces.</p> <p>We have some objects that are used as parameter objects for a SQL interface, here's an example:</p> <pre><code>using (DatabaseCommand cmd = conn.CreateCommand( "SELECT A, B, C FROM tablename WHERE ID = :ID", SqlParameter.Int32(":ID", 1234))) { ... } </code></pre> <p>For some of these parameters, I'd like to enable some specialized options, but instead of adding more properties to the Int32 method (which is just one of many), I thought I'd look into fluent interfaces.</p> <p>Here's an example where I've added what I am looking into:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Substitute .Precision(15) ) </code></pre> <p>I know these two options doesn't make sense for this type of parameter, but that's not what the question is about.</p> <p>In the above case, Substitute would have to be a static property (or method if I just add some parenthesis) on the SqlParameterOption class, whereas Precision would have to be an instance method.</p> <p>What if I reorder them?</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(SqlParameterOption .Precision(15) .Substitute ) </code></pre> <p>Then Substitute would have to be the instance property and Precision the static method. This won't compile of course, I can't have both a static and a non-static property or method with the same name.</p> <p>How do I do this? Am I completely on the wrong track here?</p> <p>While re-reading the question, I had an idea, would this different syntax below make more sense?</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute </code></pre> <p>In this case both would be instance methods on whatever With returns, which would be a specialized class or interface for SqlParameter options like this. I'm not sure I'd like to dump the <em>.With</em> part, as this would expose all methods of the object, instead of just the <em>fluent</em> ones.</p> <p>Advice and some good url's would be most welcome, I've scoured over many examples, but they tend to show examples like this:</p> <pre><code>order .AddFreeShipping() .IncludeItem(15) .SuppressTax(); </code></pre> <p>(lifted from <a href="http://blog.troyd.net/PermaLink,guid,5cdd4862-857a-488d-a577-c6d21b548f19.aspx" rel="nofollow noreferrer">this page</a>)</p> <hr> <p><strong>Edit</strong>: Followup after responses From <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a>:</p> <pre><code>class SqlParameterOption { public SqlParameterOption Precision(int p) {/* ... */; return this;} public SqlParameterOption Substitute() {/* ... */; return this;} /* ... */ } /* ... */ SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); </code></pre> <p>With this approach, With would have to take the object, and apply it to the parameter. I'm fine with that.</p> <p>If I used the syntax I added as an example, it would be like this:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); </code></pre> <p>In this case, With wouldn't know when the chain ended, so each option would have to apply its effect directly.</p> <p>What is preferred? That the options build up an effect object that will have to be applied later, or that each effect applies its effect directly?</p> <p><strong>My decision</strong>: As <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a> says, if the changes are irreversible, and could potentially be subject to a reversal, building up state and failing at some point with an exception is the way I'll go.</p> <p>However, in this case, I'm going with a simpler approach that modifies the SqlParameter object directly.</p> <p>In this case, my code will look like this:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With .Precision(15) .Substitute()); </code></pre> <p><strong>Edit:</strong> Gah, that's how it goes when I focus on just one thing.</p> <p>I can't use that syntax, I'll go with the following, as suggested by <a href="https://stackoverflow.com/users/1659/marxidad">@marxidad</a>:</p> <pre><code>SqlParameter.Int32(":ID", 1234).With(new SqlParameterOption() .Precision(15) .Substitute()); </code></pre> <p>The reason is of course that the method that takes the SqlParameter object as an argument is unable to cope with the object returned by With, so although the SqlParameter object is constructed and set up properly, it became incompatible with the intended usage.</p>
[ { "answer_id": 218036, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "SqlParameterOption's" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
218,025
<p>I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.</p> <p>I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.</p> <p>Could someone provide me with a definition of both terms, and details of how they differ?</p>
[ { "answer_id": 218055, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 9, "selected": true, "text": "function f(x,y,z) { z(x(y));}\n" }, { "answer_id": 10443057, "author": "dodgy_coder", "author_id": 507950, "author_profile": "https://Stackoverflow.com/users/507950", "pm_score": 6, "selected": false, "text": "let multiply x y = x * y \nlet double = multiply 2\nlet ten = double 5\n" }, { "answer_id": 12847240, "author": "Ji Han", "author_id": 1685865, "author_profile": "https://Stackoverflow.com/users/1685865", "pm_score": 4, "selected": false, "text": "lambda x: lambda y: lambda z: x + y + z\n" }, { "answer_id": 16766060, "author": "gsklee", "author_id": 857514, "author_profile": "https://Stackoverflow.com/users/857514", "pm_score": 3, "selected": false, "text": "function f(x, y, z) {\n return x + y + z;\n}\n\nvar partial = f.bind(null, 1);\n\n6 === partial(2, 3);\n" }, { "answer_id": 22952234, "author": "nomen", "author_id": 738762, "author_profile": "https://Stackoverflow.com/users/738762", "pm_score": 1, "selected": false, "text": "(+) :: Int -> Int -> Int\n" }, { "answer_id": 23438430, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 7, "selected": false, "text": "Add" }, { "answer_id": 34126762, "author": "sunny-mittal", "author_id": 2214364, "author_profile": "https://Stackoverflow.com/users/2214364", "pm_score": 2, "selected": false, "text": "# partial application\npartial_apply = (func) ->\n args = [].slice.call arguments, 1\n -> func.apply null, args.concat [].slice.call arguments\n\nsum_variadic = -> [].reduce.call arguments, (acc, num) -> acc + num\n\nadd_to_7_and_5 = partial_apply sum_variadic, 7, 5\n\nadd_to_7_and_5 10 # returns 22\nadd_to_7_and_5 10, 11, 12 # returns 45\n\n# currying\ncurry = (func) ->\n num_args = func.length\n helper = (prev) ->\n ->\n args = prev.concat [].slice.call arguments\n return if args.length < num_args then helper args else func.apply null, args\n helper []\n\nsum_of_three = (x, y, z) -> x + y + z\ncurried_sum_of_three = curry sum_of_three\ncurried_sum_of_three 4 # returns a function expecting more arguments\ncurried_sum_of_three(4)(5) # still returns a function expecting more arguments\ncurried_sum_of_three(4)(5)(6) # returns 15\ncurried_sum_of_three 4, 5, 6 # returns 15\n" }, { "answer_id": 42495958, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 2, "selected": false, "text": "public static <A,B,X> Function< B, X > partiallyApply( BiFunction< A, B, X > aBiFunction, A aValue ){\n return b -> aBiFunction.apply( aValue, b );\n}\n\npublic static <A,X> Supplier< X > partiallyApply( Function< A, X > aFunction, A aValue ){\n return () -> aFunction.apply( aValue );\n}\n\npublic static <A,B,X> Function< A, Function< B, X > > curry( BiFunction< A, B, X > bif ){\n return a -> partiallyApply( bif, a );\n}\n" }, { "answer_id": 45954876, "author": "Roland", "author_id": 480894, "author_profile": "https://Stackoverflow.com/users/480894", "pm_score": 4, "selected": false, "text": "f" }, { "answer_id": 47256293, "author": "sunny-mittal", "author_id": 2214364, "author_profile": "https://Stackoverflow.com/users/2214364", "pm_score": 3, "selected": false, "text": "add = (x, y) => x + y\n" }, { "answer_id": 51253347, "author": "Kamafeather", "author_id": 3088045, "author_profile": "https://Stackoverflow.com/users/3088045", "pm_score": 4, "selected": false, "text": "process" }, { "answer_id": 64467751, "author": "basickarl", "author_id": 1137669, "author_profile": "https://Stackoverflow.com/users/1137669", "pm_score": 2, "selected": false, "text": "function bothPartialAndCurry(firstArgument) {\n return function(secondArgument) {\n return firstArgument + secondArgument;\n }\n}\n\nconst partialAndCurry = bothPartialAndCurry(1);\nconst result = partialAndCurry(2);\n" }, { "answer_id": 72051129, "author": "Roman Mahotskyi", "author_id": 7291317, "author_profile": "https://Stackoverflow.com/users/7291317", "pm_score": 1, "selected": false, "text": "const add = (a, b) => a + b\n\nconst addC = (a) => (b) => a + b // curried function. Where C means curried\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1577190/" ]
218,027
<p>When debugging, a trick I do whenever I want to exit the current method without running of its any statements, I move the current execution pointer to the end of the method, then click F10/11.</p> <p>Is there a keyboard shortcut (or can I program one) to accomplish this?</p> <p>(I don't mean shift-F11 (step out) - that does run all the code until the method's end, which I do not want).</p>
[ { "answer_id": 220528, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 3, "selected": true, "text": "Ctrl+M, Ctrl+M" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
218,035
<p>Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.</p>
[ { "answer_id": 218052, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 4, "selected": true, "text": "class CColorEdit : public CEdit\n{\n ....\n CBrush m_brBkgnd;\n afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor)\n {\n m_brBkgnd.DeleteObject();\n m_brBkgnd.CreateSolidBrush(nCtlColor);\n }\n}\n" }, { "answer_id": 16296246, "author": "amolbk", "author_id": 432849, "author_profile": "https://Stackoverflow.com/users/432849", "pm_score": 3, "selected": false, "text": "ON_WM_CTLCOLOR()" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
218,042
<p>I want to show the publish date in the About dialog.</p>
[ { "answer_id": 218114, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "FileInfo oMyFile = new\n FileInfo(Assembly.GetExecutingAssembly().Location);\n\nDateTime oBuildDate = oMyFile.LastWriteTime // or LastWriteTimeUtc - don't use \"CreationTime\"\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
218,043
<p>I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:</p> <pre><code>var delselection = window.getSelection(); var startOffset = delselection.anchorOffset; var endOffset = delselection.focusOffset; var startNode = delselection.anchorNode.parentNode; var endNode = delselection.focusNode.parentNode; </code></pre> <p>However i have no idea how to do this in IE6, anyone able to point me in the right direction?</p>
[ { "answer_id": 1945890, "author": "Roy Leban", "author_id": 189641, "author_profile": "https://Stackoverflow.com/users/189641", "pm_score": 1, "selected": false, "text": "var selObj = null;\nvar selSave = null;\nvar selSaveEnd = null;\n\nfunction SaveSelection(obj) {\n if (obj.selectionStart) {\n selObj = obj;\n selSave = obj.selectionStart;\n selSaveEnd = obj.selectionEnd;\n }\n else {\n // Internet Explorer case\n selSave = document.selection.createRange();\n }\n}\n\nfunction RestoreSelection() {\n if (selObj) {\n selObj.focus();\n selObj.selectionStart = selSave;\n selObj.selectionEnd = selSaveEnd;\n }\n else {\n // Internet Explorer case\n selSave.select();\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11198/" ]
218,057
<p>Without routing, <code>HttpContext.Current.Session</code> is there so I know that the <code>StateServer</code> is working. When I route my requests, <code>HttpContext.Current.Session</code> is <code>null</code> in the routed page. I am using .NET 3.5 sp1 on IIS 7.0, without the MVC previews. It appears that <code>AcquireRequestState</code> is never fired when using the routes and so the session variable isn't instantiated/filled.</p> <p>When I try to access the Session variables, I get this error:</p> <p><code>base {System.Runtime.InteropServices.ExternalException} = {"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the &lt;configuration&gt;.</code></p> <p>While debugging, I also get the error that the <code>HttpContext.Current.Session</code> is not accessible in that context.</p> <p>--</p> <p>My <code>web.config</code> looks like this:</p> <pre><code>&lt;configuration&gt; ... &lt;system.web&gt; &lt;pages enableSessionState="true"&gt; &lt;controls&gt; ... &lt;/controls&gt; &lt;/pages&gt; ... &lt;/system.web&gt; &lt;sessionState cookieless="AutoDetect" mode="StateServer" timeout="22" /&gt; ... &lt;/configuration&gt; </code></pre> <p>Here's the IRouteHandler implementation:</p> <pre><code>public class WebPageRouteHandler : IRouteHandler, IRequiresSessionState { public string m_VirtualPath { get; private set; } public bool m_CheckPhysicalUrlAccess { get; set; } public WebPageRouteHandler(string virtualPath) : this(virtualPath, false) { } public WebPageRouteHandler(string virtualPath, bool checkPhysicalUrlAccess) { m_VirtualPath = virtualPath; m_CheckPhysicalUrlAccess = checkPhysicalUrlAccess; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (m_CheckPhysicalUrlAccess &amp;&amp; !UrlAuthorizationModule.CheckUrlAccessForPrincipal( m_VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod)) { throw new SecurityException(); } string var = String.Empty; foreach (var value in requestContext.RouteData.Values) { requestContext.HttpContext.Items[value.Key] = value.Value; } Page page = BuildManager.CreateInstanceFromVirtualPath( m_VirtualPath, typeof(Page)) as Page;// IHttpHandler; if (page != null) { return page; } return page; } } </code></pre> <p>I've also tried to put <code>EnableSessionState="True"</code> on the top of the aspx pages but still, nothing.</p> <p>Any insights? Should I write another <code>HttpRequestHandler</code> that implements <code>IRequiresSessionState</code>?</p> <p>Thanks.</p>
[ { "answer_id": 218068, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": " <sessionstate mode=\"StateServer\" timeout=\"20\" server=\"127.0.0.1\" port=\"42424\" />\n" }, { "answer_id": 218104, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<sessionState mode=\"InProc\" timeout=\"20\" cookieless=\"AutoDetect\" />\n" }, { "answer_id": 218532, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": " Page page = BuildManager.CreateInstanceFromVirtualPath(\n m_VirtualPath, \n typeof(Page)) as Page;// IHttpHandler;\n" }, { "answer_id": 221227, "author": "Loki", "author_id": 57936, "author_profile": "https://Stackoverflow.com/users/57936", "pm_score": 7, "selected": true, "text": "<configuration>\n ...\n <system.webServer>\n ...\n <modules>\n <remove name=\"Session\" />\n <add name=\"Session\" type=\"System.Web.SessionState.SessionStateModule\"/>\n ...\n </modules>\n </system.webServer>\n</configuration>\n" }, { "answer_id": 364711, "author": "Mike", "author_id": 36668, "author_profile": "https://Stackoverflow.com/users/36668", "pm_score": 2, "selected": false, "text": "<remove name=\"FormsAuthentication\" />\n<add name=\"FormsAuthentication\" type=\"System.Web.Security.FormsAuthenticationModule\"/>\n" }, { "answer_id": 381354, "author": "gandjustas", "author_id": 20655, "author_profile": "https://Stackoverflow.com/users/20655", "pm_score": 5, "selected": false, "text": "runAllManagedModulesForAllRequests=\"true\"" }, { "answer_id": 6429098, "author": "Frankie Rodriguez", "author_id": 808903, "author_profile": "https://Stackoverflow.com/users/808903", "pm_score": 4, "selected": false, "text": "runAllManagedModulesForAllRequests=true" }, { "answer_id": 46367550, "author": "ViqMontana", "author_id": 4300608, "author_profile": "https://Stackoverflow.com/users/4300608", "pm_score": 3, "selected": false, "text": "global.asax.cs" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57936/" ]
218,060
<p>Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution? </p>
[ { "answer_id": 218600, "author": "yoyoyoyosef", "author_id": 25571, "author_profile": "https://Stackoverflow.com/users/25571", "pm_score": 9, "selected": true, "text": "Random rand = new Random(); //reuse this if you are generating many\ndouble u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles\ndouble u2 = 1.0-rand.NextDouble();\ndouble randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *\n Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)\ndouble randNormal =\n mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)\n" }, { "answer_id": 4594881, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 4, "selected": false, "text": "Random" }, { "answer_id": 12924249, "author": "Gordon Slysz", "author_id": 246758, "author_profile": "https://Stackoverflow.com/users/246758", "pm_score": 5, "selected": false, "text": "double mean = 100;\ndouble stdDev = 10;\n\nMathNet.Numerics.Distributions.Normal normalDist = new Normal(mean, stdDev);\ndouble randomGaussianValue= normalDist.Sample();\n" }, { "answer_id": 15556411, "author": "Superbest", "author_id": 1042555, "author_profile": "https://Stackoverflow.com/users/1042555", "pm_score": 6, "selected": false, "text": "var r = new Random();\nvar x = r.NextGaussian();\n" }, { "answer_id": 18460552, "author": "Hameer Abbasi", "author_id": 774273, "author_profile": "https://Stackoverflow.com/users/774273", "pm_score": 2, "selected": false, "text": "public class Gaussian\n{\n private bool _available;\n private double _nextGauss;\n private Random _rng;\n\n public Gaussian()\n {\n _rng = new Random();\n }\n\n public double RandomGauss()\n {\n if (_available)\n {\n _available = false;\n return _nextGauss;\n }\n\n double u1 = _rng.NextDouble();\n double u2 = _rng.NextDouble();\n double temp1 = Math.Sqrt(-2.0*Math.Log(u1));\n double temp2 = 2.0*Math.PI*u2;\n\n _nextGauss = temp1 * Math.Sin(temp2);\n _available = true;\n return temp1*Math.Cos(temp2);\n }\n\n public double RandomGauss(double mu, double sigma)\n {\n return mu + sigma*RandomGauss();\n }\n\n public double RandomGauss(double sigma)\n {\n return sigma*RandomGauss();\n }\n}\n" }, { "answer_id": 32109567, "author": "Daniel Howard", "author_id": 5245862, "author_profile": "https://Stackoverflow.com/users/5245862", "pm_score": 0, "selected": false, "text": " //\n // by Dan\n // islandTraderFX\n // copyright 2015\n // Siesta Key, FL\n // \n// 0.0 3231 ********************************\n// 0.1 1981 *******************\n// 0.2 1411 **************\n// 0.3 1048 **********\n// 0.4 810 ********\n// 0.5 573 *****\n// 0.6 464 ****\n// 0.7 262 **\n// 0.8 161 *\n// 0.9 59 \n//Total: 10000\n\ndouble g()\n{\n double res = 1000000;\n return random.Next(0, (int)(res * random.NextDouble()) + 1) / res;\n}\n\npublic static class RandomProvider\n{\n public static int seed = Environment.TickCount;\n\n private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>\n new Random(Interlocked.Increment(ref seed))\n );\n\n public static Random GetThreadRandom()\n {\n return randomWrapper.Value;\n }\n} \n" }, { "answer_id": 42769720, "author": "Doomjunky", "author_id": 697612, "author_profile": "https://Stackoverflow.com/users/697612", "pm_score": 3, "selected": false, "text": " static Random _rand = new Random();\n\n public static double Draw()\n {\n while (true)\n {\n // Get random values from interval [0,1]\n var x = _rand.NextDouble(); \n var y = _rand.NextDouble(); \n\n // Is the point (x,y) below the graph of the density function?\n if (y < f(x)) \n return x;\n }\n }\n\n // Probability density function of the normal \"Gaussian\" distribution\n public static double f(double x, double μ = 0.5, double σ = 0.5)\n {\n return 1d / Math.Sqrt(2 * σ * σ * Math.PI) * Math.Exp(-((x - μ) * (x - μ)) / (2 * σ * σ));\n }\n" }, { "answer_id": 48199345, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public class Gaussian : Random\n{\n\n private double u1;\n private double u2;\n private double temp1;\n private double temp2;\n\n public Gaussian(int seed):base(seed)\n {\n }\n\n public Gaussian() : base()\n {\n }\n\n /// <summary>\n /// Obtains normally (Gaussian) distrubuted random numbers, using the Box-Muller\n /// transformation. This transformation takes two uniformly distributed deviates\n /// within the unit circle, and transforms them into two independently distributed normal deviates.\n /// </summary>\n /// <param name=\"mu\">The mean of the distribution. Default is zero</param>\n /// <param name=\"sigma\">The standard deviation of the distribution. Default is one.</param>\n /// <returns></returns>\n\n public double RandomGauss(double mu = 0, double sigma = 1)\n {\n if (sigma <= 0)\n throw new ArgumentOutOfRangeException(\"sigma\", \"Must be greater than zero.\");\n\n u1 = base.NextDouble();\n u2 = base.NextDouble();\n temp1 = Math.Sqrt(-2 * Math.Log(u1));\n temp2 = 2 * Math.PI * u2;\n\n return mu + sigma*(temp1 * Math.Cos(temp2));\n }\n}\n" }, { "answer_id": 69943473, "author": "Andrew Allbright", "author_id": 2646461, "author_profile": "https://Stackoverflow.com/users/2646461", "pm_score": 2, "selected": false, "text": "using System;\n\npublic class CustomMath\n{\n private static readonly Random _random = new Random();\n public static double GaussianRandom() =>\n _random.NextDouble() + _random.NextDouble() + _random.NextDouble() - 1.5;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23681/" ]
218,061
<p>I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.</p> <p>Feel free to up/downvote if you (don't) like the idea and <strong>please contribute</strong> if you like it.</p> <h2>Clarification:</h2> <p>There's a fine distinction between the <em>directory that contains the executable file</em> and the <em>current working directory</em> (given by <code>pwd</code> under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).</p>
[ { "answer_id": 218062, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "System.getProperty" }, { "answer_id": 218064, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "Assembly" }, { "answer_id": 218090, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 2, "selected": false, "text": "Unit Forms;\npath := ExtractFilePath(Application.ExeName);\n" }, { "answer_id": 218099, "author": "Alex McBride", "author_id": 27059, "author_profile": "https://Stackoverflow.com/users/27059", "pm_score": 3, "selected": false, "text": "path = os.path.dirname(__file__)\n" }, { "answer_id": 218121, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "path = File.dirname(__FILE__)\n" }, { "answer_id": 218218, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 2, "selected": false, "text": "pwd" }, { "answer_id": 218239, "author": "Rajish", "author_id": 29576, "author_profile": "https://Stackoverflow.com/users/29576", "pm_score": 2, "selected": false, "text": " #include <unistd.h>\n\n char *getcwd(char *buf, size_t size);\n\n char *getwd(char *buf); //deprecated\n\n char *get_current_dir_name(void);\n" }, { "answer_id": 367086, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "getBaseTemplatePath()\ngetCurrentTemplatePath()\n" }, { "answer_id": 676413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "System.getProperty(\"user.dir\")\n" }, { "answer_id": 677995, "author": "mouviciel", "author_id": 45249, "author_profile": "https://Stackoverflow.com/users/45249", "pm_score": 3, "selected": false, "text": "NSString * applicationPath = [[NSBundle mainBundle] bundlePath];\n" }, { "answer_id": 3460438, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 2, "selected": false, "text": "set path [info script]\n" }, { "answer_id": 4045617, "author": "d7samurai", "author_id": 478267, "author_profile": "https://Stackoverflow.com/users/478267", "pm_score": 2, "selected": false, "text": "System.IO.Directory.GetCurrentDirectory" }, { "answer_id": 8499498, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 2, "selected": false, "text": "<?php\n echo __DIR__; //same as dirname(__FILE__). will return the directory of the running script\n echo $_SERVER[\"DOCUMENT_ROOT\"]; // will return the document root directory under which the current script is executing, as defined in the server's configuration file.\n echo getcwd(); //will return the current working directory (it may differ from the current script location).\n?>\n" }, { "answer_id": 9367717, "author": "rishi", "author_id": 1111779, "author_profile": "https://Stackoverflow.com/users/1111779", "pm_score": 2, "selected": false, "text": "getApplicationInfo().dataDir;\n" }, { "answer_id": 11308250, "author": "ctrl-alt-delor", "author_id": 537980, "author_profile": "https://Stackoverflow.com/users/537980", "pm_score": 1, "selected": false, "text": "set oldpwd=%cd%\ncd %0\\..\nset app_dir=%pwd%\ncd %oldpwd%\n" }, { "answer_id": 11738178, "author": "Deanna", "author_id": 588306, "author_profile": "https://Stackoverflow.com/users/588306", "pm_score": 2, "selected": false, "text": "App.Path" }, { "answer_id": 28197929, "author": "Gregory Pakosz", "author_id": 216063, "author_profile": "https://Stackoverflow.com/users/216063", "pm_score": 1, "selected": false, "text": "GetModuleFileNameW" }, { "answer_id": 39348193, "author": "Quark", "author_id": 4374374, "author_profile": "https://Stackoverflow.com/users/4374374", "pm_score": 2, "selected": false, "text": "public static File getApplicationDir() \n{\n URL url = ClassLoader.getSystemClassLoader().getResource(\".\");\n File applicationDir = null;\n try {\n applicationDir = new File(url.toURI());\n } catch(URISyntaxException e) {\n applicationDir = new File(url.getPath());\n }\n\n return applicationDir;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968/" ]
218,065
<p>I have a div with <code>overflow:hidden</code>, inside which I show a phone number as the user types it. The text inside the div is aligned to right and incoming characters are added to right as the text grows to left.</p> <p>But once the text is big enough not to fit in the div, last characters of the number is automatically cropped and the user cannot see the new characters she types.</p> <p>What I want to do is crop the left characters, like the div is showing the rightmost of its content and overflowing to the left side. How can I create this effect?</p> <p><img src="https://i.imgur.com/CRbCCPm.jpg" alt="overflowing phone number to left"></p>
[ { "answer_id": 218071, "author": "Rob Bell", "author_id": 2179408, "author_profile": "https://Stackoverflow.com/users/2179408", "pm_score": 8, "selected": true, "text": "direction: rtl;\n" }, { "answer_id": 678539, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<span>" }, { "answer_id": 10269998, "author": "catdotgif", "author_id": 242390, "author_profile": "https://Stackoverflow.com/users/242390", "pm_score": 3, "selected": false, "text": "float:right" }, { "answer_id": 12646655, "author": "Abe", "author_id": 1706909, "author_profile": "https://Stackoverflow.com/users/1706909", "pm_score": 6, "selected": false, "text": ".outer-div {\n width:70%;\n margin-left:auto;\n margin-right:auto;\n text-align:right;\n overflow:hidden;\n white-space: nowrap;\n}\n\n.inner-div {\n float:right;\n}\n\n:\n\n<div class=\"outer-div\">\n <div class=\"inner-div\"> \n <p>A very long line that should be trimmed on the left</p>\n </div>\n</div>\n" }, { "answer_id": 39874526, "author": "Dji", "author_id": 5134827, "author_profile": "https://Stackoverflow.com/users/5134827", "pm_score": 3, "selected": false, "text": "<div style=\"direction: rtl;\">\n <span style=\"white-space: nowrap; direction: ltr; display: inline-block;\">your short or long comment<span>\n</div>\n" }, { "answer_id": 54228719, "author": "Subramanian Narasimhan", "author_id": 5194497, "author_profile": "https://Stackoverflow.com/users/5194497", "pm_score": 0, "selected": false, "text": "<div id=\"outer-div\">\n\n <p>ipsum dolor amet bacon venison porchetta spare ribs, tongue turducken alcatra doner leberkas t-bone rump ball tip hamburger drumstick. Shoulder strip steak ribeye, kielbasa fatback pig kevin drumstick biltong pork short loin rump. Biltong doner ribeye, alcatra landjaeger tenderloin drumstick t-bone pastrami andouille. Sirloin spare ribs fatback, bresaola strip steak alcatra landjaeger kielbasa cupim doner. </p>\n\n</div>\n" }, { "answer_id": 69010726, "author": "Andreas Furster", "author_id": 3269816, "author_profile": "https://Stackoverflow.com/users/3269816", "pm_score": 3, "selected": false, "text": "p {\n display: flex;\n justify-content: flex-end;\n white-space: nowrap;\n overflow: hidden;\n\n font-size: 2em;\n width: 120px;\n background: yellow;\n}" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
218,096
<p>We are monitoring the progress of a customized app (whose source is not under our control) which writes to a XML Manifest. At times , the application is stuck due to unable to write into the Manifest file. Although we are covering our traces by explicitly closing the file handle using File.Close and also creating the file variables in Using Blocks. But somehow it keeps happening. ( Our application is multithreaded and at most three threads might be accessing the file. ) Another interesting thing is that their app updates this manifest at three different events(add items, deleting items, completion of items) but we are only suffering about one event (completion of items). My code is listed here</p> <pre><code>using (var st = new FileStream(MenifestPath, FileMode.Open, FileAccess.Read)) { using (TextReader r = new StreamReader(st)) { var xml = r.ReadToEnd(); r.Close(); st.Close(); //................ Rest of our operations } } </code></pre>
[ { "answer_id": 218253, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 3, "selected": true, "text": "FILE_SHARE_READ | FILE_SHARE_WRITE" }, { "answer_id": 218315, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 1, "selected": false, "text": "using" }, { "answer_id": 220353, "author": "tshak", "author_id": 22894, "author_profile": "https://Stackoverflow.com/users/22894", "pm_score": 0, "selected": false, "text": "string xmlText = File.ReadAllText(ManifestFile);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17519/" ]
218,113
<p>One thing that always been a pain is to log SQL (JDBC) errors when you have a PreparedStatement instead of the query itself.</p> <p>You always end up with messages like:</p> <pre><code>2008-10-20 09:19:48,114 ERROR LoggingQueueConsumer-52 [Logger.error:168] Error executing SQL: [INSERT INTO private_rooms_bans (room_id, name, user_id, msisdn, nickname) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE room_id = ?, name = ?, user_id = ?, msisdn = ?, nickname = ?] </code></pre> <p>Of course I could write a helper method for retrieving the values and parsing/substitute the question marks with real values (and probably will go down that path if I don't get an outcome of this question), but I just wanted to know if this problem was resolved before by someone else and/or if is there any generic logging helper that would do that automagically for me.</p> <p><strong>Edited after a few answers:</strong></p> <p>The libraries provided so far seems to be suitable to logging the statements for debugging, which no doubt is useful. However, I am looking to a way of taking a PreparedStatement itself (not some subclass) and logging its SQL statement whenever an error occur. I wouldn't like to deploy a production app with an alternate implementation of PreparedStatement. </p> <p>I guess what I am looking for an utility class, not a PreparedStatement specialization.</p> <p>Thanks!</p>
[ { "answer_id": 3468960, "author": "user418544", "author_id": 418544, "author_profile": "https://Stackoverflow.com/users/418544", "pm_score": 4, "selected": true, "text": "jdbc.url=jdbc:log4jdbc:hsqldb:mem:sample\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14540/" ]
218,117
<p>Today when I was in computer organization class, teacher talked about something interesting to me. When it comes to talk about Why cache memory works, he said that:</p> <pre><code>for (i=0; i&lt;M; i++) for(j=0; j&lt;N; j++) X[i][j] = X[i][j] + K; //X is double(8 bytes) </code></pre> <p>it is not good to change the first line with the second. What is your opinions on this? And why it is like that?</p>
[ { "answer_id": 218152, "author": "Scottie T", "author_id": 6688, "author_profile": "https://Stackoverflow.com/users/6688", "pm_score": 2, "selected": false, "text": "do jj = 1,N\n do ii = 1,M\n x(ii,jj) = x(ii,jj) + K;\n enddo\nenddo\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26379/" ]
218,120
<p>I am interested in using Xaml with expression blend for creating user interfaces in an application. However, because of the limitations of the target architecture, I cannot use WPF or C#.</p> <p>So, what I am interested in is in any examples / existing projects or advice from anyone who has experiance of this technology on the use of Xaml in it's "Pure" form as a specification language not tied to WPF.</p> <p>Specific questions:</p> <p>1) Is it possible to use Blend + Xaml without the WPF elements, or without C# backing classes?</p> <p>2) Are there any other implementations of Xaml parsers etc. which use different architectures, and can they work with blend or similar tools.</p> <p>3) Are there alternative editor / designer tools which can help in this situation?</p> <p>I am aware of the MyXaml and MycroXaml projects, and have found a lot of resources on the web about Xaml, but 99% of it relates directly to WPF. This is fine for understanding the concepts of Xaml, but doesn't help with the implimentation I need.</p> <p>Many thanks!</p>
[ { "answer_id": 1030188, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 1, "selected": false, "text": "windows = []\nREXML::XPath.each(doc, \"//Window\") do |xml|\n windows << Window.new(xml)\nend\n\n#... invoking ...\n\n@items = []\nxml.each_element(\"Canvas/*\") do |itemXML|\n @items << WindowItem.makeItem(itemXML)\nend\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15667/" ]
218,122
<p>When using webforms the appropriate place to assign master pages to a page dynamically seems to be the pages PreInit event: </p> <pre><code>this.Master.MasterPageFile = "~/leaf.Master" </code></pre> <p>If nessasary, master pages in a hierarchy of nested master pages may be set here too:</p> <pre><code>this.Master.MasterPageFile = "~/leaf.Master" this.Master.Master.MasterPageFile = "~/root.Master" </code></pre> <p>Using the MVC framework you can set a single master page name dynamically using the controllers View method by passing the <em>masterName</em>, but how do you set other master pages higher up in the hierarchy?</p> <p><strong>Update</strong><br> Sorry I was not clear. </p> <p>By hierarchy i mean a chain of nested master pages, so how can i set the very top master page in a chain of nested master pages?</p> <p>For example we have a set up such that different customer types have different master pages and nested within this master page is an additional master page for specific user roles. We need to dynamically set the root customer master as well as the role master.</p>
[ { "answer_id": 218351, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 2, "selected": false, "text": " ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29547/" ]
218,123
<p>When I asked <a href="https://stackoverflow.com/questions/167575/should-a-project-manager-enforce-coding-standards">this question</a> I got almost always a definite yes you should have coding standards. </p> <p>What was the strangest coding standard rule that you were ever forced to follow?</p> <p>And by strangest I mean funniest, or worst, or just plain odd. </p> <p>In each answer, please mention which language, what your team size was, and which ill effects it caused you and your team.</p>
[ { "answer_id": 218135, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 8, "selected": false, "text": "int appCount = 0; // Number of apples.\nint pearCount = 0; // Number of pears.\n" }, { "answer_id": 218142, "author": "Ralph M. Rickenbach", "author_id": 4549416, "author_profile": "https://Stackoverflow.com/users/4549416", "pm_score": 3, "selected": false, "text": "if something then\nbegin\n ...\nend\nelse\nbegin\n ...\nend;\n" }, { "answer_id": 218188, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 4, "selected": false, "text": "IO" }, { "answer_id": 218203, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 8, "selected": false, "text": "int value = (a < b) ? a : b;\n" }, { "answer_id": 218222, "author": "azkotoki", "author_id": 28581, "author_profile": "https://Stackoverflow.com/users/28581", "pm_score": 5, "selected": false, "text": "select id, name from people" }, { "answer_id": 218268, "author": "Michael Easter", "author_id": 12704, "author_profile": "https://Stackoverflow.com/users/12704", "pm_score": 7, "selected": false, "text": "if ( x == y ) \n {\n System.out.println(\"this is painful\");\n x = 0;\n y++;\n }\n" }, { "answer_id": 218414, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": false, "text": "PER_PERSON\n PER_ID\n PER_NameFirst\n PER_NameLast\n ...\nCAT_CAT\n CAT_ID\n CAT_Name\n CAT_Breed\n ...\nDOG_DOG\n DOG_ID\n DOG_Name\n DOG_Breed\n ...\nPERCD_PERSON_CAT_DOG (for the join data)\n PERCD_ID\n PERCD_PER_ID\n PERCD_CAT_ID\n PERCD_DOG_ID\n" }, { "answer_id": 218824, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 5, "selected": false, "text": "NABC_The_Package_Name.X := NABC_The_Package_Name.X + \n CXYZ_Some_Other_Package_Name.Delta_X;\n" }, { "answer_id": 219134, "author": "Kristof Neirynck", "author_id": 11451, "author_profile": "https://Stackoverflow.com/users/11451", "pm_score": 7, "selected": false, "text": "-- doesn't work\nselect * from 0examples;\n\n-- does work\nselect * from [0examples];\n" }, { "answer_id": 219855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": " for(int i = 0; i < 10; i++)\n {\nmyFunc();\n }\n" }, { "answer_id": 219874, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 7, "selected": false, "text": "while (true) {\n" }, { "answer_id": 219940, "author": "Adam Straughan", "author_id": 14019, "author_profile": "https://Stackoverflow.com/users/14019", "pm_score": 6, "selected": false, "text": "if (bob EQ 7 AND alice LEQ 10)\n{\n // blah\n}\n" }, { "answer_id": 220287, "author": "billmcc", "author_id": 13213, "author_profile": "https://Stackoverflow.com/users/13213", "pm_score": 7, "selected": false, "text": "#define BEGIN {\n#define END }\n" }, { "answer_id": 220485, "author": "Jason Sundram", "author_id": 2683, "author_profile": "https://Stackoverflow.com/users/2683", "pm_score": 0, "selected": false, "text": "int numberofCycles_;\n" }, { "answer_id": 220559, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 4, "selected": false, "text": "/// <comment>\n/// </comment>\n/// <table>\n/// <thead>\n/// <tcolumns>\n/// <column>Date</column>\n/// <column>Modified By</column>\n/// <column>Comment</column>\n/// </tcolumns>\n/// </thead>\n/// <rows>\n/// <row>\n/// <column>10/10/2006</column>\n/// <column>Fred</column>\n/// <column>Created function</column>\n/// </row>\n/// </rows>\n/// <parameters>\n" }, { "answer_id": 220591, "author": "Hans", "author_id": 24031, "author_profile": "https://Stackoverflow.com/users/24031", "pm_score": 2, "selected": false, "text": "this->" }, { "answer_id": 221510, "author": "Daniel Rikowski", "author_id": 23368, "author_profile": "https://Stackoverflow.com/users/23368", "pm_score": 6, "selected": false, "text": "customer.reserve_field_14" }, { "answer_id": 222094, "author": "DarthNoodles", "author_id": 24854, "author_profile": "https://Stackoverflow.com/users/24854", "pm_score": 3, "selected": false, "text": "/*********...80charswide...***\n * START INSPECT\n */\n\n some changed code...\n\n /*\n * END INSPECT\n *********...80charswide...****/\n" }, { "answer_id": 279107, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "if (test)\n{\n int i;\n ...\n}\n" }, { "answer_id": 371441, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 3, "selected": false, "text": "int someInt = 5 ;\n" }, { "answer_id": 447508, "author": "Mark Thistle", "author_id": 54651, "author_profile": "https://Stackoverflow.com/users/54651", "pm_score": 3, "selected": false, "text": "void doSomething()\n{\n}\n//----------------------------------------------------------------------------\n" }, { "answer_id": 545833, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 2, "selected": false, "text": "SELECT this, that, `key` FROM sometable WHERE such AND suchmore;\n" }, { "answer_id": 546001, "author": "MunkiPhD", "author_id": 30816, "author_profile": "https://Stackoverflow.com/users/30816", "pm_score": 2, "selected": false, "text": "int x=0; //declare variable x and assign it to 0\n" }, { "answer_id": 649033, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 5, "selected": false, "text": "EVENT.LIST[DATE.INDEX][-1] = _ ;ADD THE MOST RECENT EVENT\n EVENTS[LEN(EVENTS)] ;TO THE END OF EVENT LIST\n" }, { "answer_id": 1060195, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "static" }, { "answer_id": 1357845, "author": "soru", "author_id": 132903, "author_profile": "https://Stackoverflow.com/users/132903", "pm_score": 5, "selected": false, "text": "a = 3 + 6 * 2;\n" }, { "answer_id": 1358589, "author": "Brian Surowiec", "author_id": 39605, "author_profile": "https://Stackoverflow.com/users/39605", "pm_score": 1, "selected": false, "text": "public class Record\n{\n private string tablename;\n private Database database;\n\n public NameValueCollection Fields;\n\n public Record(string TableName) : this(TableName, null) { }\n public Record(string TableName, Database db)\n {\n tablename = TableName;\n database = db;\n }\n\n public string TableName\n {\n get { return tablename; }\n }\n\n public ulong ID\n {\n get { return GetULong(\"ID\"); }\n set { Fields[\"ID\"] = value.ToString(); }\n\n }\n\n public virtual ulong GetULong(string field)\n {\n try { return ulong.Parse(this[field]); }\n catch(Exception) { return 0; }\n }\n\n public virtual bool Change()\n {\n InitializeDB(); // opens the connection\n // loop over the Fields object and build an update query\n DisposeDB(); // closes the connection\n // return the status\n }\n\n public virtual bool Create()\n {\n // works almost just like the Change method\n }\n\n public virtual bool Read()\n {\n InitializeDB(); // opens the connection\n // use the value of the ID property to build a select query\n // populate the Fields collection with the columns/values if the read was successful\n DisposeDB(); // closes the connection\n // return the status \n }\n}\n\npublic class User\n{\n public User() : base(\"User\") { }\n public User(Database db) : base(\"User\", db) { }\n\n public string Username\n {\n get { return Fields[\"Username\"]; }\n set\n {\n Fields[\"Username\"] = value.ToString(); // yes, there really is a redundant ToString call\n }\n }\n}\n" }, { "answer_id": 1450928, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "'Module Name\n'Module Description\n'Parameters and description of each parameter\n'Called by\n'Calls\n" }, { "answer_id": 1713149, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 1, "selected": false, "text": "System.IO\npublic void StartIO(Stream ioStream)\n" }, { "answer_id": 2094095, "author": "jammycakes", "author_id": 886, "author_profile": "https://Stackoverflow.com/users/886", "pm_score": 3, "selected": false, "text": "Try...Catch" }, { "answer_id": 3030879, "author": "Mark Simpson", "author_id": 83891, "author_profile": "https://Stackoverflow.com/users/83891", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Add an item to the collection\n/// </summary>\n/// <parameter name=\"item\">The item to add</parameter>\n/// <returns>Whether the addition succeeded</returns>\npublic bool Add(int item) { ... }\n" }, { "answer_id": 3544787, "author": "corydoras", "author_id": 150172, "author_profile": "https://Stackoverflow.com/users/150172", "pm_score": 3, "selected": false, "text": "hr_admin" }, { "answer_id": 3766478, "author": "Holgi", "author_id": 453961, "author_profile": "https://Stackoverflow.com/users/453961", "pm_score": 2, "selected": false, "text": "a &= ~(1 << i)\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
218,133
<p>I want to deserialize an object but don't know the class up front. So, consider the following code...</p> <pre><code>IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); MyObject obj = (MyObject)formatter.Deserialize(stream); </code></pre> <p>What could I do if I don't know the class up front? Say, for example "MyFile.bin" was a MyObject or a MyFoo. How do I determine which object to instantiate?</p> <p>Something like...</p> <pre><code>if (magic happens here == typeof(MyObject)) MyObject obj = (MyObject) formatter.Deserialize(stream); else if (more magic happens here == typeof(MyFoo)) MyFoo foo = (MyFoo)formatter.Deserialize(stream); </code></pre>
[ { "answer_id": 218141, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": true, "text": "object result = formatter.Deserialize(stream); \nType t = result.GetType();\n" }, { "answer_id": 218154, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "MyFoo foo = result As MyFoo;\nif(foo != null) { // it was one of those\n // special code\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893/" ]
218,144
<p>I'm wrapping up a <code>Javascript</code> widget in a <code>Wicket</code> component. I want to let the JS side talk to the component. What I've got so far:</p> <p>Component in question goes like</p> <pre><code>talker = new GridAjaxBehavior(); this.add(talker); </code></pre> <p>in constructor</p> <p>and then, later on, puts something like</p> <pre><code>"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");"; </code></pre> <p>into the JS.</p> <p>where <code>GridAjaxBehavior</code> extends <code>AbstractDefaultAjaxBehavior</code>. I want GridAjaxBehavior to spit back some XML when the JS calls it. </p> <p>Am I doing this the right way? What should GridAjaxBehaviour do to spit back the XML?</p> <p>Thanks</p>
[ { "answer_id": 713544, "author": "Eric Ryan Harrison", "author_id": 79033, "author_profile": "https://Stackoverflow.com/users/79033", "pm_score": 0, "selected": false, "text": "\"var MyGridTalker = new talker(\" + this.talker.getCallbackUrl();" }, { "answer_id": 717457, "author": "tpdi", "author_id": 85931, "author_profile": "https://Stackoverflow.com/users/85931", "pm_score": 2, "selected": false, "text": "public AjaxChildNotifyingDropDownChoice(...code elided for clarity...) {\n this.child = child;\n\n // Ajax won't work without this:\n setOutputMarkupId(true);\n // \n add( new OnChangeAjaxBehavior() {\n @Override\n public void onUpdate(final AjaxRequestTarget target) {\n\n // tell child to update its list\n // based on newly selected value\n\n // when the Ajax is called, \n // my owning component's model\n // is already updated\n\n // note we could just type getModel()\n // I'm making explicit that we're calling it\n // on the enclosing class \n // (which a non-static inner class has a hidden ref to) \n child.setNewModelBasedOnSelectionOf( \n AjaxChildNotifyingDropDownChoice.this.getModel());\n\n // now add the child to the target\n // Wicket javascript will receive the new \n // options and re-render the child dropdown\n target.add(child);\n\n }\n });\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29574/" ]
218,150
<p>If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?</p>
[ { "answer_id": 218170, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 3, "selected": false, "text": "ArgumentException" }, { "answer_id": 218214, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "System.Exception" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127460/" ]
218,155
<p>To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.</p> <p>So, what's the correct way of doing such a thing? I've tried</p> <pre><code>panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); </code></pre> <p>but this won't work. What would you suggest?</p>
[ { "answer_id": 218259, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 5, "selected": false, "text": "frame.setContentPane(newContents());\nframe.revalidate(); // frame.pack() if you want to resize.\n" }, { "answer_id": 218357, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 5, "selected": false, "text": "JFrame frame=new JFrame();\nframe.getContentPane().add(new JPanel());\n" }, { "answer_id": 222239, "author": "ShawnD", "author_id": 6186, "author_profile": "https://Stackoverflow.com/users/6186", "pm_score": 3, "selected": false, "text": "myJFrame.getContentPane().removeAll()\nmyJFrame.getContentPane().invalidate()\n\nmyJFrame.getContentPane().add(newContentPanel)\nmyJFrame.getContentPane().revalidate()\n" }, { "answer_id": 896462, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "public class PanelTest extends JFrame {\n\n Container contentPane;\n\n public PanelTest() {\n super(\"Changing JPanel inside a JFrame\");\n contentPane=getContentPane();\n }\n\n public void createChangePanel() {\n contentPane.removeAll();\n JPanel newPanel=new JPanel();\n contentPane.add(newPanel);\n System.out.println(\"new panel created\");//for debugging purposes\n validate();\n setVisible(true);\n }\n}\n" }, { "answer_id": 6068965, "author": "Gabriel", "author_id": 762328, "author_profile": "https://Stackoverflow.com/users/762328", "pm_score": 1, "selected": false, "text": "// Hiding all components (JPanels) added to a container (ex: another JPanel)\nfor (Component component : this.container.getComponents()) {\n component.setVisible(false);\n}" }, { "answer_id": 9454510, "author": "giannis christofakis", "author_id": 839554, "author_profile": "https://Stackoverflow.com/users/839554", "pm_score": 0, "selected": false, "text": "class Frame1 extends javax.swing.JFrame {\n\n remove(previouspanel); //or getContentPane().removeAll();\n\n add(newpanel); //or setContentPane(newpanel);\n\n invalidate(); validate(); // or ((JComponent) getContentPane()).revalidate();\n\n repaint(); //DO NOT FORGET REPAINT\n\n}\n" }, { "answer_id": 11876811, "author": "Dudu", "author_id": 1586522, "author_profile": "https://Stackoverflow.com/users/1586522", "pm_score": 0, "selected": false, "text": "ContentPane" }, { "answer_id": 68197712, "author": "Adnane Afifi", "author_id": 13686714, "author_profile": "https://Stackoverflow.com/users/13686714", "pm_score": 2, "selected": false, "text": "Game game = new Game();\ngetContentPane().removeAll(); \nsetContentPane(game); \ngetContentPane().revalidate(); //IMPORTANT\ngetContentPane().repaint(); //IMPORTANT\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15187/" ]
218,156
<p>The following code</p> <pre><code>number=1 if [[ $number =~ [0-9] ]] then echo matched fi </code></pre> <p>works. If I try to use quotes in the regex, however, it stops:</p> <pre><code>number=1 if [[ $number =~ "[0-9]" ]] then echo matched fi </code></pre> <p>I tried <code>"\[0-9\]"</code>, too. What am I missing?</p> <p>Funnily enough, <a href="http://www.tldp.org/LDP/abs/html/abs-guide.html#REGEXMATCHREF" rel="noreferrer">bash advanced scripting guide</a> suggests this should work.</p> <p>Bash version 3.2.39.</p>
[ { "answer_id": 218217, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "$ bash --version\nGNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)\nCopyright (C) 2007 Free Software Foundation, Inc.\n$ number=2\n$ if [[ $number =~ \"[0-9]\" ]]; then echo match; fi\n$ if [[ $number =~ [0-9] ]]; then echo match; fi\nmatch\n$ re=\"[0-9]\"\n$ if [[ $number =~ $re ]]; then echo MATCH; fi\nMATCH\n\n$ bash --version\nGNU bash, version 3.00.0(1)-release (i586-suse-linux)\nCopyright (C) 2004 Free Software Foundation, Inc.\n$ number=2\n$ if [[ $number =~ \"[0-9]\" ]]; then echo match; fi\nmatch\n$ if [[ \"$number\" =~ [0-9] ]]; then echo match; fi\nmatch\n" }, { "answer_id": 6497584, "author": "Nicholas Sushkin", "author_id": 789544, "author_profile": "https://Stackoverflow.com/users/789544", "pm_score": 5, "selected": false, "text": "$ shopt -u compat31\n$ shopt compat31\ncompat31 off\n$ set -x\n$ if [[ \"9\" =~ \"[0-9]\" ]]; then echo match; else echo no match; fi\n+ [[ 9 =~ \\[0-9] ]]\n+ echo no match\nno match\n" }, { "answer_id": 18728266, "author": "Ankur Agarwal", "author_id": 494074, "author_profile": "https://Stackoverflow.com/users/494074", "pm_score": 3, "selected": false, "text": " $ if [[ 234 =~ \"[0-9]\" ]]; then echo matches; fi # string match\n $ \n\n $ if [[ 234 =~ [0-9] ]]; then echo matches; fi # regex natch \n matches\n\n\n $ var=\"[0-9]\"\n\n $ if [[ 234 =~ $var ]]; then echo matches; fi # regex match\n matches\n\n\n $ if [[ 234 =~ \"$var\" ]]; then echo matches; fi # string match after substituting $var as [0-9]\n\n $ if [[ 'rss$var919' =~ \"$var\" ]]; then echo matches; fi # string match after substituting $var as [0-9]\n\n $ if [[ 'rss$var919' =~ $var ]]; then echo matches; fi # regex match after substituting $var as [0-9]\n matches\n\n\n $ if [[ \"rss\\$var919\" =~ \"$var\" ]]; then echo matches; fi # string match won't work\n\n $ if [[ \"rss\\\\$var919\" =~ \"$var\" ]]; then echo matches; fi # string match won't work\n\n\n $ if [[ \"rss'$var'\"\"919\" =~ \"$var\" ]]; then echo matches; fi # $var is substituted on LHS & RHS and then string match happens \n matches\n\n $ if [[ 'rss$var919' =~ \"\\$var\" ]]; then echo matches; fi # string match !\n matches\n\n\n\n $ if [[ 'rss$var919' =~ \"$var\" ]]; then echo matches; fi # string match failed\n $ \n\n $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches; fi # string match\n matches\n\n\n\n $ echo $var\n [0-9]\n\n $ \n\n $ if [[ abc123def =~ \"[0-9]\" ]]; then echo matches; fi\n\n $ if [[ abc123def =~ [0-9] ]]; then echo matches; fi\n matches\n\n $ if [[ 'rss$var919' =~ '$var' ]]; then echo matches; fi # string match due to single quotes on RHS $var matches $var\n matches\n\n\n $ if [[ 'rss$var919' =~ $var ]]; then echo matches; fi # Regex match \n matches\n $ if [[ 'rss$var' =~ $var ]]; then echo matches; fi # Above e.g. really is regex match and not string match\n $\n\n\n $ if [[ 'rss$var919[0-9]' =~ \"$var\" ]]; then echo matches; fi # string match RHS substituted and then matched\n matches\n\n $ if [[ 'rss$var919' =~ \"'$var'\" ]]; then echo matches; fi # trying to string match '$var' fails\n\n\n $ if [[ '$var' =~ \"'$var'\" ]]; then echo matches; fi # string match still fails as single quotes are omitted on RHS \n\n $ if [[ \\'$var\\' =~ \"'$var'\" ]]; then echo matches; fi # this string match works as single quotes are included now on RHS\n matches\n" }, { "answer_id": 21762673, "author": "Digital Trauma", "author_id": 2113226, "author_profile": "https://Stackoverflow.com/users/2113226", "pm_score": 3, "selected": false, "text": "$ number=1\n$ if [[ $number =~ $(echo \"[0-9]\") ]]; then echo matched; fi\nmatched\n$ \n" }, { "answer_id": 73324448, "author": "Near Privman", "author_id": 579103, "author_profile": "https://Stackoverflow.com/users/579103", "pm_score": 1, "selected": false, "text": "# Bash's built-in regular expression matching requires the regular expression\n# to be unqouted (see https://stackoverflow.com/q/218156), which makes it harder\n# to use some special characters, e.g., the dollar sign.\n# This wrapper works around the issue by using a local variable, which means the\n# quotes are not passed on to the regex engine.\nregex_match() {\n local string regex\n string=\"${1?}\"\n regex=\"${2?}\"\n # shellcheck disable=SC2046 `regex` is deliberately unquoted, see above.\n [[ \"${string}\" =~ ${regex} ]]\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8437/" ]
218,158
<p>Is there a nicer way of styling a <code>&lt;hr /&gt;</code> tag using CSS, that is cross-browser consistent and doesn't involve wrapping a <code>div</code> around it? I'm struggling to find one.</p> <p>The best way I have found, is as follows:</p> <p><strong>CSS</strong></p> <pre><code>.hr { height:20px; background: #fff url(nice-image.gif) no-repeat scroll center; } hr { display:none; } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class="hr"&gt;&lt;hr /&gt;&lt;/div&gt; </code></pre>
[ { "answer_id": 218165, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "block" }, { "answer_id": 218221, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 4, "selected": true, "text": "hr {\n border : 0;\n height : 15px;\n background : url(hr.gif) 0 0 no-repeat;\n margin : 1em 0;\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
218,162
<p>I have an XHTML strict page that has an invisible div that is controlled by Javascript. The div is set to transparent and visible by the script and a mouseover event to make the div opaque on hover.</p> <p>When someone using a browser (or firefox with noscript) without javascript the div simply remains invisible. The problem with this is that I do not want the content to be inaccessible. I also do not want to leave the div visible then use the script to make it transparent as the div is located at the bottom of the document and it causes a noticeable flicker whenever a page loads.</p> <p>I have tried using noscript tags to embed an additional style sheet that is only loaded for people without the luxury of Javascript but this fails the XHTML strict validation. Is there any other way to include extra styling information inside a noscript block that is XHTML valid?</p> <p><strong>Ed:</strong></p> <p>With a simple test case I get a validation error of: <strong>document type does not allow element "style" here.</strong> This is with an empty XHTML Strict document with a style element inside a noscript element. The noscript is inside the body.</p>
[ { "answer_id": 218176, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<noscript>" }, { "answer_id": 218917, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 5, "selected": true, "text": "noscript" }, { "answer_id": 337894, "author": "Andrew Duffy", "author_id": 42902, "author_profile": "https://Stackoverflow.com/users/42902", "pm_score": 4, "selected": false, "text": "script" }, { "answer_id": 1332058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<!doctype html>\n<html>\n <head>\n <noscript>\n <style>body{background:red}</style>\n </noscript>\n </head>\n <body>\n <p>is this red? it should <script>document.writeln(\"not\");</script> be. <noscript>indeed.</noscript></p>\n </body>\n</html>\n" }, { "answer_id": 8207484, "author": "renoirb", "author_id": 852395, "author_profile": "https://Stackoverflow.com/users/852395", "pm_score": 4, "selected": false, "text": "style" }, { "answer_id": 13460921, "author": "koppor", "author_id": 873282, "author_profile": "https://Stackoverflow.com/users/873282", "pm_score": 0, "selected": false, "text": ".hidden {\n visibility:hidden;\n}\n" }, { "answer_id": 38395681, "author": "mtb", "author_id": 5520058, "author_profile": "https://Stackoverflow.com/users/5520058", "pm_score": 2, "selected": false, "text": "<noscript>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11753/" ]
218,174
<p>I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).</p> <pre><code>$array1 = array(1 =&gt; 'a', 2 =&gt; 'b'); $array2 = array(3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Essentially I want to combine the two arrays as if it were something like this</p> <pre><code>$array3 = array(1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Thanks</p>
[ { "answer_id": 218198, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": true, "text": "$array3 = $array1 + $array2;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
218,181
<p>Is there a built-in way to URL encode a string in Excel VBA or do I need to hand roll this functionality? </p>
[ { "answer_id": 218199, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 8, "selected": true, "text": "URLEncode()" }, { "answer_id": 3812363, "author": "Tom", "author_id": 460541, "author_profile": "https://Stackoverflow.com/users/460541", "pm_score": 5, "selected": false, "text": "Private Const CP_UTF8 = 65001\n\n#If VBA7 Then\n Private Declare PtrSafe Function WideCharToMultiByte Lib \"kernel32\" ( _\n ByVal CodePage As Long, _\n ByVal dwFlags As Long, _\n ByVal lpWideCharStr As LongPtr, _\n ByVal cchWideChar As Long, _\n ByVal lpMultiByteStr As LongPtr, _\n ByVal cbMultiByte As Long, _\n ByVal lpDefaultChar As Long, _\n ByVal lpUsedDefaultChar As Long _\n ) As Long\n#Else\n Private Declare Function WideCharToMultiByte Lib \"kernel32\" ( _\n ByVal CodePage As Long, _\n ByVal dwFlags As Long, _\n ByVal lpWideCharStr As Long, _\n ByVal cchWideChar As Long, _\n ByVal lpMultiByteStr As Long, _\n ByVal cbMultiByte As Long, _\n ByVal lpDefaultChar As Long, _\n ByVal lpUsedDefaultChar As Long _\n ) As Long\n#End If\n\nPublic Function UTF16To8(ByVal UTF16 As String) As String\nDim sBuffer As String\nDim lLength As Long\nIf UTF16 <> \"\" Then\n #If VBA7 Then\n lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, 0, 0, 0, 0)\n #Else\n lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, 0, 0, 0, 0)\n #End If\n sBuffer = Space$(lLength)\n #If VBA7 Then\n lLength = WideCharToMultiByte(CP_UTF8, 0, CLngPtr(StrPtr(UTF16)), -1, CLngPtr(StrPtr(sBuffer)), LenB(sBuffer), 0, 0)\n #Else\n lLength = WideCharToMultiByte(CP_UTF8, 0, StrPtr(UTF16), -1, StrPtr(sBuffer), LenB(sBuffer), 0, 0)\n #End If\n sBuffer = StrConv(sBuffer, vbUnicode)\n UTF16To8 = Left$(sBuffer, lLength - 1)\nElse\n UTF16To8 = \"\"\nEnd If\nEnd Function\n\nPublic Function URLEncode( _\n StringVal As String, _\n Optional SpaceAsPlus As Boolean = False, _\n Optional UTF8Encode As Boolean = True _\n) As String\n\nDim StringValCopy As String: StringValCopy = IIf(UTF8Encode, UTF16To8(StringVal), StringVal)\nDim StringLen As Long: StringLen = Len(StringValCopy)\n\nIf StringLen > 0 Then\n ReDim Result(StringLen) As String\n Dim I As Long, CharCode As Integer\n Dim Char As String, Space As String\n\n If SpaceAsPlus Then Space = \"+\" Else Space = \"%20\"\n\n For I = 1 To StringLen\n Char = Mid$(StringValCopy, I, 1)\n CharCode = Asc(Char)\n Select Case CharCode\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n Result(I) = Char\n Case 32\n Result(I) = Space\n Case 0 To 15\n Result(I) = \"%0\" & Hex(CharCode)\n Case Else\n Result(I) = \"%\" & Hex(CharCode)\n End Select\n Next I\n URLEncode = Join(Result, \"\")\n\nEnd If\nEnd Function\n" }, { "answer_id": 12158058, "author": "Michael-O", "author_id": 696632, "author_profile": "https://Stackoverflow.com/users/696632", "pm_score": 4, "selected": false, "text": "Dim ScriptEngine As ScriptControl\nSet ScriptEngine = New ScriptControl\nScriptEngine.Language = \"JScript\"\n\nScriptEngine.AddCode \"function encode(str) {return encodeURIComponent(str);}\"\nDim encoded As String\nencoded = ScriptEngine.Run(\"encode\", \"€ömE.sdfds\")\n" }, { "answer_id": 14495932, "author": "ozmike", "author_id": 334106, "author_profile": "https://Stackoverflow.com/users/334106", "pm_score": 4, "selected": false, "text": "Function encodeURL(str As String)\nDim ScriptEngine As ScriptControl\nSet ScriptEngine = New ScriptControl\nScriptEngine.Language = \"JScript\"\n\nScriptEngine.AddCode \"function encode(str) {return encodeURIComponent(str);}\"\nDim encoded As String\n\n\nencoded = ScriptEngine.Run(\"encode\", str)\nencodeURL = encoded\nEnd Function\n" }, { "answer_id": 17053561, "author": "Joshua Honig", "author_id": 842685, "author_profile": "https://Stackoverflow.com/users/842685", "pm_score": 2, "selected": false, "text": "Public Declare PtrSafe Sub Mem_Copy Lib \"kernel32\" _\n Alias \"RtlMoveMemory\" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)\n\nPublic Declare PtrSafe Sub Mem_Read2 Lib \"msvbvm60\" _\n Alias \"GetMem2\" (ByRef Source As Any, ByRef Destination As Any)\n\nPublic Function URLEncodePart(ByRef RawURL As String) As String\n\n Dim pChar As LongPtr, iChar As Integer, i As Long\n Dim strHex As String, pHex As LongPtr\n Dim strOut As String, pOut As LongPtr\n Dim pOutStart As LongPtr, pLo As LongPtr, pHi As LongPtr\n Dim lngLength As Long\n Dim cpyLength As Long\n Dim iStart As Long\n\n pChar = StrPtr(RawURL)\n If pChar = 0 Then Exit Function\n\n lngLength = Len(RawURL)\n strOut = Space(lngLength * 3)\n pOut = StrPtr(strOut)\n pOutStart = pOut\n strHex = \"0123456789ABCDEF\"\n pHex = StrPtr(strHex)\n\n iStart = 1\n For i = 1 To lngLength\n Mem_Read2 ByVal pChar, iChar\n Select Case iChar\n Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126\n ' Ok\n Case Else\n If iStart < i Then\n cpyLength = (i - iStart) * 2\n Mem_Copy ByVal pOut, ByVal pChar - cpyLength, cpyLength\n pOut = pOut + cpyLength\n End If\n\n pHi = pHex + ((iChar And &HF0) / 8)\n pLo = pHex + 2 * (iChar And &HF)\n\n Mem_Read2 37, ByVal pOut\n Mem_Read2 ByVal pHi, ByVal pOut + 2\n Mem_Read2 ByVal pLo, ByVal pOut + 4\n pOut = pOut + 6\n\n iStart = i + 1\n End Select\n pChar = pChar + 2\n Next\n\n If iStart <= lngLength Then\n cpyLength = (lngLength - iStart + 1) * 2\n Mem_Copy ByVal pOut, ByVal pChar - cpyLength, cpyLength\n pOut = pOut + cpyLength\n End If\n\n URLEncodePart = Left$(strOut, (pOut - pOutStart) / 2)\n\nEnd Function\n" }, { "answer_id": 22223068, "author": "Paul", "author_id": 2314900, "author_profile": "https://Stackoverflow.com/users/2314900", "pm_score": 0, "selected": false, "text": "Function macUriEncode(value As String) As String\n\n Dim script As String\n script = \"do shell script \" & \"\"\"/usr/bin/python -c 'import sys, urllib; print urllib.quote(sys.argv[1])' \"\"\" & Chr(38) & \" quoted form of \"\"\" & value & \"\"\"\"\n\n macUriEncode = MacScript(script)\n\nEnd Function\n" }, { "answer_id": 24301379, "author": "Jamie Bull", "author_id": 1706564, "author_profile": "https://Stackoverflow.com/users/1706564", "pm_score": 6, "selected": false, "text": "ENCODEURL" }, { "answer_id": 28923996, "author": "El Scripto", "author_id": 4539790, "author_profile": "https://Stackoverflow.com/users/4539790", "pm_score": 4, "selected": false, "text": "Public Function encodeURL(str As String)\n Dim ScriptEngine As Object\n Dim encoded As String\n\n Set ScriptEngine = CreateObject(\"scriptcontrol\")\n ScriptEngine.Language = \"JScript\"\n\n encoded = ScriptEngine.Run(\"encodeURIComponent\", str)\n\n encodeURL = encoded\nEnd Function\n" }, { "answer_id": 32611655, "author": "ndd", "author_id": 5342823, "author_profile": "https://Stackoverflow.com/users/5342823", "pm_score": 0, "selected": false, "text": "Public Function UTF8Encode( _\n StringToEncode As String, _\n Optional UsePlusRatherThanHexForSpace As Boolean = False _\n) As String\n\n Dim TempAns As String\n Dim TempChr As Long\n Dim CurChr As Long\n Dim Offset As Long\n Dim TempHex As String\n Dim CharToEncode As Long\n Dim TempAnsShort As String\n\n CurChr = 1\n\n Do Until CurChr - 1 = Len(StringToEncode)\n CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))\n' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024\n' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows\n\n Select Case CharToEncode\n' 7 U+0000 U+007F 1 0xxxxxxx\n Case 48 To 57, 65 To 90, 97 To 122\n TempAns = TempAns & Mid(StringToEncode, CurChr, 1)\n Case 32\n If UsePlusRatherThanHexForSpace = True Then\n TempAns = TempAns & \"+\"\n Else\n TempAns = TempAns & \"%\" & Hex(32)\n End If\n Case 0 To &H7F\n TempAns = TempAns + \"%\" + Hex(CharToEncode And &H7F)\n Case &H80 To &H7FF\n' 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx\n' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps\n' offset 192 = &HC0 = 1100 0000 b added to start of UTF-8 cyrillic char map at &H410\n CharToEncode = CharToEncode - 192 + &H410\n TempAnsShort = \"%\" & Right(\"0\" & Hex((CharToEncode And &H3F) Or &H80), 2)\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40) And &H1F) Or &HC0), 2) & TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n'' debug and development version\n'' CharToEncode = CharToEncode - 192 + &H410\n'' TempChr = (CharToEncode And &H3F) Or &H80\n'' TempHex = Hex(TempChr)\n'' TempAnsShort = \"%\" & Right(\"0\" & TempHex, 2)\n'' TempChr = ((CharToEncode And &H7C0) / &H40) Or &HC0\n'' TempChr = ((CharToEncode \\ &H40) And &H1F) Or &HC0\n'' TempHex = Hex(TempChr)\n'' TempAnsShort = \"%\" & Right(\"0\" & TempHex, 2) & TempAnsShort\n'' TempAns = TempAns + TempAnsShort\n\n Case &H800 To &HFFFF\n' 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx\n' not tested . Doesnot match Case condition... very strange\n MsgBox (\"Char to encode matched U+0800 U+FFFF: \" & CharToEncode & \" = &H\" & Hex(CharToEncode))\n'' CharToEncode = CharToEncode - 192 + &H410\n TempAnsShort = \"%\" & Right(\"0\" & Hex((CharToEncode And &H3F) Or &H80), 2)\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000) And &HF) Or &HE0), 2) & TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &H10000 To &H1FFFFF\n' 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched &H10000 &H1FFFFF: \" & CharToEncode & \" = &H\" & Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &H410\n TempAnsShort = \"%\" & Right(\"0\" & Hex((CharToEncode And &H3F) Or &H80), 2)\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40000) And &H7) Or &HF0), 2) & TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &H200000 To &H3FFFFFF\n' 26 U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched U+200000 U+3FFFFFF: \" & CharToEncode & \" = &H\" & Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &H410\n TempAnsShort = \"%\" & Right(\"0\" & Hex((CharToEncode And &H3F) Or &H80), 2)\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000000) And &H3) Or &HF8), 2) & TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case &H4000000 To &H7FFFFFFF\n' 31 U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx\n'' MsgBox (\"Char to encode matched U+4000000 U+7FFFFFFF: \" & CharToEncode & \" = &H\" & Hex(CharToEncode))\n' sample offset. tobe verified\n CharToEncode = CharToEncode - 192 + &H410\n TempAnsShort = \"%\" & Right(\"0\" & Hex((CharToEncode And &H3F) Or &H80), 2)\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H1000000) And &H3F) Or &H80), 2) & TempAnsShort\n TempAnsShort = \"%\" & Right(\"0\" & Hex(((CharToEncode \\ &H40000000) And &H1) Or &HFC), 2) & TempAnsShort\n TempAns = TempAns + TempAnsShort\n\n Case Else\n' somethig else\n' to be developped\n MsgBox (\"Char to encode not matched: \" & CharToEncode & \" = &H\" & Hex(CharToEncode))\n\n End Select\n\n CurChr = CurChr + 1\n Loop\n\n UTF8Encode = TempAns\nEnd Function\n" }, { "answer_id": 33537531, "author": "Jimit Rupani", "author_id": 5088258, "author_profile": "https://Stackoverflow.com/users/5088258", "pm_score": 0, "selected": false, "text": "Function URLEncode(ByVal str As String) As String\n Dim intLen As Integer\n Dim x As Integer\n Dim curChar As Long\n Dim newStr As String\n intLen = Len(str)\n newStr = \"\"\n\n For x = 1 To intLen\n curChar = Asc(Mid$(str, x, 1))\n\n If (curChar < 48 Or curChar > 57) And _\n (curChar < 65 Or curChar > 90) And _\n (curChar < 97 Or curChar > 122) Then\n newStr = newStr & \"%\" & Hex(curChar)\n Else\n newStr = newStr & Chr(curChar)\n End If\n Next x\n\n URLEncode = newStr\n End Function\n" }, { "answer_id": 34601029, "author": "omegastripes", "author_id": 2165759, "author_profile": "https://Stackoverflow.com/users/2165759", "pm_score": 3, "selected": false, "text": "htmlfile" }, { "answer_id": 38385767, "author": "francisaugusto", "author_id": 3715676, "author_profile": "https://Stackoverflow.com/users/3715676", "pm_score": 0, "selected": false, "text": "select case" }, { "answer_id": 49502477, "author": "Florent B.", "author_id": 2887618, "author_profile": "https://Stackoverflow.com/users/2887618", "pm_score": 2, "selected": false, "text": "WorksheetFunction.EncodeUrl" }, { "answer_id": 53291144, "author": "ADJenks", "author_id": 5078765, "author_profile": "https://Stackoverflow.com/users/5078765", "pm_score": 0, "selected": false, "text": "encodeURIComponent()" }, { "answer_id": 60490097, "author": "Henrik Erlandsson", "author_id": 343825, "author_profile": "https://Stackoverflow.com/users/343825", "pm_score": 2, "selected": false, "text": "Public Function URLEncode(str As Variant) As String\n Dim i As Integer, sChar() As String, sPerc() As String\n sChar = Split(\"%|!|*|'|(|)|;|:|@|&|=|+|$|,|/|?|#|[|]| \", \"|\")\n sPerc = Split(\"%25 %21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D +\", \" \")\n URLEncode = Nz(str)\n For i = 0 To 19\n URLEncode = Replace(URLEncode, sChar(i), sPerc(i))\n Next i\nEnd Function\n" }, { "answer_id": 71775940, "author": "Excel Hero", "author_id": 3566998, "author_profile": "https://Stackoverflow.com/users/3566998", "pm_score": -1, "selected": false, "text": "ENCODEURL()" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
218,190
<p>Object-relational mapping has been well discussed, including on here. I have experience with a few approaches and the pitfalls and compromises. True resolution seems like it requires changes to the OO or relational models themselves.</p> <p>If using a functional language, does the same problem present itself? It seems to me that these two paradigms should fit together better than OO and RDBMS. The idea of thinking in sets in an RDBMS seems to mesh with the automatic parallelism that functional approaches seem to promise. </p> <p>Does anyone have any interesting opinions or insights? What's the state of play in the industry?</p>
[ { "answer_id": 219446, "author": "Jonathan Tran", "author_id": 12887, "author_profile": "https://Stackoverflow.com/users/12887", "pm_score": 2, "selected": false, "text": "create table temp_foo_1 as select ...;\ncreate table temp_foo_2 as select ...;\n...\ncreate table foo_results as\n select * from temp_foo_n inner join temp_foo_1 ... inner join temp_foo_2 ...;\n" }, { "answer_id": 38142568, "author": "jmlamare", "author_id": 6537016, "author_profile": "https://Stackoverflow.com/users/6537016", "pm_score": 3, "selected": false, "text": "List<Person> persons = queryFactory.selectFrom(person)\n .where(\n person.firstName.eq(\"John\"),\n person.lastName.eq(\"Doe\"))\n .fetch();\n" }, { "answer_id": 52717720, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 4, "selected": false, "text": "MULTISET()" }, { "answer_id": 56097446, "author": "Lin Pengcheng", "author_id": 11485521, "author_profile": "https://Stackoverflow.com/users/11485521", "pm_score": 2, "selected": false, "text": " Clojure -> DBMS, Super Foxpro\n STM -> Transaction,MVCC\nPersistent Collections -> db, table, col\n hash-map -> indexed data\n Watch -> trigger, log\n Spec -> constraint\n Core API -> SQL, Built-in function\n function -> Stored Procedure\n Meta Data -> System Table\n\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14663/" ]
218,208
<p>I have a Makefile building many C files with long long command lines and we've cleaned up the output by having rules such as:</p> <pre><code>.c${MT}.doj: @echo "Compiling $&lt;";\ $(COMPILER) $(COPTS) -c -o $@ $&lt; </code></pre> <p>Now this is great as the @ suppresses the compilation line being emitted. But when we get an error, all we get is the error message, no command line. Can anyone think of a "neat" way to emit the command line? All I can think of doing is echoing it to a file and have a higher level make catch the error and cat the file. Hacky I know.</p>
[ { "answer_id": 218295, "author": "Rajish", "author_id": 29576, "author_profile": "https://Stackoverflow.com/users/29576", "pm_score": 4, "selected": true, "text": ".c${MT}.doj:\n @echo \"Compiling $<\";\\\n $(COMPILER) $(COPTS) -c -o $@ $< \\\n || echo \"Error in command: $(COMPILER) $(COPTS) -c -o $@ $<\" \\\n && false\n" }, { "answer_id": 218297, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 0, "selected": false, "text": "abc" }, { "answer_id": 10265312, "author": "Seth Kingsley", "author_id": 497813, "author_profile": "https://Stackoverflow.com/users/497813", "pm_score": 3, "selected": false, "text": "make" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,219
<p>I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this</p> <pre><code>document.getElementById('mytext').onkeypress = function (evt) { var e = evt || window.event; if (e.keyCode &amp;&amp; e.keyCode==46) e.keyCode = 44; else if (e.which &amp;&amp; e.which==46) { e.which = 44; } }; </code></pre> <p>but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?</p>
[ { "answer_id": 218225, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "window.onload = function () {\n var input = document.getElementById(\"mytext\");\n\n input.onkeypress = function () {\n var evt = arguments[0] || event;\n var char = String.fromCharCode(evt.which || evt.keyCode);\n\n // Is it a period?\n if (char == \".\") {\n // Replace it with a comma\n input.value += \",\";\n\n // Cancel the original event\n evt.cancelBubble = true;\n return false;\n }\n }\n};\n" }, { "answer_id": 218410, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 1, "selected": false, "text": "document.getElementById('mytext').onkeyup = function(){\n this.value = this.value.replace('.', ',');\n}\n" }, { "answer_id": 218707, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "event.preventDefault()" }, { "answer_id": 72490246, "author": "SethWhite", "author_id": 3803371, "author_profile": "https://Stackoverflow.com/users/3803371", "pm_score": 0, "selected": false, "text": " document.addEventListener('keydown', $event => {\n if($event.code === 'Period'){\n $event.preventDefault();\n let inputEl = document.querySelector(\"#my-input\");\n inputEl.setRangeText(\n ',',\n inputEl.selectionStart,\n inputEl.selectionEnd,\n \"end\"\n );\n }\n })\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27789/" ]
218,245
<p>Is there support in Ruby for (for lack of a better word) non-escaped (verbatim) strings?</p> <p>Like in C#:</p> <pre><code>@"c:\Program Files\" </code></pre> <p>...or in Tcl:</p> <pre><code>{c:\Program Files\} </code></pre>
[ { "answer_id": 218257, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 4, "selected": true, "text": "%" }, { "answer_id": 218271, "author": "Antonio Cangiano", "author_id": 6551, "author_profile": "https://Stackoverflow.com/users/6551", "pm_score": 2, "selected": false, "text": "string =<<SQL\n SELECT * \n FROM Book\n WHERE price > 100.00\n ORDER BY title;\nSQL\n" }, { "answer_id": 218272, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "mystring = %q[\"'\\t blahblahblah]\n" }, { "answer_id": 220103, "author": "Farrel", "author_id": 7889, "author_profile": "https://Stackoverflow.com/users/7889", "pm_score": 2, "selected": false, "text": ">> puts \"a\\tb\"\na b\n=> nil\n>> puts 'a\\tb'\na\\tb\n=> nil\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
218,255
<p>I'm a pretty active command line user and I have shell accounts all over the place. MacBooks, Linux desktop machines, Linux servers, Cygwin on XP, you name it.</p> <p>How can I keep my shell configuration (<code>.bashrc</code>, <code>.vimrc</code> etc.) in sync across all these machines using the limited tools available across all platforms?</p> <p>I have been using <code>rsync</code> in a pretty limited manner that involves manually copying some files over when I need them, but I want a standard way for setting up the same basic shell environment across all my machines. Tell me your shell account management strategy.</p>
[ { "answer_id": 6876048, "author": "mustpax", "author_id": 20476, "author_profile": "https://Stackoverflow.com/users/20476", "pm_score": 5, "selected": true, "text": "$ ls ~/Dropbox/shell/bash\nbashbootstrap bashrc\nbashrc-Darwin bashrc-Darwin-laptopname bashrc-Darwin-mininame\nbashrc-Linux bashrc-Linux-machineone bashrc-Linux-machinetwo\n" }, { "answer_id": 69968041, "author": "Kyle", "author_id": 3786271, "author_profile": "https://Stackoverflow.com/users/3786271", "pm_score": 0, "selected": false, "text": "device1" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20476/" ]
218,256
<p>I used to be able to do the following in Preview 3</p> <pre><code>&lt;%=Html.BuildUrlFromExpression&lt;AController&gt;(c =&gt; c.AnAction(par1, par2)%&gt; </code></pre> <p>How am I supposed to create urls in a strongly typed way with the MVC Beta? The only thing so far I have found is </p> <pre><code>&lt;%= Html.ActionLink("aName", "ActionName", "ControllerName")%&gt; </code></pre> <p>This is not strongly typed off course.</p>
[ { "answer_id": 218280, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "Microsoft.Web.Mvc" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
218,264
<p>What's a good way to survive abnormally high traffic spikes?</p> <p>My thought is that at some trigger, my website should temporarily switch into a "low bandwidth" mode: switch to basic HTML pages, minimal graphics, disable widgets that might put unnecessary load on the database, and so-on.</p> <p>My thoughts are:</p> <ul> <li>Monitor CPU usage</li> <li>Monitor bandwidth</li> <li>Monitor requests / minute</li> </ul> <p>I am familiar with options like caching, switching to static content or a content delivery network, and so on as a means to survive, so perhaps the question should focus more on how one detects when the website is about to become overloaded. (Although answers on other survival methods are of course still more than welcome.) Lets say that the website is running Apache on Linux and PHP. This is probably the most common configuration and should allow the maximum number of people to gain assistance from the answers. Lets also assume that expensive options like buying another server and load balancing are unavailable - for most of us at least, a mention on Slashdot is going to be a once-in-a-lifetime occurrence, and not something we can spend money preparing for.</p>
[ { "answer_id": 77012, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 0, "selected": false, "text": "RewriteEngine on\nRewriteCond %{HTTP_REFERER} slashdot\\.org [NC]\nRewriteRule .* - [F]\n" }, { "answer_id": 83056, "author": "akraut", "author_id": 3971, "author_profile": "https://Stackoverflow.com/users/3971", "pm_score": 3, "selected": false, "text": "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\n\nRewriteCond %{HTTP_USER_AGENT} !^Googlebot\nRewriteCond %{HTTP_USER_AGENT} !^CoralWebPrx\nRewriteCond %{QUERY_STRING} !(^|&)coral-no-serve$\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?digg\\.com [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?slashdot\\.org [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?slashdot\\.com [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?fark\\.com [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?somethingawful\\.com [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?kuro5hin\\.org [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?engadget\\.com [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?boingboing\\.net [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?del\\.icio\\.us [OR]\nRewriteCond %{HTTP_REFERER} ^http://([^/]+\\.)?delicious\\.com\nRewriteRule ^(.*)?$ http://example.com.nyud.net/$1 [R,L]\n</IfModule>\n" }, { "answer_id": 407423, "author": "Nathacof", "author_id": 47440, "author_profile": "https://Stackoverflow.com/users/47440", "pm_score": 1, "selected": false, "text": "netstat -plant | awk '$4 ~ /:80\\>/ {print}' | wc -l" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17440/" ]
218,284
<p>I'd like to be able to read the mac address from the first active network adapter using VB.net or C# (using .NET 3.5 SP1) for a winform application</p>
[ { "answer_id": 218314, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": " Dim mc As System.Management.ManagementClass\n Dim mo As ManagementObject\n mc = New ManagementClass(\"Win32_NetworkAdapterConfiguration\")\n Dim moc As ManagementObjectCollection = mc.GetInstances()\n For Each mo In moc\n If mo.Item(\"IPEnabled\") = True Then\n ListBox1.Items.Add(\"MAC address \" & mo.Item(\"MacAddress\").ToString())\n End If\n Next\n" }, { "answer_id": 218338, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 5, "selected": false, "text": " foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())\n {\n if (nic.OperationalStatus == OperationalStatus.Up)\n {\n Console.WriteLine(nic.GetPhysicalAddress().ToString());\n break;\n }\n }\n" }, { "answer_id": 218443, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace MacAddress\n{\n class MacAddress\n {\n byte[] _address;\n\n public MacAddress(byte[] b)\n {\n if (b == null)\n throw new ArgumentNullException(\"b\");\n if (b.Length != 8)\n throw new ArgumentOutOfRangeException(\"b\");\n _address = new byte[b.Length];\n Array.Copy(b, _address, b.Length);\n }\n\n public byte[] Address { get { return _address; } }\n\n public override string ToString()\n {\n return Address[0].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[1].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[2].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[3].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[4].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture) + \":\" +\n Address[5].ToString(\"X2\", System.Globalization.CultureInfo.InvariantCulture);\n }\n\n public static List<MacAddress> GetMacAddresses()\n {\n int size = 0;\n // this chunk of code teases out the first adapter info\n int r = GetAdaptersInfo(null, ref size);\n if ((r != IPConfigConst.ERROR_SUCCESS) && (r != IPConfigConst.ERROR_BUFFER_OVERFLOW))\n {\n return null;\n }\n Byte[] buffer = new Byte[size];\n r = GetAdaptersInfo(buffer, ref size);\n if (r != IPConfigConst.ERROR_SUCCESS)\n {\n return null;\n }\n AdapterInfo Adapter = new AdapterInfo();\n ByteArray_To_IPAdapterInfo(ref Adapter, buffer, Marshal.SizeOf(Adapter));\n\n List<MacAddress> addresses = new List<MacAddress>();\n do\n {\n addresses.Add(new MacAddress(Adapter.Address));\n IntPtr p = Adapter.NextPointer;\n if (p != IntPtr.Zero)\n {\n IntPtr_To_IPAdapterInfo(ref Adapter, p, Marshal.SizeOf(Adapter));\n }\n else\n {\n break;\n }\n } while (true);\n return addresses;\n }\n\n // glue definitions into windows\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n private struct IPAddrString\n {\n public IntPtr NextPointer;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]\n public String IPAddressString;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4 * 4)]\n public String IPMaskString;\n public int Context;\n }\n\n private class IPConfigConst\n {\n public const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;\n public const int MAX_ADAPTER_NAME_LENGTH = 256;\n public const int MAX_ADAPTER_ADDRESS_LENGTH = 8;\n public const int ERROR_BUFFER_OVERFLOW = 111;\n public const int ERROR_SUCCESS = 0;\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n private struct AdapterInfo\n {\n public IntPtr NextPointer;\n public int ComboIndex;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_NAME_LENGTH + 4)]\n public string AdapterName;\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = IPConfigConst.MAX_ADAPTER_DESCRIPTION_LENGTH + 4)]\n public string Description;\n public int AddressLength;\n [MarshalAs(UnmanagedType.ByValArray, SizeConst = IPConfigConst.MAX_ADAPTER_ADDRESS_LENGTH)]\n public Byte[] Address;\n public int Index;\n public int Type;\n public int DhcpEnabled;\n public IntPtr CurrentIPAddress;\n public IPAddrString IPAddressList;\n public IPAddrString GatewayList;\n public IPAddrString DhcpServer;\n public Boolean HaveWins;\n public IPAddrString PrimaryWinsServer;\n public IPAddrString SecondaryWinsServer;\n public int LeaseObtained;\n public int LeaseExpires;\n }\n [DllImport(\"Iphlpapi.dll\", CharSet = CharSet.Auto)]\n private static extern int GetAdaptersInfo(Byte[] PAdapterInfoBuffer, ref int size);\n [DllImport(\"Kernel32.dll\", EntryPoint = \"CopyMemory\")]\n private static extern void ByteArray_To_IPAdapterInfo(ref AdapterInfo dst, Byte[] src, int size);\n [DllImport(\"Kernel32.dll\", EntryPoint = \"CopyMemory\")]\n private static extern void IntPtr_To_IPAdapterInfo(ref AdapterInfo dst, IntPtr src, int size);\n }\n}\n" }, { "answer_id": 5803033, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 2, "selected": false, "text": "using Linq..\n\nusing System.Net.NetworkInformation;\n..\n\nNetworkInterface nic =\n NetworkInterface.GetAllNetworkInterfaces()\n .Where(n => n.OperationalStatus == OperationalStatus.Up).FirstOrDefault();\n\nif (nic != null)\n return nic.GetPhysicalAddress().ToString();\n" }, { "answer_id": 17714400, "author": "charlitos1mx", "author_id": 2593899, "author_profile": "https://Stackoverflow.com/users/2593899", "pm_score": 0, "selected": false, "text": "Imports System.Net.NetworkInformation\n" }, { "answer_id": 24390098, "author": "AlainD", "author_id": 2377399, "author_profile": "https://Stackoverflow.com/users/2377399", "pm_score": 0, "selected": false, "text": "private const int MAX_ADAPTER_NAME_LENGTH = 256;\n[DllImport (\"iphlpapi.dll\", SetLastError = true)]\nprivate static extern int GetAdaptersInfo(byte[] abyAdaptor, ref int nSize);\n\n// ...\nprivate static string m_szAdaptorName = \"DM9CE1\";\n\n// ...\nprivate void GetNetworkAdaptorName()\n{\n // The initial call is to determine the size of the memory required. This will fail\n // with the error code \"111\" which is defined by MSDN to be \"ERROR_BUFFER_OVERFLOW\".\n // The structure size should be 640 bytes per adaptor.\n int nSize = 0;\n int nReturn = GetAdaptersInfo(null, ref nSize);\n\n // Allocate memory and get data\n byte[] abyAdapatorInfo = new byte[nSize];\n nReturn = GetAdaptersInfo(abyAdapatorInfo, ref nSize);\n if (nReturn == 0)\n {\n // Find the start and end bytes of the name in the returned structure\n int nStartNamePos = 8;\n int nEndNamePos = 8;\n while ((abyAdapatorInfo[nEndNamePos] != 0) &&\n ((nEndNamePos - nStartNamePos) < MAX_ADAPTER_NAME_LENGTH))\n {\n // Another character in the name\n nEndNamePos++;\n }\n\n // Convert the name from a byte array into a string\n m_szAdaptorName = Encoding.UTF8.GetString(\n abyAdapatorInfo, nStartNamePos, (nEndNamePos - nStartNamePos));\n }\n else\n {\n // Failed? Use a hard-coded network adaptor name.\n m_szAdaptorName = \"DM9CE1\";\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,322
<p>If I have a property:</p> <pre><code>public list&lt;String&gt; names { get; set; } </code></pre> <p>How can I generate and handle a custom Event for arguments sake called 'onNamesChanged' whenever a name gets added to the list?</p>
[ { "answer_id": 218347, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "class Foo {}\nclass FooCollection : Collection<Foo>\n{\n protected override void InsertItem(int index, Foo item)\n {\n // your code...\n base.InsertItem(index, item);\n }\n protected override void SetItem(int index, Foo item)\n {\n // your code...\n base.SetItem(index, item);\n }\n // etc\n}\n" }, { "answer_id": 218349, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "\n class Example\n {\n private BindingList<string> m_names = new BindingList<string>();\n public IEnumerable<string> Names { get { return m_names; } }\n public event AddingNewEventHandler NamesAdded\n {\n add { m_names.AddingNew += value; }\n remove { m_names.AddingNew -= value; }\n }\n public void Add(string name)\n {\n m_names.Add(name);\n }\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
218,335
<p>Is is possible to write MS SQL Server add-in? I'm thinking of some application integrated with database server available form SQL Server Enterprise Manager.</p>
[ { "answer_id": 218445, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 0, "selected": false, "text": "C:\\WINDOWS\\system32\\mmc.exe /32 \"C:\\WINDOWS\\system32\\SQLServerManager.msc\"\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15640/" ]
218,337
<p>i'm fairly new to NHibernate and although I'm finding tons of infos on NHibernate mapping on the web, I am too silly to find this piece of information.</p> <p>So the problem is, i've got the following Model:</p> <p><img src="https://i.stack.imgur.com/DihaU.jpg" alt="Datamodel"></p> <p>this is how I'd like it to look. One clean person that has two Address Properties. </p> <p>In the database I'd like to persist this in one table. So the Person row would have a ShippingStreetname and a Streetname Column, the one mapped to ShippingAddress.Streetname and the other to Address.StreetName</p> <p>I found an <a href="http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-2-value-objects.aspx" rel="nofollow noreferrer">article on fluent interfaces</a>, but still haven't figured out how to do this through the XML Configuration.</p> <p>Thanks in advance!</p> <p>Update: I found the solution to this by myself. This can be done through the node and works rather straightforward.</p> <p>To achieve the mapping of Address and ShippingAddress I just had to add the following to the </p> <pre><code>&lt;component name="Address" class="Address"&gt; &lt;property name="Streetname"&gt;&lt;/property&gt; &lt;property name="Zip"&gt;&lt;/property&gt; &lt;property name="City"&gt;&lt;/property&gt; &lt;property name="Country"&gt;&lt;/property&gt; &lt;/component&gt; &lt;component name="ShippingAddress" class="Address"&gt; &lt;property name="Streetname" column="ShippingStreetname" /&gt; &lt;property name="Zip" column="ShippingZip" /&gt; &lt;property name="City" column="ShippingCity" /&gt; &lt;property name="Country" column="ShippingCountry" /&gt; &lt;/component&gt; </code></pre>
[ { "answer_id": 218360, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<many-to-one name=\"ShippingAddress\" class=\"Yournamespace.Address\"/>\n<many-to-one name=\"Address\" class=\"Yournamespace.Address\"/>\n" }, { "answer_id": 218606, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 2, "selected": true, "text": "<component name=\"Address\" class=\"Address\">\n <property name=\"Streetname\"></property>\n <property name=\"Zip\"></property>\n <property name=\"City\"></property>\n <property name=\"Country\"></property>\n</component>\n\n<component name=\"ShippingAddress\" class=\"Address\">\n <property name=\"Streetname\" column=\"ShippingStreetname\" />\n <property name=\"Zip\" column=\"ShippingZip\" />\n <property name=\"City\" column=\"ShippingCity\" />\n <property name=\"Country\" column=\"ShippingCountry\" />\n</component>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
218,350
<p>Does Java Connection.close rollback into a finally block?.</p> <p>I know .Net SqlConnection.close does it.</p> <p>With this I could make try/finally blocks without catch...</p> <p>Example:</p> <pre><code>try { conn.setAutoCommit(false); ResultSet rs = executeQuery(conn, ...); .... executeNonQuery(conn, ...); .... conn.commit(); } finally { conn.close(); } </code></pre>
[ { "answer_id": 223138, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": false, "text": "try {\n conn.setAutoCommit(false);\n ResultSet rs = executeQuery(conn, ...);\n ....\n executeNonQuery(conn, ...);\n ....\n\n conn.commit();\n} finally {\n conn.rollback();\n conn.close();\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29600/" ]
218,359
<p>I have a custom class that implements that IComparable. This class is stored in a Generic List. I now need to compare to lists to see which objects are in list A but not in list B. </p> <p>I thought the most simple way of doing this would be to iterate through list B and do A.contains().</p> <p>I do not know how to get it to use my CompareTo() (or another method that I can override so that I can say if it contains a certain object or not). I could be wrong but as I understand it the contains checks if the objects are actually the same (i.e. points to the same place in memory).</p> <p>Could anyone help me please?</p>
[ { "answer_id": 218367, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "Equals" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6486/" ]
218,384
<p>What are Null Pointer Exceptions (<code>java.lang.NullPointerException</code>) and what causes them?</p> <p>What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?</p>
[ { "answer_id": 218390, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 10, "selected": false, "text": "NullPointerException" }, { "answer_id": 218394, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 9, "selected": false, "text": "null" }, { "answer_id": 218408, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 8, "selected": false, "text": "null" }, { "answer_id": 218510, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 13, "selected": true, "text": "int" }, { "answer_id": 219697, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 8, "selected": false, "text": "this" }, { "answer_id": 9043523, "author": "ashish bhatt", "author_id": 64135, "author_profile": "https://Stackoverflow.com/users/64135", "pm_score": 8, "selected": false, "text": "Object object;" }, { "answer_id": 16050670, "author": "nathan1138", "author_id": 2028133, "author_profile": "https://Stackoverflow.com/users/2028133", "pm_score": 9, "selected": false, "text": "null" }, { "answer_id": 18974045, "author": "javid piprani", "author_id": 760930, "author_profile": "https://Stackoverflow.com/users/760930", "pm_score": 8, "selected": false, "text": "public class Student {\n\n private int id;\n\n public int getId() {\n return this.id;\n }\n\n public setId(int newId) {\n this.id = newId;\n }\n}\n" }, { "answer_id": 23852556, "author": "Makoto", "author_id": 1079354, "author_profile": "https://Stackoverflow.com/users/1079354", "pm_score": 8, "selected": false, "text": "NullPointerException" }, { "answer_id": 24100776, "author": "fgb", "author_id": 298029, "author_profile": "https://Stackoverflow.com/users/298029", "pm_score": 10, "selected": false, "text": "synchronized" }, { "answer_id": 24347569, "author": "Stephen C", "author_id": 139985, "author_profile": "https://Stackoverflow.com/users/139985", "pm_score": 9, "selected": false, "text": "NullPointerException" }, { "answer_id": 24407197, "author": "L. G.", "author_id": 891479, "author_profile": "https://Stackoverflow.com/users/891479", "pm_score": 8, "selected": false, "text": "NullPointerException" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29182/" ]
218,388
<p>I want to stitch 2 pieces of png side by side. In Cocoa, I would use [NSImage initWithSize], and then just drawInRect. </p> <p>But UIImage don't have initWithSize class, how would I do this now?</p>
[ { "answer_id": 218454, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 4, "selected": true, "text": "UIGraphicsBeginImageContext()" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9774/" ]
218,399
<p>What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request?</p> <p>Using parameters:</p> <pre><code>var ajax = new Ajax.Request('server.php',{ parameters: 'store=11200&amp;product=Meat', onSuccess: function(myData){whatever} }); </code></pre> <p>Using URL:</p> <pre><code>var ajax = new Ajax.Request('server.php?store=11200&amp;product=Meat',{ onSuccess: function(myData){whatever} }); </code></pre>
[ { "answer_id": 218417, "author": "Evan DiBiase", "author_id": 2399475, "author_profile": "https://Stackoverflow.com/users/2399475", "pm_score": 5, "selected": true, "text": "parameters" }, { "answer_id": 218437, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "{store: 11200, product: \"Meat\"}" }, { "answer_id": 218513, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "new Ajax.Request('/myurl.php', {\n method: 'get',\n parameters: $('myForm').serialize(),\n onSuccess: successFunc(),\n onFailure: failFunc()\n}\n" }, { "answer_id": 219224, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 1, "selected": false, "text": "var ajax = new Ajax.Request('server.php',{\n parameters: {\n store: 11200,\n product: \"Meat\"\n }\n onSuccess: function(myData){whatever}\n});\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12579/" ]
218,405
<p>I've been testing an application using my machine as a server, and everything's going fine with it, but when I try to set it up to run on the test server, I get this error:</p> <blockquote> <p>Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154.</p> </blockquote> <p>Any ideas?</p> <p>Thanks</p>
[ { "answer_id": 218423, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 3, "selected": true, "text": "HKEY_CLASSES_ROOT\\CLSID\\{xxxx}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13244/" ]
218,439
<p>Suppose we have the following code:</p> <pre><code>ExpressionHelper.GetRouteValuesFromExpression&lt;AccountController&gt;(ax =&gt; ax.MyAction("a", "b")); </code></pre> <p>(from ASP.NET MVC Futures assembly). Method is reasonably fast - it executes 10k iterations in 150ms.</p> <p>Now, we change code to this:</p> <pre><code>string a = "a"; string b = "b"; ExpressionHelper.GetRouteValuesFromExpression&lt;AccountController&gt;(ax =&gt; ax.MyAction(a, b)); </code></pre> <p>This code will execute 10k iterations in 15 <strong>seconds</strong></p> <p>The problem is the following code:</p> <pre><code>Expression&lt;Func&lt;object&gt;&gt; lambdaExpression = Expression.Lambda&lt;Func&lt;object&gt;&gt;(Expression.Convert(arg, typeof (object))); Func&lt;object&gt; func = lambdaExpression.Compile(); value = func() </code></pre> <p>Is there a better way to get value from expression than compiling expression every time? This can greatly affect ASP.NET MVC link generation speed.</p>
[ { "answer_id": 218456, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "Dictionary<Expression<Action<T>>, Action<T>> m_Cache =\n new Dictionary<Expression<Action<T>>, Action<T>>();\n\npublic void GetRouteValuesFromExpression<T>(Expression<Action<T>> expr) {\n Action<T> compiled = null;\n if (!m_Cache.TryGetValue(expr, ref compiled)) {\n compiled = expr.Compile();\n m_Cached.Add(expr, compiled);\n }\n // execute …\n}\n" }, { "answer_id": 218581, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "Func<object>" }, { "answer_id": 218671, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "var body = (MethodCallExpression)expr.Body;\nvar arg1 = (MemberExpression)body.Arguments[0];\nvar contextType = arg1.Member.DeclaringType;\nvar field = contextType.GetField(arg1.Member.Name);\nConsole.WriteLine(field.GetValue(…));\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28912/" ]
218,451
<p>Part of my latest webapp needs to write to file a fair amount as part of its logging. One problem I've noticed is that if there are a few concurrent users, the writes <em>can</em> overwrite each other (instead of appending to file). I assume this is because of the destination file can be open in a number of places at the same time.</p> <p><code>flock(...)</code> is usually superb but it doesn't appear to work on NFS... Which is a huge problem for me as the production server uses a NFS array.</p> <p>The closest thing I've seen to an actual solution involves trying to create a lock dir and waiting until it can be created. To say this lacks elegance is understatement of the year, possibly decade.</p> <p>Any better ideas?</p> <p>Edit: I should add that I don't have root on the server and doing the storage in another way isn't really feasible any time soon, not least within my deadline.</p>
[ { "answer_id": 218460, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "flock()" }, { "answer_id": 218539, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "flock()" }, { "answer_id": 218790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if ($memcache->add($filename, 1, 1))\n{\n $memcache->delete($filename);\n}\n" }, { "answer_id": 275807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "while ! ln -s . lock; do :; done\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
218,461
<p>I would like to know what is the difference between initializing a static member inline as in:</p> <pre><code>class Foo { private static Bar bar_ = new Bar(); } </code></pre> <p>or initializing it inside the static constructor as in:</p> <pre><code>class Foo { static Foo() { bar_ = new Bar(); } private static Bar bar_; } </code></pre>
[ { "answer_id": 218477, "author": "Torbjørn", "author_id": 22621, "author_profile": "https://Stackoverflow.com/users/22621", "pm_score": 2, "selected": false, "text": "class Foo\n{\n private static IBar _bar;\n\n static Foo()\n {\n if(something)\n {\n _bar = new BarA();\n }\n else\n {\n _bar = new BarB();\n }\n }\n}\n" }, { "answer_id": 218719, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "For static members, static initializers \nStatic ctors (execute bottom up)\nBase static initializer\nBase static ctor and so on\n\nFor instance members, initializers in current class execute first\nThen initializers in base class execute ( up the chain)\nThen top-most base ctor is executed (and we walk down now. Instance ctors execute top-down)\nFinally current type's ctor is executed.\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10688/" ]
218,462
<p>Specifically, I want to copy a link (with text and location) and then to be able to paste it, e.g., into Word as a link.</p>
[ { "answer_id": 219223, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": false, "text": "var richText = \"<a href=\\\"\" + gContextMenu.linkURL + \"\\\">\" + gContextMenu.linkText() + \"</a>\";\nvar xfer = Components.classes[\"@mozilla.org/widget/transferable;1\"].createInstance(Components.interfaces.nsITransferable);\nxfer.addDataFlavor(\"text/html\");\n\nvar htmlString = Components.classes[\"@mozilla.org/supports-string;1\"].createInstance(Components.interfaces.nsISupportsString);\nhtmlString.data = richText;\nxfer.setTransferData(\"text/html\", htmlString, richText.length * 2);\n\nvar clipboard = Components.classes[\"@mozilla.org/widget/clipboard;1\"].getService(Components.interfaces.nsIClipboard);\nclipboard.setData(xfer, null, Components.interfaces.nsIClipboard.kGlobalClipboard);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224/" ]
218,466
<p>I'm having a hard time coding understanding the format of the specifier and string functions.</p> <p>My aim is to use <code>%[]</code> to readin all characters and spaces and then use the strcpy function followed by the strcat function.</p> <p>So far i've managed to enter individual characters and print them out, excluding spaces.</p> <p>here's the code so far;</p> <pre><code>int main(int argc, char** argv) { char words[30]; int loops; printf("How many letters would you like to enter? - "); scanf("%d",&amp;loops); for(int i=0;i&lt;loops;i++){ printf("Provide some text as input:"); scanf("%s", &amp;words[i]); } printf("%d", strlen(words)); printf("%s",&amp;words); return (EXIT_SUCCESS); } </code></pre>
[ { "answer_id": 218517, "author": "Peter Olsson", "author_id": 2703, "author_profile": "https://Stackoverflow.com/users/2703", "pm_score": 0, "selected": false, "text": "scanf(\"%c\", &words[i]);\n" }, { "answer_id": 218607, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "char phrase[30];\nprintf(\"Enter a phrase: \");\nscanf(\"%29[^\\n]\", phrase);\nprintf(\"You just entered: '%s'\\n\", phrase);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,472
<p>At a new job I started, we have both a Java application that handles most of the heavy lifting in the core business logic, and we also have a Rails application that of course handles the web interface to this server. Both of these access the same database.</p> <p>Up until now, most of the focus has been on the Java application, and as such, there are no migrations in the Rails project. The sql to update the shared database is managed in a file like changes.sql.</p> <p>As you can imagine, this makes it somewhat difficult to develop.</p> <p>My initial thought was to combine the codebases for the Java project and the Rails application, because there is a dependency there, and to manage that SQL file in the source. However, I thought I'd ask here to see if anyone else had tackled this issue with some degree of success.</p>
[ { "answer_id": 222753, "author": "rwc9u", "author_id": 7778, "author_profile": "https://Stackoverflow.com/users/7778", "pm_score": 1, "selected": false, "text": " # Use SQL instead of Active Record's schema dumper when creating the test database.\n # This is necessary if your schema can't be completely dumped by the schema dumper,\n # like if you have constraints or database-specific column types\n config.active_record.schema_format = :sql\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29104/" ]
218,488
<h2>Problem</h2> <p>I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest.<br> Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible.<br> Example of timestamped data:</p> <pre><code>struct STimestampedData { time_t m_timestamp; // Sorting criterion CData m_data; // Payload } </code></pre> <h2>Approach with <code>stl::vector</code>, <code>sort()</code> and <code>equal_range()</code></h2> <p>Since a <code>map</code> or <code>set</code> only allows me to find exact matches, I don't get any further using one of these. So now I have a <code>vector</code> to which I append data as it is coming in. Before searching I use <code>&lt;algorithm&gt;</code>'s <code>sort()</code> and supply it with a custom comparison function.<br> After that I use <code>&lt;algorithm&gt;</code>'s <code>equal_range()</code> to find the two neighbors of a specified value <code>x</code>. From these two values I check which one is closest to <code>x</code> and then I have my best match.</p> <p><br> While this is not too complex, I wonder if there are more elegant solutions to this.<br> Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here?</p> <h2>Update: Linear vs. binary search</h2> <p>I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly.<br> The reason I am sorting a vector with <code>sort()</code> is because it has random access iterators which is not the case with a <code>map</code>. Using a <code>map</code> would not allow <code>equal_range()</code> to do a search with twice logarithmic complexity.<br> Am I correct?</p>
[ { "answer_id": 218720, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "struct TimestampCompare\n{\n bool operator()(const STimestampedData & left, const STimestampedData & right) const\n {\n return left.m_timestamp < right.m_timestamp;\n }\n};\ntypedef std::set<STimestampedData,TimestampCompare> TimestampedDataSet;\n\nTimestampedDataSet::iterator FindClosest(TimestampedDataSet & data, STimestampedData & searchkey)\n{\n if (data.empty())\n return data.end();\n TimestampedDataSet::iterator upper = data.lower_bound(searchkey);\n if (upper == data.end())\n return --upper;\n if (upper == data.begin() || upper->m_timestamp == searchkey.m_timestamp)\n return upper;\n TimestampedDataSet::iterator lower = upper;\n --lower;\n if ((searchkey.m_timestamp - lower->m_timestamp) < (upper->m_timestamp - searchkey.m_timestamp))\n return lower;\n return upper;\n}\n" }, { "answer_id": 6508063, "author": "Waqas", "author_id": 819344, "author_profile": "https://Stackoverflow.com/users/819344", "pm_score": 0, "selected": false, "text": "//the function should return the element from iArr which has the least distance from input\ndouble nearestValue(vector<double> iArr, double input)\n{\n double pivot(0),temp(0),index(0);\n pivot = abs(iArr[0]-input);\n for(int m=1;m<iArr.size();m++)\n { \n temp = abs(iArr[m]-input);\n\n if(temp<pivot)\n {\n pivot = temp;\n index = m;\n }\n }\n\n return iArr[index];\n}\n\nvoid main()\n{\n vector<double> iArr;\n\n srand(time(NULL));\n for(int m=0;m<10;m++)\n {\n iArr.push_back(rand()%20);\n cout<<iArr[m]<<\" \";\n }\n\n cout<<\"\\nnearest value is: \"<<lib.nearestValue(iArr,16)<<\"\\n\";\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27596/" ]
218,491
<p>Is it possible to configure Windows Servers that reside on the same domain such that when a web service call is made from a web app using an IP address, the request does not go via a proxy server?</p> <p>The web service is running on one of the servers on the domain. </p> <p>I want to configure IP based security on the server that hosts the web service such that it only allows connections from specific servers. Currently all requests go via the proxy server rendering IPSec problematic.</p> <p>Within the browser I can specify that requests following a specific pattern should bypass the proxy server. It's essentially this behaviour I want to replicate with the servers.</p> <p>Thanks</p>
[ { "answer_id": 287023, "author": "Reiwoldt", "author_id": 29588, "author_profile": "https://Stackoverflow.com/users/29588", "pm_score": 1, "selected": true, "text": "Set xmlhttp = Server.CreateObject(\"Msxml2.ServerXMLHTTP.4.0\") \n\nxmlhttp.SetProxy 2,\"proxyname:port\", \"addresses that should bypass the proxy\"\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29588/" ]
218,507
<p>I have a home project that really needs to be in Source Control. I tried installing Subversion, which I have some experience with, but couldn't get it working. I don't particularly want to use SourceSafe. I'm a bit nervous about Git/Mercury as being somewhat cryptic, although this is only based on opinion rather than my experience.</p> <p>Main requirements are:</p> <ol> <li>Must be open source (well, it needs to be free but that sounds a bit cheap!)</li> <li>Must run on Win32</li> <li>Would prefer a GUI interface if one is available</li> </ol> <p>Many thanks in advance!</p> <p><strong>edit:</strong> Just to let you all know, I installed VisualSVN and had it working in no time. Thanks for the great advice.</p>
[ { "answer_id": 237818, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "git" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25462/" ]
218,512
<p>I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?</p>
[ { "answer_id": 218576, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": 5, "selected": false, "text": "ispell" }, { "answer_id": 218630, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": 7, "selected": true, "text": "M-x ispell-change-dictionary\n" }, { "answer_id": 13035639, "author": "boclodoa", "author_id": 1768960, "author_profile": "https://Stackoverflow.com/users/1768960", "pm_score": 5, "selected": false, "text": "%%% Local Variables:\n%%% ispell-local-dictionary: \"british\"\n%%% End:\n" }, { "answer_id": 27044941, "author": "oracleyue", "author_id": 3491484, "author_profile": "https://Stackoverflow.com/users/3491484", "pm_score": 4, "selected": false, "text": "M-x ispell-change-dictionary" }, { "answer_id": 30855069, "author": "spookylukey", "author_id": 182604, "author_profile": "https://Stackoverflow.com/users/182604", "pm_score": 2, "selected": false, "text": ".dir-locals.el" }, { "answer_id": 51846570, "author": "return42", "author_id": 300130, "author_profile": "https://Stackoverflow.com/users/300130", "pm_score": 2, "selected": false, "text": "(global-set-key [f7] 'spell-checker)\n\n(require 'ispell)\n(require 'flyspell)\n\n(defun spell-checker ()\n \"spell checker (on/off) with selectable dictionary\"\n (interactive)\n (if flyspell-mode\n (flyspell-mode-off)\n (progn\n (flyspell-mode)\n (ispell-change-dictionary\n (completing-read\n \"Use new dictionary (RET for *default*): \"\n (and (fboundp 'ispell-valid-dictionary-list)\n (mapcar 'list (ispell-valid-dictionary-list)))\n nil t))\n )))\n" }, { "answer_id": 70717060, "author": "Giacomo Indiveri", "author_id": 17936582, "author_profile": "https://Stackoverflow.com/users/17936582", "pm_score": 0, "selected": false, "text": ";; Toggle both distionary and input method with C-\\\n(let ((languages '(\"en\" \"it\" \"de\")))\n (setq ispell-languages-ring (make-ring (length languages)))\n (dolist (elem languages) (ring-insert ispell-languages-ring elem)))\n \n(defun ispell-cycle-languages ()\n (interactive)\n (let ((language (ring-ref ispell-languages-ring -1)))\n (ring-insert ispell-languages-ring language) \n (ispell-change-dictionary language)\n (cond\n ((string-match \"it\" language) (activate-input-method \"italian-postfix\"))\n ((string-match \"de\" language) (activate-input-method \"german-postfix\"))\n ((string-match \"en\" language) (deactivate-input-method)))))\n(define-key (current-global-map) [remap toggle-input-method] 'ispell-cycle-languages)\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900/" ]
218,522
<p>I have a Java servlet which generates xml, translates it with an xslt stylesheet, and then displays the resulting HTML. This is the first time I've worked with xslt. What's a good way to debug xslt? I have (or can get) some sample XML files to apply the transform too. But I'm not really even sure of the syntax so something that would give me syntax warnings would be great.</p>
[ { "answer_id": 2319729, "author": "chiborg", "author_id": 130121, "author_profile": "https://Stackoverflow.com/users/130121", "pm_score": 4, "selected": false, "text": "<xsl:message>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092/" ]
218,531
<p>I have a situation where I want to create a signature of a data structure:</p> <pre><code>my $signature = ds_to_sig( { foo =&gt; 'bar', baz =&gt; 'bundy', boing =&gt; undef, number =&gt; 1_234_567, } ); </code></pre> <p>The aim should be that if the data structure changes then so should the signature.</p> <p>Is there an established way to do this?</p>
[ { "answer_id": 218558, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "use Storable;\n$Storable::canonical = 1;\nsub ds_to_sig {\n my $structure = shift;\n return hash(freeze $structure);\n}\n" }, { "answer_id": 218598, "author": "friedo", "author_id": 20745, "author_profile": "https://Stackoverflow.com/users/20745", "pm_score": 4, "selected": true, "text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nuse Storable ('freeze');\n\n$Storable::canonical = 1;\n\nmy $one = { foo => 42, bar => [ 1, 2, 3 ] };\nmy $two = { foo => 42, bar => [ 1, 2, 3 ] };\n\nmy $one_s = freeze $one;\nmy $two_s = freeze $two;\n\nprint \"match\\n\" if $one_s eq $two_s;\n" }, { "answer_id": 218633, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "Digest::MD5->new->add(\n Data::Dumper->new([$structure])\n ->Purity(0)\n ->Terse(1)\n ->Indent(0)\n ->Useqq(1)\n ->Sortkeys(1)\n ->Dump()\n)->b64digest();\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5349/" ]
218,535
<p>I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with <em>iText</em> or a Word document with <em>Aspose.Words</em>. I need to preserve any formatting within the HTML documents (within reason, honouring &lt;b&gt; tags is a must, CSS like &lt;span style="blah"&gt; is a nice-to-have). </p> <p>Both iText and Aspose work (roughly) along the lines:</p> <pre><code>Document document = new Document( Size.A4, Aspect.PORTRAIT ); document.setFont( "Helvetica", 20, Font.BOLD ); document.insert( "some string" ) document.setBold( true ); document.insert( "A bold string" ); </code></pre> <p>Therefore (I think) I need some kind of HTML parser which will I can inspect for strings and styles to insert into my document.</p> <p>Can anybody suggest a good library or a sensible approach to this problem? Platform is Java</p>
[ { "answer_id": 219780, "author": "Craig Angus", "author_id": 15352, "author_profile": "https://Stackoverflow.com/users/15352", "pm_score": 3, "selected": true, "text": "<br>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29620/" ]
218,556
<p>I've been given a requirement for an internal web application to send documents to a printer transparently. The idea would be that the user can select their nearest printer, and the web application would send their print jobs to the printer they selected.</p> <p>The first printer we have to roll out against are Canons, so my questions is: How would I go about sending a document to print aross the network to a specific Canon? The type of Cannon is question is an iR5570 and the documents that will be said will mainly be Word and PDFs</p> <p>I'm currently working my way through the terrible, IE only Canon Developer site, but I'm kinda hoping someone can point me in the right direction or point me at a 3rd party assembly :)</p>
[ { "answer_id": 218677, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "System.Drawing.Printing" }, { "answer_id": 221818, "author": "Douglas Anderson", "author_id": 5678, "author_profile": "https://Stackoverflow.com/users/5678", "pm_score": 3, "selected": false, "text": "Microsoft.Office.Interop.Word.ApplicationClass msWord = new Microsoft.Office.Interop.Word.ApplicationClass();\n\nobject paramUnknown = Type.Missing;\nobject missing = Type.Missing;\nobject paramSaveChangesNo = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;\n//object paramFonts = Microsoft.Office.Interop.Word.wde\nobject paramFormatPDF = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;\nobject paramTrue = true;\nobject paramReadOnly = true; \nobject sourceDoc = @\"c:\\input.doc\" \nobject target = @\"c:\\output.pdf\";\n\nmsWord.Visible = false;\n\n//open .doc\nmsWord.Documents.Open(ref sourceDoc, ref paramUnknown, ref paramReadOnly, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown);\n\n//so it won't show on the taskbar\nmsWord.Application.Visible = false;\nmsWord.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;\n\n//save .doc to new target name and format\nmsWord.ActiveDocument.SaveAs(ref targetDoc, ref paramFormatPDF, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramTrue, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown, ref paramUnknown);\n\nmsWord.ActiveDocument.Close(ref missing, ref missing, ref missing);\n\nmsWord.Quit(ref paramSaveChangesNo, ref paramUnknown, ref paramUnknown);\n" }, { "answer_id": 11325934, "author": "masoud Cheragee", "author_id": 720242, "author_profile": "https://Stackoverflow.com/users/720242", "pm_score": -1, "selected": false, "text": "PdfFilePrinter p = new PdfFilePrinter();\n\np.PdfFileName = @\"c:\\1.pdf\";\np.Print();\np.PdfFileName = @\"c:\\2.pdf\";\np.Print();\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
218,563
<p>How can I implement the "tap and hold" behavior in an MFC CListCtrl?</p> <p>I have an MFC CListCtrl in a CDialog and I need to add to the CListCtrl the "tap and hold" behavior.</p> <p>That is what I mean for "tap and hold":</p> <p>If the user clicks (a "standard" click with the left button of the mouse) on a CListCtrl item then function A will be called.</p> <p>If the user click on a CListCtrl item and keep pressed down the left button of the mouse for more than one second then function B will be called.</p>
[ { "answer_id": 222166, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 1, "selected": false, "text": "BOOL CMyDialog::OnInitDialog() \n{\n MyListboxCtrl.SubclassDlgItem(ID_MYLISTBOX,this);\n CDialog::OnInitDialog();\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15485/" ]
218,573
<p>I've seen some developers put instance variable declarations at the end of classes though I mostly see them placed at the top. The only reasons I can think of for doing this are stylistic preference or maybe it somehow makes them easier to work with in an IDE. Is there a more legitimate reason for choosing this style?</p>
[ { "answer_id": 1411795, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 1, "selected": false, "text": "private" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1294/" ]
218,604
<p>For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?</p>
[ { "answer_id": 218620, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 2, "selected": false, "text": "whatmask 72.20.10.0/24\n" }, { "answer_id": 218648, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "int keepBits = 24; /* actually get it from somewhere else? */\n\nint mask = (0xffffffff >> (32 - keepBits )) << (32 - keepBits);\n" }, { "answer_id": 218661, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 1, "selected": false, "text": "int keepbits = 24;\nint mask = keepbits > 0 ? 0x00 - (1<<(32 - keepbits)) : 0xFFFFFFFF;\n" }, { "answer_id": 218748, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "uint32_t ipv4Netmask;\n\nipv4Netmask = UINT32_MAX;\nipv4Netmask <<= 32 - cidr;\nipv4Netmask = htonl(ipv4Netmask);\n" }, { "answer_id": 218826, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 0, "selected": false, "text": "option explicit\n\n'whatmask 72.20.10.0/24\nIf WScript.Arguments.Unnamed.Count < 1 Then\n WScript.Echo \"WhatMask xxx.xxx.xxx.xxx/xx\"\n Wscript.Quit\nEnd If\n\nDim sToFind\nDim aParts\nDim nSubnet\n\nsToFind = WScript.Arguments(0)\naParts = Split( sToFind, \"/\", 2 )\nnSubnet = aParts(1)\n\nif nSubnet < 1 or nSubnet > 32 then\n WScript.echo \"Subnet out of range [1..32]\"\n Wscript.quit\nend if\n\nDim sBinary\nsBinary = String( nSubnet, \"1\")\nsBinary = sBinary & String( 32 - nSubnet, \"0\" )\n\nwscript.echo \"0x\" & lcase( binary2hexadecimal( sBinary ) )\n\nfunction binary2hexadecimal( sBin )\n dim sSlice\n dim sResult\n dim i\n for i = 1 to len( sBin ) step 4\n sSlice = mid( sBin, i, 4 )\n sResult = sResult & hex( binary2decimal( sSlice ) )\n next\n binary2hexadecimal = sResult\nend function\n\nfunction binary2decimal( sFourbits )\n dim i\n dim bit\n dim nResult\n nResult = 0\n for i = 4 to 1 step -1\n bit = mid(sFourbits, i, 1 )\n nResult = nResult * 2 + bit\n next\n binary2decimal = nResult\nend function\n" }, { "answer_id": 583404, "author": "joeforker", "author_id": 36330, "author_profile": "https://Stackoverflow.com/users/36330", "pm_score": 2, "selected": true, "text": "int suffix = 24;\nint mask = 0xffffffff ^ 0xffffffff >> suffix;\n" }, { "answer_id": 2641483, "author": "Chris Weber", "author_id": 194653, "author_profile": "https://Stackoverflow.com/users/194653", "pm_score": -1, "selected": false, "text": "/* C# version merging some of the other contributions and corrected for byte order. */\n\nint cidr = 24;\n\nvar ipv4Netmask = 0xFFFFFFFF;\n\nipv4Netmask <<= 32 - cidr;\n\nbyte[] bytes = BitConverter.GetBytes(ipv4Netmask);\n\nArray.Reverse(bytes);\n\nipv4Netmask = BitConverter.ToUInt32(bytes, 0); \n\n// mask is now ready for use such as:\n\nvar netmask = new IPAddress(ipv4Netmask);\n" }, { "answer_id": 4462135, "author": "RichB", "author_id": 47056, "author_profile": "https://Stackoverflow.com/users/47056", "pm_score": 0, "selected": false, "text": "0xFFFFFFFF << 32 - cidr\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19655/" ]
218,613
<p>I hope there's a SharePoint expert here on SO who can help with this.</p> <p>Here's the problem. My SharePoint logs contain this line, several times:</p> <p><code>An SPRequest object was not disposed before the end of this thread. To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it. This object will now be disposed. Allocation Id: {8D090AD2-5D55-42C2-9873-2D5486FE257C} To determine where this object was allocated, create a registry key at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\HeapSettings. Then create a new DWORD named SPRequestStackTrace with the value 1 under this key.</code></p> <p>I edited the registry and added the key, but the stacktrace is nowhere to be found. It's not in the SharePoint logs or in the Event Viewer. </p> <p>I really need to find the source of these SPSite/SPWeb leaks and fix them, but I can't just start editing code that may or may not be the source of the problem. Does anyone have any suggestions?</p>
[ { "answer_id": 219179, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 1, "selected": false, "text": "try \n{\n //instantiate the SPSite and SPWeb with elevated privileges: \n SPSecurity.RunWithElevatedPrivileges(delegate() \n {\n using (SPSite mySite = new SPSite(url)) \n {\n using (myWeb = mySite.OpenWeb()) \n {\n //do stuff here\n }\n }\n });\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ]
218,616
<p>Given the Python function:</p> <pre><code>def a_method(arg1, arg2): pass </code></pre> <p>How can I extract the number and names of the arguments. I.e., given that I have a reference to <code>func</code>, I want the <code>func.[something]</code> to return <code>("arg1", "arg2")</code>.</p> <p>The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed <code>"a,b"</code> when I call <code>a_method("a", "b")</code>?</p>
[ { "answer_id": 218625, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 7, "selected": false, "text": "a_method.func_code.co_argcount\n" }, { "answer_id": 218709, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 10, "selected": true, "text": "inspect" }, { "answer_id": 220366, "author": "hlzr", "author_id": 19139, "author_profile": "https://Stackoverflow.com/users/19139", "pm_score": 4, "selected": false, "text": "class LogWrappedFunction(object):\n def __init__(self, function):\n self.function = function\n\n def logAndCall(self, *arguments, **namedArguments):\n print \"Calling %s with arguments %s and named arguments %s\" %\\\n (self.function.func_name, arguments, namedArguments)\n self.function.__call__(*arguments, **namedArguments)\n\ndef logwrap(function):\n return LogWrappedFunction(function).logAndCall\n\n@logwrap\ndef doSomething(spam, eggs, foo, bar):\n print \"Doing something totally awesome with %s and %s.\" % (spam, eggs)\n\n\ndoSomething(\"beans\",\"rice\", foo=\"wiggity\", bar=\"wack\")\n" }, { "answer_id": 2991341, "author": "Damian", "author_id": 288183, "author_profile": "https://Stackoverflow.com/users/288183", "pm_score": 4, "selected": false, "text": "\nIn [6]: def test(a, b):print locals()\n ...: \n\nIn [7]: test(1,2) \n{'a': 1, 'b': 2}\n" }, { "answer_id": 16542145, "author": "Mehdi Behrooz", "author_id": 748126, "author_profile": "https://Stackoverflow.com/users/748126", "pm_score": 5, "selected": false, "text": "import inspect, itertools \n\ndef my_decorator():\n\n def decorator(f):\n\n def wrapper(*args, **kwargs):\n\n # if you want arguments names as a list:\n args_name = inspect.getargspec(f)[0]\n print(args_name)\n\n # if you want names and values as a dictionary:\n args_dict = dict(itertools.izip(args_name, args))\n print(args_dict)\n\n # if you want values as a list:\n args_values = args_dict.values()\n print(args_values)\n" }, { "answer_id": 40363565, "author": "argaen", "author_id": 3481357, "author_profile": "https://Stackoverflow.com/users/3481357", "pm_score": 5, "selected": false, "text": "def _get_args_dict(fn, args, kwargs):\n args_names = fn.__code__.co_varnames[:fn.__code__.co_argcount]\n return {**dict(zip(args_names, args)), **kwargs}\n" }, { "answer_id": 41526819, "author": "jeromej", "author_id": 1524913, "author_profile": "https://Stackoverflow.com/users/1524913", "pm_score": -1, "selected": false, "text": "dir()" }, { "answer_id": 42949339, "author": "ASMik09", "author_id": 1981531, "author_profile": "https://Stackoverflow.com/users/1981531", "pm_score": 2, "selected": false, "text": "inspect.getfullargspec" }, { "answer_id": 44261531, "author": "lovesh", "author_id": 535962, "author_profile": "https://Stackoverflow.com/users/535962", "pm_score": 2, "selected": false, "text": "def get_func_args(f):\n if hasattr(f, 'args'):\n return f.args\n else:\n return list(inspect.signature(f).parameters)\n" }, { "answer_id": 45332292, "author": "Peter Majko", "author_id": 4528229, "author_profile": "https://Stackoverflow.com/users/4528229", "pm_score": 4, "selected": false, "text": "func_args = inspect.getargspec(function).args\n" }, { "answer_id": 45781963, "author": "Kfir Eisner", "author_id": 7337300, "author_profile": "https://Stackoverflow.com/users/7337300", "pm_score": 4, "selected": false, "text": "Signature" }, { "answer_id": 53715901, "author": "Alpha", "author_id": 1332656, "author_profile": "https://Stackoverflow.com/users/1332656", "pm_score": 2, "selected": false, "text": "*args" }, { "answer_id": 55160591, "author": "smarie", "author_id": 7262247, "author_profile": "https://Stackoverflow.com/users/7262247", "pm_score": 0, "selected": false, "text": "inspect.signature" }, { "answer_id": 57373751, "author": "dildeolupbiten", "author_id": 8016168, "author_profile": "https://Stackoverflow.com/users/8016168", "pm_score": 4, "selected": false, "text": "def get_parameters(func):\n keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]\n sorter = {j: i for i, j in enumerate(keys[::-1])} \n values = func.__defaults__[::-1]\n kwargs = {i: j for i, j in zip(keys, values)}\n sorted_args = tuple(\n sorted([i for i in keys if i not in kwargs], key=sorter.get)\n )\n sorted_kwargs = {\n i: kwargs[i] for i in sorted(kwargs.keys(), key=sorter.get)\n } \n return sorted_args, sorted_kwargs\n\n\ndef f(a, b, c=\"hello\", d=\"world\"): var = a\n \n\nprint(get_parameters(f))\n" }, { "answer_id": 57597386, "author": "Nikolay Makhalin", "author_id": 6408118, "author_profile": "https://Stackoverflow.com/users/6408118", "pm_score": 3, "selected": false, "text": "inspect.signature" }, { "answer_id": 69107403, "author": "Brisco", "author_id": 10603374, "author_profile": "https://Stackoverflow.com/users/10603374", "pm_score": -1, "selected": false, "text": "def print_func_name_and_args(func):\n \n def wrapper(*args, **kwargs):\n print(f\"Function name: '{func.__name__}' supplied args: '{args}'\")\n func(args[0], args[1], args[2])\n return wrapper\n\n\n@print_func_name_and_args\ndef my_function(n1, n2, n3):\n print(n1 * n2 * n3)\n \nmy_function(1, 2, 3)\n\n#Function name: 'my_function' supplied args: '(1, 2, 3)'\n" }, { "answer_id": 69762539, "author": "x4444", "author_id": 895676, "author_profile": "https://Stackoverflow.com/users/895676", "pm_score": -1, "selected": false, "text": "inspect" }, { "answer_id": 71565623, "author": "Jose Enrique", "author_id": 3308840, "author_profile": "https://Stackoverflow.com/users/3308840", "pm_score": 1, "selected": false, "text": "import inspect\n\n\nargs_names = inspect.signature(function).parameters.keys()\nargs_dict = {\n **dict(zip(args_names, args)),\n **kwargs,\n}\n\n\n" }, { "answer_id": 73114235, "author": "Thiago Lutten Leitão", "author_id": 19620075, "author_profile": "https://Stackoverflow.com/users/19620075", "pm_score": 0, "selected": false, "text": "parameters_list = list(inspect.signature(self.YOUR_FUNCTION).parameters))\n" }, { "answer_id": 74437996, "author": "Zio", "author_id": 13111269, "author_profile": "https://Stackoverflow.com/users/13111269", "pm_score": 0, "selected": false, "text": "import inspect\n\ndef get_arguments(func, args, kwargs, is_method=False):\n offset = 1 if is_method else 0\n specs = inspect.getfullargspec(func)\n d = {}\n for i, parameter in enumerate(specs.args[offset:]):\n i += offset\n if i < len(args):\n d[parameter] = args[i]\n elif parameter in kwargs:\n d[parameter] = kwargs[parameter]\n else:\n d[parameter] = specs.defaults[i - len(args)]\n return d\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
218,623
<p>I've seen a couple of font topics on SO and it seems a majority of people use monospace fonts for programming tasks. I have been using Verdana for programming for a couple of years and I really like the enhanced readability, without missing anything monospace related.</p> <p>Why do you use a monospace font?</p>
[ { "answer_id": 218639, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 7, "selected": false, "text": "Il 0O" }, { "answer_id": 218646, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 5, "selected": false, "text": "if ((var1 == FOO) && ((var2 == BAR) ||\n (var2 == FOOBAR)))\n" }, { "answer_id": 218749, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 7, "selected": false, "text": "!" }, { "answer_id": 218751, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "var expr = x => x + 1;\n" }, { "answer_id": 1651110, "author": "SLaks", "author_id": 34397, "author_profile": "https://Stackoverflow.com/users/34397", "pm_score": 3, "selected": false, "text": "lIiO0" }, { "answer_id": 3375951, "author": "bwerks", "author_id": 307163, "author_profile": "https://Stackoverflow.com/users/307163", "pm_score": 5, "selected": false, "text": "identifier.Method().Property.ToString();\nidentifier.Method().OtherGuy.ToString(); //how lined up and pretty!\nidentifier.Method().Sumthing.YouGetThePoint;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5409/" ]
218,638
<p>Using the ClearCase find command, how do I find all files in a directory that do not have the name pom.xml? </p> <p>I'd like to pass other selection options to the ClearCase find command so I'd prefer not to execute another command.</p> <p>I am using a RedHat linux version of ClearCase. I have tried "cleartool find ! -name pom.xml -print" and that does not work.</p> <p>PS: I do not use ClearCase by choice, it's mandated on my project. This is one of the reasons I hate it. I've read the man pages several times and see no clear way to do this that works!</p>
[ { "answer_id": 218976, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 2, "selected": false, "text": "cleartool ls -short -nxname | grep -v pom.xml\n" }, { "answer_id": 224759, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "#!/bin/sh\nif [ $1 != $2 ] ; then\n echo $1\nfi\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476/" ]
218,663
<p>I work for a custom cabinetry manufacturer and we write our own pricing program for our product. I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet. I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up. Is there any way in Access VBA to know whether the new record is being pasted or entered manually?</p>
[ { "answer_id": 218783, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Option Compare Database\nPublic gvarPasted As Boolean\n\nPrivate Sub txtText_AfterUpdate()\nIf Not gvarPasted Then\n 'Open pop-up here\nElse\n gvarPasted = False\nEnd If\nEnd Sub\n\nPrivate Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer)\n'Detect ctrl-V combination\nIf Shift = acCtrlMask And KeyCode = vbKeyV Then\n gvarPasted = True\nEnd If\nEnd Sub\n" }, { "answer_id": 218958, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": true, "text": "Public gvarPasted As Boolean\n\nFunction AssignVar()\n gvarPasted = True\n DoCmd.RunCommand acCmdPaste\nEnd Function\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4549/" ]
218,680
<p>I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.</p> <p>I can of course do a Regex.IsMatch() inside a try/catch and see if it blows up that way, but are there any smarter ways of doing it? Speed is not an issue as such, I just prefer to avoid throwing exceptions for no reason.</p>
[ { "answer_id": 218716, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "System.Text.RegularExpressions.RegexNode.ScanRegex()" }, { "answer_id": 1775017, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 6, "selected": false, "text": "private static bool IsValidRegex(string pattern)\n{\n if (string.IsNullOrWhiteSpace(pattern)) return false;\n\n try\n {\n Regex.Match(\"\", pattern);\n }\n catch (ArgumentException)\n {\n return false;\n }\n\n return true;\n}\n" }, { "answer_id": 20140018, "author": "Niharika Singh", "author_id": 3020847, "author_profile": "https://Stackoverflow.com/users/3020847", "pm_score": -1, "selected": false, "text": "public static bool VerifyRegEx(string testPattern)\n{\n bool isValid = true;\n if ((testPattern != null) && (testPattern.Trim().Length > 0))\n {\n try\n {\n Regex.Match(\"\", testPattern);\n }\n catch (ArgumentException)\n {\n // BAD PATTERN: Syntax error\n isValid = false;\n }\n }\n else\n {\n //BAD PATTERN: Pattern is null or blank\n isValid = false;\n }\n return (isValid);\n}\n" }, { "answer_id": 59981119, "author": "MiMFa", "author_id": 5258809, "author_profile": "https://Stackoverflow.com/users/5258809", "pm_score": 2, "selected": false, "text": " public static bool IsValidRegexPattern(string pattern, string testText = \"\", int maxSecondTimeOut = 20)\n {\n if (string.IsNullOrEmpty(pattern)) return false;\n Regex re = new Regex(pattern, RegexOptions.None, new TimeSpan(0, 0, maxSecondTimeOut));\n try { re.IsMatch(testText); }\n catch{ return false; } //ArgumentException or RegexMatchTimeoutException\n return true;\n }\n" }, { "answer_id": 72884286, "author": "Johan B", "author_id": 2886589, "author_profile": "https://Stackoverflow.com/users/2886589", "pm_score": 0, "selected": false, "text": "namespace ProgrammingTools.Regex\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text.RegularExpressions; \n\n public enum eValidregex { No, Yes, YesButUseCompare }\n\n public class RegEx_Validate\n {\n public static eValidregex IsValidRX ( string pattern , out Regex RX )\n {\n RX = null; \n\n if ( pattern.Length == 0 )\n return eValidregex.No;\n\n List<char> c1 = new List<char>\n {\n '\\\\' , '.' , '(' , ')' , '{' , '}' , '^' , '$' , '+' , '*' , '?' , '[' , ']', '|'\n };\n\n if ( c1.Count( e => pattern.Contains( e ) ) > 0 )\n {\n TimeSpan ts_timeout = new TimeSpan(days: 0,hours: 0,minutes: 0,seconds: 1,milliseconds: 0);\n\n try\n {\n RX = new Regex( pattern , RegexOptions.Compiled | RegexOptions.IgnoreCase , ts_timeout );\n return eValidregex.Yes;\n }\n catch ( ArgumentNullException )\n {\n return eValidregex.No;\n }\n catch ( ArgumentOutOfRangeException )\n {\n return eValidregex.No;\n }\n catch ( ArgumentException )\n {\n return eValidregex.No;\n }\n }\n else\n {\n return eValidregex.YesButUseCompare;\n }\n\n }\n\n }\n\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469/" ]
218,681
<p>The following code snippet illustrates a memory leak when opening XPS files. If you run it and watch the task manager, it will grow and not release memory until the app exits.</p> <p>'****** Console application BEGINS.</p> <pre><code>Module Main Const DefaultTestFilePath As String = "D:\Test.xps" Const DefaultLoopRuns As Integer = 1000 Public Sub Main(ByVal Args As String()) Dim PathToTestXps As String = DefaultTestFilePath Dim NumberOfLoops As Integer = DefaultLoopRuns If (Args.Count &gt;= 1) Then PathToTestXps = Args(0) If (Args.Count &gt;= 2) Then NumberOfLoops = CInt(Args(1)) Console.Clear() Console.WriteLine("Start - {0}", GC.GetTotalMemory(True)) For LoopCount As Integer = 1 To NumberOfLoops Console.CursorLeft = 0 Console.Write("Loop {0:d5}", LoopCount) ' The more complex the XPS document and the more loops, the more memory is lost. Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read) Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence ' This line leaks a chunk of memory each time, when commented out it does not. FixedDocSequence = XPSItem.GetFixedDocumentSequence End Using Next Console.WriteLine() GC.Collect() ' This line has no effect, I think the memory that has leaked is unmanaged (C++ XPS internals). Console.WriteLine("Complete - {0}", GC.GetTotalMemory(True)) Console.WriteLine("Loop complete but memory not released, will release when app exits (press a key to exit).") Console.ReadKey() End Sub End Module </code></pre> <p>'****** Console application ENDS.</p> <p>The reason it loops a thousand times is because my code processes lots of files and leaks memory quickly forcing an OutOfMemoryException. Forcing Garbage Collection does not work (I suspect it is an unmanaged chunk of memory in the XPS internals).</p> <p>The code was originally in another thread and class but has been simplified to this.</p> <p>Any help greatly appreciated.</p> <p>Ryan</p>
[ { "answer_id": 219165, "author": "Ryan O'Neill", "author_id": 26221, "author_profile": "https://Stackoverflow.com/users/26221", "pm_score": 4, "selected": true, "text": " Using XPSItem As New Windows.Xps.Packaging.XpsDocument(PathToTestXps, System.IO.FileAccess.Read)\n Dim FixedDocSequence As Windows.Documents.FixedDocumentSequence\n Dim DocPager As Windows.Documents.DocumentPaginator\n\n FixedDocSequence = XPSItem.GetFixedDocumentSequence\n DocPager = FixedDocSequence.DocumentPaginator\n DocPager.ComputePageCount()\n\n ' This is the fix, each page must be laid out otherwise resources are never released.'\n For PageIndex As Integer = 0 To DocPager.PageCount - 1\n DirectCast(DocPager.GetPage(PageIndex).Visual, Windows.Documents.FixedPage).UpdateLayout()\n Next\n FixedDocSequence = Nothing\n End Using\n" }, { "answer_id": 2410588, "author": "Sean Aitken", "author_id": 71524, "author_profile": "https://Stackoverflow.com/users/71524", "pm_score": 3, "selected": false, "text": "ContextLayoutManager.From(Dispatcher.CurrentDispatcher).UpdateLayout();\n" }, { "answer_id": 7102886, "author": "edrowland", "author_id": 514588, "author_profile": "https://Stackoverflow.com/users/514588", "pm_score": 0, "selected": false, "text": "DocumentPaginator paginator \n = document.GetFixedDocumentSequence().DocumentPaginator;\nint numberOfPages = paginator.ComputePageCount();\n\n\nfor (int i = 0; i < NumberOfPages; ++i)\n{\n DocumentPage docPage = paginator.GetPage(nPage);\n using (docPage) // using is *probably* correct.\n {\n // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n\n ((FixedPage)(docPage.Visual)).UpdateLayout();\n\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n // Adding THAT line cured my leak.\n\n RenderTargetBitmap bitmap = GetXpsPageAsBitmap(docPage, dpi);\n\n .... etc...\n }\n\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26221/" ]
218,691
<p>Is there a way to temporary swap Flex's main application to another then switch back. Scenario : Main app started, display login box - then go on with main app. Login box is an application as well. </p> <p>Application.application is a read only property, that attempt failed.</p>
[ { "answer_id": 220714, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 0, "selected": false, "text": "<mx:Application>\n <mx:ViewStack>\n <mx:Box> <!-- or whatever for login-->\n </mx:Box>\n <mx:Box> <!-- application UI widgets here -->\n </mx:Box>\n </mx:ViewStack>\n</mx:Application>\n" }, { "answer_id": 221956, "author": "ianmjones", "author_id": 3023, "author_profile": "https://Stackoverflow.com/users/3023", "pm_score": 2, "selected": false, "text": "private var mainModuleLogOnEventDispatcher:*;\n\n[Bindable]\nprivate var _logOnDetails:LogOnDetails = new LogOnDetails();\n\nprivate function onCreationComplete(event:Event):void\n{\n // Load log on module.\n loadMainModule(\"LogOnModule.swf\");\n\n // Pre-load main module while user is logging on.\n var mm:IModuleInfo = ModuleManager.getModule(\"MainModule.swf\");\n mm.load();\n}\n\n[Bindable]\nprivate function set logOnDetails(value:LogOnDetails):void\n{\n _logOnDetails = value;\n}\n\nprivate function get logOnDetails():LogOnDetails\n{\n return _logOnDetails;\n} \n\nprivate function loadMainModule(moduleName:String):void\n{\n // Unload anything already loaded.\n if (mainModule.url.length > 0)\n {\n mainModule.unloadModule();\n mainModule.url = \"\";\n }\n mainModule.addEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);\n mainModule.url = moduleName;\n}\n\nprivate function handleMainModuleReadyEvent(event:ModuleEvent):void\n{\n // Remove listener, we've caught the event now.\n mainModule.removeEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);\n\n // Add listeners to other events or apply data.\n if (mainModule.url == \"LogOnModule.swf\")\n {\n mainModuleLogOnEventDispatcher = mainModule.child;\n if (mainModule.child != null) {\n mainModuleLogOnEventDispatcher.addEventListener(\"logOnEvent\", handleLogOnEvent);\n }\n }\n if (mainModule.url == \"MainModule.swf\")\n {\n var mm:* = mainModule.child;\n if (mainModule.child != null)\n {\n mm.logOnDetails = logOnDetails;\n }\n } \n}\n\nprivate function handleLogOnEvent(logOnEvent:LogOnEvent):void\n{\n mainModuleLogOnEventDispatcher.removeEventListener(\"logOnEvent\", handleLogOnEvent);\n\n logOnDetails = logOnEvent.logOnDetails;\n\n // Now get person's details and swap in main module if successful.\n var parameters:Object = new Object();\n parameters.cmd = \"viewPerson\";\n parameters.token = logOnDetails.logOnToken;\n viewPersonRequest.send(parameters);\n}\n\nprivate function handleViewPersonRequestResult(event:ResultEvent):void\n{\n\n //*** Loads of setting logonDetails and error handling removed!!! ***//\n loadMainModule(\"MainModule.swf\");\n currentState = \"LoggedOn\";\n return;\n}\n\nprivate function onLogOff(event:MouseEvent):void\n{\n // Make sure we don't auto-logon when we log off.\n var logOnPrefs:SharedObject = SharedObject.getLocal(\"LogOn\", \"/\");\n logOnPrefs.data.loggedOff = true;\n\n var parameters:Object = new Object();\n parameters.cmd = \"logoff\";\n parameters.token = logOnDetails.logOnToken;\n logoffRequest.send(parameters);\n loadMainModule(\"LogOnModule.swf\");\n currentState = \"\";\n}\n\n<!-- *** Loads of view state related mxml removed *** -->\n<mx:VBox width=\"100%\" height=\"100%\" horizontalAlign=\"center\" verticalAlign=\"middle\" id=\"mainModuleVBox\">\n <basic:IJModuleLoader id=\"mainModule\" url=\"\" width=\"100%\" height=\"100%\" horizontalAlign=\"center\" verticalAlign=\"middle\"/>\n</mx:VBox>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,696
<p>Is there a generic way to clone objects in VBA? So that i could copy x to y instead of copying just the pointer?</p> <pre><code> Dim x As New Class1 Dim y As Class1 x.Color = 1 x.Height = 1 Set y = x y.Color = 2 Debug.Print "x.Color=" &amp; x.Color &amp; ", x.Height=" &amp; x.Height </code></pre> <p>By generic i mean something like <code>Set y = CloneObject(x)</code> rather than having to create my own method for the class copying its properties one by one.</p>
[ { "answer_id": 220060, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 4, "selected": true, "text": "Option Explicit\n\nPublic prop1 As Long\nPrivate DontCloneThis As Variant\n\nPublic Property Get PrivateThing()\n PrivateThing = DontCloneThis\nEnd Property\n\nPublic Property Let PrivateThing(value)\n DontCloneThis = value\nEnd Property\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ]
218,732
<p>In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded. I would like to execute some logic after the form has loaded.</p> <p>Can anyone advise on a solution?</p>
[ { "answer_id": 218740, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": false, "text": "this.BeginInvoke((MethodInvoker) delegate {\n // some code\n});\n" }, { "answer_id": 19086655, "author": "Sharmila", "author_id": 2829952, "author_profile": "https://Stackoverflow.com/users/2829952", "pm_score": 3, "selected": false, "text": "Form MessageForm = new Form();\nMessageForm.Shown += (s, e1) => { \n Thread t = new Thread(() => Thread.Sleep(1500)); \n t.Start(); \n t.Join(); \n MessageForm.Close(); \n};\n" }, { "answer_id": 30114883, "author": "E Coder", "author_id": 3737230, "author_profile": "https://Stackoverflow.com/users/3737230", "pm_score": -1, "selected": false, "text": " LoadingForm.ActiveForm.Close();\n" }, { "answer_id": 32681376, "author": "Ahmed Sabry", "author_id": 4707576, "author_profile": "https://Stackoverflow.com/users/4707576", "pm_score": 3, "selected": false, "text": "private void Main_Load(object sender, System.EventArgs e)\n{\n //Register it to Start in Load \n //Starting from the Next time.\n this.Activated += AfterLoading;\n}\n\nprivate void AfterLoading(object sender, EventArgs e)\n{\n this.Activated -= AfterLoading;\n //Write your code here.\n}\n" }, { "answer_id": 49187186, "author": "Jamie", "author_id": 5340571, "author_profile": "https://Stackoverflow.com/users/5340571", "pm_score": 1, "selected": false, "text": "using System.Windows.Forms;\n" }, { "answer_id": 61083584, "author": "J. Fischlein", "author_id": 11512069, "author_profile": "https://Stackoverflow.com/users/11512069", "pm_score": 1, "selected": false, "text": " public Form1(string myFile)\n {\n InitializeComponent();\n this.Show();\n if (myFile != null)\n {\n OpenFile(myFile);\n }\n }\n\n private void OpenFile(string myFile = null)\n {\n MessageBox.Show(myFile);\n }\n" }, { "answer_id": 67451920, "author": "user3029478", "author_id": 3029478, "author_profile": "https://Stackoverflow.com/users/3029478", "pm_score": 2, "selected": false, "text": " private void Form1_Load(object sender, EventArgs e)\n {\n this.Shown += new EventHandler(Form1_Shown);\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324/" ]
218,733
<p>I have a <code>GridView</code> control in an Asp.net application, that has a <code>&lt;asp:buttonField&gt;</code> of <code>type="image"</code> and <code>CommandName="Delete"</code>.</p> <p>Is there any way to execute a piece of javascript before reaching the <code>OnRowDelete</code> event?</p> <p>I want just a simple confirm before deleting the row.</p> <p>Thanks!</p> <p><strong>EDIT</strong>: Please Note that <code>&lt;asp:ButtonField&gt;</code> tag <strong>does not have</strong> an <code>OnClientClick</code> attribute.</p>
[ { "answer_id": 218785, "author": "steve_c", "author_id": 769, "author_profile": "https://Stackoverflow.com/users/769", "pm_score": 6, "selected": true, "text": "<script type=\"text/javascript\">\n function confirmDelete()\n {\n return confirm(\"Are you sure you want to delete this?\");\n }\n</script>\n\n...\n\n<asp:TemplateField>\n <ItemTemplate>\n <asp:ImageButton ID=\"DeleteButton\" runat=\"server\"\n ImageUrl=\"...\" AlternateText=\"Delete\" ToolTip=\"Delete\"\n CommandName=\"Delete\" CommandArgument='<%# Eval(\"ID\") %>'\n OnClientClick=\"return confirmDelete();\" />\n </ItemTemplate>\n</asp:TemplateField>\n" }, { "answer_id": 219052, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 0, "selected": false, "text": "function confirmDeleteContact() {\n if (confirm(\"Are you sure you want to delete this contact?\")) {\n document.all.answer.value=\"yes\";\n } else {\n document.all.answer.value=\"no\";\n }\n}\n" }, { "answer_id": 219104, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "GridView" }, { "answer_id": 2358775, "author": "Tod Birdsall", "author_id": 29613, "author_profile": "https://Stackoverflow.com/users/29613", "pm_score": 4, "selected": false, "text": "<script type=\"text/javascript\"> \n $(\".deleteLink\").click(function() {\n return confirm('Are you sure you wish to delete this record?');\n });\n</script>\n\n...\n\n<asp:ButtonField ButtonType=\"Link\" Text=\"Delete\"\n CommandName=\"Delete\" ItemStyle-CssClass=\"deleteLink\" />\n" }, { "answer_id": 14798490, "author": "user1308314", "author_id": 1308314, "author_profile": "https://Stackoverflow.com/users/1308314", "pm_score": -1, "selected": false, "text": "using System.Windows.Forms;\n\nprotected void BorrowItem_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n\n if (e.CommandName == \"Delete\")\n {\n\n if (System.Windows.Forms.MessageBox.Show(\"Do you want to delete\", \"Delete\",MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) != System.Windows.Forms.DialogResult.OK)\n {\n return;\n }\n }\n//Continue execution...\n}\n\n//drimaster\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
218,744
<p>What are good reasons to prohibit inheritance in Java, for example by using final classes or classes using a single, private parameterless constructor? What are good reasons of making a method final?</p>
[ { "answer_id": 218774, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": false, "text": " String blah = someOtherString;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
218,747
<p>I have a problem with Visual C++ 2008. I have installed opencv and I've created a new program and I build it with no errors. However, it complains about not finding MSVCR90D.dll when debugging. In release mode there is no problem at all. </p> <p>I do have MSVCR90D.dll in one of Winsxs folders. Does anyone know a get-around to this problem? Is this a known bug? </p> <p>Gerard</p>
[ { "answer_id": 221238, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "/pb your.debug.exe" }, { "answer_id": 693992, "author": "x_x", "author_id": 84155, "author_profile": "https://Stackoverflow.com/users/84155", "pm_score": 3, "selected": false, "text": "C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\Debug_NonRedist\\x86\\Microsoft.VC90.DebugCRT" }, { "answer_id": 3158007, "author": "opie", "author_id": 381112, "author_profile": "https://Stackoverflow.com/users/381112", "pm_score": 0, "selected": false, "text": "\"C:\\WINDOWS\\WinSxS\\Manifests\"" }, { "answer_id": 66439937, "author": "Humayun Khan", "author_id": 4790414, "author_profile": "https://Stackoverflow.com/users/4790414", "pm_score": 0, "selected": false, "text": "type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b'\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,760
<p>Although elements like <code>&lt;div&gt;</code>s normally grow to fit their contents, using the <code>float</code> property can cause a startling problem for CSS newbies: <strong>If floated elements have non-floated parent elements, the parent will collapse.</strong></p> <p>For example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div style="float: left;"&gt;Div 1&lt;/div&gt; &lt;div style="float: left;"&gt;Div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The parent div in this example will <strong>not expand</strong> to contain its floated children - it will appear to have <code>height: 0</code>.</p> <h1>How do you solve this problem?</h1> <p><em>I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.</em></p> <h2>Solution 1</h2> <p>Float the parent.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="float: left;"&gt; &lt;div style="float: left;"&gt;Div 1&lt;/div&gt; &lt;div style="float: left;"&gt;Div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Pros</strong>: Semantic code.<br /> <strong>Cons</strong>: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?</p> <h2>Solution 2</h2> <p>Give the parent an explicit height.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="height: 300px;"&gt; &lt;div style="float: left;"&gt;Div 1&lt;/div&gt; &lt;div style="float: left;"&gt;Div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Pros</strong>: Semantic code.<br /> <strong>Cons</strong>: Not flexible - if the content changes or the browser is resized, the layout will break.</p> <h2>Solution 3</h2> <p>Append a &quot;spacer&quot; element inside the parent element, like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; &lt;div style="float: left;"&gt;Div 1&lt;/div&gt; &lt;div style="float: left;"&gt;Div 2&lt;/div&gt; &lt;div class="spacer" style="clear: both;"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Pros</strong>: Straightforward to code.<br /> <strong>Cons</strong>: Not semantic; the spacer div exists only as a layout hack.</p> <h2>Solution 4</h2> <p>Set parent to <code>overflow: auto</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="overflow: auto;"&gt; &lt;div style="float: left;"&gt;Div 1&lt;/div&gt; &lt;div style="float: left;"&gt;Div 2&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Pros</strong>: Doesn't require extra div.<br /> <strong>Cons</strong>: Seems like a hack - that's not the <code>overflow</code> property's stated purpose.</p> <h1>Comments? Other suggestions?</h1>
[ { "answer_id": 218799, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 6, "selected": false, "text": "overflow: auto" }, { "answer_id": 218809, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "overflow: auto" }, { "answer_id": 219487, "author": "Bryan A", "author_id": 29707, "author_profile": "https://Stackoverflow.com/users/29707", "pm_score": 3, "selected": false, "text": ".clear \n{\n clear: both;\n}\n" }, { "answer_id": 617189, "author": "DisgruntledGoat", "author_id": 37947, "author_profile": "https://Stackoverflow.com/users/37947", "pm_score": 3, "selected": false, "text": "inline-block" }, { "answer_id": 2373465, "author": "tybro0103", "author_id": 202875, "author_profile": "https://Stackoverflow.com/users/202875", "pm_score": 4, "selected": false, "text": "overflow:auto" }, { "answer_id": 2373514, "author": "Sarfraz", "author_id": 139459, "author_profile": "https://Stackoverflow.com/users/139459", "pm_score": 4, "selected": false, "text": "{ clear: both; }" }, { "answer_id": 11594657, "author": "João Paulo Macedo", "author_id": 1171873, "author_profile": "https://Stackoverflow.com/users/1171873", "pm_score": 2, "selected": false, "text": ".cf:after {\n content: \" \";\n display: block;\n visibility: hidden;\n height: 0;\n clear: both;\n}\n" }, { "answer_id": 11597829, "author": "A.M.K", "author_id": 900747, "author_profile": "https://Stackoverflow.com/users/900747", "pm_score": 9, "selected": false, "text": "<div class=\"clearfix\">\n <div style=\"float: left;\">Div 1</div>\n <div style=\"float: left;\">Div 2</div>\n</div>​\n" }, { "answer_id": 12554475, "author": "cssisashtandw3tooo", "author_id": 1692685, "author_profile": "https://Stackoverflow.com/users/1692685", "pm_score": 2, "selected": false, "text": "auto" }, { "answer_id": 18061246, "author": "jave.web", "author_id": 1835470, "author_profile": "https://Stackoverflow.com/users/1835470", "pm_score": 0, "selected": false, "text": "clear:both" }, { "answer_id": 19379043, "author": "Christian Gray", "author_id": 2881715, "author_profile": "https://Stackoverflow.com/users/2881715", "pm_score": 3, "selected": false, "text": ".clearfix:after {\n content: \".\";\n display: block;\n height: 0;\n clear: both;\n visibility: hidden;\n}\n\n.clearfix {\n display: inline-block;\n}\n\n* html .clearfix {\n height: 1%;\n}\n\n.clearfix {\n display: block;\n}\n" }, { "answer_id": 24516684, "author": "Leons Kalapurakal", "author_id": 3789139, "author_profile": "https://Stackoverflow.com/users/3789139", "pm_score": 2, "selected": false, "text": " <div style=\"clear:both\"></div>\n" }, { "answer_id": 27205635, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 4, "selected": false, "text": ".clearfix:before, .clearfix:after {\n content: \"\";\n display: table;\n}\n\n.clearfix:after {\n clear: both;\n}\n\n.clearfix {\n *zoom: 1;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
218,777
<p>Is it right to use a private constant in the following situation:</p> <p>Say I have a game with a lives variable and a startingLives variable. At the start of the game I set the lives variable to equal the startingLives variable. This is how I would normally do it:</p> <pre><code>private var lives:int = 0; private var startingLives:int = 3; private function startGame():void { lives = startingLives; } </code></pre> <p>(example code is ActionScript btw)</p> <p>My question is - should this really be:</p> <pre><code>private var lives:int = 0; private const STARTING_LIVES:int = 3; private function startGame():void { lives = STARTING_LIVES; } </code></pre> <p>StartingLives seems unlikely to change at runtime, so should I use a const, and change back to a variable if it turns out not to be constant? </p> <p>UPDATE: The consensus seems to be that this is a good use of a constant, but what about amdfan's suggestion that you may want to load the value in from a config file?</p>
[ { "answer_id": 218782, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 3, "selected": true, "text": "DEFAULT_STARTING_LIVES" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ]
218,786
<p>I keep on hearing about concurrent programing every where. Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?</p>
[ { "answer_id": 218817, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 7, "selected": true, "text": "std::thread" }, { "answer_id": 17737426, "author": "Marcus Thornton", "author_id": 2288882, "author_profile": "https://Stackoverflow.com/users/2288882", "pm_score": 1, "selected": false, "text": "fork()" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
218,794
<p>I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:</p> <pre><code>var form = $("form"); var action = form.attr("action"); var serializedForm = form.serialize(); $.post(action, serializedForm, function(data) { ... }); </code></pre> <p>The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.</p> <p>Is there a way to get the fields trimmed <strong>without</strong> doing the following:</p> <pre><code>$("#name").val( jQuery.trim( $("#name") ) ); </code></pre>
[ { "answer_id": 219013, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 3, "selected": false, "text": "$('input, textarea').each(function(){\n $(this).val(jQuery.trim($(this).val()));\n});\n" }, { "answer_id": 219018, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 1, "selected": false, "text": "$(\"input, textarea\").each(function(){\n $(this).val(jQuery.trim($(this).val()));\n});\n" }, { "answer_id": 219336, "author": "Jethro Larson", "author_id": 22425, "author_profile": "https://Stackoverflow.com/users/22425", "pm_score": 4, "selected": true, "text": "//Serialize form as array\nvar serializedForm = form.serializeArray();\n//trim values\nfor(var i =0, len = serializedForm.length;i<len;i++){\n serializedForm[i] = $.trim(serializedForm[i]);\n}\n//turn it into a string if you wish\nserializedForm = $.param(serializedForm);\n" }, { "answer_id": 435977, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "var dataString = \"source=contactDiv\";\ndataString += getDataString(divId, \"input\"); // add inputs\ndataString += getDataString(divId, \"select\"); //add select elements\n" }, { "answer_id": 1374677, "author": "Ulf Lindback", "author_id": 30354, "author_profile": "https://Stackoverflow.com/users/30354", "pm_score": 2, "selected": false, "text": "var form = $(\"form\");\nvar action = form.attr(\"action\");\nvar formArr = form. serializeArray();\n$.each(formArr , function(i, field) {\n formArr[i].value = $.trim(field.value);\n});\nvar serializedForm = $.param(formArr);\n$.post(action, serializedForm, function(data)\n{\n ...\n});\n" }, { "answer_id": 64290494, "author": "Billu", "author_id": 7186739, "author_profile": "https://Stackoverflow.com/users/7186739", "pm_score": 0, "selected": false, "text": "var formFilters = $('input, textarea');\n formFilters.each(function(){\n $(this).val($(this).val().trim());\n });\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ]
218,798
<p>The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?</p>
[ { "answer_id": 218833, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 5, "selected": false, "text": "function isObject ( obj ) {\n return obj && (typeof obj === \"object\");\n}\n" }, { "answer_id": 218834, "author": "pawel", "author_id": 4879, "author_profile": "https://Stackoverflow.com/users/4879", "pm_score": 8, "selected": true, "text": "Array.isArray(obj)" }, { "answer_id": 218838, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": ">>> var a = [];\n>>> var o = {};\n>>> a instanceof Array\ntrue\n>>> o instanceof Array\nfalse\n" }, { "answer_id": 23716468, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 3, "selected": false, "text": "exports.is_dictionary = function (obj) {\n if(!obj) return false;\n if(Array.isArray(obj)) return false;\n if(obj.constructor != Object) return false;\n return true;\n};\n\n// return true\ntest.equal(nsa_utils.is_dictionary({}), true);\ntest.equal(nsa_utils.is_dictionary({abc:123, def:456}), true);\n\n// returns false\ntest.equal(nsa_utils.is_dictionary([]), false);\ntest.equal(nsa_utils.is_dictionary([123, 456]), false);\ntest.equal(nsa_utils.is_dictionary(null), false);\ntest.equal(nsa_utils.is_dictionary(NaN), false);\ntest.equal(nsa_utils.is_dictionary('hello'), false);\ntest.equal(nsa_utils.is_dictionary(0), false);\ntest.equal(nsa_utils.is_dictionary(123), false);\n" }, { "answer_id": 45459626, "author": "Viktor Ivliiev", "author_id": 4479867, "author_profile": "https://Stackoverflow.com/users/4479867", "pm_score": 0, "selected": false, "text": "isArrayHashs = (attr) ->\n !!attr && attr.constructor == Array && isHash(attr[0])\n\nisHash = (attr) ->\n !!attr && !$.isNumeric(attr) && attr.constructor == Object\n" }, { "answer_id": 61426885, "author": "Bob Stein", "author_id": 673991, "author_profile": "https://Stackoverflow.com/users/673991", "pm_score": 2, "selected": false, "text": "typeof null === 'object'" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29653/" ]
218,806
<p>I am wondering how the JBoss ExceptionSorter classes are able to check for database errors.</p> <p>The application (the EJB or persistence framework) is holding the reference to the database Connection, so SQLExceptions are caught by the application. How is JBoss able to see the contents of the exception?</p> <p>Does JBoss wrap the connection and intercept these messages or something like that?</p>
[ { "answer_id": 360041, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<property name=\"exceptionSorterClassName\"><value>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</value></property>\n" }, { "answer_id": 13593728, "author": "GreenGiant", "author_id": 539048, "author_profile": "https://Stackoverflow.com/users/539048", "pm_score": 3, "selected": true, "text": "java.sql.SQLException: ORA-00942: table or view does not exist\n at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)\n at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)\n at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)\n at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)\n at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:810)\n at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1039)\n at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:850)\n at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1134)\n at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3339)\n at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3384)\n at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:342)\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25688/" ]
218,808
<p>I've got a <code>DateTime?</code> that I'm trying to insert into a field using a <code>DbParameter</code>. I'm creating the parameter like so:</p> <pre><code>DbParameter datePrm = updateStmt.CreateParameter(); datePrm.ParameterName = "@change_date"; </code></pre> <p>And then I want to put the value of the <code>DateTime?</code> into the <code>dataPrm.Value</code> while accounting for <code>null</code>s.</p> <p>I thought initially I'd be clever:</p> <pre><code>datePrm.Value = nullableDate ?? DBNull.Value; </code></pre> <p>but that fails with the error</p> <blockquote> <p>Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'</p> </blockquote> <p>So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:</p> <pre><code>datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value; </code></pre> <p>but that doesn't work either:</p> <blockquote> <p>Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'</p> </blockquote> <p>But I don't want to convert between those types!</p> <p>So far the only thing I can get to work is:</p> <pre><code>if (nullableDate.HasValue) datePrm.Value = nullableDate.Value; else datePrm.Value = DBNull.Value; </code></pre> <p>Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?</p> <p><strong>Update:</strong> I don't really get why the ?? version doesn't work. MSDN says:</p> <blockquote> <p>The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.</p> </blockquote> <p>That's exactly what I want!</p> <p><strong>Update2:</strong> Well it was kind of obvious in the end:</p> <pre><code>datePrm.Value = nullableDate ?? (object)DBNull.Value; </code></pre>
[ { "answer_id": 218843, "author": "dnolan", "author_id": 29086, "author_profile": "https://Stackoverflow.com/users/29086", "pm_score": 3, "selected": false, "text": "datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : DBNull.Value;\n" }, { "answer_id": 218844, "author": "Dan", "author_id": 28537, "author_profile": "https://Stackoverflow.com/users/28537", "pm_score": 1, "selected": false, "text": "datePrm.Value = nullableDate.HasValue ? (object)nullableDate.Value : (object)DBNull.Value;\n" }, { "answer_id": 218862, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": false, "text": "public static class DBNullableExtensions\n{\n public static object ToDBValue<T>(this Nullable<T> value) where T:struct\n { \n return value.HasValue ? (object)value.Value : DBNull.Value;\n }\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n int? x = null;\n\n Console.WriteLine( x.ToDBValue() == DBNull.Value );\n }\n}\n" }, { "answer_id": 218896, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 7, "selected": true, "text": "datePrm.Value = nullableDate ?? (object)DBNull.Value;\n" }, { "answer_id": 29258351, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 3, "selected": false, "text": "System.Data.SqlTypes" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
218,813
<p>I have a static method in my code that I would like somehow to mock.</p> <p>I am using jmock.</p> <p>One way I suppose I could do this is to have "wrapper class" around the static method and mock this but I was hoping for a better solution.</p> <p>I am going about this the wrong way?</p> <p>FEEDBACK:</p> <p>I was going to have a interface and class that had a method that just called the static method. It would allow me to mock the logic by just mocking the call to this wrapper class. (I feel dirty even talking about it :) )</p>
[ { "answer_id": 1053272, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 3, "selected": false, "text": "\n List<Person> peopleAboveAge = \n find(\"select p from Person p where p.age >= ?\", age);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050/" ]
218,825
<p>I have three Java <code>JCheckboxes</code> in a column, arranged by setting the layout of the container <code>JPanel</code> to <code>GridLayout(3, 1, 1, 1)</code>. When I run the program, there is too much vertical space between the JCheckBoxes; it looks like more than 1 pixel. Since I've already set the vertical space between the JCheckboxes in the layout to be 1 pixel, how else can I reduce the vertical space between these JCheckboxes?</p> <p>Thanks.</p>
[ { "answer_id": 219198, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 2, "selected": false, "text": "GridLayout" }, { "answer_id": 221513, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 2, "selected": false, "text": "JCheckBox checkBox = new JCheckBox();\ncheckBox.setBorder(BorderFactory.createEmptyBorder());\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,845
<p>I have a news site with articles tagged in categories.</p> <p>My Controller is called "Category" and this URL:</p> <blockquote> <p><code>http://mysite.com/Category/Sport</code></p> </blockquote> <p>passes <code>Sport</code> to action <code>Index</code> in controller <code>Category</code>.</p> <p>I want to allow the following URLs:</p> <blockquote> <p><code>http://mysite.com/Sport/Hockey</code><br> <code>http://mysite.com/Sport/Football</code><br> <code>http://mysite.com/Science/Evolution</code> </p> </blockquote> <p>Which passes all category information to action <code>Index</code> in controller <code>Category</code>.</p> <p>How do I create a catch-all route that handles all these and shuttles them to category?</p>
[ { "answer_id": 37267580, "author": "jgauffin", "author_id": 70386, "author_profile": "https://Stackoverflow.com/users/70386", "pm_score": 0, "selected": false, "text": "routes.MapRoute(\"Default\", \"{category}/{subcategory}\",\n new { controller = \"CategoryController\", action = \"Display\", id = \"\" }\n);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29181/" ]
218,848
<p>I need to give users the ability to optionally add metadata to documents. Another way to state this is the fact that users need to add at least 5 categories to a document.</p> <p>Basically what I want to do is dynamically add metadata (or categories) to a document on an ad hoc basis. Here are the options that I have thought of:</p> <p><strong>Option 1:</strong> Should I do this by dynamically creating new table columns in the database? </p> <p><strong>Option 2:</strong> Should I define 5 columns called attirbute1,attirbute2,attirbute3,attirbute4,attirbute5 and then only use and show them if the user requires the attributes. </p> <p><strong>Option 3:</strong> Should I create a metadata table that keeps track of the columns and the data associated with them? </p> <p>What do you think is the best way to achieve this? Can you think of any other ways to easily add this functionality. The problem is that the functionality needs to be very generic.</p>
[ { "answer_id": 218993, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 1, "selected": false, "text": "create table DocMetaData\n(\n DocumentHandle varchar NOT NULL,\n MetaDataName varchar NOT NULL,\n MetaDataText varchar NOT NULL\n);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29441/" ]
218,857
<p>I have a class that contains a bunch of properties. It is a mistake by a programmer if they call ToString() on an object of that type. Take this example code:</p> <pre><code>using System; public class Foo { public int ID = 123; public string Name = "SomeName"; private string ToString() { return null; } } public class MyClass { public static void Main() { Foo myObj = new Foo(); WL("I want this to be a compiler error: {0}", myObj.ToString()); RL(); } #region Helper methods private static void WL(object text, params object[] args) { Console.WriteLine(text.ToString(), args); } private static void RL() { Console.ReadLine(); } #endregion } </code></pre> <p>You could reason that if ID is what most people want written out as a string, then I should implement ToString so that it returns the ID. However, I believe that is a bad practice because programmers will "accidentally" get working code. A programmer using my class should specify what they want.</p> <p>Instead, what I would like is if someone calls myObj.ToString() to have that show up as a compile time error. I thought I could do that by creating a private ToString() function, but that doesn't work.</p> <p>The reason I brought this up is that we ended up with a query string that contained the fully qualified class name rather then an ID. </p> <p>So the question is: <strong>Is there any way to "hide" the ToString() function so that calling it on an object of my class causes a compiler error?</strong></p>
[ { "answer_id": 218868, "author": "Sander", "author_id": 2928, "author_profile": "https://Stackoverflow.com/users/2928", "pm_score": 4, "selected": false, "text": "[Obsolete(\"Use the XYZ properties instead of .ToString() on Foobar\", true)]\n" }, { "answer_id": 218885, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 6, "selected": false, "text": "ToString()" }, { "answer_id": 218997, "author": "mockobject", "author_id": 29649, "author_profile": "https://Stackoverflow.com/users/29649", "pm_score": 3, "selected": false, "text": " [Obsolete(\"dont' use\", true)]\n public override string ToString()\n {\n throw new Exception(\"don't use\");\n }\n" }, { "answer_id": 219825, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 3, "selected": false, "text": "public new void ToString() { }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,866
<p>I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:</p> <pre><code>Org1 Emp1 Name, Emp1 Phone, Emp1 Address Emp2 Name, Emp2 Phone, Emp2 Address Org2 Emp1 Name, Emp1 Phone, Emp1 Address Emp2 Name, Emp2 Phone, Emp2 Address </code></pre> <p>How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?</p> <p>Many Thanks.</p>
[ { "answer_id": 218900, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 3, "selected": true, "text": "$currentOrg = '';\nwhile ($row = mysql_fetch_object($query)) {\n if ($row->org != $currentOrg) {\n echo \"$row->org\".\n }\n $currentorg = $row->org;\n}\n" }, { "answer_id": 218918, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "// Get the data\n$data = mysql_query('SELECT org, emp_name, emp_phone, emp_address FROM x');\n\n// Store it all in a 2D array, keyed by org\n$rows = array();\nwhile ($row = mysql_fetch_assoc($data))\n{\n // Initialise each org to an empty array (not really needed in PHP but I prefer it)\n if (empty($rows[$row['org']]))\n $rows[$row['org']] = array();\n\n $rows[$row['org']][] = $row;\n}\n\n// Print it out\nforeach ($rows as $org => $employees)\n{\n print('<tr><td rowspan=\"' . count($employees) . '\">' . htmlentities($org) . '</td>');\n\n foreach ($employees as $i => $employee)\n {\n // If $i == 0, we've already printed the <tr> before the loop\n if ($i)\n print('<tr>');\n\n print('<td>......</td></tr>');\n }\n}\n" }, { "answer_id": 218922, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "rowspan" }, { "answer_id": 218924, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "$sql = $mysqli->query('SELECT * FROM `organisation_members` ORDER BY `organisation` DESC');\n\nif (!$sql || $sql->num_rows) {\n // No data\n} else {\n $data = array();\n while ($row = $sql->fetch_assoc()) {}\n if (!array_key_exists($row['organisation'], $data)) {\n $data[$row['organisation']] = array();\n }\n $data[$row['organisation']][]['name'] = $row['name'];\n // ...\n }\n $sql->close();\n echo '<table>';\n foreach ($data as $org => $people) {\n $people_in_org = count($data[$org]) - 1;\n $counter = 0;\n\n echo '<tr>';\n echo '<td rowspan=\"' . $people_in_org + 1 . '\">' . $org . '</td>';\n\n while ($counter < $people_in_org) {\n if (counter > 0) {\n echo '<tr>';\n }\n echo '<td>' . $people[$counter]['name'] . '</td>';\n // etc\n echo '</tr>';\n }\n }\n echo '</table>';\n}\n" }, { "answer_id": 219031, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 0, "selected": false, "text": "WITH ROLLUP" }, { "answer_id": 966010, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " <?php\n\n require_once \"HTML/Table.php\";\n\n\n\n\n $table = new HTML_Table(array('border'=>'1'));\n $bo=array(\n array('6','a2','a3','a4'),\n array('1','b2','b3','b4'),\n array('1','c2','c3','c4') ,\n array('2','c2','c3','c4') ,\n array('2','c2','c3','c4') ,\n array('4','c2','c3','c4') );\n\n foreach ($bo as $r => $borow)\n $table->addRow($borow);\n\n $rsFirst=0;\n $rsLen=0; \n foreach ($bo as $r => $borow) {\n if ($r!=0 and $borow[0]!=$prevrow[0] ) {\n //jump in values\n $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));\n $rsFirst=$r;\n $rsLen=0;\n }\n $prevrow=$borow;\n $rsLen++; \n if ($r==sizeof($bo) - 1) {\n $table->setCellAttributes ( $rsFirst,0, array('rowspan'=>$rsLen));\n }\n }\n\n\n echo $table->toHTML();\n\n ?>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29656/" ]
218,888
<p>I have 3 classes that are essentially the same but don't implement an interface because they all come from different web services. </p> <p>e.g.</p> <ul> <li>Service1.Object1</li> <li>Service2.Object1</li> <li>Service3.Object1</li> </ul> <p>They all have the same properties and I am writing some code to map them to each other using an intermediary object which implements my own interface IObject1</p> <p>I've done this using generics</p> <pre><code>public static T[] CreateObject1&lt;T&gt;(IObject1[] properties) where T : class, new() { //Check the type is allowed CheckObject1Types("CreateObject1&lt;T&gt;(IObject1[])", typeof(T)); return CreateObjectArray&lt;T&gt;(properties); } private static void CheckObject1Types(string method, Type type) { if (type == typeof(Service1.Object1) || type == typeof(Service2.Object1) || type == typeof(Service3.Object1) || type == typeof(Service1.Object1[]) || type == typeof(Service2.Object1[]) || type == typeof(Service3.Object1[])) { return; } throw new ArgumentException("Incorrect type passed to ServiceObjectFactory::" + method + ". Type:" + type.ToString()); } </code></pre> <p>My client code looks like:</p> <pre><code>//properties is an array of my intermediary objects Object1[] props = ServiceObjectFactory.CreateObject1&lt;Object1&gt;(properties); </code></pre> <p>What I want to do is get rid of the CheckObject1Types method and use constraints instead so that I get a build error if the types aren't valid, because at the moment I can call this method with any type and the ArgumentException is thrown by the CheckObject1Types method.</p> <p>So I'd like to do something like:</p> <pre><code>public static T[] CreateObject1&lt;T&gt;(IObject1[] properties) where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1 { return CreateObjectArray&lt;T&gt;(properties); } </code></pre> <p>Any ideas?</p> <p><strong>Edit:</strong> I don't want to change the Reference.cs files for each webservice because all it takes is a team mate to update the web reference and BAM! broken code.</p>
[ { "answer_id": 218930, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "namespace TestServices\n{\n internal partial class Service1SoapClient : System.ServiceModel.ClientBase<T>, K\n {\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
218,904
<p>I am using TortoiseSVN for my Subversion repository held on a USB drive. When I move from one PC to another, is there a way to automatically identify that files are out of date (without using the Check for Modifications menu). It would be nice just to be able to see that the folder on my hard drive did not match that of the repository, rather than seeing the green tick.</p>
[ { "answer_id": 219033, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 3, "selected": true, "text": "[autorun]\nopen=CheckForMods.bat\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21862/" ]
218,908
<p>Is there a best way to turn an integer into its month name in .net?</p> <p>Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.</p>
[ { "answer_id": 218927, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": false, "text": "somedatetime.ToString(\"MMMM\")" }, { "answer_id": 218947, "author": "Tokabi", "author_id": 315, "author_profile": "https://Stackoverflow.com/users/315", "pm_score": 3, "selected": false, "text": "Microsoft.VisualBasic" }, { "answer_id": 218948, "author": "Ovidiu Pacurar", "author_id": 28419, "author_profile": "https://Stackoverflow.com/users/28419", "pm_score": 4, "selected": false, "text": "//This was wrong\n//CultureInfo.DateTimeFormat.MonthNames[index];\n\n//Correct but keep in mind CurrentInfo could be null\nDateTimeFormatInfo.CurrentInfo.MonthNames[index];\n" }, { "answer_id": 218957, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 9, "selected": true, "text": "CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1);\n" }, { "answer_id": 1442023, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Enum.Parse();" }, { "answer_id": 12257805, "author": "user1534576", "author_id": 1534576, "author_profile": "https://Stackoverflow.com/users/1534576", "pm_score": 3, "selected": false, "text": "DateTime dt = new DateTime(year, month, day);\nResponse.Write(day + \"-\" + dt.ToString(\"MMMM\") + \"-\" + year);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
218,909
<p><strong>EDIT:</strong> See <a href="https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252">my working code</a> in the answers below.</p> <hr> <p><strong>In brief:</strong> I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: <em>File does not begin with '%PDF-'</em>.</p> <p><strong>In detail:</strong> So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: <em>File does not begin with '%PDF-'</em>. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?</p> <p>To create the PDF, I'm using <a href="http://xmlgraphics.apache.org/fop" rel="nofollow noreferrer">Apache FOP</a>. I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html#basics" rel="nofollow noreferrer">basic usage pattern</a> and <a href="http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup" rel="nofollow noreferrer">this example code</a>.</p> <p>Here's my JSP file:</p> <pre><code>&lt;%@ taglib uri="utilTLD" prefix="util" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %&gt; &lt;%@ page language="java" session="false" %&gt; &lt;%@ page contentType="application/pdf" %&gt; &lt;%-- Construct and initialise the PrintReportsBean --%&gt; &lt;jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" /&gt; &lt;jsp:setProperty name="printReportsBean" property="*"/&gt; &lt;c:set scope="page" var="xml" value="${printReportsBean.download}"/&gt; </code></pre> <p>Here's my Java Bean method:</p> <pre><code>//earlier in the class... private static FopFactory fopFactory = FopFactory.newInstance(); public File getDownload() throws UtilException { OutputStream out = null; File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf"); File fo = new File("C:\\somedirectory", "HelloWorld.fo"); try { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); out = new FileOutputStream(pdf); out = new BufferedOutputStream(out); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); //identity transformer Source src = new StreamSource(fo); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); return pdf; } catch (Exception e) { throw new UtilException("Could not get download. Msg = "+e.getMessage()); } finally { try { out.close(); } catch (IOException io) { throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage()); } } } </code></pre> <p>I realise that this is a very specific problem, but any help would be much appreciated!</p>
[ { "answer_id": 219102, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 0, "selected": false, "text": "<%@ page trimDirectiveWhitespaces=\"true\" %>\n" }, { "answer_id": 221252, "author": "Philip Morton", "author_id": 21709, "author_profile": "https://Stackoverflow.com/users/21709", "pm_score": 2, "selected": false, "text": "<%@ taglib uri=\"utilTLD\" prefix=\"util\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/xml\" prefix=\"x\" %>\n<%@ page language=\"java\" session=\"false\" %>\n<%@ page contentType=\"application/pdf\" %>\n\n<%-- Construct and initialise the PrintReportsBean --%>\n<jsp:useBean id=\"printReportsBean\" scope=\"request\" class=\"some.package.PrintReportsBean\" />\n<jsp:setProperty name=\"printReportsBean\" property=\"*\"/>\n\n<%\n // get report format as input parameter \n ServletOutputStream servletOutputStream = response.getOutputStream();\n\n // reset buffer to remove any initial spaces\n response.resetBuffer(); \n\n response.setHeader(\"Content-disposition\", \"attachment; filename=HelloWorld.pdf\");\n\n // check that user is authorised to download product\n printReportsBean.getDownload(servletOutputStream);\n%>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]