qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
223,149
<p>Say you create a form using ASP.NET MVC that has a dynamic number of form elements.</p> <p>For instance, you need a checkbox for each product, and the number of products changes day by day.</p> <p>How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.</p>
[ { "answer_id": 223158, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 0, "selected": false, "text": "string[]" }, { "answer_id": 223168, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": true, "text": "<input class=\"approveCheck\" id=\"<%= \"approveCheck\" + recordId %>\" \n name=\"<%= \"approveCheck\" + recordId %>\" type=\"checkbox\" />\n foreach (var key in Request.Form.Keys)\n {\n string keyString = key.ToString();\n if (keyString.StartsWith(\"approveCheck\", StringComparison.OrdinalIgnoreCase))\n {\n string recNum = keyString.Substring(12, keyString.Length - 12);\n\n string approvedKey = Request.Form[\"approveCheck\" + recNum];\n bool approved = !String.IsNullOrEmpty(approvedKey);\n // ...\n" }, { "answer_id": 223262, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<%var i = 0;\n foreach (var product (IList<ProductSelection>)ViewData[\"products\"]) {%>\n <%=Html.Hidden(string.Format(\"products[{0}].Id\", i), product.Id)%>\n <%=Html.Checkbox(string.Format(\"products[{0}].Selected\", i))%>\n <%=product.Name%><br/>\n<%}%>\n <input name=\"products[0].Id\" type=\"hidden\" value=\"123\">\n<input name=\"products[0].Selected\" type=\"checkbox\">\nWidget\n<input name=\"products[1].Id\" type=\"hidden\" value=\"987\">\n<input name=\"products[1].Selected\" type=\"checkbox\">\nGadget\n public ActionResult SelectProducts(IList<ProductSelection> products)\n{\n ...\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7837/" ]
223,151
<p>I'd like to write a Ruby snippet that gets run when my Gem is first installed via <code>[sudo ]gem install mygem</code>. Can it be done?</p>
[ { "answer_id": 226438, "author": "IDBD", "author_id": 7403, "author_profile": "https://Stackoverflow.com/users/7403", "pm_score": -1, "selected": false, "text": "irb(main):001:0> system 'gem list | grep rails'\nrails (2.1.1, 2.1.0)\n=> true\nirb(main):002:0> system 'gem list | grep railssssss'\n=> false\n" }, { "answer_id": 27998791, "author": "Panic", "author_id": 669745, "author_profile": "https://Stackoverflow.com/users/669745", "pm_score": 1, "selected": false, "text": "# your_gem.gemspec\nGem::Specification.new do |spec|\n # ...\n spec.extensions = ['Rakefile']\nend\n # Rakefile\ntask :prepare do\n # Execute your post-installation code here\nend\n\ntask default: :prepare\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
223,153
<p>I am trying to call a COM object from PHP using the COM interop extension. One function requires an OLE_COLOR as an argument? Is there any way to pass this kind of value from PHP?</p> <p>I have tried passing a simple integer value with no success.</p> <pre><code>$this-&gt;oBuilder-&gt;Font-&gt;Color = 255; </code></pre>
[ { "answer_id": 432916, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 2, "selected": true, "text": "$Color = new COM('ColorClass');\n$Color->set_color_function($red, $green, $blue);\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
223,162
<p>How do I pull out the filename from a full path using regular expressions in C#?</p> <p>Say I have the full path <code>C:\CoolDirectory\CoolSubdirectory\CoolFile.txt</code>.</p> <p>How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.</p> <p>Also, in the course of trying to solve this problem, I realized that I can just use <code>System.IO.Path.GetFileName</code>, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.</p>
[ { "answer_id": 223172, "author": "Dour High Arch", "author_id": 22437, "author_profile": "https://Stackoverflow.com/users/22437", "pm_score": 5, "selected": false, "text": "Path.GetFileName()" }, { "answer_id": 223176, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 5, "selected": true, "text": "// using System.Text.RegularExpressions;\n\n/// <summary>\n/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM\n/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com\n/// \n/// A description of the regular expression:\n/// \n/// Any character that is NOT in this class: [\\\\], any number of repetitions\n/// End of line or string\n/// \n///\n/// </summary>\npublic static Regex regex = new Regex(\n @\"[^\\\\]*$\",\n RegexOptions.IgnoreCase\n | RegexOptions.CultureInvariant\n | RegexOptions.IgnorePatternWhitespace\n | RegexOptions.Compiled\n );\n" }, { "answer_id": 223178, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 3, "selected": false, "text": "string filename = Regex.Match(filename, @\".*\\\\([^\\\\]+$)\").Groups[1].Value;\n" }, { "answer_id": 223180, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 1, "selected": false, "text": "\\w+:\\\\(\\w+\\\\)*(?<file>\\w*\\.\\w*)\n" }, { "answer_id": 223214, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 3, "selected": false, "text": "string filename = Regex.Match(fullpath, @\"[^\\\\]*$\").Value;\n string filename = Regex.Match(fullpath, \"[^\\\\\"+System.IO.Path.PathSeparator+\"]*$\").Value;\n Regex string[] pathparts = fullpath.Split(new []{System.IO.Path.PathSeparator});\nstring file = pathparts[pathparts.Length-1];\n string file = System.IO.Path.GetFileName(fullpath);\n" }, { "answer_id": 224566, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 0, "selected": false, "text": "Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), \"My App Stuff\");\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18927/" ]
223,173
<p>I've got two directories containing ~20 GB of music files (mostly mp3, some ogg), and I would like to detect all duplicate songs. There are two complicating factors:</p> <ol> <li>A song may have different filenames in the two directories.</li> <li>Two files containing the same song may have different ID3 tags and thus have different checksums.</li> </ol> <p>What is a good approach to solving this?</p>
[ { "answer_id": 71106818, "author": "derat", "author_id": 6882947, "author_profile": "https://Stackoverflow.com/users/6882947", "pm_score": 0, "selected": false, "text": "fpcalc" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13051/" ]
223,187
<pre><code>SqlConnection connection = new SqlConnection(FROM_CONFIGURATION) SqlCommand command = new SqlCommand("SomeSQL", connection); connection.Open(); command.ExecuteNonQuery(); command.Dispose(); connection.Dispose(); </code></pre> <p>It is recommended that the code above should include try/catch (or using) so that if an exception is thrown, all resources are disposed properly.</p> <p>But if you have to worry about disposing stuff manually, then what's the point of the GC?! Isn't GC there to take care of this for the coder?</p>
[ { "answer_id": 223213, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "using using (SqlConnection connection = new SqlConnection(FROM_CONFIGURATION))\nusing (SqlCommand command = new SqlCommand(\"SomeSQL\", connection))\n{\n connection.Open(); \n command.ExecuteNonQuery(); \n command.Dispose(); \n connection.Dispose();\n}\n using" }, { "answer_id": 223225, "author": "IAmCodeMonkey", "author_id": 27613, "author_profile": "https://Stackoverflow.com/users/27613", "pm_score": 2, "selected": false, "text": "using (SqlConnection connection = new SqlConnection(...))\nusing (SqlCommand command = connection.CreateCommand())\n{\n ...\n}\n" }, { "answer_id": 223260, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 3, "selected": false, "text": "class MonkeyGrabber : IDisposable {\n public MonkeyGrabber() { /* construction grabs a real, live monkey from the cage */\n public void Dispose() { Dispose(true); /* releases the monkey back into the cage */ }\n // the rest of the monkey grabbing is left as an exercise to grad student drones\n}\n\nclass MonkeyMonitor {\n public void CheckMonkeys() {\n if (_monkeyPool.GettingTooRowdy()) {\n MonkeyGrabber grabber = new MonkeyGrabber();\n grabber.Spank();\n }\n }\n}\n" }, { "answer_id": 223286, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "using IDisposable" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,189
<p>How can I create a Delphi TSpeedButton or SpeedButton in C# 2.0?</p>
[ { "answer_id": 2244350, "author": "reSPAWNed", "author_id": 71793, "author_profile": "https://Stackoverflow.com/users/71793", "pm_score": 3, "selected": false, "text": "public class ButtonNoFocus : Button\n{\n public ButtonNoFocus()\n : base()\n {\n base.SetStyle(ControlStyles.Selectable, false);\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,195
<p>If A references assembly B 1.1 and C, and C references B 1.2, how do you avoid assembly conflicts?</p> <p>I nievely assumed C's references would be encapsulated away and would not cause any problems, but it appears all the dll's are copied to the bin, which is where the problem occurs.</p> <p>I understand the two ways around this are to use the GAC or assembly bindings? The GAC doesn't seem like the best approach to me, as I don't like assuming dlls will be there, I prefer to reference dlls from a lib directory in my solution.</p> <p>Where as assembly bindings don't seem robust to me, what if one version of the assembly has functionality that the other doesn't, will this not produce problems?</p> <hr> <p>In my case its because I'm using a 3rd party dll uses a older version of nHibernate, than I'm using myself.</p>
[ { "answer_id": 223276, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 1, "selected": false, "text": "<configuration>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"myAssembly\"\n publicKeyToken=\"32ab4ba45e0a69a1\"\n culture=\"neutral\" />\n <bindingRedirect oldVersion=\"1.0.0.0\"\n newVersion=\"2.0.0.0\"/>\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n</configuration>\n" }, { "answer_id": 7167517, "author": "Peter Kelly", "author_id": 215600, "author_profile": "https://Stackoverflow.com/users/215600", "pm_score": 3, "selected": false, "text": "extern" }, { "answer_id": 18003025, "author": "burton", "author_id": 2249908, "author_profile": "https://Stackoverflow.com/users/2249908", "pm_score": 2, "selected": false, "text": " <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"MyAssembly\" publicKeyToken=\"...\" />\n <codeBase version=\"1.1.0.0\" href=\"MyAssembly_v1.1.0.0.dll\"/>\n <codeBase version=\"2.0.0.0\" href=\"MyAssembly_v2.0.0.0.dll\"/>\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
223,215
<p>At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:</p> <pre><code>class Header { int type; int payloadLength; }; </code></pre> <p>All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like:</p> <pre><code>char* Header::GetPayload() { return ((char*) &amp;payloadLength) + sizeof(payloadLength); } </code></pre> <p>or even:</p> <pre><code>char* Header::GetPayload() { return ((char*) this) + sizeof(Header); } </code></pre> <p>That seemed kind of verbose, so I came up with:</p> <pre><code>char* Header::GetPayload() { return (char*) &amp;this[1]; } </code></pre> <p>It seems rather disturbing at first, possibly too odd to use -- but very compact. There was a lot of debate on whether it was brilliant or an abomination. </p> <p>So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off?</p> <p>-Update:</p> <p>We did try the zero sized array, but at the time, compilers gave warnings. We eventually went to the inhertited technique: Message derives from Header. It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.</p>
[ { "answer_id": 223224, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 4, "selected": false, "text": "#pragma pack" }, { "answer_id": 223230, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 6, "selected": true, "text": "class Header\n{\n int type;\n int payloadLength;\n char status;\n};\n" }, { "answer_id": 223237, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 1, "selected": false, "text": "char* Header::GetPayload()\n{\n return ((char*) this) + sizeof(*this);\n}\n" }, { "answer_id": 223279, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "struct Header\n{\n int type;\n int payloadlength;\n}\nstruct MessageBuffer\n{\n struct Header header;\n char[MAXSIZE] payload;\n}\n\nclass Message\n{\n private:\n MessageBuffer m;\n\n public:\n Message( MessageBuffer buf ) { m = buf; }\n\n struct Header GetHeader( )\n {\n return m.header;\n }\n\n char* GetPayLoad( )\n {\n return &m.payload;\n }\n}\n" }, { "answer_id": 223292, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 1, "selected": false, "text": "sizeof() #pragma pack SRowSet" }, { "answer_id": 223382, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 2, "selected": false, "text": "template<typename T. typename RetType>\nRetType JustPast(const T* pHeader)\n{\n return reinterpret_cast<RetType>(pHeader + sizeof(T));\n}\n" }, { "answer_id": 223462, "author": "Jan de Vos", "author_id": 11215, "author_profile": "https://Stackoverflow.com/users/11215", "pm_score": 2, "selected": false, "text": "struct bla {\n int i;\n int j;\n char data[0];\n}\n" }, { "answer_id": 223600, "author": "Raindog", "author_id": 29049, "author_profile": "https://Stackoverflow.com/users/29049", "pm_score": 1, "selected": false, "text": "struct header\n{\n short id;\n short size;\n}\n\nstruct foo\n{\n header hd;\n short hit_points;\n}\n\n\nshort get_foo_data(char *packet)\n{\n return reinterpret_cast<foo*>(packet)->hit_points;\n}\n\nvoid handle_packet(char *packet)\n{\n header *hd = reinterpret_cast<header*>(packet);\n switch(hd->id)\n {\n case FOO_PACKET_ID:\n short val = get_foo_data(packet);\n //snip\n }\n}\n" }, { "answer_id": 223756, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "class Header\n{\n int type;\n int payloadLength;\n char payload[0];\n\n};\n\nchar* Header::GetPayload()\n{\n return payload;\n}\n" }, { "answer_id": 224076, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "#include <stdint.h>\n#include <arpa/inet.h>\n\nclass Header {\nprivate:\n uint32_t type;\n uint32_t payloadlength;\npublic:\n uint32_t getType() { return ntohl(type); }\n uint32_t getPayloadLength() { return ntohl(payloadlength); }\n};\n\nclass Message {\nprivate:\n Header head;\n char payload[1]; /* or maybe std::vector<char>: see below */\npublic:\n uint32_t getType() { return head.getType(); }\n uint32_t getPayloadLength() { return head.getPayloadLength(); }\n const char *getPayload() { return payload; }\n};\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17975/" ]
223,219
<p>I want to do something like </p> <pre><code>insert into my table (select * from anothertable where id &lt; 5) </code></pre> <p>What is the correct MSSQL syntax?</p> <p>Thanks!</p>
[ { "answer_id": 223236, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 4, "selected": true, "text": "INSERT INTO MyTable\nSELECT * FROM AnotherTable\nWHERE AnotherTable.ID < 5\n" }, { "answer_id": 223239, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 2, "selected": false, "text": "INSERT INTO myTable(COL1, COL2, COL3) \nSELECT COL1, COL2, COL3 FROM anotherTable where anotherTable.id < 5\n" }, { "answer_id": 223244, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 0, "selected": false, "text": "Insert Into MyTable\n (\n Col1,\n Col2,\n Col3\n )\nSelect\n Col1,\n Col2,\n Col3\nFrom\n AnotherTable\nWhere\n ID < 5\n" }, { "answer_id": 223411, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 0, "selected": false, "text": "select *\ninto MyTable\nfrom AnotherTable\nwhere ID < 5\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
223,238
<p>Which Oracle database role will allow a user to select from a table in another schema without specifying the schema identifier? i.e., as user A- Grant select on A.table to user B; B can then- "Select * from table" without specifying the 'A'. One of our databases allows this, the other returns a 'table or view does not exist' error. </p>
[ { "answer_id": 223278, "author": "asalamon74", "author_id": 21348, "author_profile": "https://Stackoverflow.com/users/21348", "pm_score": 2, "selected": false, "text": "alter session set current_schema=A" }, { "answer_id": 225107, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 2, "selected": false, "text": "SELECT * FROM all_objects WHERE object_name = 'mytablename'\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,249
<p>In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.</p> <p><strong>Is there any way to add files to the sub-tree or group for a Windows Form class?</strong></p>
[ { "answer_id": 223254, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": false, "text": "<Compile Include=\"MyForm.MyCoolSubFile.cs\">\n <DependentUpon>MyForm.cs</DependentUpon>\n</Compile>\n" }, { "answer_id": 223259, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 5, "selected": true, "text": "<Compile Include=\"AlertDialog.xaml.cs\">\n <DependentUpon>AlertDialog.xaml</DependentUpon>\n</Compile>\n" }, { "answer_id": 223264, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<Compile Include=\"Linq\\Extensions\\DataProducerExt.cs\" />\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.SingleReturn.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Grouping.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Pipeline.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Conversion.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n<Compile Include=\"Linq\\Extensions\\DataProducerExt.Math.cs\">\n <DependentUpon>DataProducerExt.cs</DependentUpon>\n</Compile>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5692/" ]
223,253
<p>I have a requirement to install multiple web setup projects (using VS2005 and ASP.Net/C#) into the same virtual folder. The projects share some assembly references (the file systems are all structured to use the same 'bin' folder), making deployment of changes to those assemblies problematic since the MS installer will only overwrite assemblies if the currently installed version is older than the one in the MSI.</p> <p>I'm not suggesting that the pessimistic installation scheme is wrong - only that it creates a problem in the environment I've been given to work with. Since there are a sizable number of common assemblies and a significant number of developers who might change a common assembly but forget to update its version number, trying to manage versioning manually will eventually lead to massive confusion at install time.</p> <p>On the flip side of this issue, it's also important not to spontaneously update version numbers and replace <em>all</em> common assemblies with <em>every</em> install, since that could (temporarily at least) obscure cases where actual changes were made.</p> <p>That said, what I'm looking for is a means to update assembly version information (preferably using MSBuild) only in cases where the assembly constituents (code modules, resources etc) has/have actually changed.</p> <p>I've found a few references that are at least partially pertinent <a href="http://code.msdn.microsoft.com/AssemblyInfoTaskvers/Release/ProjectReleases.aspx?ReleaseId=232" rel="noreferrer" title="here">here </a> (AssemblyInfo task on MSDN) and <a href="http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/94054d89-ba19-4658-9e4e-ce7d8ff4dea3/" rel="noreferrer" title="here">here</a> (looks similar to what I need, but more than two years old and without a clear solution).</p> <p>My team also uses TFS version control, so an automated solution should probably include a means by which the AssebmlyInfo can be checked out/in during the build.</p> <p>Any help would be much appreciated.</p> <p>Thanks in advance.</p>
[ { "answer_id": 224116, "author": "David White", "author_id": 30183, "author_profile": "https://Stackoverflow.com/users/30183", "pm_score": 3, "selected": false, "text": "<FileUpdate \nFiles=\"$(WebDir)\\Properties\\AssemblyInfo.cs\"\nRegex=\"(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\"\nReplacementText=\"$(Major).$(ServicePack).$(Build).$(Revision)\" \nCondition=\"'$(Configuration)' == 'Release'\"\n/>\n using System;\nusing System.IO;\nusing Microsoft.Build.Framework;\nusing Microsoft.Build.Utilities;\n\nnamespace CredibleCustomBuildTasks\n{\n public class IncrementTask : Task\n {\n [Required]\n public bool SaveChange { get; set; }\n\n [Required]\n public string IncrementFileName { get; set; }\n\n [Output]\n public int Increment { get; set; }\n\n public override bool Execute()\n {\n if (File.Exists(IncrementFileName))\n {\n string lines = File.ReadAllText(IncrementFileName);\n int result;\n if(Int32.TryParse(lines, out result))\n {\n Increment = result + 1;\n }\n else\n {\n Log.LogError(\"Unable to parse integer in '{0}' (contents of {1})\");\n return false;\n }\n }\n else\n {\n Increment = 1;\n }\n\n if (SaveChange)\n {\n File.Delete(IncrementFileName);\n File.WriteAllText(IncrementFileName, Increment.ToString());\n }\n return true;\n }\n }\n}\n <IncrementTask \nIncrementFileName=\"$(BuildNumberFile)\" \nSaveChange=\"false\">\n <Output TaskParameter=\"Increment\" PropertyName=\"Build\" />\n</IncrementTask>\n <IncrementTask \nIncrementFileName=\"$(BuildNumberFile)\" \nSaveChange=\"true\"\nCondition=\"'$(Configuration)' == 'Release'\" />\n" }, { "answer_id": 1042306, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace UpdateVersion\n{\n class SetVersion\n {\n static void Main(string[] args)\n {\n String FilePath = args[0];\n String MajVersion=args[1];\n String MinVersion = args[2];\n String BuildNumber = args[3];\n string RevisionNumber = null;\n\n StreamReader Reader = File.OpenText(FilePath);\n string contents = Reader.ReadToEnd();\n Reader.Close();\n\n MatchCollection match = Regex.Matches(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", RegexOptions.IgnoreCase);\n if (match[0].Value != null)\n {\n string strRevisionNumber = match[0].Value;\n\n RevisionNumber = strRevisionNumber.Substring(strRevisionNumber.LastIndexOf(\".\") + 1, (strRevisionNumber.LastIndexOf(\"\\\"\")-1) - strRevisionNumber.LastIndexOf(\".\"));\n\n String replaceWithText = String.Format(\"[assembly: AssemblyVersion(\\\"{0}.{1}.{2}.{3}\\\")]\", MajVersion, MinVersion, BuildNumber, RevisionNumber);\n string newText = Regex.Replace(contents, @\"\\[assembly: AssemblyVersion\\(\"\".*\"\"\\)\\]\", replaceWithText);\n\n StreamWriter writer = new StreamWriter(FilePath, false);\n writer.Write(newText);\n writer.Close();\n }\n else\n {\n Console.WriteLine(\"No matching values found\");\n }\n }\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7388/" ]
223,268
<p>I know there is built-in Internet explorer, but what I'm looking for is to open Firefox/Mozilla window (run the application) with specified URL. Anyone can tell me how to do that in C# (.nET) ?</p>
[ { "answer_id": 223307, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 0, "selected": false, "text": "C:\\Program Files\\Mozilla Firefox>firefox.exe http://google.com\n" }, { "answer_id": 223320, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 5, "selected": true, "text": "string url = \"http://stackoverflow.com/\";\nSystem.Diagnostics.Process.Start(url); \n" }, { "answer_id": 5402343, "author": "Bruno Le Duic", "author_id": 629672, "author_profile": "https://Stackoverflow.com/users/629672", "pm_score": 4, "selected": false, "text": "System.Diagnostics.Process.Start(\"firefox.exe\", \"http://www.google.com\");\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21209/" ]
223,272
<p>I have a simple query like this:</p> <pre><code>select * from mytable where id &gt; 8 </code></pre> <p>I want to make the 8 a variable. There's some syntax like </p> <pre><code>declare @myvar int myvar = 8 </code></pre> <p>but I don't know the exact syntax.</p> <p>What is it?</p> <p>Thanks!</p>
[ { "answer_id": 223280, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "declare @myvar int\n\nselect @myvar = 8\n" }, { "answer_id": 223281, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 5, "selected": true, "text": "DECLARE @MyVariable INT\nSET @MyVariable = 8\n" }, { "answer_id": 223289, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 3, "selected": false, "text": "declare @myvar int\n\nSet @myvar = 8\n\nselect * from mytable where id > @myvar\n" }, { "answer_id": 223807, "author": "JasonFruit", "author_id": 21778, "author_profile": "https://Stackoverflow.com/users/21778", "pm_score": 2, "selected": false, "text": "SET @one = 1\nSET @two = 2\n SELECT @one = 1, @two = 2\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
223,283
<p>Even a simple <a href="http://en.wikipedia.org/wiki/Notepad_%28software%29" rel="noreferrer">Notepad</a> application in C# consumes megabytes of RAM as seen in the task manager. On minimizing the application the memory size in the task manager goes down considerably and is back up when the application is maximized.</p> <p>I read somewhere that the .NET process reserves a lot of memory for runtime allocation in advance. That's why .NET applications have a larger memory footprint to start with. But this memory can be released using Win32 API calls. A trade-off is that runtime allocation becomes slow - is that true?</p>
[ { "answer_id": 223300, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 6, "selected": true, "text": "[DllImport(\"psapi.dll\")]\nstatic extern int EmptyWorkingSet(IntPtr hwProc);\n\nstatic void MinimizeFootprint()\n{\n EmptyWorkingSet(Process.GetCurrentProcess().Handle);\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29443/" ]
223,285
<p>I am using the following code:</p> <pre><code>&lt;?php $stock = $_GET[s]; //returns stock ticker symbol eg GOOG or YHOO $first = $stock[0]; $url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html"; $data = file_get_contents($url); $r_header = '/Prev. Week(.+?)Next Week/'; $r_date = '/\&lt;b\&gt;(.+?)\&lt;\/b\&gt;/'; preg_match($r_header,$data,$header); preg_match($r_date, $header[1], $date); echo $date[1]; ?&gt; </code></pre> <p>I've checked the regular expressions <a href="http://www.quanetic.com/regex.php" rel="nofollow noreferrer">here</a> and they appear to be valid. If I check just $url or $data they come out correctly and if I print $data and check the source the code that I'm looking for to use in the regex is in there. If you're interested in checking anything, an example of a proper URL would be <a href="http://biz.yahoo.com/research/earncal/g/goog.html" rel="nofollow noreferrer">http://biz.yahoo.com/research/earncal/g/goog.html</a></p> <p>I've tried everything I could think of, including both var_dump($header) and var_dump($date), both of which return empty arrays.</p> <p>I have been able to create other regular expressions that works. For instance, the following correctly returns "Earnings":</p> <pre><code>$r_header = '/Company (.+?) Calendar/'; preg_match($r_header,$data,$header); echo $header[1]; </code></pre> <p>I am going nuts trying to figure out why this isn't working. Any help would be awesome. Thanks.</p>
[ { "answer_id": 223358, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "<a href=\"...\">Prev. Week</a> ..." }, { "answer_id": 223366, "author": "J.T. Grimes", "author_id": 1676, "author_profile": "https://Stackoverflow.com/users/1676", "pm_score": 2, "selected": false, "text": "$r_header = '/Prev\\. Week((?s:.*))Next Week/';\n s ." }, { "answer_id": 223377, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "/your-regex/s $r_header /Prev\\. Week(.+?)Next Week/s < >" }, { "answer_id": 223380, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<?php\n$stock = \"goog\";//$_GET[s]; //returns stock ticker symbol eg GOOG or YHOO\n$first = $stock[0];\n\n$url = \"http://biz.yahoo.com/research/earncal/\".$first.\"/\".$stock.\".html\";\n$data = file_get_contents($url);\n\n$r_header = '/Prev. Week(.+?)Next Week/s';\n$r_date = '/\\<b\\>(.+?)\\<\\/b\\>/s';\n\n\npreg_match($r_header,$data,$header);\npreg_match($r_date, $header[1], $date);\n\nvar_dump($header);\n?>\n" }, { "answer_id": 223390, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "s (PCRE_DOTALL) . < >" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30098/" ]
223,308
<p>I am trying to use page methods in my asp.net page. I have enable page methods set to true on the script manager, the webmethod attribute defined on the method, the function is public static string, I know the function works because when I run it from my code behind it generates the expected result, but when I call it via page method in my result function the result is always alerted as undefined. If I use fiddler it doesn't even look like there is additional traffic or a new request created. I'm running the site on port 82 if that makes a difference. I'm at a loss here. Can someone give me some pointers?</p>
[ { "answer_id": 223464, "author": "Chris Westbrook", "author_id": 16891, "author_profile": "https://Stackoverflow.com/users/16891", "pm_score": 0, "selected": false, "text": " function getName()\n {\n var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');\n var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;\n //alert(value);\n PageMethods.getAdCodeInfo(value,onSuccess(),onError());\n }\n\n function onSuccess(result)\n {\n alert(result);\n }\n\n function onError(error)\n {\n alert(\"error \"+error);\n }\n" }, { "answer_id": 223513, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": true, "text": "PageMethods.getAdCodeInfo(value, onSuccess, onError)\n onSuccess onError" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
223,312
<p>Quite simple really:</p> <pre><code>var req:URLRequest=new URLRequest(); req.url="http://somesite.com"; var header:URLRequestHeader=new URLRequestHeader("my-bespoke-header","1"); req.requestHeaders.push(header); req.method=URLRequestMethod.GET; stream.load(req); </code></pre> <p>Yet, if I inspect the traffic with WireShark, the <code>my-bespoke-header</code> is not being sent. If I change to <code>URLRequestMethod.POST</code> and append some data to <code>req.data</code>, then the header is sent, but the receiving application requires a GET not a POST. </p> <p>The documentation mentions a blacklist of headers that will not get sent. <code>my-bespoke-header</code> is not one of these. It's possibly worth mentioning that the originating request is from a different port on the same domain. Nothing is reported in the policyfile log, so it seems unlikely, but is this something that can be remedied by force loading a crossdomain.xml with a <code>allow-http-request-headers-from</code> despite the fact that this is not a crossdomain issue? Or is it simply an undocumented feature of the Flash Player that it can only send custom headers with a POST request?</p>
[ { "answer_id": 223464, "author": "Chris Westbrook", "author_id": 16891, "author_profile": "https://Stackoverflow.com/users/16891", "pm_score": 0, "selected": false, "text": " function getName()\n {\n var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');\n var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;\n //alert(value);\n PageMethods.getAdCodeInfo(value,onSuccess(),onError());\n }\n\n function onSuccess(result)\n {\n alert(result);\n }\n\n function onError(error)\n {\n alert(\"error \"+error);\n }\n" }, { "answer_id": 223513, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": true, "text": "PageMethods.getAdCodeInfo(value, onSuccess, onError)\n onSuccess onError" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
223,313
<p>What is MySQL equivalent of the <code>Nz</code> Function in Microsoft Access? Is <code>Nz</code> a SQL standard?</p> <p>In Access, the <code>Nz</code> function lets you return a value when a variant is null. <a href="http://www.techonthenet.com/access/functions/advanced/nz.php" rel="nofollow noreferrer">Source</a></p> <p>The syntax for the <code>Nz</code> function is:</p> <pre><code>Nz ( variant, [ value_if_null ] ) </code></pre>
[ { "answer_id": 223329, "author": "Mike Wills", "author_id": 2535, "author_profile": "https://Stackoverflow.com/users/2535", "pm_score": 2, "selected": false, "text": "IFNULL COALESCE IFNULL" }, { "answer_id": 223560, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "COALESCE() IFNULL()" }, { "answer_id": 16490031, "author": "diamondsea", "author_id": 2209980, "author_profile": "https://Stackoverflow.com/users/2209980", "pm_score": 2, "selected": false, "text": "SELECT Nz(MightBeNullVar, 0) FROM ... (MS Access version)\nSELECT COALESCE(MightBeNullVar, 0) FROM ... (MySQL version)\nSELECT IFNULL(MightBeNullVar, 0) FROM ... (MySQL version)\n SELECT COALESCE(MightBeNullVar, MightAlsoBeNullVar, CouldBeNullVar, 0) FROM ... (MySQL version)\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30076/" ]
223,316
<p>In an effort to satisfy "The Joel Test" question #2 "Can you make a build in one step?", I'm trying to complete a release candidate build script with the creation of a CD iso from the collection of files gathered and generated by the installer creator.</p> <p>There seem to be many good tools (many free) out there that will create ISOs, but I need to find one that can be run at the windows command line so I can integrate it into the NAnt build script that's fired off by Cruise Control.</p> <p>Build environment is:</p> <ul> <li>Windows Server 2003</li> <li>.NET 1.1 - 3.5 (application we're creating is built on 2.0)</li> <li>NullSoft installer (NSIS)</li> <li>CruiseControl.net</li> <li>NAnt</li> </ul> <p>I've been googling around, but no luck yet.</p> <p>Anyone have a recommendation?</p>
[ { "answer_id": 224991, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "add_option = '-a'\nadd_option_value = installer_fullpath\nresponse_option = '-py' # answer yes to all options \n\n\n# Get the tempfile name -- to resolve long name issue\n# --> My file names were initially too long for MagicIso and it would choke\nf_handle = tempfile.TemporaryFile(suffix='.iso', prefix='mi_', dir='.')\ntemp_filename = f_handle.name\nf_handle.close() # File automatically deleted on close \n\nargs = (magiciso_exe_fullpath,temp_filename,response_option,add_option,add_option_value)\n\n# log output to file\nmagiciso_con_f = open(MAGICISO_CON_LOG,'w')\n\nmagiciso_process = subprocess.Popen(args,stdout=magiciso_con_f,stderr=magiciso_con_f)\nmagiciso_process.wait()\n" }, { "answer_id": 267943, "author": "Gerhard", "author_id": 34989, "author_profile": "https://Stackoverflow.com/users/34989", "pm_score": 4, "selected": false, "text": "mkisofs mkisofs -v -dvd-video -V \"VOLUME_NAME\" -o \"c:\\my movies\\iso\\movie.iso\" \"c:\\my movies\\dvd\"\nmkisofs -r -R -J -l -L -o image-file.iso c:\\project\\install\n" }, { "answer_id": 346258, "author": "festive_ken", "author_id": 43929, "author_profile": "https://Stackoverflow.com/users/43929", "pm_score": 4, "selected": false, "text": "CDBuilder builder = new CDBuilder();\nbuilder.UseJoliet = true;\nbuilder.VolumeIdentifier = \"A_SAMPLE_DISK\";\nbuilder.AddFile(@\"Folder\\Hello.txt\", Encoding.ASCII.GetBytes(\"Hello World!\"));\nbuilder.Build(@\"C:\\temp\\sample.iso\");\n" }, { "answer_id": 346264, "author": "alexandrul", "author_id": 19756, "author_profile": "https://Stackoverflow.com/users/19756", "pm_score": 2, "selected": false, "text": "mkisofs.exe" }, { "answer_id": 3519413, "author": "kibibu", "author_id": 81804, "author_profile": "https://Stackoverflow.com/users/81804", "pm_score": 4, "selected": false, "text": "cdbxpcmd.exe -iso -format cdbxpcmd --burn-data -folder:input -iso:output.iso -format:iso -changefiledates\n output.iso input cdbxpcmd --burn-data -layout:mycompilation.dxp -iso:output.iso -format:iso\n" }, { "answer_id": 46068167, "author": "KERR", "author_id": 3996028, "author_profile": "https://Stackoverflow.com/users/3996028", "pm_score": 3, "selected": false, "text": "# Author: Hrisan Dzhankardashliyski\n# Date: 20/05/2015\n\n# Inspiration from\n#\n# http://blogs.msdn.com/b/opticalstorage/archive/2010/08/13/writing-optical-discs-using-imapi-2-in-powershell.aspx</a>\n#\n# and\n#\n# http://tools.start-automating.com/Install-ExportISOCommand/</a>\n#\n# with help from\n#\n# http://stackoverflow.com/a/9802807/223837</a>\n\n$InputFolder = \"\"\n\nfunction WriteIStreamToFile([__ComObject] $istream, [string] $fileName)\n{\n# NOTE: We cannot use [System.Runtime.InteropServices.ComTypes.IStream],\n# since PowerShell apparently cannot convert an IStream COM object to this\n# Powershell type. (See <a href=\"http://stackoverflow.com/a/9037299/223837\">http://stackoverflow.com/a/9037299/223837</a> for\n# details.)\n#\n# It turns out that .NET/CLR _can_ do this conversion.\n#\n# That is the reason why method FileUtil.WriteIStreamToFile(), below,\n# takes an object, and casts it to an IStream, instead of directly\n# taking an IStream inputStream argument.\n\n$cp = New-Object CodeDom.Compiler.CompilerParameters\n$cp.CompilerOptions = \"/unsafe\"\n$cp.WarningLevel = 4\n$cp.TreatWarningsAsErrors = $true\n\nAdd-Type -CompilerParameters $cp -TypeDefinition @\"\nusing System;\nusing System.IO;\nusing System.Runtime.InteropServices.ComTypes;\n\nnamespace My\n{\n\npublic static class FileUtil {\npublic static void WriteIStreamToFile(object i, string fileName) {\nIStream inputStream = i as IStream;\nFileStream outputFileStream = File.OpenWrite(fileName);\nint bytesRead = 0;\nint offset = 0;\nbyte[] data;\ndo {\ndata = Read(inputStream, 2048, out bytesRead);\noutputFileStream.Write(data, 0, bytesRead);\noffset += bytesRead;\n} while (bytesRead == 2048);\noutputFileStream.Flush();\noutputFileStream.Close();\n}\n\nunsafe static private byte[] Read(IStream stream, int toRead, out int read) {\nbyte[] buffer = new byte[toRead];\nint bytesRead = 0;\nint* ptr = &bytesRead;\nstream.Read(buffer, toRead, (IntPtr)ptr);\nread = bytesRead;\nreturn buffer;\n}\n}\n\n}\n\"@\n\n[My.FileUtil]::WriteIStreamToFile($istream, $fileName)\n}\n\n# The Function defines the ISO parameturs and writes it to file\nfunction createISO([string]$VolName,[string]$Folder,[bool]$IncludeRoot,[string]$ISOFile){\n\n# Constants from <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa364840.aspx\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa364840.aspx</a>\n$FsiFileSystemISO9660 = 1\n$FsiFileSystemJoliet = 2\n$FsiFileSystemUDF = 4\n\n$fsi = New-Object -ComObject IMAPI2FS.MsftFileSystemImage\n\n#$fsi.FileSystemsToCreate = $FsiFileSystemISO9660 + $FsiFileSystemJoliet\n\n$fsi.FileSystemsToCreate = $FsiFileSystemUDF\n#When FreeMediaBlocks is set to 0 it allows the ISO file to be with unlimited size\n$fsi.FreeMediaBlocks = 0\n$fsi.VolumeName = $VolName\n\n$fsi.Root.AddTree($Folder, $IncludeRoot)\n\nWriteIStreamToFile $fsi.CreateResultImage().ImageStream $ISOFile\n}\n\nFunction Get-Folder($initialDirectory)\n\n{\n[System.Reflection.Assembly]::LoadWithPartialName(\"System.windows.forms\")\n\n$foldername = New-Object System.Windows.Forms.FolderBrowserDialog\n$foldername.rootfolder = \"MyComputer\"\n\nif($foldername.ShowDialog() -eq \"OK\")\n{\n$folder += [string]$foldername.SelectedPath\n}\nreturn $folder\n}\n\n# Show an Open Folder Dialog and return the directory selected by the user.\nfunction Read-FolderBrowserDialog([string]$Message, [string]$InitialDirectory, [switch]$NoNewFolderButton)\n{\n$browseForFolderOptions = 0\nif ($NoNewFolderButton) { $browseForFolderOptions += 512 }\n$app = New-Object -ComObject Shell.Application\n$folder = $app.BrowseForFolder(0, $Message, $browseForFolderOptions, $InitialDirectory)\nif ($folder) { $selectedDirectory = $folder.Self.Path }\nelse { $selectedDirectory = '' }\n[System.Runtime.Interopservices.Marshal]::ReleaseComObject($app) > $null\nreturn $selectedDirectory\n}\n\n#Prompts the user to save the ISO file, if the files does not exists it will create it otherwise overwrite without prompt\nFunction Get-SaveFile($initialDirectory)\n{\n[System.Reflection.Assembly]::LoadWithPartialName(\"System.windows.forms\") |\nOut-Null\n\n$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog\n$SaveFileDialog.CreatePrompt = $false\n$SaveFileDialog.OverwritePrompt = $false\n$SaveFileDialog.initialDirectory = $initialDirectory\n$SaveFileDialog.filter = \"ISO files (*.iso)| *.iso\"\n$SaveFileDialog.ShowHelp = $true\n$SaveFileDialog.ShowDialog() | Out-Null\n$SaveFileDialog.filename\n}\n\n# Show message box popup and return the button clicked by the user.\nfunction Read-MessageBoxDialog([string]$Message, [string]$WindowTitle, [System.Windows.Forms.MessageBoxButtons]$Buttons = [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]$Icon = [System.Windows.Forms.MessageBoxIcon]::None)\n{\nAdd-Type -AssemblyName System.Windows.Forms\nreturn [System.Windows.Forms.MessageBox]::Show($Message, $WindowTitle, $Buttons, $Icon)\n}\n\n# GUI interface for the PowerShell script\n[void] [System.Reflection.Assembly]::LoadWithPartialName(\"System.Drawing\")\n[void] [System.Reflection.Assembly]::LoadWithPartialName(\"System.Windows.Forms\") #loading the necessary .net libraries (using void to suppress output)\n\n$Form = New-Object System.Windows.Forms.Form #creating the form (this will be the \"primary\" window)\n$Form.Text = \"ISO Creator Tool:\"\n$Form.Size = New-Object System.Drawing.Size(600,300) #the size in px of the window length, height\n$Form.FormBorderStyle = 'FixedDialog'\n$Form.MaximizeBox = $false\n$Form.MinimizeBox = $false\n\n$objLabel = New-Object System.Windows.Forms.Label\n$objLabel.Location = New-Object System.Drawing.Size(20,20)\n$objLabel.Size = New-Object System.Drawing.Size(120,20)\n$objLabel.Text = \"Please select a Folder:\"\n$Form.Controls.Add($objLabel)\n\n$InputBox = New-Object System.Windows.Forms.TextBox\n$InputBox.Location = New-Object System.Drawing.Size(150,20)\n$InputBox.Size = New-Object System.Drawing.Size(300,20)\n$InputBox.Enabled = $false\n$Form.Controls.Add($InputBox)\n\n$objLabel2 = New-Object System.Windows.Forms.Label\n$objLabel2.Location = New-Object System.Drawing.Size(20,80)\n$objLabel2.Size = New-Object System.Drawing.Size(120,20)\n$objLabel2.Text = \"ISO File Name:\"\n$Form.Controls.Add($objLabel2)\n\n$InputBox2 = New-Object System.Windows.Forms.TextBox\n$InputBox2.Location = New-Object System.Drawing.Size(150,80)\n$InputBox2.Size = New-Object System.Drawing.Size(300,20)\n$InputBox2.Enabled = $false\n$Form.Controls.Add($InputBox2)\n\n$objLabel3 = New-Object System.Windows.Forms.Label\n$objLabel3.Location = New-Object System.Drawing.Size(20,50)\n$objLabel3.Size = New-Object System.Drawing.Size(120,20)\n$objLabel3.Text = \"ISO Volume Name:\"\n$Form.Controls.Add($objLabel3)\n\n$InputBox3 = New-Object System.Windows.Forms.TextBox\n$InputBox3.Location = New-Object System.Drawing.Size(150,50)\n$InputBox3.Size = New-Object System.Drawing.Size(150,20)\n$Form.Controls.Add($InputBox3)\n\n$objLabel4 = New-Object System.Windows.Forms.Label\n$objLabel4.Location = New-Object System.Drawing.Size(20,120)\n$objLabel4.Size = New-Object System.Drawing.Size(120,20)\n$objLabel4.Text = \"Status Msg:\"\n$Form.Controls.Add($objLabel4)\n\n$InputBox4 = New-Object System.Windows.Forms.TextBox\n$InputBox4.Location = New-Object System.Drawing.Size(150,120)\n$InputBox4.Size = New-Object System.Drawing.Size(200,20)\n$InputBox4.Enabled = $false\n$InputBox4.Text = \"Set ISO Parameters...\"\n$InputBox4.BackColor = \"LimeGreen\"\n$Form.Controls.Add($InputBox4)\n\n$Button = New-Object System.Windows.Forms.Button\n$Button.Location = New-Object System.Drawing.Size(470,20)\n$Button.Size = New-Object System.Drawing.Size(80,20)\n$Button.Text = \"Browse\"\n$Button.Add_Click({\n$InputBox.Text=Read-FolderBrowserDialog\n$InputBox4.Text = \"Set ISO Parameters...\"\n\n})\n$Form.Controls.Add($Button)\n\n$Button2 = New-Object System.Windows.Forms.Button\n$Button2.Location = New-Object System.Drawing.Size(470,120)\n$Button2.Size = New-Object System.Drawing.Size(80,80)\n$Button2.Text = \"CreateISO\"\n$Button2.Add_Click({\n\nif(($InputBox.Text -eq \"\") -or ($InputBox3.Text -eq \"\")){\nRead-MessageBoxDialog \"You have to select folder and specify ISO Volume Name\" \"Error: No Parameters entered!\"\n} else{\n$SaveDialog = Get-SaveFile\n#If you click cancel when save file dialog is called\nif ($SaveDialog -eq \"\"){\nreturn\n}\n$InputBox2.Text= $SaveDialog\n$InputBox2.Refresh()\nif($checkBox1.Checked){\n$includeRoot=$true\n}\nelse{\n$includeRoot=$false\n}\n$InputBox4.BackColor = \"Red\"\n$InputBox4.Text = \"Generating ISO File!\"\n$InputBox4.Refresh()\ncreateISO $InputBox3.Text $InputBox.Text $includeRoot $InputBox2.Text\n$InputBox4.BackColor = \"LimeGreen\"\n$InputBox4.Text = \"ISO Creation Finished!\"\n$InputBox4.Refresh()\n}\n})\n$Form.Controls.Add($Button2)\n\n$objLabel5 = New-Object System.Windows.Forms.Label\n$objLabel5.Location = New-Object System.Drawing.Size(20,160)\n$objLabel5.Size = New-Object System.Drawing.Size(280,20)\n$objLabel5.Text = \"Check the box if you want to include the top folder:\"\n$Form.Controls.Add($objLabel5)\n\n$checkBox1 = New-Object System.Windows.Forms.CheckBox\n$checkBox1.Location = New-Object System.Drawing.Size(300,156)\n$Form.Controls.Add($checkBox1)\n\n$Form.Add_Shown({$Form.Activate()})\n[void] $Form.ShowDialog()\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5496/" ]
223,317
<p>This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it. </p> <pre><code>public JsonResult SomeControllerAction() { //The current method has the HttpContext just fine bool currentIsNotNull = (this.HttpContext == null); //which is false //creating a new instance of another controller SomeOtherController controller = new SomeOtherController(); bool isNull = (controller.HttpContext == null); // which is true //The actual HttpContext is fine in both bool notNull = (System.Web.HttpContext.Current == null); // which is false } </code></pre> <p>I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current. </p> <p>Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?</p>
[ { "answer_id": 223334, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 0, "selected": false, "text": "\nreturn RedirectToAction(\"SomeAction\", \"SomeOtherController\", new {param1 = \"Something\" });\n" }, { "answer_id": 225912, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 6, "selected": false, "text": "public new HttpContextBase HttpContext {\n get {\n HttpContextWrapper context = \n new HttpContextWrapper(System.Web.HttpContext.Current);\n return (HttpContextBase)context; \n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17091/" ]
223,322
<p>I'm trying to have a new layer appear above existing content on my site when a link/button is clicked. I am using jquery - but the code I have doesn't seem to work as expected.</p> <p>Here is what I have:</p> <pre><code> $(document).ready(function(){ $("#button").click(function () { $("#showme").insertAfter("#bodytag") $("#showme").fadeIn(2000); }); </code></pre> <p>});</p> <p>The effect I'm after is to have <code>&lt;div id="showme"&gt;...&lt;/div&gt;</code> appear directly after the #bodytag. <code>&lt;div id="showme"&gt;...&lt;/div&gt;</code> has a z-index higher than anything else on the site, so it should just appear above the content directly after the #bodytag.</p> <p>Thanks for the assistance.</p>
[ { "answer_id": 223330, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "#showme position static" }, { "answer_id": 223379, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 3, "selected": true, "text": "$().ready(function(){\n $(\"#button\").click(function () {\n $(\"#showme\").insertAfter(\"#bodytag\").fadeIn(2000);\n });\n});\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,325
<p>Building a java application that supports different Locales, but would like to customize the <code>DateFormat</code> display beyond what is available between <code>FULL</code>, <code>LONG</code>, <code>MEDIUM</code>, and <code>SHORT</code> DateFormat options. Would like to do things like place a character between the date and time components of a <code>DateFormat.getDateTimeFormat()</code>, lowercase the AM/PM, etc, at least for english.</p> <p>can think of 3 ways to do it:</p> <p>1) if locale is english, use my custom format string on a <code>new SimpleDateFormat</code> object.</p> <p>2) modify the default format strings for existing locales</p> <p>3) create a new locale variant that specifies the format strings I want</p> <p>Can't figure out how to do 2 or 3 (or if it's even possible), and would rather not do 1... has anyone dealt with anything like this before?</p> <p>also, seems like 2 or 3 would be necessary for lowercasing the AM/PM ? (Specifiying the AmPmMarkers resource for the locale's dateformat settings)</p>
[ { "answer_id": 223343, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": " // This is an incredibly ugly hack, but it's based on the fact that\n // Java for some reason decided that Italy uses \".\" between\n // hours.minutes.seconds, even though \"locale\" and strftime say\n // something different.\n hmsTimeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);\n if (hmsTimeFormat instanceof SimpleDateFormat)\n {\n String str = ((SimpleDateFormat)hmsTimeFormat).toPattern();\n str = str.replace('.', ':');\n hmsTimeFormat = new SimpleDateFormat(str);\n }\n" }, { "answer_id": 226424, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SimpleDateFormat sdf = (SimpleDateFormat)sdf.getDateTimeInstance(DateTime.SHORT,DateTime.SHORT, locale);\nif (formatString != null) {\n sdf = new SimpleDateFormat(formatString);\n}\nif (am!= null && pm != null) {\n DateFormatSymbols symbols = sdf.getDateFormatSymbols();\n symbols.setAmPmStrings(new String[]{am, pm});\n sdf.setDateFormatSymbols(symbols);\n}\n" }, { "answer_id": 230653, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "Settings formats = new Settings();\nProperties SDFFormats = formats.load(propertiesFile);\n\nString SDFAmerica = SDFFormats.getProperty(\"FormatAmerica\");\n FormatAmerica = MMM-dd-yyyy\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,328
<p>I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':</p> <p>here is my HTML snippet:</p> <p>headerRows[0][10].contents</p> <pre><code> [&lt;font size="+0"&gt;&lt;font face="serif" size="1"&gt;&lt;b&gt;Apples Produced&lt;/b&gt;&lt;font size="3"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;] </code></pre> <p>Note that this is a list item from Python [].</p> <p>I need the value Apples Produced but can't get to it.</p> <p>Any suggestions would be appreciated</p> <p>Suggestions on a good book that explains this would earn my eternal gratitude</p> <hr> <p>Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute</p> <p>say it is:</p> <pre><code> [&lt;font size="+0"&gt;&lt;font face="serif" size="1"&gt;&lt;I&gt;Apples Produced&lt;/I&gt;&lt;font size="3"&gt; &lt;/font&gt;&lt;/font&gt;&lt;/font&gt;] </code></pre> <p><I>Apples Produced</I><br> </p> <p>I am trying to learn to read/understand the documentation and your response will help</p> <p>I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me.</p> <p>Cheers</p>
[ { "answer_id": 223534, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "findNext headerRows[0][10].findNext('b').string\n <b> findAll NavigableString >>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>')\n>>> u''.join([s.string for s in s.findAll(text=True)])\nu'Test 1 More Test 2'\n" }, { "answer_id": 223994, "author": "ThePants", "author_id": 29260, "author_profile": "https://Stackoverflow.com/users/29260", "pm_score": 0, "selected": false, "text": " def clean(self, val):\n if type(val) is not StringType: val = str(val)\n val = re.sub(r'<.*?>', '', s) #remove tags\n val = re.sub(\"\\s+\" , \" \", val) #collapse internal whitespace\n return val.strip() #remove leading & trailing whitespace\n" }, { "answer_id": 629326, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "headerRows[0][10].contents[0].find('b').string\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30105/" ]
223,352
<p>I'm trying to determine the reason for a stalled process on Linux. It's a telecom application, running under fairly heavy load. There is a separate process for each of 8 T1 spans. Every so often, one of the processes will get very unresponsive - up to maybe 50 seconds before an event is noted in the normally very busy process's log.</p> <p>It is likely some system resource that runs short. The obvious thing - CPU usage - looks to be OK. </p> <p>Which linux utilities might be best for catching and analyzing this sort of thing, and be as unobtrusive about it as possible, as this is a highly loaded system? It would need to be processes rather than system oriented, it would seem. Maybe ongoing monitoring of /proc/pid/XX? Top wouldn't seem to be too useful here.</p>
[ { "answer_id": 223592, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 3, "selected": false, "text": "strace -f -o LOG -p <pid>\n strace -e file -f -o LOG ....\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,354
<p>I've got a really simple rails question here but I can't seem to find the answer anywhere. I guess some of the problems stem from me following a tutorial for Rails 1.2 with Rails 2.1. Anyway..</p> <p>I'm writing a blog system and I'm implementing the comments bit. I have comments displaying fine once I've created them using script/console, but getting the comment form itself working is the hard bit.</p> <p>In posts_controller.rb I have</p> <pre><code> def comment Post.find(params[:id]).comments.create(params[:comment]) flash[:notice] = "Added comment" #render :action =&gt; show redirect_to :action =&gt; show end </code></pre> <p>and in show.html.erb (the view) I have</p> <pre><code>&lt;%= form_tag :action =&gt; "comment", :id =&gt; @post %&gt; &lt;%= text_area "comment", "body" %&gt;&lt;br&gt; &lt;%= submit_tag "Post Comment" %&gt; </code></pre> <p>When I submit the form it tries to go to the urb /posts/comment/1 which is obviously incorrect, and it complains that it can't find a template. Obviously I don't want a template there because I've told it to redirect to the show action because I want it to just re-display the post's show page, with the new comment there.</p> <p>I've tried both the commented out line (render :action => show) and the redirect_to line, and neither seem to do anything at all.</p> <p>I'm sure I'm missing something simple, but what is it?</p>
[ { "answer_id": 223515, "author": "Vitalie", "author_id": 27913, "author_profile": "https://Stackoverflow.com/users/27913", "pm_score": -1, "selected": false, "text": " form_for :comment, :url => { :post_id => @post } do |f|\n f.text_area :body\n submit_tag \"Post\"\n end\n gem install -v 1.2.6 rails\n" }, { "answer_id": 223555, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 0, "selected": false, "text": "show index create show new edit update destroy" }, { "answer_id": 223580, "author": "RichH", "author_id": 16779, "author_profile": "https://Stackoverflow.com/users/16779", "pm_score": 4, "selected": true, "text": "redirect_to :action => 'show', :id => params[:id]" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
223,360
<p>How does the Chinese GB18030 code set differ from Unicode?</p> <p>What special techniques are required for handling GB18030?</p> <p>Are there any (open source) libraries for handling GB18030?</p>
[ { "answer_id": 3224578, "author": "dan04", "author_id": 287586, "author_profile": "https://Stackoverflow.com/users/287586", "pm_score": 4, "selected": false, "text": "find index" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15168/" ]
223,373
<p>I would like my GWT program to be able to determine whether it's in hosted mode or in web mode. Is there a way to do this?</p> <p>Thanks! </p>
[ { "answer_id": 1066457, "author": "Chris Ruffalo", "author_id": 128339, "author_profile": "https://Stackoverflow.com/users/128339", "pm_score": 0, "selected": false, "text": "if(GWT.isScript()) {\n //some code not in the JRE emulation here\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
223,384
<p>I have a static object at runtime that is basically a list of other objects (ints, strings, Dictionary, other objects, etc). Is there way to determine the memory used by my static "list of other objects" object at runtime? This would be handy for instrumentation and reporting purposes.</p>
[ { "answer_id": 226224, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": 0, "selected": false, "text": "using (MemoryStream memstream = new MemoryStream())\n{\n BinaryFormatter formatter = new BinaryFormatter();\n\n try\n {\n formatter.Serialize(memstream, myObjectOfObjects);\n mem_footprint += memstream.Length;\n }\n catch \n {\n // not a serializable object \n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
223,393
<p>What is the Perl equivalent of <code>strlen()</code>?</p>
[ { "answer_id": 223401, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 7, "selected": true, "text": "length($string)" }, { "answer_id": 224035, "author": "JDrago", "author_id": 29060, "author_profile": "https://Stackoverflow.com/users/29060", "pm_score": 5, "selected": false, "text": "length($string)\n" }, { "answer_id": 225944, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 5, "selected": false, "text": "print \"foo\" =~ y===c; # prints 3\n" }, { "answer_id": 48983029, "author": "RANA DINESH", "author_id": 8556604, "author_profile": "https://Stackoverflow.com/users/8556604", "pm_score": 1, "selected": false, "text": "length() $string ='String Name';\n$size=length($string);\n" }, { "answer_id": 56991682, "author": "pslessard", "author_id": 11631864, "author_profile": "https://Stackoverflow.com/users/11631864", "pm_score": 0, "selected": false, "text": "my $length = map $_, $str =~ /(.)/gs;\nmy $length = () = $str =~ /(.)/gs;\nmy $length = split '', $str;\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
223,395
<p>If I HTML encode any data entered by website users when I redisplay it, will this prevent CSS vulnerabilities? </p> <p>Also, is there a tool/product available that will sanitize my user input for me, so that I don't have to write my own routines.</p>
[ { "answer_id": 223492, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 3, "selected": false, "text": "< > \" ' &" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,400
<p>I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.</p> <p>My object is structured like list.list.uniqueCustomerIdentifier</p> <p>I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.</p>
[ { "answer_id": 223414, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 2, "selected": false, "text": "var results = from item in list\n group item by item.id into g\n select g.First();\n" }, { "answer_id": 223479, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "SelectMany IEnumerable<IEnumerable<T>> IEnumerable<T>" }, { "answer_id": 224013, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "var result = \n myList\n .SelectMany(x => x.InnerList)\n .Select(y => y.uniqueCustomerIdentifier)\n .GroupBy(id => id)\n .Where(g => g.Skip(1).Any())\n .Select(g => g.Key)\n .ToList()\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22706/" ]
223,421
<p>My question is quite relevant to <a href="https://stackoverflow.com/questions/42785/how-do-you-retrofit-unit-tests-into-a-code-base">something asked before</a> but I need some practical advice.</p> <p>I have "Working effectively with legacy code" in my hands and I 'm using advice from the book as I read it in the project I 'm working on. The project is a C++ application that consists of a few libraries but the major portion of the code is compiled to a single executable. I 'm using googletest for adding unit tests to existing code when I have to touch something.</p> <p>My problem is how can I setup my build process so I can build my unit tests since there are two different executables that need to share code while I am not able to extract the code from my "under test" application to a library. Right now I have made my build process for the application that holds the unit tests link against the object files generated from the build process of the main application but I really dislike it. Are there any suggestions?</p>
[ { "answer_id": 223595, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "all: tests executables\n\nrun-tests: tests\n <commands to run the test suite>\n\nexecutables: <file list>\n <commands to build the files>\n\ntests: unit-test1 unit-test2 etc\n\nunit-test1: ,files that are required for your unit-test1>\n <commands to build unit-test1>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6403/" ]
223,431
<p>Which industry-class database has the most <strong>unique</strong> features? (with "unique" meaning that no other RDBMS has them)</p> <p>I think my choice here is Oracle 11g:</p> <ol> <li>Flashback query (you can estract data as it was a moment in the past)</li> <li>ASM - automatic storage management</li> <li>Native code compilation of stored procedures</li> <li>Audit features (tracing everything, from logins to statements)</li> </ol> <p>and many others.</p>
[ { "answer_id": 224892, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "CHECK DOMAIN ASSERTION" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23034/" ]
223,433
<p>I get to dust off my VBScript hat and write some classic ASP to query a SQL Server 2000 database.</p> <p>Here's the scenario:</p> <ul> <li>I have two <em>datetime</em> fields called <strong>fieldA</strong> and <strong>fieldB</strong>.</li> <li><strong>fieldB</strong> will never have a year value that's greater than the year of <strong>fieldA</strong></li> <li>It <strong>is</strong> possible the that two fields will have the same year.</li> </ul> <p>What I want is all records where <strong>fieldA</strong> >= <strong>fieldB</strong>, <em>independent of the year</em>. Just pretend that each field is just a month &amp; day.</p> <p>How can I get this? My knowledge of T-SQL date/time functions is spotty at best.</p>
[ { "answer_id": 223446, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "select *\nfrom t\nwhere datepart(month,t.fieldA) >= datepart(month,t.fieldB)\n or (datepart(month,t.fieldA) = datepart(month,t.fieldB)\n and datepart(day,t.fieldA) >= datepart(day,t.fieldB))\n select *\nfrom t\nwhere substring(convert(varchar,t.fieldA,21),5,20)\n >= substring(convert(varchar,t.fieldB,21),5,20)\n" }, { "answer_id": 223448, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 5, "selected": true, "text": "SELECT * from table where\nMONTH(fieldA) > MONTH(fieldB) OR(\nMONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB))\n" }, { "answer_id": 223463, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM SOME_TABLE\nWHERE MONTH(fieldA) > MONTH(fieldB)\nOR ( MONTH(fieldA) = MONTH(fieldB) AND DAY(fieldA) >= DAY(fieldB) )\n" }, { "answer_id": 23343503, "author": "user3065891", "author_id": 3065891, "author_profile": "https://Stackoverflow.com/users/3065891", "pm_score": 0, "selected": false, "text": "Create table #t (calDate date)\nDeclare @curDate date = '2010-01-01'\nwhile @curDate < '2021-01-01'\nbegin\n insert into #t values (@curDate)\n Set @curDate = dateadd(dd,1,@curDate)\nend \n Declare @testDate date = getdate()\nSELECT *\nFROM #t\nWHERE datediff(dd,dateadd(yy,1900 - year(@testDate),@testDate),dateadd(yy,1900 - year(calDate),calDate)) >= 0\n Declare @testDate date = getdate()\nSELECT *\nFROM #t\nWHERE datediff(dd,dateadd(yy,1900 - year(@testDate),@testDate),dateadd(yy,1900 - year(calDate),calDate)) < 0\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
223,468
<p>Question: </p> <pre><code>((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3)) </code></pre> <p>This was #1 on the midterm, I put "81 9" he thought I forgot to cross one out lawl, so I cross out 81, and he goes aww. Anyways, I dont understand why it's 81.</p> <p>I understand why <code>(lambda (x) (* x x)) (* 3 3) = 81</code>, but the first lambda I dont understand what the x and y values are there, and what the <code>[body] (x y)</code> does.</p> <p>So I was hoping someone could explain to me why the first part doesn't seem like it does anything.</p>
[ { "answer_id": 223484, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 4, "selected": true, "text": "((lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3))\n (lambda (x y) (x y)) x y (lambda (x) (* x x)) (* 3 3) ((lambda (x) (* x x))\n (* 3 3))\n" }, { "answer_id": 223609, "author": "Michał Kwiatkowski", "author_id": 21998, "author_profile": "https://Stackoverflow.com/users/21998", "pm_score": 3, "selected": false, "text": "((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))\n (lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3)\n (lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3)\n (call-1 square 9)\n (square 9)\n" }, { "answer_id": 223917, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 2, "selected": false, "text": "((lambda (x y) (funcall x y)) (lambda (x) (* x x)) (* 3 3))\n (funcall (lambda (x y) (funcall x y))\n (lambda (x) (* x x))\n (* 3 3))\n (funcall (lambda (x) (* x x)) (* 3 3))\n (let ((x (* 3 3)))\n (* x x))\n (let ((x 9))\n (* x x))\n (* 9 9)\n" }, { "answer_id": 224319, "author": "grettke", "author_id": 121526, "author_profile": "https://Stackoverflow.com/users/121526", "pm_score": 1, "selected": false, "text": "(define (square x) (* x x))\n\n(define (call-with arg fun) (fun arg))\n\n(call-with (* 3 3) square)\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18431/" ]
223,472
<p>Aspell-net is a port of the GNU Aspell for .Net Framework. The library itself is open source, and is under the LGPL license, but the english dictionary for aspell is mentioned as copyrighted on the sourceforge.net project home page at <a href="http://aspell-net.sourceforge.net/" rel="nofollow noreferrer">http://aspell-net.sourceforge.net/</a></p> <p>Did any of you guys use aspell-net before? and what license did you release your software under? The project I work on is a commercial one, and do you guys forsee any problem? Should I pay for the aspell english dictionary?</p> <p>Thanks.</p>
[ { "answer_id": 223484, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 4, "selected": true, "text": "((lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3))\n (lambda (x y) (x y)) x y (lambda (x) (* x x)) (* 3 3) ((lambda (x) (* x x))\n (* 3 3))\n" }, { "answer_id": 223609, "author": "Michał Kwiatkowski", "author_id": 21998, "author_profile": "https://Stackoverflow.com/users/21998", "pm_score": 3, "selected": false, "text": "((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))\n (lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3)\n (lambda (x y) (x y))\n (lambda (x) (* x x))\n (* 3 3)\n (call-1 square 9)\n (square 9)\n" }, { "answer_id": 223917, "author": "Luís Oliveira", "author_id": 2967, "author_profile": "https://Stackoverflow.com/users/2967", "pm_score": 2, "selected": false, "text": "((lambda (x y) (funcall x y)) (lambda (x) (* x x)) (* 3 3))\n (funcall (lambda (x y) (funcall x y))\n (lambda (x) (* x x))\n (* 3 3))\n (funcall (lambda (x) (* x x)) (* 3 3))\n (let ((x (* 3 3)))\n (* x x))\n (let ((x 9))\n (* x x))\n (* 9 9)\n" }, { "answer_id": 224319, "author": "grettke", "author_id": 121526, "author_profile": "https://Stackoverflow.com/users/121526", "pm_score": 1, "selected": false, "text": "(define (square x) (* x x))\n\n(define (call-with arg fun) (fun arg))\n\n(call-with (* 3 3) square)\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,480
<p>Simple question that keeps bugging me.</p> <p>Should I HTML encode user input right away and store the encoded contents in the database, or should I store the raw values and HTML encode when displaying?</p> <p>Storing encoded data greatly reduces the risk of a developer forgetting to encode the data when it's being displayed. However, storing the encoded data will make datamining somewhat more cumbersome and it will take up a bit more space, even though that's usually a non-issue.</p>
[ { "answer_id": 223494, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 6, "selected": true, "text": "sanitize user input -> protect against sql injection -> db -> encode for display\n" }, { "answer_id": 223518, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "&amp; strlen() magic_quotes magic_entities" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469/" ]
223,490
<p>My company requires me to use Outlook for my E-mail. Outlook does virtually nothing the way I want to do it and it frustrates me greatly. (I'm not trying to start a flame war here, it must do exactly what thousands of CEO's want it to do, but I'm not a CEO.)</p> <p>I would like to be able to automatically extract the thousands of E-mails and attachments currently in my Outlook account and save them in my own alternative storage format where I can easily search them and organize them the way I want. (I'm not requesting suggestions for the new format.)</p> <p>Maybe some nice open source program already can do this... that would be great. Please let me know.</p> <p>Otherwise, <b>how can I obtain the message content and the attachments without going through the huge collection manually?</b> Even if I could only get the message content and the names of the attachments, that would be sufficient. Is there documentation of the Outlook mail storage format? Is there a way to query Outlook for the data?</p> <p>Maybe there is an alternative approach I haven't considered?</p> <p>My preferred language to do this is C#, but I can use others if needed.</p>
[ { "answer_id": 223542, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 4, "selected": true, "text": " private RDOSession _MailSession = new RDOSession();\n private RDOFolder _IncommingInbox;\n private RDOFolder _ArchiveFolder;\n private string _SaveAttachmentPath;\n\n public MailBox(string Logon_Profile, string IncommingMailPath, \n string ArchiveMailPath, string SaveAttPath)\n {\n _MailSession.Logon(Logon_Profile, null, null, true, null, null);\n _IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath);\n _ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath);\n _SaveAttachmentPath = SaveAttPath;\n }\npublic void ProcessMail()\n {\n\n foreach (RDOMail msg in _IncommingInbox.Items)\n {\n foreach (RDOAttachment attachment in msg.Attachments)\n {\n attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName);\n }\n }\n if (msg.Body != null)\n {\n ProcessBody(msg.Body);\n }\n\n }\n\n }\n MailBox pwaMail = new MailBox(\"Self Email User\", @\"\\\\Mailbox - Someone\\Inbox\",\n @\"\\\\EMail - Incomming\\Backup\", @\"\\\\SomePath\");\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10722/" ]
223,495
<p>Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a common base class. For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without. I need to call the parameterless method via the Invoke method. Right now, all I get is an error telling me that I'm trying to call an ambiguous method.</p> <p>Yes, I <em>could</em> just cast the object as an instance of my base class and call the method I need. Eventually that <em>will</em> happen, but right now, internal complications will not allow it.</p> <p>Any help would be great! Thanks.</p>
[ { "answer_id": 223505, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "Type tp = myInstance.GetType();\n\n//call parameter-free overload\ntp.InvokeMember( \"methodName\", BindingFlags.InvokeMethod, \n Type.DefaultBinder, myInstance, new object[0] );\n\n//call parameter-ed overload\ntp.InvokeMember( \"methodName\", BindingFlags.InvokeMethod, \n Type.DefaultBinder, myInstance, new { param1, param2 } );\n" }, { "answer_id": 223521, "author": "baretta", "author_id": 30052, "author_profile": "https://Stackoverflow.com/users/30052", "pm_score": 3, "selected": false, "text": "typeof ( Class ).GetMethod ( \"Method\", new Type [ 0 ] { } ).Invoke ( instance, null );\n" }, { "answer_id": 223525, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 8, "selected": true, "text": "class SomeType \n{\n void Foo(int size, string bar) { }\n void Foo() { }\n}\n\nSomeType obj = new SomeType();\n// call with int and string arguments\nobj.GetType()\n .GetMethod(\"Foo\", new Type[] { typeof(int), typeof(string) })\n .Invoke(obj, new object[] { 42, \"Hello\" });\n// call without arguments\nobj.GetType()\n .GetMethod(\"Foo\", new Type[0])\n .Invoke(obj, new object[0]);\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13611/" ]
223,526
<p>I'm writing a small application in VB.NET and I would like some of the classes to be able to write themselves out to XML to serve as a "save" feature. I have seen XSD files used to generate VB classes that can serialize themselves into and out of XML very easily. How would I do this if I do have any pre-existing XML format that I need to conform to as I'm just creating the classes myself?</p>
[ { "answer_id": 223567, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 4, "selected": true, "text": "[XmlRoot(\"foo\")]\npublic class Foo\n{\n [XmlAttribute(\"bar\")] \n public string bar;\n [XmlAttribute(\"baz\")] \n public double baz;\n}\n <XmlRoot (\"foo\")> _\nPublic Class Foo\n <XmlAttribute (\"bar\")>_\n Public bar As String\n <XmlAttribute (\"baz\")>_\n Public baz As String\nEnd Class\n using(XmlSerializer xmls = new XmlSerializer(typeof(Foo)){\n TextWriter tw = new StreamWriter( \"foo.xml\" );\n //use it!\n}\n Using xmls As New XmlSerializer(gettype(Foo)), _\n tw As TextWriter = New StreamWriter(\"foo.xml\")\n\n ''//use it!\nEnd Using\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5904/" ]
223,533
<p>I am looking for a solution or recommendation to a problem I am having. I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.</p> <p>The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel. If we use Excel or even export to CSV, we need to be able to import to move to .resx files. So, what is the best method for this?</p> <p>I am aware of this question, <a href="https://stackoverflow.com/questions/198772/convert-a-visual-studio-resource-file-to-a-text-file">Convert a Visual Studio resource file to a text file?</a> already and the use of Resx Editor but an easier solution would be preferred.</p>
[ { "answer_id": 224214, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 2, "selected": false, "text": "namespace SampleResourceImport\n{\n class Program\n {\n static void Main(string[] args)\n {\n\n XmlDocument doc = new XmlDocument();\n string filePath = @\"[file path to your resx file]\";\n doc.Load(filePath);\n XmlElement root = doc.DocumentElement;\n\n XmlElement datum = null;\n XmlElement value = null;\n XmlAttribute datumName = null;\n XmlAttribute datumSpace = doc.CreateAttribute(\"xml:space\");\n datumSpace.Value = \"preserve\";\n\n // The following mocks the actual retrieval of your localized text\n // from a CSV or ?? document...\n // CSV parsers are common enough that it shouldn't be too difficult\n // to find one if that's the direction you go.\n Dictionary<string, string> d = new Dictionary<string, string>();\n d.Add(\"Label1\", \"First Name\");\n d.Add(\"Label2\", \"Last Name\");\n d.Add(\"Label3\", \"Date of Birth\");\n\n foreach (KeyValuePair<string, string> pair in d)\n {\n datum = doc.CreateElement(\"data\");\n datumName = doc.CreateAttribute(\"name\");\n datumName.Value = pair.Key;\n value = doc.CreateElement(\"value\");\n value.InnerText = pair.Value;\n\n datum.Attributes.Append(datumName);\n datum.Attributes.Append(datumSpace);\n datum.AppendChild(value);\n root.AppendChild(datum);\n }\n\n doc.Save(filePath);\n }\n }\n}\n" }, { "answer_id": 13387693, "author": "CSC", "author_id": 393097, "author_profile": "https://Stackoverflow.com/users/393097", "pm_score": 2, "selected": false, "text": "=CONCATENATE(\"<data name=\",\"\"\"\",A14,\"\"\" xml:space=\"\"preserve\"\">\",\"<value>\", B14, \"</value>\", \"</data>\")\n" }, { "answer_id": 19037147, "author": "Andy Gaskell", "author_id": 30697, "author_profile": "https://Stackoverflow.com/users/30697", "pm_score": 0, "selected": false, "text": "require 'csv'\nrequire 'builder'\n\nfile = ARGV[0]\n\nbuilder = Builder::XmlMarkup.new(:indent => 2)\n\nCSV.foreach(file) do |row|\n builder.data(:name => row[0], \"xml:space\" => :preserve) {|d| d.value(row[1]) }\nend\n\nFile.open(file + \".xml\", 'w') { |f| f.write(builder.target!) }\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305/" ]
223,535
<p>Is there a way to manually increase / decrease the timeout of a specific aspx page?</p>
[ { "answer_id": 223551, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 4, "selected": true, "text": " <configuration>\n <location path=\"~/Default.aspx\">\n <system.web>\n <httpRuntime executionTimeout=\"1000\"/> \n </system.web> \n </location>\n </configuration>\n" }, { "answer_id": 223578, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<appSettings>\n <!-- Application Timeout is 10 minutes -->\n <add key=\"SessionTimeoutMilliseconds\" value=\"600000\"/> \n</appSettings>\n ' Register Javascript timeout event to redirect to the login page after inactivity\nPage.ClientScript.RegisterStartupScript(Me.GetType, \"TimeoutScript\", _\n \"setTimeout(\"\"top.location.href = '/EAF/Login.aspx'\"\",\" & _\n ConfigurationManager.AppSettings(\"SessionTimeoutMilliseconds\") & \");\", True)\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
223,548
<p>I have been reading the <a href="http://msdn.microsoft.com/en-us/library/ms997565.aspx" rel="nofollow noreferrer">MSDN</a> documentation on subclassing and I have been successful in handling events in a subclass</p> <p>My issue is with passing messages back to the original WndProc.</p> <p>As an example, if I have a window, with a sub-classed groupbox control and a button as a child of that groupbox, I want to handle the button event in the original window procedure, not the subclassed groupbox procedure.</p> <p>Essentially, I want an empty subclass procedure:</p> <pre><code>LRESULT FAR PASCAL SubClassFunc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return CallWindowProc(oldProc, hwnd, uMsg, wParam, lParam); } </code></pre> <p>Where oldProc is:</p> <pre><code>FARPROC oldProc = (FARPROC)SetClassLong(group_box, GCL_WDPROC, (DWORD)SubCLassFunc); </code></pre> <p>And where the window and groupbox and button are:</p> <pre><code>HWND window = CreateWindowEx( WS_EX_WINDOWEDGE, appname, TEXT("Subclass Test"), WS_VISIBLE |WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 300, 400, NULL, NULL, hInstance, 0); HWND group_box = CreateWindowEx( 0, TEXT("BUTTON"), TEXT("Group Box"), WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 8, 8, 275, 350, window, NULL, hInstance, 0); HWND push_button = CreateWindowEx( 0, TEXT("BUTTON"), TEXT("Push Button"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_VCENTER, 50, 100, 100, 25, group_box, (HMENU)PUSH_BUTTON, hInstance, 0); </code></pre> <p>I can handle the button events in the SubClassFunc, but what I want to do is pass them back to the window WndProc. It seems that CallWindowProc isn't doing this, or I may be totally wrong in how CallWindowProc works.</p>
[ { "answer_id": 223858, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": true, "text": "SubClassFunc CallWindowProc window window group_box PostMessage SubClassFunc WM_COMMAND WM_NOTIFY window SetClassLong BUTTON BUTTON SetClassLong SetWindowLong WM_COMMAND BS_GROUPBOX WM_COMMAND window" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2067/" ]
223,549
<p>We have a product but we are doing some rebranding so we need to be able to build and maintain two versions. I used resource files combined with some #if stuff to solve the strings, images, and whatever else, but the program icon is giving me trouble. I couldn't figure it out from msdn or a google search. Thanks!</p>
[ { "answer_id": 223597, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "copy \"$(ProjectDir)$(ConfigurationName).app.ico\" \"$(ProjectDir)app.ico\"\n" }, { "answer_id": 223599, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 2, "selected": false, "text": "<PropertyGroup>\n <ApplicationIcon Condition=\" '$(Configuration)' == 'Version1' \">Icon1.ico</ApplicationIcon>\n <ApplicationIcon Condition=\" '$(Configuration)' == 'Version2' \">Icon2.ico</ApplicationIcon>\n</PropertyGroup>\n<ItemGroup Condition=\" '$(Configuration)' == 'Version1' \">\n <Content Include=\"Icon1.ico\" />\n</ItemGroup>\n<ItemGroup Condition=\" '$(Configuration)' == 'Version2' \">\n <Content Include=\"Icon2.ico\" />\n</ItemGroup>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,556
<p>Say I need some very special multiplication operator. It may be implemented in following macro:</p> <pre><code>macro @&lt;&lt;!(op1, op2) { &lt;[ ( $op1 * $op2 ) ]&gt; } </code></pre> <p>And I can use it like</p> <pre><code>def val = 2 &lt;&lt;! 3 </code></pre> <p>And its work.</p> <p>But what I really want is some 'english'-like operator for the DSL Im developing now:</p> <pre><code>macro @multiply(op1, op2) { &lt;[ ( $op1 * $op2 ) ]&gt; } </code></pre> <p>and if I try to use it like</p> <pre><code>def val = 2 multiply 3 </code></pre> <p>compiler fails with 'expected ;' error</p> <p>What is the problem? How can I implement this infix-format macro?</p>
[ { "answer_id": 223626, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 4, "selected": true, "text": "namespace Nemerle.English\n{\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"and\", false, 160, 161)]\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"or\", false, 150, 151)]\n [assembly: Nemerle.Internal.OperatorAttribute (\"Nemerle.English\", \"not\", true, 181, 180)] \n\n macro @and (e1, e2) {\n <[ $e1 && $e2 ]>\n }\n\n macro @or (e1, e2) {\n <[ $e1 || $e2 ]>\n }\n\n macro @not (e) {\n <[ ! $e ]>\n }\n public class OperatorAttribute : NemerleAttribute\n{\n public mutable env : string;\n public mutable name : string;\n public mutable IsUnary : bool;\n public mutable left : int;\n public mutable right : int;\n}\n" }, { "answer_id": 223630, "author": "noetic", "author_id": 9198, "author_profile": "https://Stackoverflow.com/users/9198", "pm_score": 1, "selected": false, "text": "namespace TestMacroLib\n{\n [assembly: Nemerle.Internal.OperatorAttribute (\"TestMacroLib\", \"multiply\", false, 160, 161)]\n public macro multiply(op1, op2)\n {\n <[ ( $op1 * $op2 ) ]>\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9198/" ]
223,559
<p>I want to know how to use variables for objects and function names in Python. In PHP, you can do this:</p> <pre><code>$className = "MyClass"; $newObject = new $className(); </code></pre> <p>How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?</p>
[ { "answer_id": 223566, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "className = MyClass\nnewObject = className()\n className MyClass MyClass className >>> className = list\n>>> newObject = className()\n>>> newObject\n[]\n list list" }, { "answer_id": 223584, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 3, "selected": false, "text": "class MyClass:\n def __init__(self):\n print \"MyClass\"\n >>> x = MyClass()\nMyClass\n >>> a = \"MyClass\"\n>>> y = eval(a)()\nMyClass\n type()" }, { "answer_id": 223586, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 6, "selected": false, "text": "import some_module\nklass = getattr(some_module, \"class_name\")\nsome_object = klass()\n class_lookup = { 'class_name' : class_name }\nsome_object = class_lookup['class_name']() #call the object once we've pulled it out of the dict\n" }, { "answer_id": 2875113, "author": "coleifer", "author_id": 254346, "author_profile": "https://Stackoverflow.com/users/254346", "pm_score": 5, "selected": false, "text": ">>> class_name = 'MyClass'\n>>> klass = type(class_name, (object,), {'msg': 'foobarbaz'})\n\n<class '__main__.MyClass'>\n\n>>> inst = klass()\n>>> inst.msg\nfoobarbaz\n" }, { "answer_id": 59900521, "author": "Yanone", "author_id": 1209986, "author_profile": "https://Stackoverflow.com/users/1209986", "pm_score": 1, "selected": false, "text": "newObject = globals()[className]()\n" }, { "answer_id": 71837153, "author": "Akash Ranjan", "author_id": 3606723, "author_profile": "https://Stackoverflow.com/users/3606723", "pm_score": 0, "selected": false, "text": ">>> class AB:\n... def __init__(self, tt):\n... print(tt, \"from class AB\")\n... \n>>> class BC:\n... def __init__(self, tt):\n... print(tt, \"from class BC\")\n... \n>>> x = { \"ab\": AB, \"bc\": BC}\n>>> x\n{'ab': <class '__main__.AB'>, 'bc': <class '__main__.BC'>}\n>>> \n>>> x['ab']('hello')\nhello from class AB\n<__main__.AB object at 0x10dd14b20>\n>>> x['bc']('hello')\nhello from class BC\n<__main__.BC object at 0x10eb33dc0>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
223,611
<p>When I try to create a new RegionInfo with certain ISO 3166 country codes ("BD" for Bangladesh, "SO" for Somalia, "LK" for Sri Lanka), I get an ArgumentException that says it's not recognized.</p> <p>What's the deal? The Intellisense of RegionInfo(string) says it conforms to ISO 3166, but these country/region codes are not supported? </p> <p>I don't get it.</p>
[ { "answer_id": 19362724, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 2, "selected": false, "text": "RegionInfo foreach (var ri in CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(ci => new RegionInfo(ci.ToString())).OrderBy(x => x.TwoLetterISORegionName))\n Console.WriteLine(\"{0,3}: {1,11}: {2} ({3})\", ri.TwoLetterISORegionName, ri, ri.EnglishName, ri.NativeName);\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
223,614
<p>How to copy file(s) from one solaris 9 machine to another solaris 9 machine using only java?</p> <p>We have ssh access to both machines. The java program will run on one of those two machines.</p> <p>Update: rsync is not really an option. can't install it easily (UNIX team is, hum, hard to deal with)</p>
[ { "answer_id": 19362724, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 2, "selected": false, "text": "RegionInfo foreach (var ri in CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(ci => new RegionInfo(ci.ToString())).OrderBy(x => x.TwoLetterISORegionName))\n Console.WriteLine(\"{0,3}: {1,11}: {2} ({3})\", ri.TwoLetterISORegionName, ri, ri.EnglishName, ri.NativeName);\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479/" ]
223,618
<p>First of all (in case this is important) I'm using ActiveState's Perl (v5.8.7 built for MSWin32-x86-multi-thread).</p> <p>I've just emerged from a three hour long debugging session, trying to find the source of an error. I found there was simply no error, but for some reason ADO's connection object was getting the <code>Errors.Count</code> increased with each printed message in my stored procedure's output.</p> <p>Consider following Transact SQL code:</p> <pre><code>CREATE PROCEDURE dbo.My_Sample() AS BEGIN TRAN my_tran -- Does something useful if @@error &lt;&gt; 0 BEGIN ROLLBACK TRAN my_tran RAISERROR( 'SP My_Sample failed', 16, 1) END ELSE BEGIN COMMIT TRAN my_tran PRINT 'SP My_Sample succeeded' END </code></pre> <p>Now imagine a Perl sub more or less like:</p> <pre><code>sub execute_SQL { # $conn is an already opened ADO connection object # pointing to my SQL Server # $sql is the T-SQL statement to be executed my($conn, $sql) = @_; $conn-&gt;Execute($sql); my $error_collection = $conn-&gt;Errors(); my $ecount = $error_collection-&gt;Count; if ($ecount == 0 ) { return 0; } print "\n" . $ecount . " errors found\n"; print "Executed SQL Code:\n$sql\n\n"; print "Errors while executing:\n"; foreach my $error (in $error_collection){ print "Error: [" . $error-&gt;{Number} . "] " . $error-&gt;{Description} . "\n"; } return 1; } </code></pre> <p>Somewhere else, in the main Perl code, I'm calling the above sub as:</p> <pre><code>execute_SQL( $conn, 'EXEC dbo.My_Sample' ); </code></pre> <p>In the end I got it that <em>every</em> PRINT statement causes a new pseudo-error to be appended to the ADO Errors collection. The quick fix I implemented was to change that PRINT in the SP into a SELECT, to bypass this.</p> <p>The questions I'd like to ask are:</p> <ul> <li>Is this behaviour normal?</li> <li>Is there a way to avoid/bypass it?</li> </ul>
[ { "answer_id": 227041, "author": "Joe Pineda", "author_id": 21258, "author_profile": "https://Stackoverflow.com/users/21258", "pm_score": 1, "selected": false, "text": "sub execute_SQL {\n # $conn is an already opened ADO connection object\n # pointing to my SQL Server\n # $sql is the T-SQL statement to be executed\n # Returns 0 if no error found, 1 otherwise\n my($conn, $sql) = @_;\n $conn->Execute($sql);\n my $error_collection = $conn->Errors();\n my $ecount = $error_collection->Count;\n if ($ecount == 0 ) { return 0; }\n\n my ($is_message, $real_error_found);\n foreach my $error (in $error_collection){\n $is_message = ($error->{SQLState} eq \"01000\" && $error->{NativeError}==0);\n $real_error_found=1 unless $is_message;\n\n if( $is_message) {\n print \"Message # \" . $error->{Number}\n . \"\\n Text: \" . $error->{Description} .\"\\n\";\n } else {\n print \"Error # \" . $error->{Number}\n . \"\\n Description: \" . $error->{Description}\n . \"\\nSource: \" . $error->{Source} . \"\\n\";\n }\n }\n\n print $message_to_print;\n return $real_error_found;\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21258/" ]
223,627
<p>I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in.</p> <p>i.e. in the surname box, I should be able to type gr, and it brings up </p> <p>green grey graham</p> <p>but at present it's not bringing up anything uless the full search string is used.</p> <p>There are 4 search controls on the form in question, and they are only used in the query if the box is filled in.</p> <p>The query is :</p> <pre><code>SELECT TabCustomers.*, TabCustomers.CustomerForname AS NameSearch, TabCustomers.CustomerSurname AS SurnameSearch, TabCustomers.CustomerDOB AS DOBSearch, TabCustomers.CustomerID AS MemberSearch FROM TabCustomers WHERE IIf([Forms]![FrmSearchCustomer]![SearchMember] Is Null ,True ,[Forms]![FrmSearchCustomer]![SearchMember]=[customerid])=True AND IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null ,True ,[Forms]![FrmSearchCustomer]![SearchFore] Like [customerforname] &amp; "*")=True AND IIf([Forms]![FrmSearchCustomer]![SearchLast] Is Null ,True ,[Forms]![FrmSearchCustomer]![SearchLast] Like [customersurname] &amp; "*")=True AND IIf([Forms]![FrmSearchCustomer]![Searchdate] Is Null ,True ,[Forms]![FrmSearchCustomer]![Searchdate] Like [customerDOB] &amp; "*")=True; </code></pre>
[ { "answer_id": 223648, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": ",[Forms]![FrmSearchCustomer]![SearchFore] Like ([customerforname] & \"*\"))=True\n" }, { "answer_id": 223710, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "SELECT TabCustomers.CustomerForname AS NameSearch, TabCustomers.CustomerSurname AS SurnameSearch, TabCustomers.CustomerDOB AS DOBSearch, TabCustomers.customerid AS MemberSearch\nFROM TabCustomers\nWHERE TabCustomers.customerid Like IIf([Forms]![FrmSearchCustomer].[Searchmember] Is Null,\"*\",[Forms]![FrmSearchCustomer]![Searchmember])\nAND Trim(TabCustomers.CustomerForname & \"\") Like IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchFore] & \"*\")\nAND Trim(TabCustomers.CustomerSurname & \"\") like IIf([Forms]![FrmSearchCustomer].[Searchlast] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchLast] & \"*\")\nAND (TabCustomers.CustomerDOB Like IIf([Forms]![FrmSearchCustomer].[SearchDate] Is Null,\"*\",[Forms]![FrmSearchCustomer]![SearchDate] ) Or TabCustomers.CustomerDOB Is Null)\n" }, { "answer_id": 223733, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 2, "selected": false, "text": ",[customerforname] Like \"\"\"\" & [Forms]![FrmSearchCustomer]![SearchFore] & \"*\"\"\" )=True\n" }, { "answer_id": 223791, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 3, "selected": false, "text": "SELECT TabCustomers.*\nFROM TabCustomers\nWHERE (Forms!FrmSearchCustomer!SearchMember Is Null Or Forms!FrmSearchCustomer!SearchMember=[customerid]) \nAnd (Forms!FrmSearchCustomer.SearchFore Is Null Or [customerforname] Like Forms!FrmSearchCustomer!SearchFore & \"*\") \nAnd (Forms!FrmSearchCustomer!SearchLast Is Null Or [customersurname] Like Forms!FrmSearchCustomer!SearchLast & \"*\") \nAnd (Forms!FrmSearchCustomer!Searchdate Is Null Or [customerDOB] Like Forms!FrmSearchCustomer!Searchdate & \"*\");\n" }, { "answer_id": 224961, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 4, "selected": true, "text": "selectClause = \"SELECT TabCustomers.* FROM TabCustomers\"\nif not isnull(Forms!FrmSearchCustomer!SearchMember) then\n whereClause = whereClause & application.buildCriteria(your field name, your field type, your control value) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchFore) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchLast) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\nif not isnull(Forms!FrmSearchCustomer!SearchDate) then\n whereClause = whereClause & application.buildCriteria(...) & \" AND \"\nendif\n--get rid of the last \"AND\"\nif len(whereClause) > 0 then\n whereClause = left(whereClause,len(whereClause)-5)\n selectClause = selectClause & \" WHERE \" & whereClause\nendif\n-- your SELECT instruction is ready ...\n 'field1 = \"GR\"' 'field1 LIKE \"GR*\"' \"GR*\" 'field1 LIKE \"GR*\" or field1 like \"BR*\"' 'LIKE \"GR*\" OR LIKE \"BR*\"' For each ctl in myForm.section(acHeader).controls\n if ctl.name like \"search_\"\n fld = myForm.recordset.fields(mid(ctl.name,8))\n if not isnull(ctl.value) then\n whereClause = whereClause & buildCriteria(fld.name ,fld.type, ctl.value) & \" AND \"\n endif\n endif\nnext ctl\nif len(whereClause)> 0 then ...\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30140/" ]
223,628
<p>I have derived a TabControl with the express purpose of enabling double buffering, except nothing is working as expected. Here is the TabControl code:</p> <pre><code>class DoubleBufferedTabControl : TabControl { public DoubleBufferedTabControl() : base() { this.DoubleBuffered = true; this.SetStyle ( ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, false ); } } </code></pre> <p>This Tabcontrol is then set with it's draw mode as 'OwnerDrawnFixed' so i can changed the colours. Here is the custom drawing method:</p> <pre><code> private void Navigation_PageContent_DrawItem(object sender, DrawItemEventArgs e) { //Structure. Graphics g = e.Graphics; TabControl t = (TabControl)sender; TabPage CurrentPage = t.TabPages[e.Index]; //Get the current tab Rectangle CurrentTabRect = t.GetTabRect(e.Index); //Get the last tab. Rectangle LastTab = t.GetTabRect(t.TabPages.Count - 1); //Main background rectangle. Rectangle BackgroundRect = new Rectangle(LastTab.Width, t.Bounds.Y - 4, t.Width - (LastTab.Width), t.Height); //Tab background rectangle. Rectangle TabBackgroundRect = new Rectangle(0, LastTab.Y + LastTab.Height, LastTab.Width, t.Bounds.Height - (LastTab.Y + LastTab.Height)); //Set anitialiasing for the text. e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; //String format for the text. StringFormat StringFormat = new StringFormat(); StringFormat.Alignment = StringAlignment.Center; StringFormat.LineAlignment = StringAlignment.Center; //Fill the background. g.FillRectangle(Brushes.LightGray, BackgroundRect); g.FillRectangle(Brushes.Bisque, TabBackgroundRect); //Draw the selected tab. if(e.State == DrawItemState.Selected) { g.FillRectangle(Brushes.White, e.Bounds); Rectangle SelectedTabOutline = new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 4); g.DrawRectangle(new Pen(Brushes.LightGray, 4f), SelectedTabOutline); g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Bold, GraphicsUnit.Point), new SolidBrush(Color.FromArgb(70, 70, 70)), CurrentTabRect, StringFormat); } else { g.FillRectangle(new SolidBrush(Color.FromArgb(230, 230, 230)), e.Bounds); g.DrawString(CurrentPage.Text, new Font("Arial", 12f, FontStyle.Regular, GraphicsUnit.Point), Brushes.Gray, CurrentTabRect, StringFormat); } } </code></pre> <p>All to no avail however, as this control is not double buffered and still flickers when resized.</p> <p><strong>Any ideas?</strong></p>
[ { "answer_id": 277872, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 0, "selected": false, "text": "this.DoubleBuffered = true" }, { "answer_id": 278958, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 2, "selected": false, "text": "TabControl TabControl protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n TabControl" }, { "answer_id": 302760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "protected override void OnPaintBackground( PaintEventArgs pevent )\n{\n //do not call base - I don't want the background re-painted!\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
223,631
<p>I'm trying to make a combo box that behaves somewhat like the Firefox 3 Awesomebar, with the following behavior:</p> <ol> <li>Type in text</li> <li>Asynchronously bring back results</li> <li>Up and down selects results in the list, <strong>BUT</strong> leaves the text that was typed in the entry box so the user can continue editing to limit the resultset differently</li> <li>Enter fires an event that the parent form will handle</li> </ol> <p>I have the asynchronous results and filtering all working, but I don't have a good method for displaying and selecting within the results.</p> <p>A combo box automatically fills the entry box with what is selected when you arrow down. Fails #3.</p> <p>I've got the DevExpress controls, but their combo box does the same thing and I can't figure out how to override either.</p> <p>A LookupEdit does not allow typing arbitrary stuff. Neither does a PopupContainerEdit.</p> <p>I want behavior that's like a textbox with a listbox below it, and up/down events in the textbox get passed to the listbox. But if I try to make a custom control that combines the two like that, I have no clue how to "float" the listbox like the dropdown on a normal combo box.</p> <p>Clues much appreciated!</p>
[ { "answer_id": 277872, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 0, "selected": false, "text": "this.DoubleBuffered = true" }, { "answer_id": 278958, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 2, "selected": false, "text": "TabControl TabControl protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n TabControl" }, { "answer_id": 302760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "protected override void OnPaintBackground( PaintEventArgs pevent )\n{\n //do not call base - I don't want the background re-painted!\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27614/" ]
223,634
<p>The other day I set up an Ubuntu installation in a VM and went to gather the tools and libraries I figured I would need for programming mostly in C++.</p> <p>I had a problem though, where to put things such as 3rd party source libraries, etc. From what I can gather, a lot of source distributions assume that a lot of their dependencies are already installed in a certain location and assume that a lot of tools are also installed in particular locations.</p> <p>To give an example of what I currently do on Windows, is I have a directory where I keep all source code. <code>C:\code</code>. In this directory, I have a directory for all 3rd party libraries, <code>c:\code\thirdparty\libs</code>. This way I can easily set up relative paths for all of the dependencies of any projects I write or come across and wish to compile. The reason I am interested in setting up a linux programming environment is that it seems that both the tool and library dependency problems have been solved efficiently making it easy for example to build OpenSSH from source.</p> <p>So what I was looking for was a decent convention I can use when I am trying to organize my projects and libraries on linux that is easy to maintain and easy to use.</p>
[ { "answer_id": 223637, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 3, "selected": false, "text": "/usr/local/lib\n/usr/local/include\n" }, { "answer_id": 223654, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 1, "selected": false, "text": "%> sudo apt-get install util-linux\n" }, { "answer_id": 224984, "author": "orj", "author_id": 20480, "author_profile": "https://Stackoverflow.com/users/20480", "pm_score": 2, "selected": false, "text": "configure makefile branches/\ntags/\ntrunk/\nvendor/somelib\nvendor/anotherlib\n vendor/somelib/1.0\nvendor/somelib/1.1\nvendor/somelib/current\n svn:externals svn propedit svn:externals trunk/libs\n ^/vendor/somelib/current somelib\n^/vendor/anotherlib/1.0 anotherlib\n trunk/source\ntrunk/libs/somelib\ntrunk/libs/anotherlib\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29049/" ]
223,640
<p>My class is implementing a super-class method which which returns <code>List&lt;JComponent&gt;</code>. The list being returned is read-only:</p> <pre><code>public abstract class SuperClass { public abstract List&lt;JComponent&gt; getComponents(); } </code></pre> <p>In my class, I want to return a field which is declared as List - i.e. a sub-list:</p> <pre><code>public class SubClass extends SuperClass { private List&lt;JButton&gt; buttons; public List&lt;JComponent&gt; getComponents() { return buttons; } } </code></pre> <p>This generates a compiler error, as <code>List&lt;JButton&gt;</code> is not a subtype of <code>List&lt;JComponent&gt;</code>.</p> <p>I can understand why it doesn't compile, as it shouldn't be allowed to add a JTextField to a List of JButtons.</p> <p>However, as the list is read-only, then "conceptually" this should be allowed. But, of course, the compiler doesn't know that it is read-only.</p> <p>Is there any way to achieve what I want to achieve, without changing the method declaration in the super-class, and the field declaration in the sub-class?</p> <p>Thanks, Calum</p>
[ { "answer_id": 223653, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "getComponents() public List<? extends JComponent> getComponents()\n" }, { "answer_id": 223670, "author": "Guðmundur Bjarni", "author_id": 27349, "author_profile": "https://Stackoverflow.com/users/27349", "pm_score": 0, "selected": false, "text": "public abstract class SuperClass {\n public abstract List<? extends JComponent> getComponents();\n}\n\n\npublic class SubClass extends SuperClass {\n private List<JButton> buttons;\n public List<? extends JComponent> getComponents() {\n return buttons;\n }\n}\n" }, { "answer_id": 223672, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 0, "selected": false, "text": "public abstract class SuperClass {\n public abstract List<? extends JComponent> getComponents();\n}\n" }, { "answer_id": 223718, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": -1, "selected": false, "text": "@SuppressWarnings public List<JComponent> getComponents()\n{\n return new ArrayList<JComponent>( buttons );\n}\n List<JComponent> list = obj.getComponents();\n" }, { "answer_id": 223768, "author": "Instantsoup", "author_id": 9861, "author_profile": "https://Stackoverflow.com/users/9861", "pm_score": 2, "selected": false, "text": "public class SubClass extends SuperClass {\n private List<JComponent> buttons = new ArrayList<JComponent>();\n public void addButton(JButton button) {\n buttons.add(button);\n }\n public List<JComponent> getComponents() {\n return Collections.unmodifiableList(buttons);\n }\n}\n public abstract class SuperClass<E extends JComponent> {\n public abstract List<E> getComponents();\n}\n\npublic class SubClass extends SuperClass<JButton> {\n private List<JButton> buttons = new ArrayList<JButton>();\n public List<JButton> getComponents() {\n return Collections.unmodifiableList(buttons);\n }\n}\n" }, { "answer_id": 223786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "return Collections.<JComponent>unmodifiableList(buttons);\n return Collections.unmodifiableList(buttons);\n List<JButton> List<JButton> List<JComponent> unmodifiableList()" }, { "answer_id": 223801, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 0, "selected": false, "text": "List<JButton> List<JComponent> List<JComponent> jc;\nList<JButton> jb = new ArrayList<JButton>();\n//if List<JButton> was a sublcass of List<JComponent> then this is a valid assignment\njc = jb;\njc.add(new JCheckBox()); //valid, as jc accepts any JComponent\n\nJButton b = jb.get(0); //this will throw a ClassCastException, rendering Generic type-safety pointless\n String Float JTable" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,643
<p>I'm currently adding some new extended classes to this code:</p> <pre><code>foreach (BaseType b in CollectionOfExtendedTypes) { if (b is ExtendedType1) { ((ExtendedType1) b).foo = this; } else if (b is ExtendedType2) { ((ExtenedType2) b).foo = this; } else { b.foo = this; } } </code></pre> <p>and was curious if there is a way to use the <code>is</code> keyword functionality in a switch statement?</p>
[ { "answer_id": 223658, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "\nTypeSwitch.Do(\n sender,\n TypeSwitch.Case<Button>(() => textBox1.Text = \"Hit a Button\"),\n TypeSwitch.Case<CheckBox>(x => textBox1.Text = \"Checkbox is \" + x.Checked),\n TypeSwitch.Default(() => textBox1.Text = \"Not sure what is hovered over\"));\n" }, { "answer_id": 223667, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 1, "selected": false, "text": "getType() BaseType" }, { "answer_id": 223688, "author": "Samuel Kim", "author_id": 437435, "author_profile": "https://Stackoverflow.com/users/437435", "pm_score": 2, "selected": false, "text": "IDictionary<Type, T> switch (b.GetType().Name)" }, { "answer_id": 223856, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": -1, "selected": false, "text": "switch is if (obj is Foo)\n if (obj.GetType() == typeof(Foo))\n is if (obj is System.Object)\n{\n //this will always execute\n}\nelse if (obj is Foo)\n{\n //this will never execute\n}\n is public enum MyType { Foo, Bar, Baz };\npublic static class MyTypeExtension\n{\n public static MyType GetMyType(this Foo o)\n {\n return MyType.Foo;\n }\n public static MyType GetMyType(this Bar o)\n {\n return MyType.Bar;\n }\n public static MyType GetMyType(this Baz o)\n {\n return MyType.Baz;\n }\n}\n switch switch (myObject.GetType())\n{\n case MyType.Foo:\n // etc.\n" }, { "answer_id": 449511, "author": "Jeffrey Hantin", "author_id": 55637, "author_profile": "https://Stackoverflow.com/users/55637", "pm_score": 0, "selected": false, "text": "\npublic class Listener\n{\n public virtual void Process(Base obj) { }\n public virtual void Process(Derived obj) { }\n public virtual void Process(OtherDerived obj) { }\n}\n\npublic class Base\n{\n public virtual void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class Derived\n{\n public override void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class OtherDerived\n{\n public override void Dispatch(Listener l) { l.Process(this); }\n}\n\npublic class ExampleListener\n{\n public override void Process(Derived obj)\n {\n Console.WriteLine(\"I got a Derived\");\n }\n\n public override void Process(OtherDerived obj)\n {\n Console.WriteLine(\"I got an OtherDerived\");\n }\n\n public void ProcessCollection(IEnumerable collection)\n {\n foreach (Base obj in collection) obj.Dispatch(this);\n }\n}\n" }, { "answer_id": 47575390, "author": "MikeT", "author_id": 735897, "author_profile": "https://Stackoverflow.com/users/735897", "pm_score": 5, "selected": false, "text": " case type varname \n" }, { "answer_id": 49688285, "author": "smoksnes", "author_id": 4949005, "author_profile": "https://Stackoverflow.com/users/4949005", "pm_score": 2, "selected": false, "text": "foreach (BaseType b in CollectionOfExtendedTypes) {\n switch (b) {\n case ExtendedType1 et1:\n // Do stuff with et1.\n et1.DoStuff();\n break;\n case ExtendedType2 et2:\n // Do stuff with et2.\n et2.DoOtherStuff();\n break;\n default:\n // Do something else...\n break;\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21387/" ]
223,644
<p>Sometimes whenever I write a program in Linux and it crashes due to a bug of some sort, it will become an uninterruptible process and continue running forever until I restart my computer (even if I log out). My questions are:</p> <ul> <li>What causes a process to become uninterruptible?</li> <li>How do I stop that from happening?</li> <li>This is probably a dumb question, but is there any way to interrupt it without restarting my computer?</li> </ul>
[ { "answer_id": 223727, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 9, "selected": true, "text": "read()" }, { "answer_id": 224042, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 6, "selected": false, "text": "SIGTERM SIGKILL TASK_INTERRUPTIBLE TASK_UNINTERRUPTIBLE TASK_KILLABLE" }, { "answer_id": 44231392, "author": "Ron Granger", "author_id": 6788490, "author_profile": "https://Stackoverflow.com/users/6788490", "pm_score": 1, "selected": false, "text": "sudo kill -HUP 1" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
223,652
<p>I was wondering if there is any way to escape a CDATA end token (<code>]]&gt;</code>) within a CDATA section in an xml document. Or, more generally, if there is some escape sequence for using within a CDATA (but if it exists, I guess it'd probably only make sense to escape begin or end tokens, anyway). </p> <p>Basically, can you have a begin or end token embedded in a CDATA and tell the parser not to interpret it but to treat it as just another character sequence.</p> <p>Probably, you should just refactor your xml structure or your code if you find yourself trying to do that, but even though I've been working with xml on a daily basis for the last 3 years or so and I have never had this problem, I was wondering if it was possible. Just out of curiosity.</p> <p>Edit:</p> <p>Other than using html encoding...</p>
[ { "answer_id": 223773, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": false, "text": "]]> <![CDATA[]]]]><![CDATA[>]]> <![CDATA[]]]]> ]] <![CDATA[>]]> >" }, { "answer_id": 223782, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 8, "selected": true, "text": "[20] CData ::= (Char* - (Char* ']]>' Char*))\n &lt; &amp; ]]> ]]> ]]> <![CDATA[Certain tokens like ]]> can be difficult and <invalid>]]> \n <![CDATA[Certain tokens like ]]]]><![CDATA[> can be difficult and <valid>]]> \n" }, { "answer_id": 224007, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "XmlElement elm = doc.CreateElement(\"foo\");\nelm.InnerText = \"<[CDATA[[Is this a problem?]]>\";\n XmlDocument doc = new XmlDocument();\n\nXmlElement elm = doc.CreateElement(\"doc\");\ndoc.AppendChild(elm);\n\nstring data = \"<![[CDATA[This is an embedded CDATA section]]>\";\nXmlCDataSection cdata = doc.CreateCDataSection(data);\nelm.AppendChild(cdata);\n Console.Write(doc.OuterXml);\n" }, { "answer_id": 5491903, "author": "Jason Pyeron", "author_id": 58794, "author_profile": "https://Stackoverflow.com/users/58794", "pm_score": 4, "selected": false, "text": "]]> > ]] ]]><![CDATA[ > \\ > ]]" }, { "answer_id": 10943547, "author": "Shawn Becker", "author_id": 1443758, "author_profile": "https://Stackoverflow.com/users/1443758", "pm_score": 2, "selected": false, "text": "]]> <htmlSource><![CDATA[ \n ... html ...\n <script type=\"text/javascript\">\n /* <![CDATA[ */\n -- some working javascript --\n /* ]]> */\n </script>\n ... html ...\n]]></htmlSource>\n /* ]]]]><![CDATA[> *//\n" }, { "answer_id": 15544083, "author": "user2194495", "author_id": 2194495, "author_profile": "https://Stackoverflow.com/users/2194495", "pm_score": 1, "selected": false, "text": "'<![CDATA['.implode(explode(']]>', $string), ']]]]><![CDATA[>').']]>'" }, { "answer_id": 18405980, "author": "Alain Tiemblo", "author_id": 731138, "author_profile": "https://Stackoverflow.com/users/731138", "pm_score": 1, "selected": false, "text": " function safeCData($string)\n {\n return '<![CDATA[' . str_replace(']]>', ']]]]><![CDATA[>', $string) . ']]>';\n }\n $string function mb_str_replace($search, $replace, $subject, &$count = 0)\n {\n if (!is_array($subject))\n {\n $searches = is_array($search) ? array_values($search) : array ($search);\n $replacements = is_array($replace) ? array_values($replace) : array ($replace);\n $replacements = array_pad($replacements, count($searches), '');\n foreach ($searches as $key => $search)\n {\n $parts = mb_split(preg_quote($search), $subject);\n $count += count($parts) - 1;\n $subject = implode($replacements[$key], $parts);\n }\n }\n else\n {\n foreach ($subject as $key => $value)\n {\n $subject[$key] = mb_str_replace($search, $replace, $value, $count);\n }\n }\n return $subject;\n }\n" }, { "answer_id": 36331725, "author": "Thomas Grainger", "author_id": 833093, "author_profile": "https://Stackoverflow.com/users/833093", "pm_score": 4, "selected": false, "text": "]]> ]]]]><![CDATA[>" }, { "answer_id": 47445432, "author": "Chad Kuehn", "author_id": 1069995, "author_profile": "https://Stackoverflow.com/users/1069995", "pm_score": -1, "selected": false, "text": "<![CDATA[\n <![CDATA[\n <div>Hello World</div>\n ]]]]><![CDATA[>\n]]>\n ]]]]><![CDATA[> ]]>" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24170/" ]
223,666
<p>I am looking for the cleanest way. I am tempted to use delegates not sure though.</p>
[ { "answer_id": 223746, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 2, "selected": true, "text": "class A\n{\n public int Value;\n public int Add(int a) { return a + Value; }\n public int Mul(int a) { return a * Value; }\n}\n\nclass Program\n{\n static void Main( string[] args )\n {\n A a = new A();\n a.Value = 10;\n Func<int, int> f;\n f = a.Add;\n Console.WriteLine(\"Add: {0}\", f(5));\n f = a.Mul;\n Console.WriteLine(\"Mul: {0}\", f(5));\n }\n}\n Func<A,int,int> f = delegate( A o, int i ) { return o.Add( i ); };\nConsole.WriteLine( \"Add: {0}\", f( a, 5 ) );\nf = ( A o, int i ) => o.Mul( i );\nConsole.WriteLine( \"Mul: {0}\", f( a, 5 ) );\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438/" ]
223,673
<p>Alright, I am going to state up front that this question may be too involved (amount of detail not complexity) for this medium. But I figured this was the best place to start.</p> <p>I am attempting to setup a proof of concept project and my BIND configuration is my first big hurdle. I want to setup 3 DNS servers on 3 physical boxes. <strong>None</strong> of these boxes needs to resolve public addresses, this is internal <strong>only</strong>. I have read through how to setup internal roots in the (mostly) excellent DNS &amp; BIND 5th ed book. But my translation of their example is not functional. All IP's are RFC 1918 non-routable.</p> <p>Box 1 will be authoritative for addresses on the <em>box1.bogus</em> domain, and Box 2 will be authoritative for addresses on the <em>box2.bogus</em> domain. Box 3 will act as both an internal root and the TLD server for the domain <em>bogus</em>.</p> <p>Current unresolved issues:</p> <ul> <li><p>I have a hints file on box 1 and 2 that contains a single <strong>NS</strong> record to the NS definition of the root zone. Additionally there is an <strong>A</strong> record that translates the NS to the ip of the root. if I <code>dig .</code> from box 1 I get an <em>authority</em> Section with the NS name, not an <em>answer</em> and <em>additional</em> record section. Therefore I am unable to actually resolve the IP of the root server from box 1.</p></li> <li><p>If I point my <code>/etc/resolv.conf</code> from box 1 directly at the root server and do a <code>dig box1.bogus</code> I get the ns.box1.bogus <em>answer</em> record and the translation in the <em>additional</em> section. However on the next iteration (when should get the A record) I get <code>dig: couldn't get address for ns.box1.bogus</code></p></li> </ul> <p>Obviously my configs are <strong>not</strong> correct. I don't see a way to attach them to this post, so if people want to walk through this step by step I will cut'n'paste them into a comment for this question. Otherwise I am open to taking this 'offline' with a "DNS guy" to figure out where I'm missing a '.' or have one too many!</p> <p>I personally think the web could do with another internal root example that doesn't make use of the Movie-U example.</p> <p>OK, if we are going to do this, then we should use a concrete example eh? I have 3 machines setup on a private VLAN for testing this. As a sanity check I paired down all my relevant configs, condensed when able, and redeployed 2 of the namesevers. I left out Scratchy for now. Same results as above. Here are the configs and initial dig outputs.</p> <hr> <h2>Bogus</h2> <pre><code>Machine Name: Bogus (I just realized I should change this...) Role: Internal Root and TLD Nameserver IP: 10.0.0.1 BIND: 9.5.0-16.a6.fc8 </code></pre> <h3>/etc/named.conf</h3> <pre><code>// Controls who can make queries of this DNS server. Currently only the // local test bed. When there is a standardized IP addr scheme, we can have // those addr ranges enabled so that even if firewall rules get broken, the // public internet can't query the internal DNS. // acl "authorized" { localhost; // localhost 10.0.0.0/24; // Local Test }; options { listen-on port 53 { 127.0.0.1; 10.0.0.1; }; listen-on-v6 port 53 { ::1; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; pid-file "/var/run/named/named.pid"; allow-query { any; }; recursion no; }; logging { channel default_debug { file "data/named.run"; severity dynamic; }; }; // // The fake root. // zone "." { type master; file "master/root"; allow-query { authorized; }; }; // // The TLD for testing // zone "bogus" { type master; file "master/bogus"; allow-query { authorized; }; allow-transfer { authorized; }; }; </code></pre> <h3> /var/named/master/root </h3> <pre><code>$TTL 3600 . SOA ns.bogustld. hostmaster.internal.bogus. ( 2008101601 ; serial 1H ; refresh 2H ; retry 14D ; expire 5M ) ; minimum ; ; Fake root zone servers defined. ; . NS ns.bogustld. ns.bogustld. A 10.0.0.1 ; ; Testing TLD ; bogus NS ns1.bogus. ns1.bogus. A 10.0.0.1 </code></pre> <h3>/var/named/master/bogus</h3> <pre><code>$TTL 3600 @ SOA ns1.internal.bogus. hostmaster.internal.bogus. ( 2008102201 ; serial date +seq 1H ; refresh 2H ; retry 14D ; expire 5M) ; min TTL ; NS ns1.internal.bogus. ; ; Auth servers ; ns1.internal.bogus. A 10.0.0.1 ; ; Customer delegations each customer 2nd level domain has it's ; own zone file. ; ;Modified to be unique nameservers in the bogus domain itchy NS ns1-itchy.bogus. ns1-itchy.bogus. A 10.0.0.2 ; scratchy NS ns1-scratchy.bogus. ns1-scratchy.bogus. A 10.0.0.3 </code></pre> <h3>Output from dig .</h3> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.5.0-P2 &lt;&lt;&gt;&gt; . ;; global options: printcmd ;; Got answer: ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 57175 ;; flags: qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;. IN A ;; AUTHORITY SECTION: . 300 IN SOA ns.bogustld. hostmaster.internal .bogus. 2008101601 3600 7200 1209600 300 ;; Query time: 1 msec ;; SERVER: 10.0.0.1#53(10.0.0.1) ;; WHEN: Tue Oct 21 12:23:59 2008 ;; MSG SIZE rcvd: 88 </code></pre> <h3>Output from dig +trace itchy.bogus </h3> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.5.0-P2 &lt;&lt;&gt;&gt; +trace itchy.bogus ;; global options: printcmd . 3600 IN NS ns.bogustld. ;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms itchy.bogus. 3600 IN NS ns1-itchy.bogus. ;; Received 69 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms itchy.bogus. 3600 IN A 10.0.0.2 itchy.bogus. 3600 IN NS ns1.itchy.bogus. ;; Received 79 bytes from 10.0.0.2#53(ns1-itchy.bogus) in 0 ms </code></pre> <hr> <h2>Itchy</h2> <pre><code>Machine Name: Itchy Role: SLD Nameserver (supposed to be owner of itchy.bogus) IP: 10.0.0.2 BIND: 9.5.0-16.a6.fc8 </code></pre> <h3>/etc/named.conf</h3> <pre><code>// Controls who can make queries of this DNS server. Currently only the // local test bed. When there is a standardized IP addr scheme, we can have // those addr ranges enabled so that even if firewall rules get broken, the // public internet can't query the internal DNS. // acl "authorized" { localhost; // localhost 10.0.0.0/24; // LAN Test }; options { listen-on port 53 { 127.0.0.1; 10.0.0.2; }; listen-on-v6 port 53 { ::1; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; pid-file "/var/run/named/named.pid"; allow-query { any; }; recursion no; }; logging { channel default_debug { file "data/named.run"; severity dynamic; }; }; zone "." IN { type hint; file "master/root.hint"; }; zone "itchy.bogus" { type master; file "master/itchy.bogus"; allow-query { authorized; }; allow-transfer { authorized; }; }; </code></pre> <h3>/var/named/master/itchy.bogus</h3> <pre><code>$TTL 3600 @ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. ( 2008102202 ; serial 1H ; refresh 2H ; retry 14D ; expire 5M ) ; minimum ; A 10.0.0.2 NS ns1.itchy.bogus. ns1 A 10.0.0.2 </code></pre> <h3>/var/named/master/root.hint</h3> <pre><code>. 3600000 NS ns.bogustld. ns.bogustld. 3600000 A 10.0.0.1 ; End of File </code></pre> <h3>/etc/resolv.conf</h3> <pre><code>nameserver 10.0.0.2 </code></pre> <h3> Output from dig .</h3> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.5.0-P2 &lt;&lt;&gt;&gt; . ;; global options: printcmd ;; Got answer: ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 31291 ;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;. IN A ;; AUTHORITY SECTION: . 3600000 IN NS ns.bogustld. ;; Query time: 0 msec ;; SERVER: 10.0.0.2#53(10.0.0.2) ;; WHEN: Tue Oct 21 17:09:53 2008 ;; MSG SIZE rcvd: 41 </code></pre> <h3>Output from dig + trace itchy.bogus </h3> <pre><code>; &lt;&lt;&gt;&gt; DiG 9.5.0-P2 &lt;&lt;&gt;&gt; +trace itchy.bogus ;; global options: printcmd . 3600000 IN NS ns.bogustld. ;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms dig: couldn't get address for 'ns.bogustld': failure </code></pre>
[ { "answer_id": 226685, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 0, "selected": false, "text": ";Should this be ns1.itchy.bogus or ns1.itchy.internal.bogus??\nitchy NS ns1-itchy.bogus.\nns1-itchy.bogus. A 10.0.0.2\n;\nscratchy NS ns1-scratchy.bogus.\nns1-scratchy.bogus. A 10.0.0.3\n" }, { "answer_id": 227096, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": true, "text": "@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (\n 2008102201 ; serial\n 1H ; refresh\n 2H ; retry\n 14D ; expire\n 5M ) ; minimum\n;\n NS ns1\n A 10.0.0.2\n ns1 A 10.0.0.2\n" }, { "answer_id": 227254, "author": "JT.", "author_id": 30145, "author_profile": "https://Stackoverflow.com/users/30145", "pm_score": 1, "selected": false, "text": "dig ;; QUESTION SECTION:\n;. IN NS\n\n;; ANSWER SECTION:\n. 3600 IN NS ns.bogustld.\n\n;; ADDITIONAL SECTION:\nns.bogustld. 3600 IN A 10.0.0.1\n ;; QUESTION SECTION:\n;. IN NS\n\n;; AUTHORITY SECTION:\n. 3600000 IN NS ns.bogustld.\n\n;; Query time: 0 msec\n dig +trace . ; <<>> DiG 9.5.0a6 <<>> +trace .\n;; global options: printcmd\n. 3005 IN NS C.ROOT-SERVERS.NET.\n. 3005 IN NS D.ROOT-SERVERS.NET.\n. 3005 IN NS E.ROOT-SERVERS.NET.\n. 3005 IN NS F.ROOT-SERVERS.NET.\n. 3005 IN NS G.ROOT-SERVERS.NET.\n. 3005 IN NS H.ROOT-SERVERS.NET.\n. 3005 IN NS I.ROOT-SERVERS.NET.\n. 3005 IN NS J.ROOT-SERVERS.NET.\n. 3005 IN NS K.ROOT-SERVERS.NET.\n. 3005 IN NS L.ROOT-SERVERS.NET.\n. 3005 IN NS M.ROOT-SERVERS.NET.\n. 3005 IN NS A.ROOT-SERVERS.NET.\n. 3005 IN NS B.ROOT-SERVERS.NET.\n;; Received 500 bytes from 64.105.172.26#53(64.105.172.26) in 19 ms\n\n. 86400 IN SOA a.root-servers.net. nstld.verisi\ngn-grs.com. 2008102201 1800 900 604800 86400\n;; Received 92 bytes from 128.63.2.53#53(H.ROOT-SERVERS.NET) in 84 ms\n ; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600 IN NS ns.bogustld.\n;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms\n\n. 3600 IN NS ns.bogustld.\n;; Received 72 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms\n ; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600000 IN NS ns.bogustld.\n;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms\n\ndig: couldn't get address for 'ns.bogustld': failure\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30145/" ]
223,677
<p>I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled.</p> <pre> $ cat uglynumber.txt: Ticket number : 303905694, FOO:BAR:BAR: Some text Case ID:123,456,789:Foobar - Some other text 303867970;[FOOBAR] Some text goes here Case Ref: 303658850 - Some random text here - host.tld #78854w </pre> <pre> $ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g" 303905694 123456789 303867970 303658850 </pre> <p>So, how to do the same with PHP?</p> <p>I found one example like this, but I can't inject that regexp into that.</p> <pre> if (preg_match("/.../", $line, $matches)) { echo "Match was found"; echo $matches[0]; } </pre>
[ { "answer_id": 226685, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 0, "selected": false, "text": ";Should this be ns1.itchy.bogus or ns1.itchy.internal.bogus??\nitchy NS ns1-itchy.bogus.\nns1-itchy.bogus. A 10.0.0.2\n;\nscratchy NS ns1-scratchy.bogus.\nns1-scratchy.bogus. A 10.0.0.3\n" }, { "answer_id": 227096, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": true, "text": "@ SOA ns1.itchy.bogus. hostmaster.itchy.bogus. (\n 2008102201 ; serial\n 1H ; refresh\n 2H ; retry\n 14D ; expire\n 5M ) ; minimum\n;\n NS ns1\n A 10.0.0.2\n ns1 A 10.0.0.2\n" }, { "answer_id": 227254, "author": "JT.", "author_id": 30145, "author_profile": "https://Stackoverflow.com/users/30145", "pm_score": 1, "selected": false, "text": "dig ;; QUESTION SECTION:\n;. IN NS\n\n;; ANSWER SECTION:\n. 3600 IN NS ns.bogustld.\n\n;; ADDITIONAL SECTION:\nns.bogustld. 3600 IN A 10.0.0.1\n ;; QUESTION SECTION:\n;. IN NS\n\n;; AUTHORITY SECTION:\n. 3600000 IN NS ns.bogustld.\n\n;; Query time: 0 msec\n dig +trace . ; <<>> DiG 9.5.0a6 <<>> +trace .\n;; global options: printcmd\n. 3005 IN NS C.ROOT-SERVERS.NET.\n. 3005 IN NS D.ROOT-SERVERS.NET.\n. 3005 IN NS E.ROOT-SERVERS.NET.\n. 3005 IN NS F.ROOT-SERVERS.NET.\n. 3005 IN NS G.ROOT-SERVERS.NET.\n. 3005 IN NS H.ROOT-SERVERS.NET.\n. 3005 IN NS I.ROOT-SERVERS.NET.\n. 3005 IN NS J.ROOT-SERVERS.NET.\n. 3005 IN NS K.ROOT-SERVERS.NET.\n. 3005 IN NS L.ROOT-SERVERS.NET.\n. 3005 IN NS M.ROOT-SERVERS.NET.\n. 3005 IN NS A.ROOT-SERVERS.NET.\n. 3005 IN NS B.ROOT-SERVERS.NET.\n;; Received 500 bytes from 64.105.172.26#53(64.105.172.26) in 19 ms\n\n. 86400 IN SOA a.root-servers.net. nstld.verisi\ngn-grs.com. 2008102201 1800 900 604800 86400\n;; Received 92 bytes from 128.63.2.53#53(H.ROOT-SERVERS.NET) in 84 ms\n ; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600 IN NS ns.bogustld.\n;; Received 57 bytes from 10.0.0.1#53(10.0.0.1) in 1 ms\n\n. 3600 IN NS ns.bogustld.\n;; Received 72 bytes from 10.0.0.1#53(ns.bogustld) in 0 ms\n ; <<>> DiG 9.5.0-P2 <<>> +trace .\n;; global options: printcmd\n. 3600000 IN NS ns.bogustld.\n;; Received 41 bytes from 10.0.0.2#53(10.0.0.2) in 0 ms\n\ndig: couldn't get address for 'ns.bogustld': failure\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30141/" ]
223,678
<p>Given the hash of a blob, is there a way to get a list of commits that have this blob in their tree?</p>
[ { "answer_id": 223870, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl -w\n\nuse strict;\n\nmy @commits;\nmy %trees;\nmy $blob;\n\nsub blob_in_tree {\n my $tree = $_[0];\n if (defined $trees{$tree}) {\n return $trees{$tree};\n }\n my $r = 0;\n open(my $f, \"git cat-file -p $tree|\") or die $!;\n while (<$f>) {\n if (/^\\d+ blob (\\w+)/ && $1 eq $blob) {\n $r = 1;\n } elsif (/^\\d+ tree (\\w+)/) {\n $r = blob_in_tree($1);\n }\n last if $r;\n }\n close($f);\n $trees{$tree} = $r;\n return $r;\n}\n\nsub handle_commit {\n my $commit = $_[0];\n open(my $f, \"git cat-file commit $commit|\") or die $!;\n my $tree = <$f>;\n die unless $tree =~ /^tree (\\w+)$/;\n if (blob_in_tree($1)) {\n print \"$commit\\n\";\n }\n while (1) {\n my $parent = <$f>;\n last unless $parent =~ /^parent (\\w+)$/;\n push @commits, $1;\n }\n close($f);\n}\n\nif (!@ARGV) {\n print STDERR \"Usage: git-find-blob blob [head ...]\\n\";\n exit 1;\n}\n\n$blob = $ARGV[0];\nif (@ARGV > 1) {\n foreach (@ARGV) {\n handle_commit($_);\n }\n} else {\n handle_commit(\"HEAD\");\n}\nwhile (@commits) {\n handle_commit(pop @commits);\n}\n git ls-tree -r" }, { "answer_id": 223890, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 8, "selected": true, "text": "git log --all -g #!/bin/sh\nobj_name=\"$1\"\nshift\ngit log \"$@\" --pretty=tformat:'%T %h %s' \\\n| while read tree commit subject ; do\n if git ls-tree -r $tree | grep -q \"$obj_name\" ; then\n echo $commit \"$subject\"\n fi\ndone\n #!/usr/bin/perl\nuse 5.008;\nuse strict;\nuse Memoize;\n\nmy $obj_name;\n\nsub check_tree {\n my ( $tree ) = @_;\n my @subtree;\n\n {\n open my $ls_tree, '-|', git => 'ls-tree' => $tree\n or die \"Couldn't open pipe to git-ls-tree: $!\\n\";\n\n while ( <$ls_tree> ) {\n /\\A[0-7]{6} (\\S+) (\\S+)/\n or die \"unexpected git-ls-tree output\";\n return 1 if $2 eq $obj_name;\n push @subtree, $2 if $1 eq 'tree';\n }\n }\n\n check_tree( $_ ) && return 1 for @subtree;\n\n return;\n}\n\nmemoize 'check_tree';\n\ndie \"usage: git-find-blob <blob> [<git-log arguments ...>]\\n\"\n if not @ARGV;\n\nmy $obj_short = shift @ARGV;\n$obj_name = do {\n local $ENV{'OBJ_NAME'} = $obj_short;\n `git rev-parse --verify \\$OBJ_NAME`;\n} or die \"Couldn't parse $obj_short: $!\\n\";\nchomp $obj_name;\n\nopen my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'\n or die \"Couldn't open pipe to git-log: $!\\n\";\n\nwhile ( <$log> ) {\n chomp;\n my ( $tree, $commit, $subject ) = split \" \", $_, 3;\n print \"$commit $subject\\n\" if check_tree( $tree );\n}\n" }, { "answer_id": 9748398, "author": "Mario", "author_id": 472, "author_profile": "https://Stackoverflow.com/users/472", "pm_score": 3, "selected": false, "text": "#!/bin/sh\nobj_name=\"$1\"\nshift\ngit ls-files --stage \\\n| if grep -q \"$obj_name\"; then\n echo Found in staging area. Run git ls-files --stage to see.\nfi\n\ngit log \"$@\" --pretty=format:'%T %h %s' \\\n| while read tree commit subject ; do\n if git ls-tree -r $tree | grep -q \"$obj_name\" ; then\n echo $commit \"$subject\"\n fi\ndone\n" }, { "answer_id": 12737458, "author": "cmyers", "author_id": 156785, "author_profile": "https://Stackoverflow.com/users/156785", "pm_score": 2, "selected": false, "text": "git gc #!/usr/bin/env ruby\n\nrequire 'log4r'\n\n# The output of git verify-pack -v is:\n# SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1\n#\n#\nGIT_PACKS_RELATIVE_PATH=File.join('.git', 'objects', 'pack', '*.pack')\n\n# 10MB cutoff\nCUTOFF_SIZE=1024*1024*10\n#CUTOFF_SIZE=1024\n\nbegin\n\n include Log4r\n log = Logger.new 'git-find-large-objects'\n log.level = INFO\n log.outputters = Outputter.stdout\n\n git_dir = %x[ git rev-parse --show-toplevel ].chomp\n\n if git_dir.empty?\n log.fatal \"ERROR: must be run in a git repository\"\n exit 1\n end\n\n log.debug \"Git Dir: '#{git_dir}'\"\n\n pack_files = Dir[File.join(git_dir, GIT_PACKS_RELATIVE_PATH)]\n log.debug \"Git Packs: #{pack_files.to_s}\"\n\n # For details on this IO, see http://stackoverflow.com/questions/1154846/continuously-read-from-stdout-of-external-process-in-ruby\n #\n # Short version is, git verify-pack flushes buffers only on line endings, so\n # this works, if it didn't, then we could get partial lines and be sad.\n\n types = {\n :blob => 1,\n :tree => 1,\n :commit => 1,\n }\n\n\n total_count = 0\n counted_objects = 0\n large_objects = []\n\n IO.popen(\"git verify-pack -v -- #{pack_files.join(\" \")}\") do |pipe|\n pipe.each do |line|\n # The output of git verify-pack -v is:\n # SHA1 type size size-in-packfile offset-in-packfile depth base-SHA1\n data = line.chomp.split(' ')\n # types are blob, tree, or commit\n # we ignore other lines by looking for that\n next unless types[data[1].to_sym] == 1\n log.info \"INPUT_THREAD: Processing object #{data[0]} type #{data[1]} size #{data[2]}\"\n hash = {\n :sha1 => data[0],\n :type => data[1],\n :size => data[2].to_i,\n }\n total_count += hash[:size]\n counted_objects += 1\n if hash[:size] > CUTOFF_SIZE\n large_objects.push hash\n end\n end\n end\n\n log.info \"Input complete\"\n\n log.info \"Counted #{counted_objects} totalling #{total_count} bytes.\"\n\n log.info \"Sorting\"\n\n large_objects.sort! { |a,b| b[:size] <=> a[:size] }\n\n log.info \"Sorting complete\"\n\n large_objects.each do |obj|\n log.info \"#{obj[:sha1]} #{obj[:type]} #{obj[:size]}\"\n end\n\n exit 0\nend\n cat edited-large-files.log | cut -d' ' -f4 | xargs git-find-blob | tee large-file-paths.log\n git-find-blob #!/usr/bin/perl\n\n# taken from: http://stackoverflow.com/questions/223678/which-commit-has-this-blob\n# and modified by Carl Myers <cmyers@cmyers.org> to scan multiple blobs at once\n# Also, modified to keep the discovered filenames\n# vi: ft=perl\n\nuse 5.008;\nuse strict;\nuse Memoize;\nuse Data::Dumper;\n\n\nmy $BLOBS = {};\n\nMAIN: {\n\n memoize 'check_tree';\n\n die \"usage: git-find-blob <blob1> <blob2> ... -- [<git-log arguments ...>]\\n\"\n if not @ARGV;\n\n\n while ( @ARGV && $ARGV[0] ne '--' ) {\n my $arg = $ARGV[0];\n #print \"Processing argument $arg\\n\";\n open my $rev_parse, '-|', git => 'rev-parse' => '--verify', $arg or die \"Couldn't open pipe to git-rev-parse: $!\\n\";\n my $obj_name = <$rev_parse>;\n close $rev_parse or die \"Couldn't expand passed blob.\\n\";\n chomp $obj_name;\n #$obj_name eq $ARGV[0] or print \"($ARGV[0] expands to $obj_name)\\n\";\n print \"($arg expands to $obj_name)\\n\";\n $BLOBS->{$obj_name} = $arg;\n shift @ARGV;\n }\n shift @ARGV; # drop the -- if present\n\n #print \"BLOBS: \" . Dumper($BLOBS) . \"\\n\";\n\n foreach my $blob ( keys %{$BLOBS} ) {\n #print \"Printing results for blob $blob:\\n\";\n\n open my $log, '-|', git => log => @ARGV, '--pretty=format:%T %h %s'\n or die \"Couldn't open pipe to git-log: $!\\n\";\n\n while ( <$log> ) {\n chomp;\n my ( $tree, $commit, $subject ) = split \" \", $_, 3;\n #print \"Checking tree $tree\\n\";\n my $results = check_tree( $tree );\n\n #print \"RESULTS: \" . Dumper($results);\n if (%{$results}) {\n print \"$commit $subject\\n\";\n foreach my $blob ( keys %{$results} ) {\n print \"\\t\" . (join \", \", @{$results->{$blob}}) . \"\\n\";\n }\n }\n }\n }\n\n}\n\n\nsub check_tree {\n my ( $tree ) = @_;\n #print \"Calculating hits for tree $tree\\n\";\n\n my @subtree;\n\n # results = { BLOB => [ FILENAME1 ] }\n my $results = {};\n {\n open my $ls_tree, '-|', git => 'ls-tree' => $tree\n or die \"Couldn't open pipe to git-ls-tree: $!\\n\";\n\n # example git ls-tree output:\n # 100644 blob 15d408e386400ee58e8695417fbe0f858f3ed424 filaname.txt\n while ( <$ls_tree> ) {\n /\\A[0-7]{6} (\\S+) (\\S+)\\s+(.*)/\n or die \"unexpected git-ls-tree output\";\n #print \"Scanning line '$_' tree $2 file $3\\n\";\n foreach my $blob ( keys %{$BLOBS} ) {\n if ( $2 eq $blob ) {\n print \"Found $blob in $tree:$3\\n\";\n push @{$results->{$blob}}, $3;\n }\n }\n push @subtree, [$2, $3] if $1 eq 'tree';\n }\n }\n\n foreach my $st ( @subtree ) {\n # $st->[0] is tree, $st->[1] is dirname\n my $st_result = check_tree( $st->[0] );\n foreach my $blob ( keys %{$st_result} ) {\n foreach my $filename ( @{$st_result->{$blob}} ) {\n my $path = $st->[1] . '/' . $filename;\n #print \"Generating subdir path $path\\n\";\n push @{$results->{$blob}}, $path;\n }\n }\n }\n\n #print \"Returning results for tree $tree: \" . Dumper($results) . \"\\n\\n\";\n return $results;\n}\n <hash prefix> <oneline log message>\n path/to/file.txt\n path/to/file2.txt\n ...\n<hash prefix2> <oneline log msg...>\n grep uniq" }, { "answer_id": 32611564, "author": "aragaer", "author_id": 390363, "author_profile": "https://Stackoverflow.com/users/390363", "pm_score": 5, "selected": false, "text": "git log --all --pretty=format:%H -- <path> | xargs -I% sh -c \"git ls-tree % -- <path> | grep -q <hash> && echo %\"\n" }, { "answer_id": 48027778, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "git describe <commit-ish>:<path> stefanbeller gitster builtin/describe.c verify-pack (commit, deep/path) git describe --tags v0.99:Makefile\nconversion-901-g7672db20c2:Makefile\n Makefile v0.99 git describe git describe git describe <blob> <commit-ish>:<path> <path> <commit-ish> <committ-ish>:<path>" }, { "answer_id": 48590251, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "git describe git log git diff --find-object=<object-id> stefanbeller gitster diffcore git-describe git describe <blob-id> <commit-ish>:<path> diff $ ./git log --oneline --find-object=v2.0.0:Makefile\n b2feb64 Revert the whole \"ask curl-config\" topic for now\n 47fbfde i18n: only extract comments marked with \"TRANSLATORS:\"\n Makefile 2.0 v1.9.2-471-g47fbfded53 v2.0.0-rc1-5-gb2feb6430b" }, { "answer_id": 66662476, "author": "andrewdotn", "author_id": 14558, "author_profile": "https://Stackoverflow.com/users/14558", "pm_score": 5, "selected": false, "text": "git whatchanged --all --find-object=<blob hash>\n --all git$ git whatchanged --all --find-object=b3bb59f06644\ncommit 8ef93124645f89c45c9ec3edd3b268b38154061a \n⋮\ndiff: do not show submodule with untracked files as \"-dirty\"\n⋮\n:100644 100644 b3bb59f06644 8f6227c993a5 M submodule.c\n\ncommit 7091499bc0a9bccd81a1c864de7b5f87a366480e \n⋮\nRevert \"submodules: fix of regression on fetching of non-init subsub-repo\"\n⋮\n:100644 100644 eef5204e641e b3bb59f06644 M submodule.c\n git whatchanged" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
223,679
<p>I am trying to prevent data races in a multihreaded server. My problem is the following: there is a <code>List&lt;RServer&gt;</code>, the type <code>RServer</code> is a class with several fields. Now, the server has several threads all running at the same time and they can modify both the <code>List</code> (adding more items) and the individual <code>RServer</code> instances (changing the fields).</p> <p>So my strategy is to make a <code>readonly object RServerLock = new object( )</code> in each of the <code>RServer</code> instances and additionally a <code>readonly object RServerListLock = new object( )</code> and enclose all the code that modifies either (the <code>List</code> or a <code>RServer</code> instance) in a <code>lock</code>. Is this safe? What happens if a thread tries to lock a <code>RServerLock</code> <em>while</em> another one is locking it?</p>
[ { "answer_id": 224552, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Opens the specified reader writer lock in read mode,\n /// specifying whether or not it may be upgraded.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <param name=\"upgradeable\"></param>\n /// <returns></returns>\n public static IDisposable Read(this ReaderWriterLockSlim slim, bool upgradeable)\n {\n return new ReaderWriterLockSlimController(slim, true, upgradeable);\n } // IDisposable Read\n\n /// <summary>\n /// Opens the specified reader writer lock in read mode,\n /// and does not allow upgrading.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <returns></returns>\n public static IDisposable Read(this ReaderWriterLockSlim slim)\n {\n return new ReaderWriterLockSlimController(slim, true, false);\n } // IDisposable Read\n\n /// <summary>\n /// Opens the specified reader writer lock in write mode.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <returns></returns>\n public static IDisposable Write(this ReaderWriterLockSlim slim)\n {\n return new ReaderWriterLockSlimController(slim, false, false);\n } // IDisposable Write\n\n private class ReaderWriterLockSlimController : IDisposable\n {\n #region Fields\n\n private bool _closed = false;\n private bool _read = false;\n private ReaderWriterLockSlim _slim;\n private bool _upgrade = false;\n\n #endregion Fields\n\n #region Constructors\n\n public ReaderWriterLockSlimController(ReaderWriterLockSlim slim, bool read, bool upgrade)\n {\n _slim = slim;\n _read = read;\n _upgrade = upgrade;\n\n if (_read)\n {\n if (upgrade)\n {\n _slim.EnterUpgradeableReadLock();\n }\n else\n {\n _slim.EnterReadLock();\n }\n }\n else\n {\n _slim.EnterWriteLock();\n }\n } // ReaderWriterLockSlimController\n\n ~ReaderWriterLockSlimController()\n {\n Dispose();\n } // ~ReaderWriterLockSlimController\n\n #endregion Constructors\n\n #region Methods\n\n public void Dispose()\n {\n if (_closed)\n return;\n _closed = true;\n\n if (_read)\n {\n if (_upgrade)\n {\n _slim.ExitUpgradeableReadLock();\n }\n else\n {\n _slim.ExitReadLock();\n }\n }\n else\n {\n _slim.ExitWriteLock();\n }\n\n GC.SuppressFinalize(this);\n } // void Dispose\n\n #endregion Methods\n } // Class ReaderWriterLockSlimController\n using(myReaderWriterLockSlim.Read())\n{\n // Do read operations.\n}\n using(myReaderWriterLockSlim.Read(true))\n{\n // Read a flag.\n if(flag)\n {\n using(myReaderWriterLockSlim.Write()) // Because we said Read(true).\n {\n // Do read/write operations.\n }\n }\n}\n using(myReaderWriterLockSlim.Write()) // This means you can also safely read.\n{\n // Do read/write operations.\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14759/" ]
223,692
<p>Well this is incredibly frustrating. After being nagged by Rails that I need to install the C-based MySQL adaptor, I did so... and then discovered that it won't work with MySQL under version 6. Now 'gem uninstall mysql' results in 'unknown gem mysql'. </p> <p>I just spent half an hour trying to get the thing to install in the first place (by juggling all the "where the hell is my config file, anyway?" type of options).</p> <p>Anyway, I can't find hints anywhere on how to use the ORIGINAL MySQL adaptor now that I've discovered that it's either that or an upgrade to MySQL 6, which I don't want to do since I'm using an XAMPP package that works very nicely already </p> <p>(This is on my local box for testing, this is not a dev or production server issue. I'll deal with that later.)</p> <p>So how do I either make sure Rails uses the built in version (using command line options?) OR remove the MySQL gem? </p> <p>(Optional third option: Suck it up and upgrade my local copy of MySQL.)</p> <p>edit: Turns out I was wrong about the version of MySQL I needed in the first place, and I fixed and upgraded a bunch of stuff. </p> <p>However, my answer to the ORIGINAL question still stands: Delete the gem. If gem itself can't delete it, just delete all traces of it and RoR will default to the original adapter. This probably doesn't work in newer version of Rails, which (I think) REQUIRE the new adapter.</p>
[ { "answer_id": 224552, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Opens the specified reader writer lock in read mode,\n /// specifying whether or not it may be upgraded.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <param name=\"upgradeable\"></param>\n /// <returns></returns>\n public static IDisposable Read(this ReaderWriterLockSlim slim, bool upgradeable)\n {\n return new ReaderWriterLockSlimController(slim, true, upgradeable);\n } // IDisposable Read\n\n /// <summary>\n /// Opens the specified reader writer lock in read mode,\n /// and does not allow upgrading.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <returns></returns>\n public static IDisposable Read(this ReaderWriterLockSlim slim)\n {\n return new ReaderWriterLockSlimController(slim, true, false);\n } // IDisposable Read\n\n /// <summary>\n /// Opens the specified reader writer lock in write mode.\n /// </summary>\n /// <param name=\"slim\"></param>\n /// <returns></returns>\n public static IDisposable Write(this ReaderWriterLockSlim slim)\n {\n return new ReaderWriterLockSlimController(slim, false, false);\n } // IDisposable Write\n\n private class ReaderWriterLockSlimController : IDisposable\n {\n #region Fields\n\n private bool _closed = false;\n private bool _read = false;\n private ReaderWriterLockSlim _slim;\n private bool _upgrade = false;\n\n #endregion Fields\n\n #region Constructors\n\n public ReaderWriterLockSlimController(ReaderWriterLockSlim slim, bool read, bool upgrade)\n {\n _slim = slim;\n _read = read;\n _upgrade = upgrade;\n\n if (_read)\n {\n if (upgrade)\n {\n _slim.EnterUpgradeableReadLock();\n }\n else\n {\n _slim.EnterReadLock();\n }\n }\n else\n {\n _slim.EnterWriteLock();\n }\n } // ReaderWriterLockSlimController\n\n ~ReaderWriterLockSlimController()\n {\n Dispose();\n } // ~ReaderWriterLockSlimController\n\n #endregion Constructors\n\n #region Methods\n\n public void Dispose()\n {\n if (_closed)\n return;\n _closed = true;\n\n if (_read)\n {\n if (_upgrade)\n {\n _slim.ExitUpgradeableReadLock();\n }\n else\n {\n _slim.ExitReadLock();\n }\n }\n else\n {\n _slim.ExitWriteLock();\n }\n\n GC.SuppressFinalize(this);\n } // void Dispose\n\n #endregion Methods\n } // Class ReaderWriterLockSlimController\n using(myReaderWriterLockSlim.Read())\n{\n // Do read operations.\n}\n using(myReaderWriterLockSlim.Read(true))\n{\n // Read a flag.\n if(flag)\n {\n using(myReaderWriterLockSlim.Write()) // Because we said Read(true).\n {\n // Do read/write operations.\n }\n }\n}\n using(myReaderWriterLockSlim.Write()) // This means you can also safely read.\n{\n // Do read/write operations.\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23965/" ]
223,700
<p>I have a class that I need to binary serialize. The class contains one field as below:</p> <pre><code>private T[,] m_data; </code></pre> <p>These multi-dimensional arrays can be fairly large (hundreds of thousands of elements) and of any primitive type. When I tried standard .net serialization on an object the file written to disk was large and I think .net is storing a lot of repeated data about element types and possibly not as efficiently as could be done.</p> <p>I have looked around for custom serializers but have not seen any that deal with multi-dimensional generic arrays. I have also experimented with built-in .net compression on a byte array of the memory stream following serializing with some success, but not as quick / compressed as I had hoped.</p> <p>My question is, should I try and write a custom serializer to optimally serialize this array for the appropriate type (this seems a little daunting), or should I use standard .net serialization and add compression?</p> <p>Any advice on the best approach would be most appreciated, or links to resources showing how to tackle serialization of a multi-dimensional generic array - as mentioned <a href="http://www.codeproject.com/KB/dotnet/FastSerializer.aspx" rel="noreferrer">existing examples</a> I have found do not support such structures.</p>
[ { "answer_id": 224008, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 4, "selected": true, "text": " int width = 1000;\n int height = 10000;\n List<int[]> list = new List<int[]>();\n for (int i = 0; i < height; i++)\n {\n list.Add(Enumerable.Range(0, width).ToArray());\n }\n int[][] bazillionInts = list.ToArray();\n using (FileStream fsZ = new FileStream(\"c:\\\\temp_zipped.txt\", FileMode.Create))\n using (FileStream fs = new FileStream(\"c:\\\\temp_notZipped.txt\", FileMode.Create))\n using (GZipStream gz = new GZipStream(fsZ, CompressionMode.Compress))\n {\n BinaryFormatter f = new BinaryFormatter();\n f.Serialize(gz, bazillionInts);\n f.Serialize(fs, bazillionInts);\n }\n int width = 1000;\n int height = 10000;\n Random rand = new Random(123456);\n int[,] bazillionInts = new int[width, height];\n for(int i = 0 ; i < width;i++)\n for (int j = 0; j < height; j++)\n {\n bazillionInts[i, j] = rand.Next(50000);\n }\n temp_notZipped.txt temp_zipped.txt" }, { "answer_id": 224598, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "* float double int Person *" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30132/" ]
223,713
<p>I've just started working with ASP.NET MVC now that it's in beta. In my code, I'm running a simple LINQ to SQL query to get a list of results and passing that to my view. This sort of thing:</p> <pre><code>var ords = from o in db.Orders where o.OrderDate == DateTime.Today select o; return View(ords); </code></pre> <p>However, in my View, I realised that I'd need to access the customer's name for each order. I started using <code>o.Customer.Name</code> but I'm fairly certain that this is executing a separate query for each order (because of LINQ's lazy loading).</p> <p>The logical way to cut down the number of queries would be to select the customer name at the same time. Something like:</p> <pre><code>var ords = from o in db.Orders from c in db.Customers where o.OrderDate == DateTime.Today and o.CustomerID == c.CustomerID select new { o.OrderID, /* ... */, c.CustomerName }; return View(ords); </code></pre> <p>Except now my "ords" variable is an IEnumerable of an anonymous type.</p> <p>Is it possible to declare an ASP.NET MVC View in such a way that it accepts an IEnumerable as its view data where T is defined by what gets passed from the controller, or will I have to define a concrete type to populate from my query?</p>
[ { "answer_id": 224005, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 6, "selected": true, "text": "public ActionResult Foo() {\n return View(new {Something=\"Hey, it worked!\"});\n}\n\n//Using a normal ViewPage\n\n<%= Html.TextBox(\"Something\") %>\n" }, { "answer_id": 4680966, "author": "Lasse Skindstad Ebert", "author_id": 395700, "author_profile": "https://Stackoverflow.com/users/395700", "pm_score": 4, "selected": false, "text": "return View(new { \n MyItem = \"Hello\", \n SomethingElse = 42, \n Third = new MyClass(42, \"Yes\") })\n @{\n string myItem = (dynamic)Model.MyItem;\n int somethingElse = (dynamic)Model.SomethingElse;\n MyClass third = (dynamic)Model.Third;\n}\n @{\n var myItem = ViewData.Eval(\"MyItem\") as string\n var somethingElse = ViewData.Eval(\"SomethingElse\") as int?\n var third = ViewData.Eval(\"Third\") as MyClass \n}\n" }, { "answer_id": 50454454, "author": "AlexMelw", "author_id": 5259296, "author_profile": "https://Stackoverflow.com/users/5259296", "pm_score": 1, "selected": false, "text": "anonymous dynamic anonymous View anonymous dynamic public class AwesomeController : Controller\n{\n // Other actions omitted...\n public ActionResult SlotCreationSucceeded(string email, string roles)\n {\n return View(\"SlotCreationSucceeded\", new { email, roles }.ToDynamic());\n }\n}\n public static class DynamicExtensions\n{\n public static dynamic ToDynamic(this object value)\n {\n IDictionary<string, object> expando = new ExpandoObject();\n\n foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))\n expando.Add(property.Name, property.GetValue(value));\n\n return (ExpandoObject) expando;\n }\n}\n anonymous dynamic public class AwesomeController : Controller\n{\n // Other actions omitted...\n public ActionResult SlotCreationSucceeded(string email, string roles)\n {\n return View(\"SlotCreationSucceeded\", new { email, roles });\n }\n}\n @{\n var anonymousModel = DynamicUtil.ToAnonymous(Model, new { email = default(string), roles = default(string) });\n}\n\n<h1>@anonymousModel.email</h1>\n<h2>@anonymousModel.roles</h2>\n public class DynamicUtil\n{\n public static T ToAnonymous<T>(ExpandoObject source, T sample)\n where T : class\n {\n var dict = (IDictionary<string, object>) source;\n\n var ctor = sample.GetType().GetConstructors().Single();\n\n var parameters = ctor.GetParameters();\n\n var parameterValues = parameters.Select(p => dict[p.Name]).ToArray();\n\n return (T) ctor.Invoke(parameterValues);\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
223,738
<p>I have a DataSet consisting of XML data, I can easily output this to a file:</p> <pre><code>DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds.Tables.Add(dt); ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]); ds.WriteXml("C:\\test.xml"); </code></pre> <p>However what I want to do is compress the XML into a ZIP or other type of compressed file and then just save this file to disk while splitting the ZIP file into 1MB chunks. I do not really want to save the uncompressed file, and then zip it, then split it.</p> <p><strong>What I'm looking for specifically is:</strong></p> <ol> <li>a suitable compression library that I can stream the XML to and have the zip file(s) saved to disk</li> <li>some sample C# code that can show me how to do this.</li> </ol>
[ { "answer_id": 223764, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "public void WriteFile(string fileName)\n{\n using (FileStream fs = new FileStream(fileName, FileMode.Create))\n {\n Stream s;\n if (Path.GetExtension(fileName) == \".cmx\")\n {\n s = new GZipStream(fs, CompressionMode.Compress);\n }\n else if (Path.GetExtension(fileName) == \".cmz\")\n {\n s = new DeflateStream(fs, CompressionMode.Compress);\n }\n else\n {\n s = fs;\n }\n WriteXml(s);\n s.Close();\n }\n} \n" }, { "answer_id": 224079, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 2, "selected": false, "text": "// get connection to the database\nvar c1= new System.Data.SqlClient.SqlConnection(connstring1);\nvar da = new System.Data.SqlClient.SqlDataAdapter()\n{\n SelectCommand= new System.Data.SqlClient.SqlCommand(strSelect, c1)\n};\n\nDataSet ds1 = new DataSet();\n\n// fill the dataset with the SELECT \nda.Fill(ds1, \"Invoices\");\n\n// write the XML for that DataSet into a zip file (split into 1mb chunks)\nusing(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())\n{\n zip.MaxOutputSegmentSize = 1024*1024;\n zip.AddEntry(zipEntryName, (name,stream) => ds1.WriteXml(stream) );\n zip.Save(zipFileName);\n}\n" }, { "answer_id": 224112, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 1, "selected": false, "text": "ZipArchive archive = new ZipArchive( new DiskFile( @\"c:\\path\\file.zip\" ) );\n\narchive.SplitSize = 1024*1024;\narchive.BeginUpdate();\n\ntry\n{\n AbstractFile destFile = archive.GetFile( \"data.xml\" );\n\n using( Stream stream = destFile.OpenWrite( true ) )\n {\n ds.WriteXml( stream );\n }\n}\nfinally\n{\n archive.EndUpdate();\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15144/" ]
223,748
<p>I have a nice little file upload control I wrote for ASP.NET webforms that utilizes an IFrame and ASP.NET AJAX.</p> <p>However, on large uploads, the browser times out before it can finish posting the form.</p> <p>Is there a way I can increase this?</p> <p>I'm not really interesting in alternative solutions, so don't suggest changing the entire thing out please. It works good for &lt;5 meg uploads, I'd just like to get it up to about 8mb.</p> <p>EDIT: Setting the timeout in Page_Load didn't appear to change anything.</p>
[ { "answer_id": 230916, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 4, "selected": false, "text": "<system.web>\n <httpRuntime maxRequestLength=\"10240\" executionTimeout=\"360\"/>\n</system.web>\n" }, { "answer_id": 230936, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": false, "text": "<httpRuntime maxRequestLength=\"10240\" />\n" }, { "answer_id": 3304300, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 2, "selected": false, "text": " <system.web>\n <httpRuntime executionTimeout=\"360\" maxRequestLength=\"100000\" />\n C:\\Windows\\System32\\inetsrv>appcmd set config \"[IISWebsitename]\" -section:requestFiltering -requestLimits.maxAllowedContentLength:100000000 -commitpath:apphost\n" }, { "answer_id": 35169737, "author": "omar nazzal", "author_id": 4086690, "author_profile": "https://Stackoverflow.com/users/4086690", "pm_score": 1, "selected": false, "text": "<system.web> <httpRuntime \n executionTimeout=\"90\" \n maxRequestLength=\"4096\" \n useFullyQualifiedRedirectUrl=\"false\" \n minFreeThreads=\"8\" \n minLocalRequestFreeThreads=\"4\" \n appRequestQueueLimit=\"100\" \n enableVersionHeader=\"true\"\n /> <httpRuntime>" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
223,750
<p>I'm pretty sure stackoverflow.com is created with ASP.NET, but no matter where I click I see no .aspx extension in the address bar. How it is done and is there a particular reason for this?</p>
[ { "answer_id": 223762, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 2, "selected": false, "text": "posts/edit/<postnumber> editPost.aspx?postNumber=<postnumber>" }, { "answer_id": 29619854, "author": "Musakkhir Sayyed", "author_id": 3894854, "author_profile": "https://Stackoverflow.com/users/3894854", "pm_score": 3, "selected": false, "text": "<configuration>\n<system.webserver>\n<rewrite>\n <rules>\n <rule name=\"RemoveASPX\" enabled=\"true\" stopProcessing=\"true\">\n <match url=\"(.*)\\.aspx\" />\n <action type=\"Redirect\" url=\"{R:1}\" />\n </rule>\n <rule name=\"AddASPX\" enabled=\"true\">\n <match url=\".*\" negate=\"false\" />\n <conditions>\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsFile\" negate=\"true\" />\n <add input=\"{REQUEST_FILENAME}\" matchType=\"IsDirectory\" negate=\"true\" />\n <add input=\"{URL}\" pattern=\"(.*)\\.(.*)\" negate=\"true\" />\n </conditions>\n <action type=\"Rewrite\" url=\"{R:0}.aspx\" />\n </rule>\n </rules>\n</rewrite>\n</system.webserver>\n</configuration>\n" }, { "answer_id": 38439103, "author": "stackoverflow-345421", "author_id": 6604063, "author_profile": "https://Stackoverflow.com/users/6604063", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.SessionState;\n\nnamespace NameSpace\n{\n public class Global : System.Web.HttpApplication\n {\n private void mapearUrlAmigaveis()\n {\n String url = Request.Path.ToString().ToLower();\n int positionQuestionMarkParameter = url.IndexOf('?');\n\n String urlSemParametros = (positionQuestionMarkParameter != -1) ? url.Substring(0, (positionQuestionMarkParameter - 1)) : url;\n String[] splitBarra = urlSemParametros.Split('/');\n int indexOfUltimaBarra = urlSemParametros.LastIndexOf('/');\n\n if (splitBarra.Length > 0)\n {\n String ultimaBarra = splitBarra[(splitBarra.Length - 1)];\n String caminhoLocalUltimaBarra = Request.PhysicalApplicationPath + ultimaBarra;\n String parametros = ((positionQuestionMarkParameter != -1) ? url.Substring((positionQuestionMarkParameter - 1), (url.Length - 1)) : String.Empty);\n if (System.IO.File.Exists(caminhoLocalUltimaBarra + \".aspx\"))\n {\n Context.RewritePath(urlSemParametros + \".aspx\" + parametros);\n }\n else if (System.IO.File.Exists(caminhoLocalUltimaBarra + \".ashx\"))\n {\n Context.RewritePath(urlSemParametros + \".ashx\" + parametros);\n }\n }\n }\n }\n}\n" }, { "answer_id": 46096020, "author": "king zecole", "author_id": 5919456, "author_profile": "https://Stackoverflow.com/users/5919456", "pm_score": 0, "selected": false, "text": " protected void Application_BeginRequest(object sender, EventArgs e)\n {\n HttpApplication app = sender as HttpApplication;\n if (app.Request.Path.ToLower().IndexOf(\".recon\") > 0)\n {\n string rawpath = app.Request.Path;\n string path = rawpath.Substring(0, rawpath.IndexOf(\".recon\"));\n app.Context.RewritePath(path+\".aspx\");\n }\n }\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
223,761
<p>I have an API consisting of ASP.NET webservices callable through GET/POST/SOAP.</p> <p>A new functionality will require me to accept files through this webservice. Basically I'm allowing users to upload files to a file archive through the API, which they'd otherwise do by logging into our browser based administration system.</p> <p>The API needs to be as easily consumed as possible. I'm thinking of dropping SOAP support since our PHP clients mainly use the GET/POST methods, and the .NET clients don't mind either way. With that as a prerequisite, I'm thinking of simply creating an UploadFile(fileName) method, and the requiring the user to send the file through POST as a normal file upload.</p> <p>However, I will not be able to specify the file field as a parameter to the method, right? So if I simply state in the documentation "file should be sent in POST field called 'File'", would that pose any problems when I need to read the file?</p> <p>All files are in binary format, PDF's, various image formats, FLV and so forth. Also, file sizes will mainly be in the 2-20MB vicinity, but given the above solution, would I have any troubles accepting files in the 250MB area?</p> <p>Receiving a file this way would result in the file being loaded completely into memory, before I write it to disk - is there any way around this, besides letting the service receive a Stream and thus disabling me from accepting other parameters, and hindering the easy usage of the service?</p> <hr> <p>Besides what's possible on my side, I'm also curious in regards to how I make it as easy as possible for the callees to send the file. I'm guessing POST is one of the most accessible ways of receiving the file, but if anyone has any comments, I'd like to hear them as well.</p>
[ { "answer_id": 223828, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "HttpWebRequest HttpWebRequest" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469/" ]
223,771
<p>So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multiple source code files in the same project. I'd strongly prefer to avoid having to dump all my source code into one file and only include the header once, as that's going to make my file very long and difficult to manage.</p> <p>Essentially, this is what's going on:</p> <pre><code>#ifndef _myheader_h #define _myheader_h typedef struct MYSTRUCT{ int blah; int blah2; } MYSTRUCT; MYSTRUCT Job_Grunt; MYSTRUCT *Grunt = &amp;Job_Grunt; MYSTRUCT Job_Uruk; MYSTRUCT *Uruk = &amp;Job_Grunt; int Other_data[100]; void load_jobs(); #endif </code></pre> <p>Example Cpp File (They pretty much all look something like this):</p> <pre><code>#include "myheader.h" void load_jobs(){ Grunt-&gt;blah = 1; Grunt-&gt;blah2 = 14; Uruk-&gt;blah = 2; Uruk-&gt;blah2 = 15; return; } </code></pre> <p>Bear in mind that I have about 5 cpp files that include this one header, each one dealing with a different type of struct found in the header file. In this example there was only the one struct containing a couple of members, when there are about 4-6 different structs with many more members in the actual header file. All the files I've included it in follow the same formula as you see in this example here.</p> <p>Now I understand that the header guard only stops each individual cpp file from including the header file more than once. What would seem to be happening is that when the compiler reads the include at the start of each cpp, it defines the header file all over again, which is causing it to spit out lines and lines of:</p> <pre><code>Multiple Definition of Uruk, first defined here Multiple Definition of Job_Uruk, first defined here Multiple Definition of Grunt, first defined here Multiple Definition of Job_Grunt, first defined here Multiple Definition of Other_data, first defined here </code></pre> <p>I'll see a set of this for just about every cpp file in the project which includes the header. I've tried moving the definitions of the struct and the struct variables to the cpp files, but then the other cpp files cannot see them or work with them, which is very important as I need all files in the project to be able to work with these structs.</p> <p>But the single most confusing part about this problem requires a little more explanation:</p> <p>The way I'm setting up these multiple files in this project is identical to the book I'm working with, All In One Game Programming by John S. Harbour. I ran into the exact same problems when I created the files for example projects in the book which called for one header included by multiple cpps in the same project.</p> <p>I could type them out, word for word from the book, and I do mean word for word...<br> and I'd get the series of MD errors for every cpp in the project. </p> <p>If I loaded the example project from the CD included with the book, it would compile and run without a problem, allthough the files themselves, as well as the project options, were by all appearances identical to the ones I had created.</p> <p>If I created my own project file, and simply added the source and header files for the example project from the CD, this, too, would also compile and run, though I can find no difference between those and mine.</p> <p>So then, I tried making my own project file, then creating the blank source and header files and adding them to it, and then filling them by copying and pasting their contents from the files on the CD they were meant to correspond to(the same ones that had worked). And sure enough, I'd get the same thing...lines and lines of MD error messages.</p> <p>I'm absolutely baffled. I've repeated all these methods multiple times, and am certain I'm not mistyping or miscopying the code. There just seems to be something about the premade files themselves; some configuration setting or something else I'm missing entirely...that will cause them to compile correctly while the files I make myself won't.</p>
[ { "answer_id": 223785, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 3, "selected": false, "text": "extern MYSTRUCT Job_Grunt;\n" }, { "answer_id": 223798, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 5, "selected": false, "text": "extern #ifdef MAINFILE\n #define EXTERN\n#else\n #define EXTERN extern\n#endif\n\nEXTERN MYSTRUCT Job_Grunt;\nEXTERN MYSTRUCT *Grunt = &Job_Grunt;\nEXTERN MYSTRUCT Job_Uruk;\nEXTERN MYSTRUCT *Uruk = &Job_Uruk;\n #define MAINFILE\n #include" }, { "answer_id": 223813, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": false, "text": "extern extern extern MYSTRUCT Job_Grunt;\nextern MYSTRUCT *Grunt;\nextern MYSTRUCT Job_Uruk;\nextern MYSTRUCT *Uruk;\n\nextern int Other_data[100];\n MYSTRUCT Job_Grunt;\nMYSTRUCT *Grunt = &Job_Grunt;\nMYSTRUCT Job_Uruk;\nMYSTRUCT *Uruk = &Job_Grunt;\n\nint Other_data[100];\n" }, { "answer_id": 223815, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": -1, "selected": false, "text": "#pragma once #pragma once" }, { "answer_id": 1032419, "author": "jbatista", "author_id": 36145, "author_profile": "https://Stackoverflow.com/users/36145", "pm_score": 0, "selected": false, "text": "g++ -o grandfather.o -c grandfather.cpp\ng++ -o father.o -c father.cpp\ng++ -fPIC -shared -o libgf.so grandfather.o\ng++ -fPIC -shared -o libfather.so father.o\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,777
<p><em>Note: I found this <a href="https://stackoverflow.com/questions/10412/creating-a-word-doc-in-cnet">"Creating a Word Doc in C#.NET"</a>, but that is not what I want.</em></p> <p>Do you know how to create a <strong>.odt</strong> to create file from C# .NET?<br> Is there a .NET component or wrapper for an OpenOffice.org library to do this?</p>
[ { "answer_id": 15763461, "author": "CloudyMarble", "author_id": 395659, "author_profile": "https://Stackoverflow.com/users/395659", "pm_score": 0, "selected": false, "text": "private XComponentContext oStrap = uno.util.Bootstrap.bootstrap();\nXMultiServiceFactory oServMan = (XmultiServiceFactory) oStrap.getServiceManager();\nXComponentLoader oDesk = (XComponentLoader) oServMan.createInstance(\"com.sun.star.frame.Desktop\");\nstring url = @\"private:factory/swriter\";\nPropertyValue[] propVals = new PropertyValue[0];\nXComponent oDoc = oDesk.loadComponentFromURL(url, \"_blank\", 0, propVals);\nstring docText = \"File Content\\n\\r\";\n((XTextDocument)oDoc).getText().setString(docText);\nstring fileName = @\"C:\\FolderName\\FileName.odt\";\nfileName = \"file:///\" + fileName.Replace(@\"\\\", \"/\");\n((XStorable)oDoc).storeAsURL(fileName, propVals);\n((Xcomponent)oDoc).dispose();\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358/" ]
223,788
<p>In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class files?</p> <p>Update:</p> <p>I jumped in and started looking at the ORM source code.. One thing was immediately confusing to me.. all the ORM classes have the class name appended with _CORE i.e. ORM_Core ORM_Iterator_Core, but the code everywhere is extending the ORM class. Problem is, I've searched the whole code base 6 different ways, and I've never seen a plain ORM class def nor an ORM interface def or anything.. Could someone enlighten me on where that magic happens?</p>
[ { "answer_id": 224341, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 2, "selected": false, "text": "From Kohana.php in the system directory:\n\n<-- snip if ($extension = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))\n{\n// Load the extension\nrequire $extension;\n}\nelseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))\n{\n// Class extension to be evaluated\n$extension = 'class '.$class.' extends '.$class.'_Core { }';\n-->\n\n<-- snip\n\n// Transparent class extensions are handled using eval. This is\n// a disgusting hack, but it gets the job done.\neval($extension);\n\n-->\n" }, { "answer_id": 224666, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 4, "selected": true, "text": "class ORM extends ORM_Core {} \n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112692/" ]
223,797
<p>Is there a way to merge two primary keys into one and then cascade update all affected relationships? Here's the scenario:</p> <p>Customers (idCustomer int PK, Company varchar(50), etc)</p> <p>CustomerContacts (idCustomerContact int PK, idCustomer int FK, Name varchar(50), etc)</p> <p>CustomerNotes (idCustomerNote int PK, idCustomer int FK, Note Text, etc)</p> <p>Sometimes customers need to be merged into one. For example, you have a customer with the id of 1 and another with the id of 2. You want to merge both, so that everything that was 2 is now 1. I know I could write a script that updates all affected tables one by one, but I'd like to make it more future proof by using the cascade rules, so I don't have to update the script every time there is a new relationship added.</p> <p>Any ideas?</p>
[ { "answer_id": 224094, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": true, "text": "INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS INFORMATION_SCHEMA.KEY_COLUMN_USAGE INFORMATION_SCHEMA.TABLE_CONSTRAINTS INFORMATION_SCHEMA.COLUMNS and INFORMATION_SCHEMA.TABLES" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13843/" ]
223,800
<p><a href="http://www.php.net/features.safe-mode" rel="noreferrer">open_basedir</a> limits the files that can be opened by PHP within a directory-tree.</p> <p>I am storing several class libraries and configuration files outside of my web root directory. This way the web server does not make them publicly accessible. However when I try to include them from my application I get an open_basedir restriction error like this:</p> <blockquote> <p>Warning: realpath() [function.realpath]: open_basedir restriction in effect. File(/var/www/vhosts/domain.tld/zend/application) is not within the allowed path(s): (/var/www/vhosts/domain.tld/httpdocs:/tmp) in /var/www/vhosts/domain.tld/httpdocs/index.php on line 5</p> </blockquote> <p>My web root is here:</p> <pre><code>/var/www/vhosts/domain.tld/httpdocs </code></pre> <p>My libraries and configuration directory are here:</p> <pre><code>/var/www/vhosts/domain.tld/zend </code></pre> <p>What would be the best workaround to relax the open_basedir restriction so that the the directory tree under the domain folder becomes available to my application? I have a number of domains that I want to do this with, and I'm also obviously wary of creating security vulnerabilities.</p> <p>Note: I am using CentOS, Apache, Plesk, and I have root ssh access to the server. And though this doesn't apply to Zend Framework directly, I am using it in this instance. So here is the inclusion from Zend's bootstrap:</p> <pre><code>define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../zend/application/')); set_include_path(APPLICATION_PATH . '/../zend/library' . PATH_SEPARATOR . get_include_path()); </code></pre>
[ { "answer_id": 223834, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 5, "selected": true, "text": "<Directory /var/www/vhosts/domain.tld/httpdocs>\nphp_admin_value open_basedir \"/var/www/vhosts/domain.tld/httpdocs:/var/www/vhosts/domain.tld/zend\"\n</Directory>\n <Directory /var/www/vhosts/domain.tld/httpdocs>\nphp_admin_value open_basedir none\n</Directory>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9290/" ]
223,802
<p>I am new to MySQL and PHP(as you can probably tell) and I was wondering if anybody knew an easy way to import a CSV file into a MySQL table.</p> <blockquote> <p>"There are any number of ways to input csv into mysql depending in what kind of access you have, if you can use the mysql client directly there is a command to load delimited data, something like that could basically be entered directly in cron and keep itself up to date. Otherwise there are various php scripts to do that sort of thing."</p> </blockquote> <p>That is something a friend told me to do, is that the easiest/best way to do it? If it is would someone mind explaining it to me?</p> <p>Thank you </p>
[ { "answer_id": 223817, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 1, "selected": false, "text": "LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29912/" ]
223,804
<p>Suppose you have two models, User and City, joined by a third model CityPermission:</p> <pre><code>class CityPermission &lt; ActiveRecord::Base belongs_to :city belongs_to :user end class City &lt; ActiveRecord::Base has_many :city_permissions has_many :users, :through =&gt; :city_permissions end class User &lt; ActiveRecord::Base has_many :city_permissions has_many :cities, :through =&gt; :city_permissions end </code></pre> <p>Currently, I create the join table, and the index for the table, using the following migration code snippet:</p> <pre><code>create_table :city_permissions do |t| t.integer :user_id, :city_id t.other_fields ... end add_index(:city_permissions, :user_id) add_index(:city_permissions, :city_id) </code></pre> <p>Are these the optimal indexes to create? Will these indexes allow quick access back and forth through the join table, as well as quick lookups within the table itself, or is there some other better way? To restate this a bit differently, will these indexes, given <code>city</code> and <code>user</code> are instance variables of class City and User, allow <code>city.users</code>, <code>city.city_permissions</code>, <code>user.cities</code>, and <code>user.city_permissions</code> to all perform equally well?</p>
[ { "answer_id": 223812, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 3, "selected": true, "text": "has_and_belongs_to_many" }, { "answer_id": 223818, "author": "jcnnghm", "author_id": 4767, "author_profile": "https://Stackoverflow.com/users/4767", "pm_score": 1, "selected": false, "text": "user.cities SELECT `cities`.* FROM `cities` INNER JOIN city_permissions ON (cities.id = city_permissions.city_id) WHERE (city_permissions.user_id = 1 )\n +----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n| 1 | SIMPLE | city_permissions | ref | index_city_permissions_on_user_id,index_city_permissions_on_city_id | index_city_permissions_on_user_id | 5 | const | 1 | Using where |\n| 1 | SIMPLE | cities | eq_ref | PRIMARY | PRIMARY | 4 | barhopolis_development.city_permissions.city_id | 1 | |\n+----+-------------+------------------+--------+---------------------------------------------------------------------+-----------------------------------+---------+-------------------------------------------------+------+-------------+\n user.city_permissions SELECT * FROM `city_permissions` WHERE (`city_permissions`.user_id = 1)\n +----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n| 1 | SIMPLE | city_permissions | ref | index_city_permissions_on_user_id | index_city_permissions_on_user_id | 5 | const | 1 | Using where |\n+----+-------------+------------------+------+-----------------------------------+-----------------------------------+---------+-------+------+-------------+\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4767/" ]
223,832
<p>What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?</p> <h3>Example</h3> <pre><code>void Test() { OnlyHexInString(&quot;123ABC&quot;); // Returns true OnlyHexInString(&quot;123def&quot;); // Returns true OnlyHexInString(&quot;123g&quot;); // Returns false } bool OnlyHexInString(string text) { // Most efficient algorithm to check each digit in C# 2.0 goes here } </code></pre>
[ { "answer_id": 223843, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 3, "selected": false, "text": "Int32.TryParse()" }, { "answer_id": 223847, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 1, "selected": false, "text": "boolean lut[256]={false,false,true,........}\n\nboolean OnlyHexInString(String text)\n{\n for(int i = 0; i < text.size(); i++)\n if(!lut[text.charAt(i)])\n return false;\n return true;\n}\n" }, { "answer_id": 223852, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 5, "selected": false, "text": "// string hex = \"bacg123\"; Doesn't parse\n// string hex = \"bac123\"; Parses\nstring hex = \"bacg123\";\nlong output;\nlong.TryParse(hex, System.Globalization.NumberStyles.HexNumber, null, out output);\n" }, { "answer_id": 223854, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 6, "selected": false, "text": "loop through the chars {\n bool is_hex_char = (current_char >= '0' && current_char <= '9') ||\n (current_char >= 'a' && current_char <= 'f') ||\n (current_char >= 'A' && current_char <= 'F');\n\n if (!is_hex_char) {\n return false;\n }\n}\n\nreturn true;\n private bool IsHex(IEnumerable<char> chars)\n{\n bool isHex; \n foreach(var c in chars)\n {\n isHex = ((c >= '0' && c <= '9') || \n (c >= 'a' && c <= 'f') || \n (c >= 'A' && c <= 'F'));\n\n if(!isHex)\n return false;\n }\n return true;\n}\n" }, { "answer_id": 223857, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 7, "selected": true, "text": "public bool OnlyHexInString(string test)\n{\n // For C-style hex notation (0xFF) you can use @\"\\A\\b(0[xX])?[0-9a-fA-F]+\\b\\Z\"\n return System.Text.RegularExpressions.Regex.IsMatch(test, @\"\\A\\b[0-9a-fA-F]+\\b\\Z\");\n}\n" }, { "answer_id": 5781008, "author": "Robert Bernstein", "author_id": 280622, "author_profile": "https://Stackoverflow.com/users/280622", "pm_score": 3, "selected": false, "text": "private static bool IsValidHexString(IEnumerable<char> hexString)\n{\n return hexString.Select(currentCharacter =>\n (currentCharacter >= '0' && currentCharacter <= '9') ||\n (currentCharacter >= 'a' && currentCharacter <= 'f') ||\n (currentCharacter >= 'A' && currentCharacter <= 'F')).All(isHexCharacter => isHexCharacter);\n}\n" }, { "answer_id": 8024808, "author": "Kumba", "author_id": 482691, "author_profile": "https://Stackoverflow.com/users/482691", "pm_score": 3, "selected": false, "text": "''' <summary>\n''' Checks if a string contains ONLY hexadecimal digits.\n''' </summary>\n''' <param name=\"str\">String to check.</param>\n''' <returns>\n''' True if string is a hexadecimal number, False if otherwise.\n''' </returns>\nPublic Function IsHex(ByVal str As String) As Boolean\n If String.IsNullOrWhiteSpace(str) Then _\n Return False\n\n Dim i As Int32, c As Char\n\n If str.IndexOf(\"0x\") = 0 Then _\n str = str.Substring(2)\n\n While (i < str.Length)\n c = str.Chars(i)\n\n If Not (((c >= \"0\"c) AndAlso (c <= \"9\"c)) OrElse\n ((c >= \"a\"c) AndAlso (c <= \"f\"c)) OrElse\n ((c >= \"A\"c) AndAlso (c <= \"F\"c))) _\n Then\n Return False\n Else\n i += 1\n End If\n End While\n\n Return True\nEnd Function\n" }, { "answer_id": 8024875, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "bool OnlyHexInString(string text) {\n for (var i = 0; i < text.Length; i++) {\n var current = text[i];\n if (!(Char.IsDigit(current) || (current >= 'a' && current <= 'f'))) {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 11143213, "author": "Prueba", "author_id": 1472819, "author_profile": "https://Stackoverflow.com/users/1472819", "pm_score": -1, "selected": false, "text": "if (IsHex(text)) {\n return true;\n} else {\n return false;\n}\n" }, { "answer_id": 14543208, "author": "Jordan Morris", "author_id": 970673, "author_profile": "https://Stackoverflow.com/users/970673", "pm_score": 2, "selected": false, "text": "for bool isHex = \n myString.ToCharArray().Any(c => !\"0123456789abcdefABCDEF\".Contains(c));\n" }, { "answer_id": 18452890, "author": "jcallejas", "author_id": 2434242, "author_profile": "https://Stackoverflow.com/users/2434242", "pm_score": 2, "selected": false, "text": " //Another workaround, although RegularExpressions is the best solution\n boolean OnlyHexInString(String text)\n {\n for(int i = 0; i < text.size(); i++)\n if( !Uri.IsHexDigit(text.charAt(i)) )\n return false;\n return true;\n }\n" }, { "answer_id": 24353176, "author": "WaltZie", "author_id": 1865608, "author_profile": "https://Stackoverflow.com/users/1865608", "pm_score": 0, "selected": false, "text": " public static bool IsHex(this string value)\n { return value.All(c => c.IsHex()); }\n\n public static bool IsHex(this char c)\n {\n c = Char.ToLower(c);\n if (Char.IsDigit(c) || (c >= 'a' && c <= 'f'))\n return true;\n else\n return false;\n }\n" }, { "answer_id": 29439742, "author": "Kapé", "author_id": 465942, "author_profile": "https://Stackoverflow.com/users/465942", "pm_score": 4, "selected": false, "text": "bool isHex = text.All(\"0123456789abcdefABCDEF\".Contains); text using System.Linq; Enumerable.All()" }, { "answer_id": 30921419, "author": "Manfred", "author_id": 5025083, "author_profile": "https://Stackoverflow.com/users/5025083", "pm_score": 1, "selected": false, "text": "Public Function IsHexString(value As String) As Boolean\n Dim hx As String = \"0123456789ABCDEF\"\n For Each c As Char In value.ToUpper\n If Not hx.Contains(c) Then Return False\n Next\n Return True\nEnd Function\n public bool IsHexString(string value)\n{\n string hx = \"0123456789ABCDEF\";\n foreach (char c in value.ToUpper()) {\n if (!hx.Contains(c))\n return false;\n }\n return true;\n}\n" }, { "answer_id": 31455671, "author": "Barak Rosenfeld", "author_id": 4274727, "author_profile": "https://Stackoverflow.com/users/4274727", "pm_score": 0, "selected": false, "text": "public static bool IsHex(this char c)\n{\n return (c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F');\n}\n" }, { "answer_id": 43493548, "author": "Rosdi Kasim", "author_id": 193634, "author_profile": "https://Stackoverflow.com/users/193634", "pm_score": 0, "selected": false, "text": "public static class StringExtensions\n{\n public static bool IsHexString(this string str)\n {\n foreach (var c in str)\n {\n var isHex = ((c >= '0' && c <= '9') ||\n (c >= 'a' && c <= 'f') ||\n (c >= 'A' && c <= 'F'));\n\n if (!isHex)\n {\n return false;\n }\n }\n\n return true;\n }\n\n //bonus, verify whether a string can be parsed as byte[]\n public static bool IsParseableToByteArray(this string str)\n {\n return IsHexString(str) && str.Length % 2 == 0;\n }\n}\n if(\"08c9b54d1099e73d121c4200168f252e6e75d215969d253e074a9457d0401cc6\".IsHexString())\n{\n //returns true...\n}\n" }, { "answer_id": 43844931, "author": "Rahbek", "author_id": 3326779, "author_profile": "https://Stackoverflow.com/users/3326779", "pm_score": 0, "selected": false, "text": "for (int i = 0; i < Request.Length; i += 2)\n if (!byte.TryParse(string.Join(\"\", Request.Skip(i).Take(2)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)) return false;\n" }, { "answer_id": 47568218, "author": "Ismet Tanrikulu", "author_id": 7249379, "author_profile": "https://Stackoverflow.com/users/7249379", "pm_score": 0, "selected": false, "text": "public static bool HexInCardUID(string test)\n {\n if (test.Trim().Length != 14)\n return false;\n for (int i = 0; i < test.Length; i++)\n if (!Uri.IsHexDigit(Convert.ToChar(test.Substring(i, 1))))\n return false;\n return true;\n }**strong text**\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
223,833
<p>This is what I have, which works in IE7, but not in Firefox:</p> <pre><code>@media screen { @import 'screen.css'; } </code></pre> <p>It works outside of the @media block in Firefox:</p> <pre><code>@import 'screen.css'; </code></pre> <p><strong>UPDATE:</strong> </p> <p>This works:</p> <pre><code>@media screen { .yui-d3f { border: 1px solid #999; height: 250px; } } </code></pre> <p>What am I missing?</p>
[ { "answer_id": 223949, "author": "Peter Coulton", "author_id": 117, "author_profile": "https://Stackoverflow.com/users/117", "pm_score": 1, "selected": false, "text": "@import 'stylesheet.css' media_type;\n @import 'firefox-screen.css' screen;\n@media screen { @import 'IE7-screen.css'; }\n" }, { "answer_id": 224278, "author": "Marcus Griep", "author_id": 28645, "author_profile": "https://Stackoverflow.com/users/28645", "pm_score": 4, "selected": true, "text": "@import @charset @import @import" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
223,844
<p>I can't find a definitive answer. Since C# 2.0 you've been able to declare</p> <pre><code>int? i = 125; </code></pre> <p>as shorthand for</p> <pre><code>Nullable&lt;int&gt; i = Nullable&lt;int&gt;(123); </code></pre> <p>I recall reading somewhere that VB.NET did not allow this shortcut. But low and behold, I tried it in VS 2008 today and it works.</p> <p>Does anyone know whether it's been this way since .NET 2.0 or was this added later?</p>
[ { "answer_id": 224110, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 5, "selected": true, "text": "Dim x as Nullable(of Integer)\n Dim x as Integer?\n" }, { "answer_id": 302422, "author": "user23462", "author_id": 23462, "author_profile": "https://Stackoverflow.com/users/23462", "pm_score": 2, "selected": false, "text": "dim oInt as object\n\ndim i as integer\n\nif oInt is nothing then \n\n msgbox(\"int is null\")\nelse\n\n i = cint(oInt)\n\nend if\n Dim oInt as nullable(of integer)\n\ndim i as integer\n\nif oInt.HasValue = false then \n\n msgbox(\"int is null\")\n\nelse\n\n i = oInt.Value\n\nend if\n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, iif(oInt.HasValue, oInt.Value, DBNull.value))\n if oInt.HasValue then \n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, oInt.Value)\nelse\n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, dbnull.value)\nend if\n AddParamToSQLCmd(sqlCmd, \"@SomeID\", SqlDbType.Int, 0, ParameterDirection.Input, oInt)\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
223,866
<p>I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. </p> <p>I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain just relying on regular expressions.</p> <p>The transcripts are being generated by www.providesupport.com and emailed to an account, I then extract a plain text transcript attachment from the email.</p> <p>The reason for parsing the file is to extract the conversation text for later but also to identify visitors and operators names so that the information can be made available via a CRM.</p> <p>Here is an example of a transcript file:</p> <pre><code>Chat Transcript Visitor: Random Website Visitor Operator: Milton Company: Initech Started: 16 Oct 2008 9:13:58 Finished: 16 Oct 2008 9:45:44 Random Website Visitor: Where do i get the cover sheet for the TPS report? * There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click "Send" button * Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor. Milton: Y-- Excuse me. You-- I believe you have my stapler? Random Website Visitor: I really just need the cover sheet, okay? Milton: it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire... Random Website Visitor: oh i found it, thanks anyway. * Random Website Visitor is now off-line and may not reply. Currently in room: Milton. Milton: Well, Ok. But… that's the last straw. * Milton has left the conversation. Currently in room: room is empty. Visitor Details --------------- Your Name: Random Website Visitor Your Question: Where do i get the cover sheet for the TPS report? IP Address: 255.255.255.255 Host Name: 255.255.255.255 Referrer: Unknown Browser/OS: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727) </code></pre>
[ { "answer_id": 223904, "author": "dalyons", "author_id": 16925, "author_profile": "https://Stackoverflow.com/users/16925", "pm_score": 2, "selected": false, "text": "visitor = text.find(/Visitor:(.*)/)\noperator = text.find(/Operator:(.*)/)\nbody = text.find(/whatever....)\n text.match(/Visitor:(.*)\\nOperator:(.*)...whatever to giant regex/m) do\n visitor = $1\n operator = $2\n etc.\nend\n" }, { "answer_id": 1657561, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "lepl from pprint import pprint\nfrom lepl import AnyBut, Drop, Eos, Newline, Separator, SkipTo, Space\n\n# field = name , \":\" , value\nname, value = AnyBut(':\\n')[1:,...], AnyBut('\\n')[::'n',...] \nwith Separator(~Space()[:]):\n field = name & Drop(':') & value & ~(Newline() | Eos()) > tuple\n\nheader_start = SkipTo('Chat Transcript' & Newline()[2])\nheader = ~header_start & field[1:] > dict\nserver_message = Drop('* ') & AnyBut('\\n')[:,...] & ~Newline() > 'Server'\nconversation = (server_message | field)[1:] > list\nfooter_start = 'Visitor Details' & Newline() & '-'*15 & Newline()\nfooter = ~footer_start & field[1:] > dict\nchat_log = header & ~Newline() & conversation & ~Newline() & footer\n\npprint(chat_log.parse_file(open('chat.log')))\n from pprint import pprint\nfrom lepl import And, Drop, Newline, Or, Regexp, SkipTo\n\ndef Field(name, value=Regexp(r'\\s*(.*?)\\s*?\\n')):\n \"\"\"'name , \":\" , value' matcher\"\"\"\n return name & Drop(':') & value > tuple\n\nFields = lambda names: reduce(And, map(Field, names))\n\nheader_start = SkipTo(Regexp(r'^Chat Transcript$') & Newline()[2])\nheader_fields = Fields(\"Visitor Operator Company Started Finished\".split())\nserver_message = Regexp(r'^\\* (.*?)\\n') > 'Server'\nfooter_fields = Fields((\"Your Name, Your Question, IP Address, \"\n \"Host Name, Referrer, Browser/OS\").split(', '))\n\nwith open('chat.log') as f:\n # parse header to find Visitor and Operator's names\n headers, = (~header_start & header_fields > dict).parse_file(f)\n # only Visitor, Operator and Server may take part in the conversation\n message = reduce(Or, [Field(headers[name])\n for name in \"Visitor Operator\".split()])\n conversation = (message | server_message)[1:]\n messages, footers = ((conversation > list)\n & Drop('\\nVisitor Details\\n---------------\\n')\n & (footer_fields > dict)).parse_file(f)\n\npprint((headers, messages, footers))\n ({'Company': 'Initech',\n 'Finished': '16 Oct 2008 9:45:44',\n 'Operator': 'Milton',\n 'Started': '16 Oct 2008 9:13:58',\n 'Visitor': 'Random Website Visitor'},\n [('Random Website Visitor',\n 'Where do i get the cover sheet for the TPS report?'),\n ('Server',\n 'There are no operators available at the moment. If you would like to leave a message, please type it in the input field below and click \"Send\" button'),\n ('Server',\n 'Call accepted by operator Milton. Currently in room: Milton, Random Website Visitor.'),\n ('Milton', 'Y-- Excuse me. You-- I believe you have my stapler?'),\n ('Random Website Visitor', 'I really just need the cover sheet, okay?'),\n ('Milton',\n \"it's not okay because if they take my stapler then I'll, I'll, I'll set the building on fire...\"),\n ('Random Website Visitor', 'oh i found it, thanks anyway.'),\n ('Server',\n 'Random Website Visitor is now off-line and may not reply. Currently in room: Milton.'),\n ('Milton', \"Well, Ok. But… that's the last straw.\"),\n ('Server',\n 'Milton has left the conversation. Currently in room: room is empty.')],\n {'Browser/OS': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',\n 'Host Name': '255.255.255.255',\n 'IP Address': '255.255.255.255',\n 'Referrer': 'Unknown',\n 'Your Name': 'Random Website Visitor',\n 'Your Question': 'Where do i get the cover sheet for the TPS report?'})\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178/" ]
223,875
<p>I am starting to develop an Eclipse plugin (technically, an OSGi plugin) and one of the first problems I've run into is that I can't seem to control the commons-logging output as I normally would.</p> <p>I've included the commons-logging package in the plugin dependencies, and indeed, when I log something (at INFO or higher severity) it is logged to the console. However, I can't seem to log at any lower level (such as DEBUG or TRACE).</p> <p>I have specified a log4j.properties file, and it is on the classpath (for the runtime, just as the commons-logging package is) but none of the settings in that properties file have any impact on the behavior of the logger.</p> <p>Here's the log4j.properties file:</p> <pre><code># Log4j Logging levels, in order of decreasing importance are: # FATAL, ERROR, WARN, INFO, DEBUG, TRACE # # Root logger option log4j.rootLogger=ERROR,stdout #,LOGFILE # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %r (%l) %t%n - %m%n </code></pre> <p>What do I need to do so that I can actually control the output of the logger?</p> <p>Here are some sample output messages, in the hopes that the formatting may coincide with a default for java.util.logging, or provide other hints to someone:</p> <pre><code>Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start SEVERE: fatal_message Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start WARNING: warn_message Oct 21, 2008 11:01:23 PM com.stottlerhenke.sentinel.client.Activator start INFO: info_message </code></pre> <p><strong>Update:</strong></p> <p>I have now tried various combinations of:</p> <ul> <li>org.osgi.service.log.LogService et al.</li> <li><a href="http://www.slf4j.org/" rel="noreferrer">slf4j</a></li> <li><a href="http://logging.apache.org/log4j/" rel="noreferrer">Log4J</a></li> <li><a href="http://commons.apache.org/logging/" rel="noreferrer">Commons-logging</a></li> <li><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/package-summary.html" rel="noreferrer">java.util.logging</a></li> </ul> <p>and I can <em>only</em> get DEBUG, or lower, level messages to appear if I am running OSGi manually from a prompt (which is impractical for what I am developing). Furthermore, I can't effect any other type of logging configuration via various properties files. Everything I try in that regard seems to be overridden by an eclipse setting.</p> <p>I've also tried putting various config files for the above libraries in numerous places, including as plug-in fragments attached to their respective libraries as suggested <a href="http://www.eclipsezone.com/eclipse/forums/t99588.html" rel="noreferrer">here</a>, and still, the same result happens.</p> <p>I've implemented a custom LogListener, and traced the entire path of a log message (as well as I know how, anyway) with System.out.println's, and debug messages <em>are</em> present right up until they are output by whatever underlying logging API I'm using, then they disappear.</p>
[ { "answer_id": 224821, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "java -jar org.eclipse.osgi_3.3.0.v20070530.jar -console -noExit -clean\n" }, { "answer_id": 235532, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 6, "selected": true, "text": "Bundle-ClassPath: lib/jena.jar,\n .,\n org.apache.log4j-1.2.12.jar,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities\n Bundle-ClassPath: lib/jena.jar,\n .,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.client.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities,\n org.apache.log4j\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ]
223,878
<p>In my question <a href="https://stackoverflow.com/questions/184729/as-a-mockist-tdd-practitioner-should-i-mock-other-methods-in-the-same-class-as">As a “mockist” TDD practitioner, should I mock other methods in the same class as the method under test?</a>, <a href="https://stackoverflow.com/users/20487/avdi">Avdi</a> answered "Personally I think that mocking on self is almost always a code smell. It's testing the implementation rather than the behavior." He may be right, but often I can't distinguish between the implementation and the behavior.</p> <p>I have another example (in Python-style pseudo-code) that may lead to helpful answers:</p> <pre><code>class Consumer: def spec_dirpath: client = VCS.get_connection(self.vcs_client_name) client.sync() return client.dirpath() def spec_filepath: filepath = os.path.join(spec_dirpath(), self.spec_filename) if not os.path.exists(filepath): raise ConsumerException return filepath def get_components: return Components.get_components_from_spec_file(self.spec_filepath()) </code></pre> <p>The idea here is that the get_components method calls the spec_filepath method in order to get a path to a file that the get_components_from_spec_file Components class method will read a list of components from. The spec_filepath method in turn calls spec_dirpath, which syncs the directory containing the spec file from the VCS system and returns the path to that directory. (Try not to look for bugs in this code--it's pseudo-code, after all.)</p> <p>I'm looking for advice on how to test these methods...</p> <p>Testing spec_dirpath should be quite straightforward. I can mock the VCS class and have it return a mock object and confirm the appropriate methods are called (and that the spec_dirpath method returns what the mock's dirpath method returns).</p> <p>But if I don't mock spec_dirpath while testing spec_filepath, how do I avoid duplicating the same test code from the spec_dirpath code in the spec_filepath test? And if I don't mock spec_filepath while testing get_components, how do I avoid duplicating the test code from both spec_filepath <em>and</em> spec_dirpath?</p>
[ { "answer_id": 224821, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": false, "text": "java -jar org.eclipse.osgi_3.3.0.v20070530.jar -console -noExit -clean\n" }, { "answer_id": 235532, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 6, "selected": true, "text": "Bundle-ClassPath: lib/jena.jar,\n .,\n org.apache.log4j-1.2.12.jar,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities\n Bundle-ClassPath: lib/jena.jar,\n .,\n lib/google-collect-snapshot.jar\nImport-Package: com.acme.client.translation,\n com.acme.client.translation.interfaces,\n com.acme.shared.osgi,\n com.acme.utilities,\n org.apache.log4j\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
223,902
<p>Take the following generics example</p> <pre><code>import java.util.List; import java.util.ArrayList; public class GenericsTest { private List&lt;Animal&gt; myList; public static void main(String args[]) { new GenericsTest(new ArrayList&lt;Animal&gt;()).add(new Dog()); } public GenericsTest(List&lt;Animal&gt; list) { myList = list; } public void add(Animal a) { myList.add(a); } public interface Animal {} public static class Dog implements Animal {} public static class Cat implements Animal {} } </code></pre> <p>It works fine. But as you know, you cannot construct it with</p> <pre><code>new GenericsTest(new ArrayList&lt;Dog&gt;()); </code></pre> <p>because, as you know, the add(Animal) would make possible to add <code>Cat</code>s. The <em>suggested</em> way of solving this problem, i.e. wildcarding does not work either, because, yes, you can change every <code>List&lt;Animal&gt;</code> in <code>List&lt;? extends Animal&gt;</code> but it has the same problem: you can create the <code>GenericsTest</code> with <code>List&lt;Cat&gt;</code> and then add <code>Dog</code>s.</p> <p>So my question is: is there a convenient way to write this class once, and then use it for all the possible <code>Animals</code>? Of course it should solve straightforwardly the above mentioned problem. </p>
[ { "answer_id": 223923, "author": "Greg Cottman", "author_id": 10496, "author_profile": "https://Stackoverflow.com/users/10496", "pm_score": 4, "selected": true, "text": "public class GenericsTest<T extends Animal>\n{\n private List<T> myList;\n\n public static void main(String args[])\n {\n new GenericsTest<Dog>(new ArrayList<Dog>());\n }\n\n public GenericsTest(List<T> list)\n {\n myList = list;\n }\n\n public void add(T a)\n {\n myList.add(a);\n }\n}\n" }, { "answer_id": 223932, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 2, "selected": false, "text": "import java.util.List;\nimport java.util.ArrayList;\n\npublic class GenericsTest<T extends Animal> {\n private final List<T> myList;\n\n public static void main(final String args[]) {\n new GenericsTest<Animal>(new ArrayList<Animal>()).add(new Dog());\n new GenericsTest<Dog>(new ArrayList<Dog>()).add(new Dog());\n new GenericsTest<Cat>(new ArrayList<Cat>()).add(new Cat());\n }\n\n public GenericsTest(final List<T> list) {\n myList = list;\n }\n\n public void add(final T a) {\n myList.add(a);\n }\n}\n\n// Can't nest as Animal needs to be in scope of class declaration\ninterface Animal {}\nclass Dog implements Animal {}\nclass Cat implements Animal {}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25891/" ]
223,918
<p>We all know you can't do the following because of <code>ConcurrentModificationException</code>:</p> <pre><code>for (Object i : l) { if (condition(i)) { l.remove(i); } } </code></pre> <p>But this apparently works sometimes, but not always. Here's some specific code:</p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) { Collection&lt;Integer&gt; l = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; 10; ++i) { l.add(4); l.add(5); l.add(6); } for (int i : l) { if (i == 5) { l.remove(i); } } System.out.println(l); } </code></pre> <p>This, of course, results in:</p> <pre><code>Exception in thread "main" java.util.ConcurrentModificationException </code></pre> <p>Even though multiple threads aren't doing it. Anyway.</p> <p>What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?</p> <p>I'm also using an arbitrary <code>Collection</code> here, not necessarily an <code>ArrayList</code>, so you can't rely on <code>get</code>.</p>
[ { "answer_id": 223927, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 8, "selected": false, "text": "Iterator<Integer> iter = l.iterator();\nwhile (iter.hasNext()) {\n if (iter.next() == 5) {\n iter.remove();\n }\n}\n .remove()" }, { "answer_id": 223929, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 12, "selected": true, "text": "Iterator.remove() List<String> list = new ArrayList<>();\n\n// This is a clever way to create the iterator and call iterator.hasNext() like\n// you would do in a while-loop. It would be the same as doing:\n// Iterator<String> iterator = list.iterator();\n// while (iterator.hasNext()) {\nfor (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {\n String string = iterator.next();\n if (string.isEmpty()) {\n // Remove the current element from the iterator and the list.\n iterator.remove();\n }\n}\n Iterator.remove() ListIterator ListIterator#add Iterator#remove put Map" }, { "answer_id": 223942, "author": "RodeoClown", "author_id": 943, "author_profile": "https://Stackoverflow.com/users/943", "pm_score": 5, "selected": false, "text": "public static void main(String[] args)\n{\n Collection<Integer> l = new ArrayList<Integer>();\n Collection<Integer> itemsToRemove = new ArrayList<>();\n for (int i=0; i < 10; i++) {\n l.add(Integer.of(4));\n l.add(Integer.of(5));\n l.add(Integer.of(6));\n }\n for (Integer i : l)\n {\n if (i.intValue() == 5) {\n itemsToRemove.add(i);\n }\n }\n\n l.removeAll(itemsToRemove);\n System.out.println(l);\n}\n" }, { "answer_id": 2841570, "author": "Ashish", "author_id": 275264, "author_profile": "https://Stackoverflow.com/users/275264", "pm_score": 5, "selected": false, "text": "\"java.util.ConcurrentModificationException\" next() remove() hasNext() public E next() {\n checkForComodification();\n try {\n E next = get(cursor);\n lastRet = cursor++;\n return next;\n } catch(IndexOutOfBoundsException e) {\n checkForComodification();\n throw new NoSuchElementException();\n }\n}\n checkForComodification final void checkForComodification() {\n if (modCount != expectedModCount)\n throw new ConcurrentModificationException();\n}\n modCount expectedModCount ConcurrentModificationException" }, { "answer_id": 11201224, "author": "Priyank Doshi", "author_id": 1392956, "author_profile": "https://Stackoverflow.com/users/1392956", "pm_score": 4, "selected": false, "text": "for (String str : new ArrayList<String>(listOfStr)) \n{\n listOfStr.remove(/* object reference or index */);\n}\n" }, { "answer_id": 13943008, "author": "Donald Raab", "author_id": 1570415, "author_profile": "https://Stackoverflow.com/users/1570415", "pm_score": 4, "selected": false, "text": "removeIf MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);\nlist.removeIf(Predicates.lessThan(3));\nAssert.assertEquals(Lists.mutable.of(3, 4, 5), list);\n MutableList<Integer> list = Lists.mutable.of(1, 2, 3, 4, 5);\nlist.removeIf(Predicates.cast(integer -> integer < 3));\nAssert.assertEquals(Lists.mutable.of(3, 4, 5), list);\n Predicates.cast() removeIf java.util.Collection" }, { "answer_id": 18357676, "author": "Antzi", "author_id": 1485230, "author_profile": "https://Stackoverflow.com/users/1485230", "pm_score": 4, "selected": false, "text": "for (Iterator<Object> it = objects.iterator(); it.hasNext();) {\n Object object = it.next();\n if (test) {\n it.remove();\n }\n}\n" }, { "answer_id": 20067507, "author": "Nandhan Thiravia", "author_id": 1711555, "author_profile": "https://Stackoverflow.com/users/1711555", "pm_score": 0, "selected": false, "text": "//\"list\" is ArrayList<Object>\n//\"state\" is some boolean variable, which when set to true, Object will be removed from the list\nint index = 0;\nwhile(index < list.size()) {\n Object r = list.get(index);\n if( state ) {\n list.remove(index);\n index = 0;\n continue;\n }\n index += 1;\n}\n" }, { "answer_id": 23908758, "author": "assylias", "author_id": 829571, "author_profile": "https://Stackoverflow.com/users/829571", "pm_score": 8, "selected": false, "text": "removeIf Collection<Integer> coll = new ArrayList<>();\n//populate\n\ncoll.removeIf(i -> i == 5);\n" }, { "answer_id": 25565900, "author": "Landei", "author_id": 375232, "author_profile": "https://Stackoverflow.com/users/375232", "pm_score": 4, "selected": false, "text": "for(int i = l.size() - 1; i >= 0; i --) {\n if (l.get(i) == 5) {\n l.remove(i);\n }\n}\n removeIf filter" }, { "answer_id": 35207600, "author": "Nurlan", "author_id": 2807072, "author_profile": "https://Stackoverflow.com/users/2807072", "pm_score": -1, "selected": false, "text": "System.arraycopy() while(list.size()>0)list.remove(list.size()-1); while(list.size()>0)list.remove(0); //region prepare data\nArrayList<Integer> ints = new ArrayList<Integer>();\nArrayList<Integer> toRemove = new ArrayList<Integer>();\nRandom rdm = new Random();\nlong millis;\nfor (int i = 0; i < 100000; i++) {\n Integer integer = rdm.nextInt();\n ints.add(integer);\n}\nArrayList<Integer> intsForIndex = new ArrayList<Integer>(ints);\nArrayList<Integer> intsDescIndex = new ArrayList<Integer>(ints);\nArrayList<Integer> intsIterator = new ArrayList<Integer>(ints);\n//endregion\n\n// region for index\nmillis = System.currentTimeMillis();\nfor (int i = 0; i < intsForIndex.size(); i++) \n if (intsForIndex.get(i) % 2 == 0) intsForIndex.remove(i--);\nSystem.out.println(System.currentTimeMillis() - millis);\n// endregion\n\n// region for index desc\nmillis = System.currentTimeMillis();\nfor (int i = intsDescIndex.size() - 1; i >= 0; i--) \n if (intsDescIndex.get(i) % 2 == 0) intsDescIndex.remove(i);\nSystem.out.println(System.currentTimeMillis() - millis);\n//endregion\n\n// region iterator\nmillis = System.currentTimeMillis();\nfor (Iterator<Integer> iterator = intsIterator.iterator(); iterator.hasNext(); )\n if (iterator.next() % 2 == 0) iterator.remove();\nSystem.out.println(System.currentTimeMillis() - millis);\n//endregion\n" }, { "answer_id": 38116468, "author": "Srinivasan Thoyyeti", "author_id": 4952219, "author_profile": "https://Stackoverflow.com/users/4952219", "pm_score": 0, "selected": false, "text": "for (Integer i : l)\n{\n if (i.intValue() == 5){\n itemsToRemove.add(i);\n break;\n }\n}\n" }, { "answer_id": 43441822, "author": "from56", "author_id": 7690376, "author_profile": "https://Stackoverflow.com/users/7690376", "pm_score": 3, "selected": false, "text": "ArrayList<String> myArray = new ArrayList<>();\n\nfor (int i = 0; i < myArray.size(); ) {\n String text = myArray.get(i);\n if (someCondition(text))\n myArray.remove(i);\n else\n i++; \n}\n" }, { "answer_id": 46733073, "author": "james.garriss", "author_id": 584674, "author_profile": "https://Stackoverflow.com/users/584674", "pm_score": 2, "selected": false, "text": "ListIterator Car List<Car> cars = ArrayList<>();\n// add cars here...\n\nfor (ListIterator<Car> carIterator = cars.listIterator(); carIterator.hasNext(); )\n{\n if (<some-condition>)\n { \n carIterator().remove()\n }\n else if (<some-other-condition>)\n { \n carIterator().add(aNewCar);\n }\n}\n" }, { "answer_id": 49335224, "author": "John", "author_id": 866333, "author_profile": "https://Stackoverflow.com/users/866333", "pm_score": 3, "selected": false, "text": "for (TouchableObj obj : untouchedSet) { // <--- This is where ConcurrentModificationException strikes\n if (obj.isTouched()) {\n untouchedSet.remove(obj);\n touchedSt.add(obj);\n break; // this is key to avoiding returning to the foreach\n }\n}\n Colletion break" }, { "answer_id": 50161275, "author": "jagdish khetre", "author_id": 6715431, "author_profile": "https://Stackoverflow.com/users/6715431", "pm_score": 0, "selected": false, "text": "java.util.concurrent public static void main(String[] args) {\n Collection<Integer> l = new CopyOnWriteArrayList<Integer>();\n \n for (int i=0; i < 10; ++i) {\n l.add(new Integer(4));\n l.add(new Integer(5));\n l.add(new Integer(6));\n }\n \n for (Integer i : l) {\n if (i.intValue() == 5) {\n l.remove(i);\n }\n }\n \n System.out.println(l);\n}\n" }, { "answer_id": 52364161, "author": "Yazon2006", "author_id": 2557258, "author_profile": "https://Stackoverflow.com/users/2557258", "pm_score": 0, "selected": false, "text": "public class Example {\n private final List<String> queue = Collections.synchronizedList(new ArrayList<String>());\n\n public void removeFromQueue() {\n synchronized (queue) {\n Iterator<String> iterator = queue.iterator();\n String string = iterator.next();\n if (string.isEmpty()) {\n iterator.remove();\n }\n }\n }\n}\n" }, { "answer_id": 52525447, "author": "pedram bashiri", "author_id": 2695227, "author_profile": "https://Stackoverflow.com/users/2695227", "pm_score": 1, "selected": false, "text": "Collection<Integer> l = new ArrayList<Integer>();\n\nfor (int i=0; i < 10; ++i) {\n l.add(new Integer(4));\n l.add(new Integer(5));\n l.add(new Integer(6));\n}\n\nl.removeIf(i -> i.intValue() == 5);\n" }, { "answer_id": 53860666, "author": "cellepo", "author_id": 1357094, "author_profile": "https://Stackoverflow.com/users/1357094", "pm_score": 0, "selected": false, "text": "Collection List List ConcurrentModificationException while Iterator Iterator final List<Integer> list = new ArrayList<>();\nfor(int i = 0; i < 10; ++i){\n list.add(i);\n}\n\nint i = 1;\nwhile(i < list.size()){\n if(list.get(i) % 2 == 0){\n list.remove(i++);\n\n } else {\n i += 2;\n }\n}\n Iterator get list Collection List Collection List get Collection list Collection Iterator final List<Integer> list = new ArrayList<>();\nfor(int i = 0; i < 10; ++i){\n list.add(i);\n}\n\nint i = 0;\nwhile(i < list.size()){\n if(list.get(i) % 2 == 0){\n list.remove(i);\n\n } else {\n ++i;\n }\n}\n" }, { "answer_id": 55161143, "author": "Nestor Milyaev", "author_id": 5778099, "author_profile": "https://Stackoverflow.com/users/5778099", "pm_score": 2, "selected": false, "text": "List<Object> l = ...\n \nList<Object> iterationList = ImmutableList.copyOf(l);\n \nfor (Object curr : iterationList) {\n if (condition(curr)) {\n l.remove(curr);\n }\n}\n" }, { "answer_id": 57298240, "author": "Rahul Vala", "author_id": 7584019, "author_profile": "https://Stackoverflow.com/users/7584019", "pm_score": 0, "selected": false, "text": "int n = list.size();\nfor(int j=0;j<n;j++){\n //you can also put a condition before remove\n list.remove(0);\n Collections.rotate(list, 1);\n}\nCollections.rotate(list, -1);\n" }, { "answer_id": 58844056, "author": "Oleg Tatarchuk", "author_id": 8483269, "author_profile": "https://Stackoverflow.com/users/8483269", "pm_score": 0, "selected": false, "text": "i for (Object i : l) {\n if (condition(i)) {\n l = (l.stream().filter((a) -> a != i)).collect(Collectors.toList());\n }\n}\n" }, { "answer_id": 64011786, "author": "Adil Karaöz", "author_id": 705908, "author_profile": "https://Stackoverflow.com/users/705908", "pm_score": 1, "selected": false, "text": "l.removeIf(current -> current == 5);\n" }, { "answer_id": 65476338, "author": "Oguzhan Cevik", "author_id": 7927573, "author_profile": "https://Stackoverflow.com/users/7927573", "pm_score": 0, "selected": false, "text": "Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();\nwhile(iterator.hasNext()){\n Map.Entry<String, String> entry = iterator.next();\n if(entry.getKey().equals(\"test\")) {\n iterator.remove();\n } \n}\n" }, { "answer_id": 66889350, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 1, "selected": false, "text": "Iterator<String> iterator = list.iterator();\nwhile (iterator.hasNext()) {\n String value = iter.next()\n if (value == \"A\") {\n list.remove(it.next()); //throws ConcurrentModificationException\n }\n}\n remove() Iterator<String> iterator = list.iterator();\nwhile (iterator.hasNext()) {\n String value = iter.next()\n if (value == \"A\") {\n it.remove()\n }\n}\n synchronize" }, { "answer_id": 68239250, "author": "Alferd Nobel", "author_id": 4005379, "author_profile": "https://Stackoverflow.com/users/4005379", "pm_score": 0, "selected": false, "text": "ConcurrentModificationException stream().map() for(:) ArrayList<BuildEntity> for(BuildEntity build : uniqueBuildEntities){\n if(build!=null){\n if(isBuildCrashedWithErrors(build)){\n log.info(\"The following build crashed with errors , will not be persisted -> \\n{}\"\n ,build.getBuildUrl());\n uniqueBuildEntities.remove(build);\n if (uniqueBuildEntities.isEmpty()) return EMPTY_LIST;\n }\n }\n }\n if(uniqueBuildEntities.size()>0) {\n dbEntries.addAll(uniqueBuildEntities);\n }\n" }, { "answer_id": 70142023, "author": "SM. Hosseini", "author_id": 8423371, "author_profile": "https://Stackoverflow.com/users/8423371", "pm_score": 0, "selected": false, "text": "public class UserProfileEntity {\n private String Code;\n private String mobileNumber;\n private LocalDateTime inputDT;\n // getters and setters here\n}\nHashMap<String, UserProfileEntity> upMap = new HashMap<>();\n\n\n// remove by value\nupMap.values().removeIf(value -> !value.getCode().contains(\"0005\"));\n\n// remove by key\nupMap.keySet().removeIf(key -> key.contentEquals(\"testUser\"));\n\n// remove by entry / key + value\nupMap.entrySet().removeIf(entry -> (entry.getKey().endsWith(\"admin\") || entry.getValue().getInputDT().isBefore(LocalDateTime.now().minusMinutes(3)));\n" }, { "answer_id": 74542733, "author": "Saeed Ir", "author_id": 1375876, "author_profile": "https://Stackoverflow.com/users/1375876", "pm_score": 0, "selected": false, "text": "for (i in myList.size-1 downTo 0) {\n myList.getOrNull(i)?.also {\n if (it == 5)\n myList.remove(it)\n }\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
223,919
<p>I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.</p> <p>Here is how I have the library and application folders set up. (I'm not sure if this is right)</p> <pre><code>AppFolder App.sln App.ncb *.h *.cpp Debug *.obj App.exe </code></pre> <p>and somewhere else on the hard drive...</p> <pre><code>LibraryFolder lib Library.lib include LibrarySolutionFolder Library.sln Library.ncb *.h *.cpp Debug *.obj Library.lib </code></pre> <p>I've been #including the library *.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories. How can I get this to link? (And am I structuring the library folders correctly?)</p>
[ { "answer_id": 223943, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "#pragma comment(lib, \"Library\")\n" }, { "answer_id": 223947, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "#pragma comment(lib,\"c:\\\\path_to_library\\\\libname.lib\")\n" }, { "answer_id": 223961, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 1, "selected": false, "text": " #pragma comment(lib,\"C:\\\\path\\\\to\\\\library.lib\")`\n #include" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2222/" ]
223,921
<p>How do you get Pro*c to work within MSVC 6?</p> <p>In otherwords compile a .pc file into a .cpp file.</p>
[ { "answer_id": 285934, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": true, "text": "$(ProjDir)\\$(InputName).cpp\n call vcvars32.bat \nproc sqlcheck=semantics userid=scott/tiger@instance code=cpp char_map=string sqlcheck=semantics parse=partial mode=ansi $(ProjDir)\\$(InputName).pc include=c:\\ora920\\oci\\include include=\"%MSVCDIR%\\include\" include=\"$(MSDEVDIR)\\..\\vc\\include\" include=\"$(MSDEVDIR)\\..\\..\\vc98\\include\"\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
223,931
<p>What are your favorite ways to encapsulate LINQ to SQL entity classes and data-context classes into business objects?</p> <p>What have you found to work in a given situation?</p> <p>Have you invented or taken to any specific patterns?</p>
[ { "answer_id": 1495281, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": true, "text": "DeleteOnSubmit Delete /// <summary>\n/// This class extends BusinessLogicDataContext.Products entity class\n/// </summary>\npublic partial class Product\n{\n /// <summary>\n /// New up a product by column: dbo.Products.ProductId in database\n /// </summary>\n public Product(Int32 id)\n {\n var dc = new BusinessLogicDataContext();\n\n // query database for the product\n var query = (\n from p in dc.Products \n where p.ProductId == id \n select p\n ).FirstOrDefault();\n\n // if database-entry does not exist in database, exit\n if (query == null) return;\n\n /* if product exists, populate self (this._ProductId and\n this._ProductName are both auto-generated private\n variables of the entity class which corresponds to the\n auto-generated public properties: ProductId and ProductName) */\n this._ProductId = query.ProductId;\n this._ProductName = query.ProductName;\n }\n\n\n /// <summary>\n /// Delete product\n /// </summary>\n public void Delete()\n {\n // if self is not poulated, exit\n if (this._ProductId == 0) return;\n\n var dc = new BusinessLogicDataContext();\n\n // delete entry in database\n dc.Products.DeleteOnSubmit(this);\n dc.SubmitChanges();\n\n // reset self (you could implement IDisposable here)\n this._ProductId = 0;\n this._ProductName = \"\";\n }\n}\n // new up a product\nvar p = new Product(1); // p.ProductId: 1, p.ProductName: \"A car\"\n\n// delete the product\np.Delete(); // p.ProductId: 0, p.ProductName: \"\"\n public interface IProduct\n{\n Int32 ProductId { get; }\n\n void Delete();\n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
223,940
<p>I researched this a while ago and can't remember how to do it. I want to be able to prevent Firefox from running it's spell-checking functionality on certain input fields from within the page. I know it's possible but can't remember how to set it up.</p>
[ { "answer_id": 223948, "author": "Wilco", "author_id": 5291, "author_profile": "https://Stackoverflow.com/users/5291", "pm_score": 7, "selected": true, "text": "<textarea spellcheck=\"false\"></textarea>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
223,946
<p>I have two LINQ objects which have exactly the same columns and I would like to be able to update one with the fields from the other. I first create a new object from some data in a file, then I query the database for an existing item with the same ID. What I would like to be able to do is update the existing objects details with the newly created objects details. </p> <p>So far the way I have been doing it is to list all the columns and update them manually but as you can see this can cause maintenance headaches.</p> <pre><code> With OldCaller .ADDRESS = NewCaller.ADDRESS .COMPANY = NewCaller.COMPANY .CONTACT_HOURS = NewCaller.CONTACT_HOURS .CONTACT_NAME = NewCaller.CONTACT_NAME .CUSTOMER_ID = NewCaller.CUSTOMER_ID .EMAIL_ADDRESS = NewCaller.EMAIL_ADDRESS .FAX_NUMBER = NewCaller.FAX_NUMBER .FAX_TYPE = NewCaller.FAX_TYPE .MOBILE = NewCaller.MOBILE .POSTCODE = NewCaller.POSTCODE .PUBLIC_ADDRESS = NewCaller.PUBLIC_ADDRESS .PUBLIC_TELEPHONE = NewCaller.PUBLIC_TELEPHONE .STATE = NewCaller.STATE .SUBURB = NewCaller.SUBURB .TELEPHONE = NewCaller.TELEPHONE End With </code></pre> <p>I would like to be able to find a way to clean this up a bit. Does anyone know of a better way to do what I need.</p>
[ { "answer_id": 228465, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 0, "selected": false, "text": " Dim _OldCallerProperties = OldCaller.GetType().GetProperties(Reflection.BindingFlags.Public)\n Dim _NewCallerProperties = NewCaller.GetType.GetProperties(Reflection.BindingFlags.Public)\n\n For Each Prop In _OldCallerProperties\n Dim _matchingProperty = _NewCallerProperties.Where(Function(p) p.Name = Prop.Name).FirstOrDefault\n Dim _newvalue = _matchingProperty.GetValue(_matchingProperty, Nothing)\n Prop.SetValue(Prop, _newvalue, Nothing)\n Next\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
223,952
<p>Is there a way to create an instance of a class based on the fact I know the name of the class at runtime. Basically I would have the name of the class in a string.</p>
[ { "answer_id": 223967, "author": "Ray Li", "author_id": 28952, "author_profile": "https://Stackoverflow.com/users/28952", "pm_score": 6, "selected": false, "text": "System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)\n" }, { "answer_id": 224077, "author": "PeteT", "author_id": 16989, "author_profile": "https://Stackoverflow.com/users/16989", "pm_score": 5, "selected": false, "text": "ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));\n" }, { "answer_id": 2809299, "author": "Asish", "author_id": 338071, "author_profile": "https://Stackoverflow.com/users/338071", "pm_score": -1, "selected": false, "text": "ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));\n ReportClass report = new ReportClass();\n ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass)); ReportClass" }, { "answer_id": 27119311, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 7, "selected": false, "text": "Car Vehicles Vehicles.Car Car public object GetInstance(string strFullyQualifiedName)\n{ \n Type t = Type.GetType(strFullyQualifiedName); \n return Activator.CreateInstance(t); \n}\n Vehicles.Car Type.GetType Type public object GetInstance(string strFullyQualifiedName)\n{\n Type type = Type.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())\n {\n type = asm.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n }\n return null;\n }\n Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type\n Activator.CreateInstance(t);\n" }, { "answer_id": 53850620, "author": "asd", "author_id": 6531907, "author_profile": "https://Stackoverflow.com/users/6531907", "pm_score": 3, "selected": false, "text": " var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance(\"MyProject.Entities.User\");\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
223,964
<p>Note: I am just consuming webservice I have no control over webservice code.</p> <p>So in .net 2.0 I reference the webservice and see a class in the webservice namespace, say foobar. It's defined as:</p> <pre><code>public class foobar : System.Web.Services.Protocols.SoapHttpClientProtocol </code></pre> <p>but in .net 3.5 when i add a reference to the same webservice I no longer have this foobar class available. I do see foobarSoap which is an interface which exposes all of the methods in the foobar class above. It's defined as:</p> <pre><code>public interface foobarSoap </code></pre> <p>However it doesn't expose the properties (for obvious reasons).</p> <p>I need to access these properties. How do I do it?</p>
[ { "answer_id": 223979, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 1, "selected": false, "text": "Wsdl.exe wsdl.exe /language:cs http://www.example.com/FooService.wsdl" }, { "answer_id": 224174, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 0, "selected": false, "text": "[ServiceContract]\npublic interface IFooService\n{\n [OperationContract] // This is not allowed, it will not compile\n string Name { get; set; }\n}\n [WebService(Namespace = \"http://tempuri.org/\")]\npublic class FooService : System.Web.Services.WebService\n{\n [WebMethod] // This is not allowed, it will not compile\n string Name { get; set; }\n}\n" }, { "answer_id": 224192, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "http://www.xmlme.com/WSShakespeare.asmx\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
223,966
<p>I have an application which allows for multiple NSDocuments to be open. In this application is a single utility window that contains some functionality that I want to apply to the frontmost document.</p> <p>I am trying to use bindings here, so the trick is how to cleanly bind the user interface of the utility window to the frontmost document. The goal is that then switching the frontmost document window will update the view in the utility window; controls that are bound to properties of the frontmost document's model would be updated appropriately when state changes in the document's model, etc.</p> <p>For sending actions from such a window, it's easy to just use first responder; the document object can intercept actions via the responder chain. But I want more than this, and of course you can't bind to the first responder.</p> <p>A few ideas that I have:</p> <ul> <li>put an object controller in my nib for the shared window. When a document window changes frontmost status, change the content of that binding. A disadvantage of this is that if I were to have another kind of utility window, I'd have to remember to hook up the bindings from the document window to that utility window too!</li> <li>Make an accessor in the application delegate that gets the frontmost document window by traversing the window list. My utility window would just bind through the application delegate's method. A disadvantage here is that it's not KVO compliant</li> <li>Have a getter and setter in the application delegate to determine (and perhaps set to be KVO-compliant? would that make sense?) the frontmost document. Perhaps use window notifications set an ivar to the appropriate value when a window loses main status. <b>Update: I'm using this for now, and it actually seems pretty clean. I set the value from the <em>windowDidBecomeMain</em> notification of my doc window and clear it (if it's the current value) in <em>windowWillClose</em>. Unless there is any major objection, this is probably the approach I'll use.</b></li> <li><a href="http://forums.macrumors.com/showthread.php?t=215361" rel="nofollow noreferrer">One idea</a> was to bind to mainWindow.windowController.document ... this comes close, except that when my shared window becomes main, then this binding goes away. So really I need to find the frontmost <em>document</em> window's controller (and of the right class).</li> </ul> <p>None of these seem quite right. Is there a better way to do this that I'm missing?</p>
[ { "answer_id": 226866, "author": "Ben Stiglitz", "author_id": 6298, "author_profile": "https://Stackoverflow.com/users/6298", "pm_score": 2, "selected": false, "text": "mainWindow.document mainYourKindOfWindow mainWindow" }, { "answer_id": 226872, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "[NSDocumentController currentDocument]" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25560/" ]
223,971
<p>Is there an easy way to convert between color models in Java (RGB, HSV and Lab). </p> <p>Assuming RGB color model:</p> <ul> <li>How do I calculate black body spectrum color palette? I want to use it for a heatmap chart.</li> <li>How about single-wavelength spectrum?</li> </ul> <p><strong>Edit:</strong> I found that the <a href="http://java.sun.com/javase/6/docs/api/java/awt/color/ColorSpace.html" rel="nofollow noreferrer">ColorSpace</a> class can be used for conversions between RGB/CIE and many other color models.</p>
[ { "answer_id": 224284, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 5, "selected": false, "text": "public Color[] generateColors(int n)\n{\n Color[] cols = new Color[n];\n for(int i = 0; i < n; i++)\n {\n cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f);\n }\n return cols;\n}\n" }, { "answer_id": 2598102, "author": "ocodo", "author_id": 311660, "author_profile": "https://Stackoverflow.com/users/311660", "pm_score": -1, "selected": false, "text": "/**\n * Generate a BitmapData HSL color square (n x n) of hue\n * At a low n dimension you get cool blocky color palettes (e.g. try n=10)\n */\nfunction generateColorSquare(n:uint, hue:uint):BitmapData\n {\n var bd:BitmapData = new BitmapData(n, n, false, 0xFFFFFF);\n for (var i:uint=n*n; i > 0; i--)\n {\n bd.setPixel(i % n, Math.floor(i / n), HSBColor.convertHSBtoRGB(hue, i / (n*n), (1/n) * (i % n) ));\n }\n return bd;\n }\n" }, { "answer_id": 46917543, "author": "Sean Carey", "author_id": 8586392, "author_profile": "https://Stackoverflow.com/users/8586392", "pm_score": 0, "selected": false, "text": "public void render(Screen screen) {\n int green = 255;\n int red = 0;\n\n for (int i = 0; i <= 255 * 2; i++) {\n int rate = i / 255;\n\n screen.fillRect((x + (i * width)/6), y, width, height, new Color(red, green, 0));\n\n red += 1 - rate;\n green -= rate;\n } \n}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18187/" ]
223,990
<p>I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:</p> <pre><code>queryset = Modelclass.objects.filter(somekey=foo) </code></pre> <p>In my template I would like to do</p> <pre><code>{% for object in data.somekey_set.FILTER %} </code></pre> <p>but I just can't seem to find out how to write FILTER.</p>
[ { "answer_id": 224003, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 8, "selected": true, "text": "render_to_response {% for object in data.filtered_set %}" }, { "answer_id": 12350892, "author": "mrmagooey", "author_id": 599251, "author_profile": "https://Stackoverflow.com/users/599251", "pm_score": 4, "selected": false, "text": "Event Event.objects.filter(date__gte=now) Events class EventManager(models.Manager):\n def get_query_set(self):\n now = datetime.now()\n return super(EventManager,self).get_query_set().filter(date__gte=now)\n class Event(models.Model):\n ...\n objects = EventManager()\n Event" }, { "answer_id": 14010929, "author": "chrisv", "author_id": 683808, "author_profile": "https://Stackoverflow.com/users/683808", "pm_score": 3, "selected": false, "text": "from django import template\n\nregister = template.Library()\n\n@register.assignment_tag\ndef query(qs, **kwargs):\n \"\"\" template tag which allows queryset filtering. Usage:\n {% query books author=author as mybooks %}\n {% for book in mybooks %}\n ...\n {% endfor %}\n \"\"\"\n return qs.filter(**kwargs)\n" }, { "answer_id": 16429027, "author": "tobych", "author_id": 76452, "author_profile": "https://Stackoverflow.com/users/76452", "pm_score": 6, "selected": false, "text": "@register.filter\ndef in_category(things, category):\n return things.filter(category=category)\n {% for category in categories %}\n {% for thing in things|in_category:category %}\n {{ thing }}\n {% endfor %}\n{% endfor %}\n" }, { "answer_id": 61519890, "author": "Krzysztof Szumko", "author_id": 11370030, "author_profile": "https://Stackoverflow.com/users/11370030", "pm_score": 1, "selected": false, "text": " class InstancesView(generic.ListView):\n model = AlarmInstance\n context_object_name = 'settings_context'\n queryset = Group.objects.all()\n template_name = 'insta_list.html'\n\n @register.filter\n def filter_unknown(self, aVal):\n result = aVal.filter(is_known=False)\n return result\n\n @register.filter\n def filter_known(self, aVal):\n result = aVal.filter(is_known=True)\n return result\n {% for instance in alarm.qar_alarm_instances|filter_unknown:alarm.qar_alarm_instances %}\n For each in model.child_object|view_filter:filter_arg\n" }, { "answer_id": 74538591, "author": "Pol Clota", "author_id": 11455992, "author_profile": "https://Stackoverflow.com/users/11455992", "pm_score": 0, "selected": false, "text": "@register.filter()\ndef query_filter(value, attr):\n return value.filter(**eval(attr))\n {{ queryset|query_filter:'{\"cod_tipoinmueble\":1,\"des_operacion\": \"alquiler\"}'|length }}\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11527/" ]
223,991
<p>Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.</p> <p>So, to be more specific, given node x, I need to find the specific window object that contains x.</p>
[ { "answer_id": 224002, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 2, "selected": false, "text": "<body>\n<div id=\"example\">Example!</div>\n<script type=\"text/javascript\">\n window.onload = function () {\n var exampleNode = document.getElementById('example');\n exampleNode.bar = function () {\n // The highest window object:\n top;\n // The parent node:\n self;\n // The parent node ( except in IE );\n this.ownerDocument.defaultView;\n };\n };\n</script>\n</body>\n <iframe src =\"/default.html\" name=\"advertisement\"></iframe> self.advertisement" }, { "answer_id": 2728464, "author": "Marco Demaio", "author_id": 260080, "author_profile": "https://Stackoverflow.com/users/260080", "pm_score": 5, "selected": true, "text": "function GetOwnerWindow(html_node)\n{\n /*\n ownerDocument is cross-browser, \n but defaultView works on all browsers except Opera/IE that use parentWinow\n */\n return (html_node.ownerDocument.defaultView) ?\n html_node.ownerDocument.defaultView : \n html_node.ownerDocument.parentWindow;\n}\n return html_node.ownerDocument.defaultView || html_node.ownerDocument.parentWindow;\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
223,993
<p>I'm in the process of trying to move our company from SalesForce to SugarCRM, but I've run in to a nasty bug (the moment I add a custom field to Accounts, all accounts stop showing up). We've paid for support from the SugarCRM people, but they only have take-forever-then-get-a-worthless-response-level tech support for the open-source version (and we avoid proprietary software like the plague). Oh, and did I mention our Salesforce contract expires at the end of the week?</p> <p>So, long story short, I'm stuck debugging the SugarCRM app myself. I'm an decently experienced programmer, and I have baseline PHP competency, but I don't even know where to being trying to solve this issue. Can any Sugar developers out there recommend any kind of process for debugging Sugar? Are there any resources out there that would help me to understand what the different PHP files do, or how the Sugar system works overall? </p> <p>Just as an example of the sort of thing I'm talking about: I figured out how to get sugar to print stack traces, and by following several I noticed a pattern with all the problem lines involving <pre>$this->_tpl_vars</pre> I'd love to try and figure out why that method call isn't working, but I don't know:</p> <p>A) what <code>_tpl_vars</code> is supposed to do<br/> B) where <code>_tpl_vars</code> is defined<br/> C) what <code>$this</code> is supposed to be<br/> D) where in the framework <code>$this</code> gets set<br/> etc.</p> <p>So if anyone can help explain how/where I would start finding answers to these questions, I'd be incredibly grateful.</p>
[ { "answer_id": 238875, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 0, "selected": false, "text": "$this class Test {\n\n var $tmp;\n\n function __construct() {\n $this->tmp = 42; \n }\n}\n" }, { "answer_id": 7770002, "author": "dkinzer", "author_id": 256854, "author_profile": "https://Stackoverflow.com/users/256854", "pm_score": 3, "selected": false, "text": "var_dump print_r <?php\n require_once('include/MVC/View/views/view.detail.php');\n require_once('custom/include/krumo/class.krumo.php');\n class AccountsViewDetail extends ViewDetail {\n\n function AccountsViewDetail() {\n parent::ViewDetail();\n }\n\n // Override the parent function \"preDisplay\" to add our own template\n function preDisplay(){\n krumo($this->bean);\n $metadataFile = $this->getMetaDataFile();\n $this->dv = new DetailView2();\n $this->dv->ss =& $this->ss;\n $this->dv->setup($this->module, $this->bean, $metadataFile, 'custom/modules/Accounts/tpls/AccountsDetailView.tpl');\n }\n\n\n }\n?>\n" } ]
2008/10/21
[ "https://Stackoverflow.com/questions/223993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5921/" ]
224,009
<p>Session variables are normally keept in the web server RAM memory.</p> <p>In a cluster, each request made by a client can be handled by a different cluster node. right?!</p> <p>So, in this case... </p> <ul> <li>What happens with session variables? Aren't they stored in the nodes RAM memory? </li> <li>How the other nodes will handled my request correctly if it doesn't have my session variables, or at least all of it?</li> <li>This issue is treated by the web server (Apache, IIS) or by the language runtime (PHP, ASP.NET, Ruby, JSP)?</li> </ul> <p>EDIT: Is there some solution for <strong>Classic ASP</strong>?</p>
[ { "answer_id": 224015, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 3, "selected": false, "text": "<sessionState\n mode=\"StateServer\"\n stateConnectionString=\"tcpip=127.0.0.1:42424\"\n sqlConnectionString=\"data source=127.0.0.1;user id=sa;password=\"\n cookieless=\"false\"\n timeout=\"20\" />\n <sessionState\n mode=\"SQLServer\"\n stateConnectionString=\"tcpip=127.0.0.1:42424\"\n sqlConnectionString=\n \"data source=SERVERHAME;user id=sa;password=\"\n cookieless=\"false\"\n timeout=\"20\"\n/>\n" }, { "answer_id": 224133, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": false, "text": "memcached -d -u www -m 2048 -l 10.0.0.8 -p 11211\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
224,026
<p>I've started to use constructs like these:</p> <pre><code>class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) </code></pre> <p>Update: based on this thread, I've revised the DictObj implementation to:</p> <pre><code>class dotdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ class AutoEnum(object): def __init__(self): self.counter = 0 self.d = {} def __getattr__(self, c): if c not in self.d: self.d[c] = self.counter self.counter += 1 return self.d[c] </code></pre> <p>where DictObj is a dictionary that can be accessed via dot notation:</p> <pre><code>d = DictObj() d.something = 'one' </code></pre> <p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p> <p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p> <p>AutoEnum is an auto-incrementing Enum, used like this:</p> <pre><code>CMD = AutoEnum() cmds = { "peek": CMD.PEEK, "look": CMD.PEEK, "help": CMD.HELP, "poke": CMD.POKE, "modify": CMD.POKE, } </code></pre> <p>Both are working well for me, but I'm feeling unpythonic about them. </p> <p>Are these in fact bad constructs?</p>
[ { "answer_id": 224080, "author": "hlzr", "author_id": 19139, "author_profile": "https://Stackoverflow.com/users/19139", "pm_score": 4, "selected": false, "text": "DictObj class Container(object):\n pass\n\n>>> myContainer = Container()\n>>> myContainer.spam = \"in a can\"\n>>> myContainer.eggs = \"in a shell\"\n class QuietContainer(object):\n def __getattr__(self, attribute):\n try:\n return object.__getattr__(self,attribute)\n except AttributeError:\n return None\n\n>>> cont = QuietContainer()\n>>> print cont.me\nNone\n" }, { "answer_id": 224722, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 4, "selected": true, "text": "class DictObj(object):\n def __getattr__(self, attr):\n return self.__dict__.get(attr)\n\n>>> d = DictObj()\n>>> d.something = 'one'\n>>> print d.something\none\n>>> print d.somethingelse\nNone\n>>> \n" }, { "answer_id": 224876, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 5, "selected": false, "text": "class AttrDict(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n" }, { "answer_id": 235675, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 2, "selected": false, "text": ".keys() .values() .items()" }, { "answer_id": 11620531, "author": "Sebastian", "author_id": 1413374, "author_profile": "https://Stackoverflow.com/users/1413374", "pm_score": 2, "selected": false, "text": "class dotdict(dict):\n __getattr__= dict.__getitem__\n __setattr__= dict.__setitem__\n __delattr__= dict.__delitem__\n class container(object):\n __getitem__ = object.__getattribute__\n __setitem__ = object.__setattr__\n __delitem__ = object.__delattr__\n" }, { "answer_id": 58514526, "author": "fkotsian", "author_id": 1580498, "author_profile": "https://Stackoverflow.com/users/1580498", "pm_score": 0, "selected": false, "text": "import json\nfrom collections import namedtuple\n\n\nclass DictTransformer():\n @classmethod\n def constantize(self, d):\n return self.transform(d, klass=namedtuple, klassname='namedtuple')\n\n @classmethod\n def transform(self, d, klass, klassname):\n return self._from_json(self._to_json(d), klass=klass, klassname=klassname)\n\n @classmethod\n def _to_json(self, d, access_method='__dict__'):\n return json.dumps(d, default=lambda o: getattr(o, access_method, str(o)))\n\n @classmethod\n def _from_json(self, jsonstr, klass, klassname):\n return json.loads(jsonstr, object_hook=lambda d: klass(klassname, d.keys())(*d.values()))\n constants = {\n 'A': {\n 'B': {\n 'C': 'D'\n }\n }\n}\nCONSTANTS = DictTransformer.transform(d, klass=namedtuple, klassname='namedtuple')\nCONSTANTS.A.B.C == 'D'\n .keys .values ._fields list(A.B.C)" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/224026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]