qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
318,341
<p>The iPhone SDK docs claim fopen() is a supported method of file access but I am unable to get it to return a FILE handle. I am accessing a directory which is included in my project. I have tried fopen "filename","dir/filename","./filename","./dir/filename","/dir/filename" all returning with a null pointer. Some people report using it with no issue so I am sure it is something simple!</p>
[ { "answer_id": 318386, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 6, "selected": true, "text": "[[NSBundle mainBundle] pathForResource: FILENAME ofType: FILEEXTENSION]" }, { "answer_id": 320731, "author": "Nick Van Brunt", "author_id": 30470, "author_profile": "https://Stackoverflow.com/users/30470", "pm_score": 5, "selected": false, "text": "NSString * path = [[NSBundle mainBundle] pathForResource: @\"some\" ofType: @\"txt\"];\nFILE *f = fopen([path cStringUsingEncoding:1],\"r\");\nif (f == NULL) NSLog([path stringByAppendingString:@\" not found\"]);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30470/" ]
318,347
<p>Edit: Warning - I now realize that the following technique is generally regarded as a bad idea because it creates hidden dependencies for the sake of looking neat.</p> <hr> <p>I recently discovered that you can use the StackTrace to infer information about the caller of a method.</p> <p>This enables you to create a seemingly "cool" API whereby you simply invoke a method without bothering to pass any explicit parameters to it, and the method works out what to do based on the StackTrace.</p> <p>Is this a bad thing to do, and if so, why?</p> <p>Example:</p> <pre><code>public class Cache { public Object CheckCache() { Object valueToReturn = null; string key = GenerateCacheKeyFromMethodPrototype(new StackTrace().GetFrame(1).GetMethod()); //frame 1 contains caller if(key is in cache) valueToReturn = itemFromCache; return valueToReturn; } } public class Foo { private static Cache cache = new Cache(); public Blah MethodFoo(param1, param2...) { Blah valueToReturn = cache.CheckCache(); //seems cool! if(valueToReturn == null) { valueToReturn = result of some calculation; //populate cache } return valueToReturn; } } </code></pre> <p>I'm sure there are errors in the above pseudocode, but you get my drift.</p> <hr> <p>Edit: thanks for everyone's responses.</p>
[ { "answer_id": 318370, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 2, "selected": false, "text": "void MethodA() {\n MethodB();\n}\n\nvoid MethodB() {\n foo();\n}\n void MethodA() {\n foo();\n}\n [MethodImpl( ... NoInline )]\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38522/" ]
318,356
<p>I am doing a join on two tables. One is a user's table and the other a list of premium users. I need to have the premium members show up first in my query. However, just because they are in the premium user table doesn't mean they are still a premium member - there is an IsActive field that also needs to be checked.</p> <p>So basically I need to return the results in the following order: </p> <ul> <li>Active Premium Users</li> <li>Regular and Inactive Premium Users</li> </ul> <p>Right now I have it as the following:</p> <pre><code>SELECT Users.MemberId, PremiumUsers.IsActive FROM Users LEFT JOIN PremiumUsers ON PremiumUsers.UserId = Users.Id ORDER BY PremiumUsers.IsActive DESC </code></pre> <p>The problem with this is that it places non-active premium members above non-premium members.</p> <p>(I'm using MS SQL Server 2005 for this)</p>
[ { "answer_id": 318369, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "ORDER BY COALESCE(PremiumUsers.IsActive, 0) DESC\n" }, { "answer_id": 318373, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 4, "selected": false, "text": "ORDER BY CASE\n WHEN PremiumUsers.IsActive = 1 THEN 1\n WHEN PremiumUsers.UserId IS NULL THEN 2\n ELSE 3\nEND\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18234/" ]
318,387
<p>I have the following method in my code:</p> <pre><code>private bool GenerateZipFile(List&lt;FileInfo&gt; filesToArchive, DateTime archiveDate) { try { using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(GetZipFileName(archiveDate)))) { zipStream.SetLevel(9); // maximum compression. byte[] buffer = new byte[4096]; foreach (FileInfo fi in filesToArchive) { string fileName = ZipEntry.CleanName(fi.Name); ZipEntry entry = new ZipEntry(fileName); entry.DateTime = fi.LastWriteTime; zipStream.PutNextEntry(entry); using (FileStream fs = File.OpenRead(fi.FullName)) { StreamUtils.Copy(fs, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.Finish(); zipStream.Close(); } return true; } catch (Exception ex) { OutputMessage(ex.ToString()); return false; } } </code></pre> <p>This code generates a ZIP file with all the correct entries, but each file is listed as being 4 TB (both unpacked and packed) and creates the following error when I try to open it:</p> <pre><code>Extracting to "C:\winnt\profiles\jbladt\LOCALS~1\Temp\" Use Path: no Overlay Files: yes skipping: QPS_Inbound-20081113.txt: this file is not in the standard Zip 2.0 format Please see www.winzip.com/zip20.htm for more information error: no files were found - nothing to do </code></pre> <p>The code is practically taken from the samples, but I seem to be missing something. Does anyone have any pointers?</p>
[ { "answer_id": 318435, "author": "Tinister", "author_id": 34715, "author_profile": "https://Stackoverflow.com/users/34715", "pm_score": 2, "selected": false, "text": "CompressionMethod CompressedSize ZipEntry CompressedSize" }, { "answer_id": 318617, "author": "Logicalmind", "author_id": 26977, "author_profile": "https://Stackoverflow.com/users/26977", "pm_score": 4, "selected": true, "text": "try\n {\n using (ZipFile zip = new ZipFile(\"MyZipFile.zip\")\n {\n zip.AddFile(\"c:\\\\photos\\\\personal\\\\7440-N49th.png\");\n zip.AddFile(\"c:\\\\Desktop\\\\2005_Annual_Report.pdf\");\n zip.AddFile(\"ReadMe.txt\");\n zip.Save();\n }\n }\n catch (System.Exception ex1)\n {\n System.Console.Error.WriteLine(\"exception: \" + ex1);\n }\n" }, { "answer_id": 364852, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "string fileName = ZipEntry.CleanName(fi.Name);\nZipEntry entry = new ZipEntry(fileName);\nentry.DateTime = fi.LastWriteTime;\nentry.Size = fi.Length;\nzipStream.PutNextEntry(entry);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
318,388
<p>I am trying to debug an intermittent error on the iPhone, a crash with a trace that looks like:</p> <pre><code>objc_message_send __invoking__ [NSInvocation invoke] HandleDelegateSource MainRunLoop .... </code></pre> <p>When GDB stops, I'd like to be able to determine details about what selector the system is attempting to be invoked - I've set a break point now around [NSInvocation Invoke], but from that point cannot figure out how to examine details of the NSInvocation object I am stopped in.</p>
[ { "answer_id": 2509558, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 2, "selected": false, "text": "Simulator: display /s $ecx\nDevice: display /s $r1\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6330/" ]
318,390
<p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p> <p>This all works great when I run the Python (command line) tool that comes with Python.</p> <p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p> <p>What environment variable do I need to set? What value should it be set to? </p>
[ { "answer_id": 318419, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": true, "text": "which python /cygdrive/c/Python25/python.exe /usr/local/bin/python" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
318,398
<p>Compiling a C++ file takes a very long time when compared to C# and Java. It takes significantly longer to compile a C++ file than it would to run a normal size Python script. I'm currently using VC++ but it's the same with any compiler. Why is this?</p> <p>The two reasons I could think of were loading header files and running the preprocessor, but that doesn't seem like it should explain why it takes so long.</p>
[ { "answer_id": 318425, "author": "Andy Brice", "author_id": 455552, "author_profile": "https://Stackoverflow.com/users/455552", "pm_score": 4, "selected": false, "text": "#include \"BigClass.h\"\n\nclass SmallClass\n{\n BigClass m_bigClass;\n}\n class BigClass;\n\nclass SmallClass\n{\n BigClass* m_bigClass;\n}\n" }, { "answer_id": 318440, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 11, "selected": true, "text": "List<T> vector<int> vector<float>" }, { "answer_id": 15191746, "author": "rileyberton", "author_id": 2129919, "author_profile": "https://Stackoverflow.com/users/2129919", "pm_score": 3, "selected": false, "text": "#include \"a.cpp\"\n#include \"b.cpp\"\n#include \"c.cpp\"\n" }, { "answer_id": 63755618, "author": "user2394284", "author_id": 2394284, "author_profile": "https://Stackoverflow.com/users/2394284", "pm_score": 1, "selected": false, "text": "// Ugly private dependencies\n#include <map>\n#include <list>\n#include <chrono>\n#include <stdio.h>\n#include <Internal/SecretArea.h>\n#include <ThirdParty/GodObjectFactory.h>\n\nclass ICantHelpButShowMyPrivatePartsSorry\n{\npublic:\n int facade(int);\n\nprivate:\n std::map<int, int> implementation_detail_1(std::list<int>);\n std::chrono::years implementation_detail_2(FILE*);\n Intern::SecretArea implementation_detail_3(const GodObjectFactory&);\n};\n" }, { "answer_id": 63831487, "author": "Yoni Davidson", "author_id": 5542086, "author_profile": "https://Stackoverflow.com/users/5542086", "pm_score": 2, "selected": false, "text": "x*y;\n foo<x> a;\n (foo < x) > a;\n namespace A{\n struct Aa{}; \n void foo(Aa arg);\n}\nnamespace B{\n struct Bb{};\n void foo(A::Aa arg, Bb arg2);\n}\nnamespace C{ \n struct Cc{}; \n void foo(A::Aa arg, B::Bb arg2, C::Cc arg3);\n}\n\nfoo(A::Aa{}, B::Bb{}, C::Cc{});\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23427/" ]
318,405
<p>Our build is dog slow. It uses nested gnu makefiles on linux. It creates three builds for three different targets from the same source tree. It uses symlinks to point to each of the three parallel directory trees in turn. We can do partial builds by using make inside subdirectories, which saves time, but if our work spans multiple directories we must build for at least one of the three targets and that takes a minimum of 45 minutes. A subdirectory only build may take "only" 5-10 minutes.</p> <p>Do you know of any quick things to check that may be bogging down this build system? For example, is there a faster alternative to symlinks?</p> <p>Addition: I've seen the paper regarding recursive makefiles. Does anyone know firsthand what would be the effects of flatting a Makefile system which currently has many makefiles (around 800) and over 4.5 million source lines of code? People currently enjoy being able to build just their current subdirectory or process (embedded linux target) by using make in that directory. </p> <p>I've just learned the build was, until recently, twice as long (<em>wince</em>), at which point the release engineer deployed ccache.</p>
[ { "answer_id": 318427, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "make -j" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,434
<p>Any good converter for GB, Big5, Unicode?</p> <p>Convert GB to Unicode, Unicode to GB, Big5 to Unicode, Unicode to Big5, GB to Big5.</p>
[ { "answer_id": 318521, "author": "huaiyuan", "author_id": 16240, "author_profile": "https://Stackoverflow.com/users/16240", "pm_score": 2, "selected": true, "text": "http://en.wikipedia.org/wiki/Iconv\nhttp://www.gnu.org/software/libiconv/\n" }, { "answer_id": 352352, "author": "Atlas", "author_id": 30787, "author_profile": "https://Stackoverflow.com/users/30787", "pm_score": 0, "selected": false, "text": "http://alf-li.pcdiscuss.com/c_convertz.html\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206630/" ]
318,441
<p>What's the difference between a keystore and a truststore?</p>
[ { "answer_id": 34770535, "author": "alessiop86", "author_id": 951075, "author_profile": "https://Stackoverflow.com/users/951075", "pm_score": 2, "selected": false, "text": "${user.home}/.keystore /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts -Djavax.net.ssl.keyStore /path/to/keyStore -Djavax.net.ssl.trustStore /path/to/trustStore java.security.UnrecoverableKeyException: Password must not be\nnull -Djavax.net.ssl.trustStorePassword=password -Djavax.net.ssl.trustStorePassword=password" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40746/" ]
318,452
<p>I'm trying to create some skinned forms (just the border and caption) with a different approach than you usually see but I'm having some issues with form flickering while I resize the form.</p> <p>I don't know how else to explain the problem, so here's a video I created to demonstrate the problem: <a href="http://www.screencast.com/t/AIqK9Szmz" rel="nofollow noreferrer">http://www.screencast.com/t/AIqK9Szmz</a></p> <p>Also, here's a VS2008 test solution with the whole code that repaints the form borders:<a href="http://stuff.nazgulled.net/misc/TestForm.zip" rel="nofollow noreferrer">http://stuff.nazgulled.net/misc/TestForm.zip</a></p> <p>Hope someone can help me get rid of the flicker...</p>
[ { "answer_id": 318481, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 2, "selected": false, "text": "this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );\nthis.SetStyle( ControlStyles.UserPaint, true );\nthis.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );\nthis.SetStyle( ControlStyles.ResizeRedraw, true );\n" }, { "answer_id": 7760004, "author": "Dan", "author_id": 419294, "author_profile": "https://Stackoverflow.com/users/419294", "pm_score": 0, "selected": false, "text": "protected override void OnResizeBegin(EventArgs e) {\n SuspendLayout();\n base.OnResizeBegin(e);\n}\nprotected override void OnResizeEnd(EventArgs e) {\n ResumeLayout();\n base.OnResizeEnd(e);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40480/" ]
318,462
<p>I have a .NET (C#) multi-threaded application and I want to know if a certain method runs inside the Finalizer thread. </p> <p>I've tried using Thread.CurrentThread.Name but it doesn't work (returns null).</p> <p>Anyone knows how can I query the current thread to discover if it's the Finalizer thread?</p>
[ { "answer_id": 318510, "author": "Yona", "author_id": 40007, "author_profile": "https://Stackoverflow.com/users/40007", "pm_score": 5, "selected": true, "text": "Thread.CurrentThread.ManagedThreadId;\n public class ThreadTest {\n public static Thread GCThread;\n\n ~ThreadTest() {\n ThreadTest.GCThread = Thread.CurrentThread;\n }\n}\n public static void Main() {\n ThreadTest test = new ThreadTest();\n test = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n\n Console.WriteLine(ThreadTest.GCThread.ManagedThreadID);\n}\n" }, { "answer_id": 318653, "author": "JoshL", "author_id": 630, "author_profile": "https://Stackoverflow.com/users/630", "pm_score": 1, "selected": false, "text": "public static void Main()\n{\n ThreadTest test = new ThreadTest();\n test = null;\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n\n Console.WriteLine(ThreadTest.GCThread.ManagedThreadID);\n}\n" }, { "answer_id": 433758, "author": "Brian Rasmussen", "author_id": 38206, "author_profile": "https://Stackoverflow.com/users/38206", "pm_score": 2, "selected": false, "text": "!threads" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
318,473
<p>I have a couple of tables which are used to log user activity for an application. The tables looks something like this (pseudo code from memory, may not be syntactically correct):</p> <pre><code>create table activity ( sessionid uniqueidentifier not null, created smalldatetime not null default getutcdate() ); create table activity_details ( sessionid uniqueidentifier not null, activity_description varchar(100) not null, created smalldatetime not null default getutcdate() ); </code></pre> <p>My goal is to populate a summary table for reporting purposes that looks something like this:</p> <pre><code>create table activity_summary ( sessionid uniqueidentifier not null, first_activity_desc varchar(100) not null, last_activity_desc varchar(100) not null ); </code></pre> <p>First and last activity descriptions would be determined chronologically. My initial thought is to update the summary table like so:</p> <pre><code>truncate table activity_summary; insert into activity_summary (sessionid) select sessionid from activity; update table activity_summary set first_activity_desc = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created asc), last_activity_summary = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created desc) from activity_summary as; </code></pre> <p>However, this seems incredibly verbose and unnecessary to me. I'm just not sure how to shrink it down. My gut feel is that I could do it somehow all within the insert statement, but I'm stumped. Any suggestions? </p>
[ { "answer_id": 318494, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": true, "text": "truncate table activity_summary;\n\ninsert into activity_summary (sessionid, first_activity_desc, last_activity_summary)\nselect a.sessionid\n,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created asc) AS first_activity_desc\n,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created desc) AS last_activity_summary\nfrom activity AS a;\n truncate table activity_summary;\n\nWITH firsts AS (\n SELECT ad.sessionid\n ,ad.activity_desc\n ,ROW_NUMBER() OVER (ORDER BY ad.created ASC) as RowNumber\n FROM activity_detail AS ad\n)\n,lasts AS (\n SELECT ad.sessionid\n ,ad.activity_desc\n ,ROW_NUMBER() OVER (ORDER BY ad.created DESC) as RowNumber\n FROM activity_detail AS ad\n)\ninsert into activity_summary (sessionid, first_activity_desc, last_activity_summary)\nselect a.sessionid\n ,firsts.activity_desc\n ,lasts.activity_desc\nfrom activity AS a\nINNER JOIN firsts ON firsts.sessionid = a.sessionid AND firsts.RowNumber = 1\nINNER JOIN lasts ON lasts.sessionid = a.sessionid AND lasts.RowNumber = 1\n" }, { "answer_id": 318514, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 1, "selected": false, "text": "insert into activity_summary\n (sessionid, first_activity_desc, last_activity_desc)\nselect\n agg.sessionid,\n adf.activity_description,\n adl.activity_description\nfrom\n (SELECT\n sessionid, MIN(created) as firstcreated, MAX(created) as lastcreated\n from\n activity_detail group by sessionid\n ) agg\n JOIN\n activity_details adf ON agg.sessionid = adf.sessionid AND agg.firstcreated = adf.created\n JOIN\n activity_details adl ON agg.sessionid = adl.sessionid AND agg.lastcreated = adl.created\n" }, { "answer_id": 318547, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "SELECT a.sessionid, d1.activity_description, d2.activity_description\n\nFROM activity a\n\nJOIN detail d1 ON a.sessionid = d1.sessionid\nJOIN detail d2 ON a.sessionid = d2.sessionid\n\nWHERE NOT EXISTS \n (SELECT 1 FROM detail WHERE sessionid = a.sessionid AND created < d1.created)\n\nAND NOT EXISTS \n (SELECT 1 FROM detail WHERE sessionid = a.sessionid AND created > d2.created)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34942/" ]
318,475
<p>I was trying the ASP.NET login control tutorial and everything works well. However, I do not know how to have the Log-in control use my own database (SQL Server 2005) instead of using it's mdf file. I also have no idea where this file was created from since it doesn't show up at all on my solution. Any literature that I can find on the workings of the Login control would be greatly appreciated. </p>
[ { "answer_id": 318522, "author": "Brant Bobby", "author_id": 4160, "author_profile": "https://Stackoverflow.com/users/4160", "pm_score": 4, "selected": true, "text": "<system.web>\n <membership defaultProvider=\"myMembershipProvider\">\n <providers>\n <clear /> <!-- remove the default provider since we're not using it anymore -->\n <add type=\"System.Web.Security.SqlMembershipProvider\"\n name=\"myMembershipProvider\"\n connectionStringName=\"myConnectionString\"\n applicationName=\"MyApplicationName\" />\n </providers>\n </membership>\n</system.web>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32812/" ]
318,488
<p>How do you build a hierarchical set of tags with data in PHP?</p> <p>For example, a nested list:</p> <pre><code>&lt;div&gt; &lt;ul&gt; &lt;li&gt;foo &lt;/li&gt; &lt;li&gt;bar &lt;ul&gt; &lt;li&gt;sub-bar &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>This would be build from flat data like this:</p> <pre><code>nested_array = array(); nested_array[0] = array('name' =&gt; 'foo', 'depth' =&gt; 0) nested_array[1] = array('name' =&gt; 'bar', 'depth' =&gt; 0) nested_array[2] = array('name' =&gt; 'sub-bar', 'depth' =&gt; 1) </code></pre> <p>It would be nice if it were nicely formatted like the example, too.</p>
[ { "answer_id": 318605, "author": "OIS", "author_id": 36175, "author_profile": "https://Stackoverflow.com/users/36175", "pm_score": 0, "selected": false, "text": "function array_to_list(array $array, $width = 3, $type = 'ul', $separator = ' ', $depth = 0)\n{\n $ulSpace = str_repeat($separator, $width * $depth++);\n $liSpace = str_repeat($separator, $width * $depth++);\n $subSpace = str_repeat($separator, $width * $depth);\n foreach ($array as $key=>$value) {\n if (is_array($value)) {\n $output[(isset($prev) ? $prev : $key)] .= \"\\n\" . array_to_list($value, $width, $type, $separator, $depth);\n } else {\n $output[$key] = $value;\n $prev = $key;\n }\n }\n return \"$ulSpace<$type>\\n$liSpace<li>\\n$subSpace\" . implode(\"\\n$liSpace</li>\\n$liSpace<li>\\n$subSpace\", $output) . \"\\n$liSpace</li>\\n$ulSpace</$type>\";\n}\n\necho array_to_list(array('gg', 'dsf', array(array('uhu'), 'df', array('sdf')), 'sdfsd', 'sdfd')) . \"\\n\";\n <ul>\n <li>\n gg\n </li>\n <li>\n dsf\n <ul>\n <li>\n\n <ul>\n <li>\n uhu\n </li>\n </ul>\n </li>\n <li>\n df\n <ul>\n <li>\n sdf\n </li>\n </ul>\n </li>\n </ul>\n </li>\n <li>\n sdfsd\n </li>\n <li>\n sdfd\n </li>\n</ul>\n function flat_array_to_hierarchical_array(array &$array, $depth = 0, $name = null, $toDepth = 0)\n{\n if ($depth == 0) {\n $temp = $array;\n $array = array_values($array);\n }\n if (($name !== null) && ($depth == $toDepth)) {\n $output[] = $name;\n } else if ($depth < $toDepth) {\n $output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $toDepth);\n }\n while ($item = array_shift($array)) {\n $newDepth = $item['depth'];\n $name = $item['name'];\n if ($depth == $newDepth) {\n $output[] = $name;\n } else if ($depth < $newDepth) {\n $output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $newDepth);\n } else {\n array_unshift($array, $item);\n return $output;\n }\n }\n $array = $temp;\n return $output;\n}\n\n$arr = flat_array_to_hierarchical_array($nested_array);\necho array_to_list($arr);\n" }, { "answer_id": 318609, "author": "phihag", "author_id": 35070, "author_profile": "https://Stackoverflow.com/users/35070", "pm_score": 3, "selected": true, "text": "<?php\n\n$nested_array = array();\n$nested_array[] = array('name' => 'foo', 'depth' => 0);\n$nested_array[] = array('name' => 'bar', 'depth' => 0);\n$nested_array[] = array('name' => 'sub-bar', 'depth' => 1);\n$nested_array[] = array('name' => 'sub-sub-bar', 'depth' => 2);\n$nested_array[] = array('name' => 'sub-bar2', 'depth' => 1);\n$nested_array[] = array('name' => 'sub-sub-bar3', 'depth' => 3);\n$nested_array[] = array('name' => 'sub-sub3', 'depth' => 2);\n$nested_array[] = array('name' => 'baz', 'depth' => 0);\n\n$doc = new DOMDocument('1.0', 'iso-8859-1');\n$doc->formatOutput = true;\n$rootNode = $doc->createElement('div');\n$doc->appendChild($rootNode);\n\n$rootList = $doc->createElement('ul');\n$rootNode->appendChild($rootList);\n\n$listStack = array($rootList); // Stack of created XML list elements\n$depth = 0; // Current depth\n\nforeach ($nested_array as $nael) {\n while ($depth < $nael['depth']) {\n // New list element\n if ($listStack[$depth]->lastChild == null) {\n // More than one level at once\n $li = $doc->createElement('li');\n $listStack[$depth]->appendChild($li);\n }\n $listEl = $doc->createElement('ul');\n $listStack[$depth]->lastChild->appendChild($listEl);\n array_push($listStack, $listEl);\n\n $depth++;\n }\n\n while ($depth > $nael['depth']) {\n array_pop($listStack);\n $depth--;\n }\n\n // Add the element itself\n $li = $doc->createElement('li');\n $li->appendChild($doc->createTextNode($nael['name']));\n $listStack[$depth]->appendChild($li);\n}\n\necho $doc->saveXML();\n printEl($rootNode);\n\nfunction printEl(DOMElement $el, $depth = 0) {\n $leftFiller = str_repeat(\"\\t\", $depth);\n $name = preg_replace('/[^a-zA-Z]/', '', $el->tagName);\n\n if ($el->childNodes->length == 0) {\n // Empty node\n echo $leftFiller . '<' . $name . \"/>\\n\";\n } else {\n echo $leftFiller . '<' . $name . \">\";\n $printedNL = false;\n\n for ($i = 0;$i < $el->childNodes->length;$i++) {\n $c = $el->childNodes->item($i);\n\n if ($c instanceof DOMText) {\n echo htmlspecialchars($c->wholeText);\n } elseif ($c instanceof DOMElement) {\n if (!$printedNL) {\n $printedNL = true;\n echo \"\\n\";\n }\n printEl($c, $depth+1);\n }\n }\n\n if (!$printedNL) {\n $printedNL = true;\n echo \"\\n\";\n }\n\n echo $leftFiller . '</' . $name . \">\\n\";\n }\n\n}\n" }, { "answer_id": 318610, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "array('html', null, array (\n array( 'div' , null , array( \n array('ul', array('id'=>'foo'), array( \n array('li', null, 'foo' ),\n array('li', null, array( \n array(null,null, 'bar'), \n array('ul', null, array( \n array('li', null, 'sub-bar' )\n ))\n ))\n ))\n ))\n ))\n));\n function tohtml( $domtree ){ \n if( is_null($domtree[0]) ){ \n if( !is_array($domtree[2])){ \n return htmlentities($domtree[2]);\n }\n die(\"text node cant have children!\"); \n }\n $html = \"<\" . $domtree[0]; \n if( !is_null( $domtree[1] ) )\n {\n foreach( $domtree[1] as $name=>$value ){ \n $html .= \" \" . $name . '=\"' . htmlentities($value) . '\"'; \n }\n }\n $html .= \">\" ; \n if( !is_null($domtree[2]) ){\n if( is_array($dometree[2]) ){ \n foreach( $domtree[2] as $id => $item ){ \n $html .= tohtml( $item ); # RECURSION\n } \n }\n else {\n $html .= htmlentities($domtree[2]);\n }\n }\n $html .= \"</\" . $domtree[1] . \">\"; \n return $html; \n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
318,489
<p>I wrote a raw TCP client for HTTP/HTTPS requests, however I'm having problems with chunked encoding responses. HTTP/1.1 is requirement therefore I should support it.</p> <p><em>Raw TCP is a business requirement that I need to keep, therefore I can't switch to .NET HTTPWebRequest/HTTPWebResponse</em> However if there is way to convert a RAW HTTP Request/Response into HTTPWebRequest/HTTPWebResponse that'd work.</p>
[ { "answer_id": 318601, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": true, "text": " Chunked-Body = *chunk\n last-chunk\n trailer\n CRLF\n\n chunk = chunk-size [ chunk-extension ] CRLF\n chunk-data CRLF\n chunk-size = 1*HEX\n last-chunk = 1*(\"0\") [ chunk-extension ] CRLF\n\n chunk-extension= *( \";\" chunk-ext-name [ \"=\" chunk-ext-val ] )\n chunk-ext-name = token\n chunk-ext-val = token | quoted-string\n chunk-data = chunk-size(OCTET)\n trailer = *(entity-header CRLF)\n done = false;\nuint8 bytes[];\nwhile (!done)\n{\n chunksizeString = readuntilCRLF(); // read in the chunksize as a string\n chunksizeString.strip(); // strip off the CRLF\n chunksize = chunksizeString.convertHexString2Int(); // convert the hex string to an integer.\n bytes.append(readXBytes(chunksize)); // read in the x bytes and append them to your buffer.\n readCRLF(); // read the trailing CRLF and throw it away.\n if (chunksize == 0)\n done = true; //\n\n}\n// now read the trailer if any\n// trailer is optional, so it may be just the empty string\ntrailer = readuntilCRLF()\ntrailer = trailer.strip()\nif (trailer != \"\")\n readCRLF(); // read out the last CRLF and we are done.\n" }, { "answer_id": 326803, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 1, "selected": false, "text": " length := 0\n read chunk-size, chunk-extension (if any) and CRLF\n while (chunk-size > 0) {\n read chunk-data and CRLF\n append chunk-data to entity-body\n length := length + chunk-size\n read chunk-size and CRLF\n }\n read entity-header\n while (entity-header not empty) {\n append entity-header to existing header fields\n read entity-header\n }\n Content-Length := length\n Remove \"chunked\" from Transfer-Encoding\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40322/" ]
318,506
<p>In .NET is it possible to convert a raw HTTP request to HTTPWebRequest object?</p> <p>I'm sure .NET internally doing it. Any idea which part of the .NET is actually handling this? Can I call it or is there any external library which allows raw HTTP connections?</p>
[ { "answer_id": 54075677, "author": "dimaaan", "author_id": 1802286, "author_profile": "https://Stackoverflow.com/users/1802286", "pm_score": 3, "selected": false, "text": "using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;\nusing System;\nusing System.Buffers;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class Program : IHttpRequestLineHandler, IHttpHeadersHandler\n{\n public static void Main(string[] args)\n {\n string requestString =\n@\"POST /resource/?query_id=0 HTTP/1.1\nHost: example.com\nUser-Agent: custom\nAccept: */*\nConnection: close\nContent-Length: 20\nContent-Type: application/json\n\n{\"\"key1\"\":1, \"\"key2\"\":2}\";\n byte[] requestRaw = Encoding.UTF8.GetBytes(requestString);\n ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(requestRaw);\n HttpParser<Program> parser = new HttpParser<Program>();\n Program app = new Program();\n Console.WriteLine(\"Start line:\");\n parser.ParseRequestLine(app, buffer, out var consumed, out var examined);\n buffer = buffer.Slice(consumed);\n Console.WriteLine(\"Headers:\");\n parser.ParseHeaders(app, buffer, out consumed, out examined, out var b);\n buffer = buffer.Slice(consumed);\n string body = Encoding.UTF8.GetString(buffer.ToArray());\n Dictionary<string, int> bodyObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, int>>(body);\n Console.WriteLine(\"Body:\");\n foreach (var item in bodyObject)\n Console.WriteLine($\"key: {item.Key}, value: {item.Value}\");\n Console.ReadKey();\n }\n\n public void OnHeader(Span<byte> name, Span<byte> value)\n {\n Console.WriteLine($\"{Encoding.UTF8.GetString(name)}: {Encoding.UTF8.GetString(value)}\");\n }\n\n public void OnStartLine(HttpMethod method, HttpVersion version, Span<byte> target, Span<byte> path, Span<byte> query, Span<byte> customMethod, bool pathEncoded)\n {\n Console.WriteLine($\"method: {method}\");\n Console.WriteLine($\"version: {version}\");\n Console.WriteLine($\"target: {Encoding.UTF8.GetString(target)}\");\n Console.WriteLine($\"path: {Encoding.UTF8.GetString(path)}\");\n Console.WriteLine($\"query: {Encoding.UTF8.GetString(query)}\");\n Console.WriteLine($\"customMethod: {Encoding.UTF8.GetString(customMethod)}\");\n Console.WriteLine($\"pathEncoded: {pathEncoded}\");\n }\n}\n Start line:\nmethod: Post\nversion: Http11\ntarget: /resource/?query_id=0\npath: /resource/\nquery: ?query_id=0\ncustomMethod:\npathEncoded: False\nHeaders:\nHost: example.com\nUser-Agent: custom\nAccept: */*\nConnection: close\nContent-Length: 20\nContent-Type: application/json\nBody:\nkey: key1, value: 1\nkey: key2, value: 2\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40322/" ]
318,511
<p>I've got a structure as follows:</p> <pre><code>typedef struct { std::wstring DevAgentVersion; std::wstring SerialNumber; } DeviceInfo; </code></pre> <p>But when I try to use it I get all sorts of memory allocation errors.</p> <p>If I try to pass it into a function like this:</p> <pre><code>GetDeviceInfo(DeviceInfo *info); </code></pre> <p>I will get a runtime check error complaining that I didn't initialize it before using it, which I seemed to have fixed with:</p> <pre><code>DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo)); </code></pre> <p>But then, in the function, when I try to set either of the structures stings, it complains that I'm trying to access a bad pointer when trying to set a value to the string.</p> <p>What is the best way to initialize this structure (and all of it's internal strings?</p>
[ { "answer_id": 318520, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 4, "selected": true, "text": "new malloc DeviceInfo wstring DeviceInfo *info = new DeviceInfo;\n malloc delete info DeviceInfo info; // constructed on the stack\nGetDeviceInfo( &info ); // pass the address of the info\n" }, { "answer_id": 318536, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "DeviceInfo info;\nGetDeviceInfo(&info);\n" }, { "answer_id": 318550, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "struct DeviceInfo\n{\n std::wstring DevAgentVersion;\n std::wstring SerialNumber;\n WhatEverReturnType GetDeviceInfo() {\n // here, to your calculation. DevAgentVersion and SerialNumber are visible.\n }\n};\n\nDeviceInfo d; WhatEverReturnType e = d.GetDeviceInfo();\n WhatEverReturnType GetDeviceInfo(DeviceInfo &info) {\n // do your calculation. info.DevAgentVersion and info.SerialNumber are visible.\n}\n\nDeviceInfo d; WhatEverReturnType e = GetDeviceInfo(d);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
318,527
<p>We are developing in an embedded type environment and find ourselves needing to create our own UI framework.</p> <p>I have done this before, but I am interested in doing a little bit of research around common design patterns for frameworks.</p> <p>Types of things that I am thinking of as patterns (somewhat far reaching):</p> <ul> <li>Widget Focus / defocus </li> <li>Widget Animation </li> <li>Data sharing between elements</li> <li>Attaching commands to widgets</li> <li>Saving state (MVC?)</li> </ul> <p>What recommended reading do you have for GUI Framework patterns?</p>
[ { "answer_id": 2038512, "author": "Stefan Monov", "author_id": 122687, "author_profile": "https://Stackoverflow.com/users/122687", "pm_score": 2, "selected": false, "text": "interface IWidget\n{\n bool HandleEvent(Event event); // returns true if event was handled\n // or false if event was ignored\n}\n\nclass Button : IWidget\n{\n public override bool HandleEvent(Event event)\n {\n switch(event.Type)\n {\n case EventType.MousePressed: DoStuff(); return true;\n case EventType.MouseScrolled: return false;\n }\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
318,528
<p>I am using SQL Advantage and need to know what the SQL is to identify the triggers associated with a table. I don't have the option to use another tool so the good old fashioned SQL solution is the ideal answer.</p>
[ { "answer_id": 321624, "author": "Bill Rawlinson", "author_id": 7329, "author_profile": "https://Stackoverflow.com/users/7329", "pm_score": 5, "selected": true, "text": "sp_depends <object_name> \n sp_helptext <trigger_name>\n sp_depends <trigger_name>\n" }, { "answer_id": 327303, "author": "John MacIntyre", "author_id": 29043, "author_profile": "https://Stackoverflow.com/users/29043", "pm_score": 1, "selected": false, "text": "select name\nfrom sysobjects\nwhere xtype='TR'\nand id in (select id from syscomments where text like '%MY-TABLE-NAME%')\n" }, { "answer_id": 4658115, "author": "Richard", "author_id": 571311, "author_profile": "https://Stackoverflow.com/users/571311", "pm_score": 3, "selected": false, "text": "select so.name, text\nfrom sysobjects so, syscomments sc\nwhere type = 'TR'\nand so.id = sc.id\nand text like '%TABLENAME%'\n" }, { "answer_id": 8679323, "author": "Annie", "author_id": 1122894, "author_profile": "https://Stackoverflow.com/users/1122894", "pm_score": 2, "selected": false, "text": "SELECT \n T.name AS TableName\n ,O.name TriggerName \n FROM sysobjects O \n INNER JOIN sys.tables T ON T.object_id = O.parent_obj\n WHERE O.type = 'TR' AND T.name IN ('tableNames')\nORDER BY TableName\n" }, { "answer_id": 39791317, "author": "Tim", "author_id": 6904629, "author_profile": "https://Stackoverflow.com/users/6904629", "pm_score": 1, "selected": false, "text": " select tr.id, tr.name, tr.type, tr.crdate, tr.loginame\nfrom sysobjects u\n join sysobjects tr on tr.id in (u.instrig, u.deltrig, u.updtrig, u.seltrig)\nwhere u.name = 'TABLENAME'\n" }, { "answer_id": 52275824, "author": "Weihui Guo", "author_id": 4271117, "author_profile": "https://Stackoverflow.com/users/4271117", "pm_score": 0, "selected": false, "text": "select * from SYS.SYSTRIGGERS --where trigdefn like '%exec%'\n" }, { "answer_id": 74066536, "author": "Ivo", "author_id": 20238908, "author_profile": "https://Stackoverflow.com/users/20238908", "pm_score": 0, "selected": false, "text": "SELECT so.name, Type=(CASE so.type WHEN 'V' Then 'View' WHEN 'P' THEN 'Procedure' WHEN 'TR' THEN 'Trigger' ELSE so.type END)\n FROM sysobjects so, sysdepends d\n WHERE\n d.depid = object_id('MyTblName')\n AND so.id =d.id \n /* Just triggers \n AND so.type = 'TR'\n */\n ORDER BY so.type,so.name\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7329/" ]
318,530
<p>Is it possible to create and initialise a <a href="http://msdn.microsoft.com/en-us/library/6918612z(VS.80).aspx" rel="noreferrer"><code>System.Collections.Generic.Dictionary</code></a> object with String key/value pairs in one statement?</p> <p>I'm thinking along the lines of the constructor for an array of Strings..</p> <p>e.g.</p> <pre><code>Private mStringArray As String() = {"String1", "String2", "etc"} </code></pre> <p>In case this is turns out to be a <a href="http://en.wikipedia.org/wiki/Syntactic_sugar" rel="noreferrer">syntactic sugar</a> kind of thing, I'd prefer an answer that I can use in .Net 2.0 (Visual Studio 2005), and Visual Basic - though I'm curious if it's possible at all so don't let that put you off ;o)</p>
[ { "answer_id": 318574, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 3, "selected": false, "text": "Dictionary<string, double> dict = new Dictionary<string, double>()\n{\n { \"pi\", 3.14},\n { \"e\", 2.71 }\n };\n" }, { "answer_id": 322077, "author": "KevB", "author_id": 6165, "author_profile": "https://Stackoverflow.com/users/6165", "pm_score": 4, "selected": true, "text": "Imports System.Collections.Generic\n\nModule Module1\n\n Sub Main()\n\n Dim items As New FancyDictionary(Of Integer, String)(New Object(,) {{1, \"First Item\"}, {2, \"Second Item\"}, {3, \"Last Item\"}})\n Dim enumerator As FancyDictionary(Of Integer, String).Enumerator = items.GetEnumerator\n\n While enumerator.MoveNext\n Console.WriteLine(String.Format(\"{0} : {1}\", enumerator.Current.Key, enumerator.Current.Value))\n End While\n\n Console.Read()\n\n End Sub\n\n Public Class FancyDictionary(Of TKey, TValue)\n Inherits Dictionary(Of TKey, TValue)\n\n Public Sub New(ByVal InitialValues(,) As Object)\n\n For i As Integer = 0 To InitialValues.GetLength(0) - 1\n\n Me.Add(InitialValues(i, 0), InitialValues(i, 1))\n\n Next\n\n End Sub\n\n End Class\n\nEnd Module\n" }, { "answer_id": 3195611, "author": "jgauffin", "author_id": 70386, "author_profile": "https://Stackoverflow.com/users/70386", "pm_score": 6, "selected": false, "text": "Dim myDic As New Dictionary(Of String, String) From {{\"1\", \"One\"}, {\"2\", \"Two\"}}\n" }, { "answer_id": 9329901, "author": "Orry", "author_id": 70454, "author_profile": "https://Stackoverflow.com/users/70454", "pm_score": 0, "selected": false, "text": "Private __sampleDictionary As New Dictionary(Of Integer, String) From\n{{1, \"This is a string value\"}, {2, \"Another value\"}}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
318,531
<p>I want to pass in the tType of a class to a function, and the class object to a generic function.</p> <p>I need to be able to cast to that Type (of class) so I can access the class's methods.</p> <p>Something like:</p> <pre><code>void GenericFunction(Object obj, Type type) { (type)obj.someContainer.Add(1); } </code></pre> <p>Would implementing an interface for these classes and then casting to that interface work? If so, could someone give an example?</p> <p>I've been Googling for the past few hours, and I've never had to do this before.</p> <p>Can someone shed some light?</p>
[ { "answer_id": 318548, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 0, "selected": false, "text": "void GenericFunction<T>(Object obj)\n where T : class {\n obj.someContainer.Add(1) as T;\n}\n" }, { "answer_id": 318586, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 0, "selected": false, "text": "void GenericFunction<T>(Object obj) where T : class \n{\n obj.someContainer.Add(1) as T;\n}\n" }, { "answer_id": 318588, "author": "Michael G", "author_id": 33082, "author_profile": "https://Stackoverflow.com/users/33082", "pm_score": 0, "selected": false, "text": "class A {\n public BindingList<int> addContainers;\n}\n\nclass B {\n public BindingList<int> addContainers;\n}\n\nclass C {\n Type type;\n Object senderObj;\n\n C(Object s, Type t)\n {\n senderObj = s;\n type = t;\n }\n\n private void AddBtn_Click(click sender, EventArgs e)\n {\n // Depending on the Type passed to the constructor, i need to cast to that type\n // so that i have access to the classes public addContainer member variable\n }\n" }, { "answer_id": 318622, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "public interface ICanReport\n{ void Report(); }\n\npublic class SomeThing : ICanReport\n{\n public void Report()\n { Console.WriteLine(\"I'm SomeThing\"); }\n}\n\npublic class SomeOtherThing : ICanReport\n{\n public void Report()\n { Console.WriteLine(\"I'm SomeOtherThing\"); }\n}\n\npublic class TestThings\n{\n //#1 use safe downcasting\n public void TheMethod(object x)\n {\n ICanReport y = x as ICanReport;\n if (y != null)\n y.Report();\n }\n\n //#2 use generics\n // 100% safe, but a little complex\n public void AnotherMethod<T>(T x) where T : ICanReport\n {\n x.Report();\n }\n\n //#3 use an interface as the parameter type.\n // simple and safe\n public void LastMethod(ICanReport x)\n {\n x.Report();\n }\n\n //sample calls\n public void Test1()\n {\n SomeThing a = new SomeThing();\n SomeOtherThing b = new SomeOtherThing();\n TheMethod(a);\n TheMethod(b);\n AnotherMethod(a);\n AnotherMethod(b);\n LastMethod(a);\n LastMethod(b);\n }\n}\n" }, { "answer_id": 318633, "author": "Jaime Garcia", "author_id": 32812, "author_profile": "https://Stackoverflow.com/users/32812", "pm_score": 0, "selected": false, "text": "Class2 Class1 using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace ReflectionTest\n{\n class Class1\n {\n public void helloWorld()\n {\n Console.WriteLine(\"Hello World 1\");\n }\n }\n\n class Class2\n {\n public void helloWorld()\n {\n Console.WriteLine(\"Hello World Class 2\");\n }\n }\n\n class Program\n {\n static void callCorrectClass(Object obj, Type type)\n {\n ConstructorInfo constructors = type.GetConstructor(System.Type.EmptyTypes);\n obj = constructors.Invoke(null);\n MethodInfo helloWorld = type.GetMethod(\"helloWorld\");\n helloWorld.Invoke(obj, null);\n }\n static void Main(string[] args)\n {\n Type type = typeof(Class2);\n callCorrectClass(new Object(), type);\n }\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33082/" ]
318,540
<p>I have a BlackBerry app running in the background that needs to know when a "Missed call" system dialog is brought up by the system, and programmatically close it without user intervention. How can I do that?</p> <p>I could actually almost know when the dialog is brought up, i.e. a little later I programmatically end the call...but how can I get a reference to the dialog, and close it?</p>
[ { "answer_id": 807832, "author": "kozen", "author_id": 98649, "author_profile": "https://Stackoverflow.com/users/98649", "pm_score": 1, "selected": false, "text": "PhoneLogListener" }, { "answer_id": 1420083, "author": "Maksym Gontar", "author_id": 67407, "author_profile": "https://Stackoverflow.com/users/67407", "pm_score": 3, "selected": true, "text": "KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, Characters.ESCAPE, 0);\ninject.post();\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39680/" ]
318,542
<p>The attached code example (pseudo code) compiles, but throws this Run-Time Error:</p> <pre><code>TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/getChildIndex() at mx.core::Container/getChildIndex()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\core\Container.as:2409] at mx.containers::ViewStack/set selectedChild()[E:\dev\3.0.x\frameworks\projects\framework\src\mx\containers\ViewStack.as:557] &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ [Bindable] private var targetViewName:String = "content"; ]]&gt; &lt;/mx:Script&gt; &lt;mx:ViewStack id="viewStack" width="100%" height="100%" selectedChild="{Container(viewStack.getChildByName(targetViewName))}"&gt; &lt;mx:Panel id="welcome" width="100%" height="100%" /&gt; &lt;mx:Panel id="content" width="100%" height="100%" /&gt; &lt;/mx:ViewStack&gt; &lt;/mx:Application&gt; </code></pre> <p>Is there some way I can get this to work without having to call a function to set the selectedChild?</p> <p>Thanks.</p>
[ { "answer_id": 319967, "author": "Niels Bosma", "author_id": 40939, "author_profile": "https://Stackoverflow.com/users/40939", "pm_score": 0, "selected": false, "text": "selectedChild=\"{this[targetViewName]}\">\n" }, { "answer_id": 320934, "author": "Eric Belair", "author_id": 31298, "author_profile": "https://Stackoverflow.com/users/31298", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n [Bindable]\n private var targetViewName:String = \"content\";\n ]]>\n </mx:Script>\n\n <mx:TabNavigator id=\"viewStack\" width=\"100%\" height=\"100%\" creationPolicy=\"all\" \n selectedChild=\"{this[targetViewName]}\">\n <mx:Panel id=\"welcome\" width=\"100%\" height=\"100%\" label=\"welcome\" />\n\n <mx:Panel id=\"content\" width=\"100%\" height=\"100%\" label=\"content\" />\n </mx:TabNavigator>\n</mx:Application>\n" }, { "answer_id": 322064, "author": "RickDT", "author_id": 5421, "author_profile": "https://Stackoverflow.com/users/5421", "pm_score": 0, "selected": false, "text": "<mx:TabNavigator id=\"viewStack\" width=\"100%\" height=\"100%\" creationPolicy=\"all\" >\n <mx:Panel id=\"welcome\" width=\"100%\" height=\"100%\" label=\"welcome\" />\n\n <mx:Panel id=\"content\" width=\"100%\" height=\"100%\" label=\"content\" addedToStage=\"viewStack.selectedChild = this\" />\n</mx:TabNavigator>\n" }, { "answer_id": 329663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" layout=\"absolute\">\n <mx:Script>\n <![CDATA[\n import mx.core.Container;\n [Bindable]\n private var targetViewName:String = \"content\";\n\n private function onClick() : void\n {\n viewStack.selectedChild = Container(viewStack.getChildByName(targetViewName)) ;\n }\n ]]>\n </mx:Script>\n\n <mx:ViewStack id=\"viewStack\" width=\"100%\" height=\"100%\" >\n <mx:Panel id=\"welcome\" width=\"100%\" height=\"100%\" title=\"welcome\"/>\n\n <mx:Panel id=\"content\" width=\"100%\" height=\"100%\" title=\"content\" />\n </mx:ViewStack>\n\n <mx:Button click=\"onClick()\" label=\"click\" />\n\n</mx:Application>\n" }, { "answer_id": 765661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<mx:Script>\n <![CDATA[\n import models.ModelLocator;\n\n [Bindable]\n private var model:ModelLocator = ModelLocator.getInstance();\n ]]>\n</mx:Script>\n\n<mx:ViewStack id=\"videoViewStack\" width=\"100%\" height=\"100%\" selectedChild=\"{this[model._videoViewStack]}\" >\n <viewsVideos:AllVideos id=\"AllVideos\" label=\"Videos\"/>\n <viewsVideos:MainVideo id=\"MainVideo\" label=\"Video\"/>\n</mx:ViewStack>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31298/" ]
318,551
<p>there was a somewhat detailed thread (228684) on how to globally (using extern struct) declare a structure that could be seen in more than 1 c++ file, but I can not figure out exactly how to do it (there was a lot of discussion about do this, do that, maybe do this, try this, etc...). </p> <p>couuld someone please post a very simple example of how to declare a structure that could be seen in 2 separate c++ files? If I put all my functions in the same file as the main it works fine, but when I try to split the functions out in different files I cannot get it to compile. </p> <p>Things I am unclear on... Should I typedef the structure? Do I define the structure in a header file and include that header in each c++ source file? Do I need the #ifndef macro in the header file? Do I declare the structure extern in the header?</p>
[ { "answer_id": 318558, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "#ifndef FOO_H\n#define FOO_H\nclass X {\n};\n#endif\n #include \"foo.h\"\nX x;\n" }, { "answer_id": 318560, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 0, "selected": false, "text": "#ifndef __my_header__\n#define __my_header__\n\nclass my_class\n{\n\n};\n\n#endif\n my_class" }, { "answer_id": 318569, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "struct foo {\n int a;\n int b;\n};\n foo foo foo extern struct foo { int a; int b; } b;\n foo b b" }, { "answer_id": 319271, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 2, "selected": false, "text": "/* foo.h */\n#ifndef EXAMPLE_FOO_H\n#define EXAMPLE_FOO_H\n\nstruct foo {\n int a;\n int b;\n};\n\nextern struct foo globalFoo;\n\n#endif /* EXAMPLE_FOO_H */\n /* foo.cpp */\n#include \"foo.h\"\n\nstruct foo globalFoo = { 1, 2 };\n /* bar1.cpp */\n#include \"foo.h\"\n\nint test1()\n{\n int c = globalFoo.b; //c is 2\n}\n /* bar2.cpp */\n#include \"foo.h\"\n\nint test2()\n{\n int x = globalFoo.a; //x is 1\n}\n extern extern struct foo globalFoo;" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,552
<p>I have a collection of collections, all the child collections have the same number of elements. The parent collection does nothing other than hold the child collections.</p> <pre><code>[0] [Child_0] [ID: 1] [0] [Child_0] [Amount: 4] [0] [Child_1] [ID: 2] [0] [Child_1] [Amount: 7] [1] [Child_0] [ID: 1] [1] [Child_0] [Amount: 2] [1] [Child_1] [ID: 2] [1] [Child_1] [Amount: 4] [2] [Child_0] [ID: 1] [2] [Child_0] [Amount: 5] [2] [Child_1] [ID: 2] [2] [Child_1] [Amount: 3] </code></pre> <p>For my output I don't care about the parent collection. I just want an anonymous type of ID and average of amounts, so for the above it would be</p> <pre><code>ID Avg 1 3.66 2 4.66 </code></pre> <p>Language of the response does not matter.</p> <p>Thanks.</p>
[ { "answer_id": 318662, "author": "Rohan West", "author_id": 38686, "author_profile": "https://Stackoverflow.com/users/38686", "pm_score": 2, "selected": false, "text": " var items = new[] \n { \n new { ID = 1, Amount = 4 }, \n new { ID = 1, Amount = 5 },\n new { ID = 2, Amount = 5 },\n new { ID = 2, Amount = 3 },\n };\n\n var results = from item in items group item by item.ID into g select new { ID = g.Key, Avg = g.Average(item => item.Amount) };\n\n foreach (var result in results)\n {\n Console.WriteLine(\"{0} - {1}\", result.ID, result.Avg);\n }\n" }, { "answer_id": 318667, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": " // the data\n var outer = new[] {\n new[] {\n new {ID=1,Amount=4}, // [0] [Child_0] [ID: 1, Amount: 4]\n new {ID=2,Amount=7} // [0] [Child_1] [ID: 2, Amount: 7]\n },\n new[] {\n new {ID=1, Amount=2}, // [1] [Child_0] [ID: 1, Amount: 2]\n new {ID=2, Amount=4} // [1] [Child_1] [ID: 2, Amount: 4]\n },\n new[] {\n new {ID=1, Amount=5}, // [2] [Child_0] [ID: 1, Amount: 5]\n new {ID=2, Amount=3} // [2] [Child_1] [ID: 2, Amount: 3]\n }\n };\n var qry = from x in outer\n from y in x\n group y by y.ID into grp\n select new { Id = grp.Key, Avg = grp.Average(z => z.Amount) };\n\n foreach (var item in qry)\n {\n Console.WriteLine(\"{0}: {1}\", item.Id, item.Avg);\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,553
<p>I have the following in my .emacs file:</p> <pre><code> (defun c++-mode-untabify () (save-excursion (goto-char (point-min)) (while (re-search-forward "[ \t]+$" nil t) (delete-region (match-beginning 0) (match-end 0))) (goto-char (point-min)) (if (search-forward "\t" nil t) (untabify (1- (point)) (point-max)))) nil) (add-hook 'c++-mode-hook '(lambda () (make-local-hook 'write-contents-hooks) (add-hook 'write-contents-hooks 'c++-mode-untabify))) </code></pre> <p>Mostly ripped off from <a href="http://www.jwz.org/doc/tabs-vs-spaces.html" rel="noreferrer">http://www.jwz.org/doc/tabs-vs-spaces.html</a>. This causes emacs to run <code>untabify</code> on the buffer before saving a C++ file.</p> <p>The problem is that after I have loaded a C++ file, the <code>untabify</code> hook is being applied to <strong>all</strong> subsequent file writes, even for buffers of other file types. This means that if I open a C++ file and then edit, say, a tab-delimited text file, the tabs get clobbered when saving the file.</p> <p>I'm not an elisp guru, but I think the <code>(make-local-hook 'write-contents-hooks)</code> line is trying to make the addition to <code>write-contents-hooks</code> apply only to the local buffer. However, it isn't working, and <code>c++-mode-untabify</code> is in <code>write-contents-hooks</code> for all buffers.</p> <p>I'm using EmacsW32 22.0 on a Windows XP box. Does anyone have any idea how to make the <code>write-contents-hooks</code> change local to a specific buffer or how to reset it to <code>nil</code> when switching to other, non-C++ buffers?</p>
[ { "answer_id": 318710, "author": "Boojum", "author_id": 37555, "author_profile": "https://Stackoverflow.com/users/37555", "pm_score": 3, "selected": false, "text": "(add-hook 'c++-mode-hook\n '(lambda ()\n (add-hook 'write-contents-hooks 'c++-mode-untabify nil t)))\n (defun c++-mode-untabify ()\n (if (string= (substring mode-name 0 3) \"C++\")\n (save-excursion\n (delete-trailing-whitespace)\n (untabify (point-min) (point-max)))))\n" }, { "answer_id": 318718, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": " (add-hook 'c++-mode-hook\n '(lambda ()\n (add-hook 'write-contents-hooks 'c++-mode-untabify nil t)))\n" }, { "answer_id": 322690, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "(add-hook 'c++-mode-hook\n '(lambda ()\n (add-hook 'before-save-hook\n (lambda ()\n (untabify (point-min) (point-max))))))\n (defun untabify-buffer ()\n \"Untabify current buffer\"\n (interactive)\n (untabify (point-min) (point-max)))\n\n(defun progmodes-hooks ()\n \"Hooks for programming modes\"\n (yas/minor-mode-on)\n (add-hook 'before-save-hook 'progmodes-write-hooks))\n\n(defun progmodes-write-hooks ()\n \"Hooks which run on file write for programming modes\"\n (prog1 nil\n (set-buffer-file-coding-system 'utf-8-unix)\n (untabify-buffer)\n (copyright-update)\n (maybe-delete-trailing-whitespace)))\n\n(defun delete-trailing-whitespacep ()\n \"Should we delete trailing whitespace when saving this file?\"\n (save-excursion\n (goto-char (point-min))\n (ignore-errors (next-line 25))\n (let ((pos (point)))\n (goto-char (point-min))\n (and (re-search-forward (concat \"@author +\" user-full-name) pos t) t))))\n\n(defun maybe-delete-trailing-whitespace ()\n \"Delete trailing whitespace if I am the author of this file.\"\n (interactive)\n (and (delete-trailing-whitespacep) (delete-trailing-whitespace)))\n\n(add-hook 'php-mode-hook 'progmodes-hooks)\n(add-hook 'python-mode-hook 'progmodes-hooks)\n(add-hook 'js2-mode-hook 'progmodes-hooks)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9199/" ]
318,556
<p>Is there a way to get drop_receiving_element to not generate "// ..</p>
[ { "answer_id": 318825, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "drop_receiving_element def drop_receiving_element(element_id, options = {})\n javascript_tag(drop_receiving_element_js(element_id, options).chop!)\nend\n javascript_tag drop_receiving_element_js(element_id, options).chop!\n send(:drop_receiving_element_js, element_id, options).chop!\n" }, { "answer_id": 320173, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 0, "selected": false, "text": "content_for <% content_for :inline_javascript do %>\n <%# Script helpers here %>\n<% end %>\n <%# Include tags for other Js code the inline scripts rely on above here %>\n<%= yield :inline_javascript %>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,567
<p>I have a database that hold's a user's optional profile. In the profile I have strings, char (for M or F) and ints.</p> <p>I ran into an issue where I try to put the sex of the user into the property of my Profile object, and the application crashes because it doesn't know how to handle a returned null value.</p> <p>I've tried casting the data to the appropriate type </p> <pre><code>char sex = (char)dt.Rows[0]["Sex"]; </code></pre> <p>Which didn't fix my problem. I then tried changing the types to Nullable and Nullable and get conversion issues all the same. My current solution that I was able to find is the following:</p> <pre><code>object.sex = null; if(dt.Rows[0]["Sex"] != DBNull.Value) object.sex = (char)dt.Rows[0]["Sex"]; object.WorkExt = null; if(dt.Rows[0]["WorkExt"] != DBNull.Value) object.WorkExt = (int)dt.Rows[0]["WorkExt"]; </code></pre> <p>Is there a simpler or better way to do this? Or am I pretty much on the right track?</p>
[ { "answer_id": 318585, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 0, "selected": false, "text": "object.sex = handle(dt.Rows[0][\"Sex\"]);\n" }, { "answer_id": 318661, "author": "gillonba", "author_id": 38660, "author_profile": "https://Stackoverflow.com/users/38660", "pm_score": 1, "selected": false, "text": "if(dt.Rows[0].IsSexNull()) {} else {}\n" }, { "answer_id": 318682, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "class Foo {\n char? sex;\n}\nFoo object;\n\nobject.sex = dt.Rows[0][\"Sex\"] as char?;\n" }, { "answer_id": 319104, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": true, "text": "Is<ColumnName>Null() using System.\nusing System.Data;\n\nclass Program\n{\n static void Main(string[] args)\n {\n DataTable dt = new DataTable();\n dt.Columns.Add(\"test\", typeof (char));\n dt.Columns[\"test\"].AllowDBNull = true;\n\n DataRow dr = dt.Rows.Add();\n char? test;\n\n try\n {\n test = (char?)dr[\"test\"];\n }\n catch (InvalidCastException)\n {\n Console.WriteLine(\"Simply casting to a nullable type doesn't work.\");\n }\n\n test = dr.Field<char?>(\"test\");\n if (test == null)\n {\n Console.WriteLine(\"The Field extension method in .NET 3.5 converts System.DBNull to null.\"); \n }\n\n test = (dr[\"test\"] is DBNull) ? null : (char?) dr[\"test\"];\n if (test == null)\n {\n Console.WriteLine(\"Before .NET 3.5, you have to check the type of the column's value.\");\n }\n\n test = (dr[\"test\"] == DBNull.Value) ? null : (char?) dr[\"test\"];\n if (test == null)\n {\n Console.WriteLine(\"Comparing the field's value to DBNull.Value is very marginally faster, but takes a bit more code.\");\n }\n\n // now let's put the data back\n\n try\n {\n dr[\"test\"] = test;\n }\n catch (ArgumentException)\n {\n Console.WriteLine(\"You can't set nullable columns to null.\");\n }\n\n dr.SetField(\"test\", test);\n if (dr[\"test\"] is DBNull)\n {\n Console.WriteLine(\"Again, in .NET 3.5 extension methods make this relatively easy.\");\n }\n\n dr[\"test\"] = (object)test ?? DBNull.Value;\n if (dr[\"test\"] is DBNull)\n {\n Console.WriteLine(\"Before .NET 3.5, you can use the null coalescing operator, but note the awful cast required.\");\n }\n\n\n Console.ReadLine();\n }\n}\n" }, { "answer_id": 320918, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " internal static T CastTo<T>(object value)\n {\n return value != DBNull.Value ? (T)value : default(T);\n }\n return new EquipmentDetails(\n CastTo<int>(reader[\"ID\"]),\n CastTo<int>(reader[\"CategoryID\"]),\n CastTo<string>(reader[\"Description\"]));\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
318,571
<p>Using MySQL syntax and having a table with a row like:</p> <pre><code>mydate DATETIME NULL, </code></pre> <p>Is there a way to do something like:</p> <pre><code>... WHERE mydate&lt;='2008-11-25'; </code></pre> <p>I'm trying but not really getting it to work.</p>
[ { "answer_id": 318597, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 5, "selected": true, "text": "WHERE DATEDIFF(mydata,'2008-11-20') >=0;\n" }, { "answer_id": 319130, "author": "Eli", "author_id": 5958, "author_profile": "https://Stackoverflow.com/users/5958", "pm_score": 5, "selected": false, "text": "WHERE mydate<='2008-11-25' create temporary table foo(d datetime);\ninsert into foo(d) VALUES ('2000-01-01');\ninsert into foo(d) VALUES ('2001-01-01');\nselect * from foo where d <= '2000-06-01';\n" }, { "answer_id": 319184, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": false, "text": "WHERE mydate <= DATE '2008-11-20'\n" }, { "answer_id": 319891, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 2, "selected": false, "text": "WHERE mydate<='2008-11-25 23:59:59'\n WHERE mydate < '2008-11-26 00:00:00'\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
318,590
<p>I'm refactoring a 500-lines of C++ code in main() for solving a differential equation. I'd like to encapsulate the big ideas of our solver into smaller functions (i.e. "SolvePotential(...)" instead of 50 lines of numerics code). </p> <p>Should I code this sequentially with a bunch of functions taking <strong>very long</strong> parameters lists, such as:</p> <pre><code>int main(int *argc, void **argv){ interpolate(x,y,z, x_interp, y_interp, z_interp, potential, &amp;newPotential); compute_flux(x,y,z, &amp;flux) compute_energy(x,y,z, &amp;eng) ... // 10 other high-level function calls with long parameter lists ... return 0; } </code></pre> <p>Or should I create a "SolvePotential" class that would be called like so:</p> <pre><code>int main(int *argc, void **argv){ potential = SolvePotential(nx, ny, nz, nOrder); potential.solve(); return 0; } </code></pre> <p>Where I would define functions in SolvePotential that uses member variables rather than long parameter lists, such as:</p> <pre><code>SolverPotential::solve(){ SolvePotential::interpolate() SolverPotential::compute_flux() SolverPotential::compute_energy() // ... // 10 other high-level function calls with NO parameter lists (just use private member variables) } </code></pre> <p>In either case, I doubt I'll re-use the code very much... really, I'm just refactoring to help with code clarity down the road.</p> <p>Maybe this is like arguing "Is it '12' or 'one dozen'?", but what do you think?</p>
[ { "answer_id": 318746, "author": "Luis", "author_id": 22609, "author_profile": "https://Stackoverflow.com/users/22609", "pm_score": 2, "selected": false, "text": "float SolvePotential(const Vector3& vn, float nOrder)\n{\n // ...\n const float newPotential = interpolate(vn, v_interp, potential);\n const float flux = compute_flux(vn);\n const float energy = compute_energy(vn);\n // ...\n return result;\n}\n" }, { "answer_id": 318901, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 0, "selected": false, "text": "SolverPotential::solve(a, b, c, d){\n SolvePotential::interpolate(a, b);\n SolverPotential::compute_flux(b, c);\n SolverPotential::compute_energy(c, d)\n" }, { "answer_id": 319049, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": true, "text": "SolverPotential::solve(){\nSolvePotential::interpolate()\nSolverPotential::compute_flux()\nSolverPotential::compute_energy()\n// ... \n// 10 other high-level function calls with NO parameter lists (just use private member variables)\n}\n // This struct could be replaced with something like typedef boost::tuple<double,double,double> coord3d\nstruct coord3d {\ndouble x, y, z;\n};\n\ncoord3d interpolate(const coord3d& coord, const coord3d& interpolated, double potential); // Just return the potential, rather than using messy output parameters\ndouble compute_flux(const coord3d coord&flux); // Return the flux instead of output params\ndouble compute_energy(const coord3d& coord); // And return the energy directly as well\n" }, { "answer_id": 319107, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 0, "selected": false, "text": "PotentialSolution solve()\n" }, { "answer_id": 332619, "author": "Francis Stephens", "author_id": 39476, "author_profile": "https://Stackoverflow.com/users/39476", "pm_score": 0, "selected": false, "text": "public class ValuePlusOne implements Computable {\n private int value;\n private int result;\n private Boolean hasRun;\n private static Map instanceMap = new HashMap();\n\n // Creates an instance reusing an existing one if possible\n public static getInstance(int value) {\n ValuePlusOne instance = (ValuePlusOne)instanceMap.get(value);\n\n if (instance = null) {\n instance = new ValuePlusOne(value);\n instanceMap.put(value,instance);\n }\n return instance;\n }\n\n // Private constructor\n private ValuePlusOne(int value) {\n this.value = value;\n hasRun = false;\n }\n\n // Computes (if not already computed) and returns the answer\n public int compute() {\n if (!hasRun) {\n hasRun = true;\n result = value + 1;\n }\n\n return result;\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40785/" ]
318,612
<p>I have a HTML table that's generated in a JSP by the displaytag tag library. I would like to suppress any zeros that appear in the table, i.e. they should be replaced by a blank cell. Is there any straightforward way to achieve this?</p>
[ { "answer_id": 319713, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 2, "selected": false, "text": "public class SuppressZeroDecorator implements DisplaytagColumnDecorator {\n\n /* (non-Javadoc)\n * @see org.displaytag.decorator.DisplaytagColumnDecorator#decorate(java.lang.Object, javax.servlet.jsp.PageContext, org.displaytag.properties.MediaTypeEnum)\n */\n public Object decorate(Object rowObject, PageContext pageContext, MediaTypeEnum mediaType) {\n\n if (rowObject != null && rowObject.toString().trim().equals(\"0\")) {\n return null;\n }\n\n return rowObject;\n }\n}\n <display:column property=\"age\" title=\"Age\" decorator=\"com.example.ZeroColumnDecorator\" />\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
318,626
<p>Theoretically, the end user should never see internal errors. But in practice, theory and practice differ. So the question is what to show the end user. Now, for the totally non-technical user, you want to show as little as possible ("<em>click here to submit a bug report</em>" kind of things), but for more advanced users, they will want to know if there is a work around, if it's been known for a while, etc. So you want to include <em>some</em> sort of info about what's wrong as well.</p> <p>The classic way to do this is either an assert with a filename:line-number or a stack trace with the same. Now this is good for the developer because it points him right at the problem; however it has some significant downsides for the user, particularly that it's very cryptic (e.g. unfriendly) and code changes change the error message (Googling for the error only works for this version).</p> <p>I have a program that I'm planning on writing where I want to address these issues. What I want is a way to attach a unique identity to every assert in such a way that editing the code around the assert won't alter it. (For example, if I cut/paste it to another file, I want the same information to be displayed) Any ideas?</p> <p>One tack I'm thinking of is to have an enumeration for the errors, but how to make sure that they are never used in more than one place?</p> <p>(Note: For this question, <em>I'm</em> only looking at errors that are caused by coding errors. Not things that could legitimately happen like bad input. OTOH those errors may be of some interest to the community at large.)</p> <p>(Note 2: The program in question would be a command line app running on the user's system. But again, that's just my situation.)</p> <p>(Note 3: the target language is <a href="http://www.digitalmars.com/d/" rel="nofollow noreferrer">D</a> and <a href="http://www.dsource.org/projects/scrapple/browser/trunk/dparser/dparse.d" rel="nofollow noreferrer">I'm very willing</a> to dive into <a href="http://www.digitalmars.com/d/2.0/templates-revisited.html" rel="nofollow noreferrer">meta-programming</a>. Answers for other languages more than welcome!)</p> <p>(note 4: I explicitly want to NOT use actual code locations but rather some kind of symbolic names for the errors. This is because if code is altered in practically any way, code locations change.) </p>
[ { "answer_id": 319840, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "int someFunction()\n{\n static const std::string loc = \"someFunction\";\n : :\n if( somethingWentWrong )\n {\n WarningMessage(loc.c_str(), \"Unable to Instantiate UtilityObject: Error 'Class Not\n Registered' in 'CoCreateInstance);\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
318,630
<p>I am creating a jQuery plugin.</p> <p>How do I get the real image width and height with Javascript in Safari?</p> <p>The following works with Firefox 3, IE7 and Opera 9:</p> <pre><code>var pic = $("img") // need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height"); var pic_real_width = pic.width(); var pic_real_height = pic.height(); </code></pre> <p>But in Webkit browsers like Safari and Google Chrome values are 0.</p>
[ { "answer_id": 318694, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 4, "selected": false, "text": "window.onload $(window).load(function() {\n var pic = $('img');\n\n pic.removeAttr(\"width\"); \n pic.removeAttr(\"height\");\n\n alert( pic.width() );\n alert( pic.height() );\n});\n" }, { "answer_id": 318796, "author": "Cugel", "author_id": 40353, "author_profile": "https://Stackoverflow.com/users/40353", "pm_score": 4, "selected": false, "text": "jQuery(document).ready(function(){\n if (jQuery.browser.safari && document.readyState != \"complete\"){\n //console.info('ready...');\n setTimeout( arguments.callee, 100 );\n return;\n } \n ... (rest of function) \n" }, { "answer_id": 670433, "author": "Xavi", "author_id": 53926, "author_profile": "https://Stackoverflow.com/users/53926", "pm_score": 9, "selected": true, "text": "var img = $(\"img\")[0]; // Get my img elem\nvar pic_real_width, pic_real_height;\n$(\"<img/>\") // Make in memory copy of image to avoid css issues\n .attr(\"src\", $(img).attr(\"src\"))\n .load(function() {\n pic_real_width = this.width; // Note: $(this).width() will not\n pic_real_height = this.height; // work for in memory images.\n });\n naturalHeight naturalWidth" }, { "answer_id": 1341685, "author": "Davin", "author_id": 136389, "author_profile": "https://Stackoverflow.com/users/136389", "pm_score": -1, "selected": false, "text": "$(this).clone().removeAttr(\"width\").attr(\"width\");\n$(this).clone().removeAttr(\"height\").attr(\"height);\n" }, { "answer_id": 3192577, "author": "FDisk", "author_id": 175404, "author_profile": "https://Stackoverflow.com/users/175404", "pm_score": 6, "selected": false, "text": "\nfunction getOriginalWidthOfImg(img_element) {\n var t = new Image();\n t.src = (img_element.getAttribute ? img_element.getAttribute(\"src\") : false) || img_element.src;\n return t.width;\n}\n" }, { "answer_id": 3216737, "author": "Jerome Jaglale", "author_id": 91225, "author_profile": "https://Stackoverflow.com/users/91225", "pm_score": 2, "selected": false, "text": "$(\"#myImg\").one(\"load\",function(){\n //do something, like getting image width/height\n}).each(function(){\n if(this.complete) $(this).trigger(\"load\");\n});\n" }, { "answer_id": 3791561, "author": "S P", "author_id": 276675, "author_profile": "https://Stackoverflow.com/users/276675", "pm_score": 1, "selected": false, "text": "event.special.load" }, { "answer_id": 4332539, "author": "Fox", "author_id": 527626, "author_profile": "https://Stackoverflow.com/users/527626", "pm_score": 3, "selected": false, "text": "(function( $ ){\n $.fn.getDimensions=function(){\n alert(\"First example:This works only for HTML code without CSS width/height definition.\");\n w=$(this, 'img')[0].width;\n h=$(this, 'img')[0].height;\n\n alert(\"This is a width/height on your monitor: \" + $(this, 'img')[0].width+\"/\"+$(this, 'img')[0].height);\n\n //This is bad practice - it shows on your monitor\n $(this, 'img')[0].removeAttribute( \"width\" );\n $(this, 'img')[0].removeAttribute( \"height\" );\n alert(\"This is a bad effect of view after attributes removing, but we get right dimensions: \"+ $(this, 'img')[0].width+\"/\"+$(this, 'img')[0].height);\n //I'am going to repare it\n $(this, 'img')[0].width=w;\n $(this, 'img')[0].height=h;\n //This is a good practice - it doesn't show on your monitor\n ku=$(this, 'img').clone(); //We will work with a clone\n ku.attr( \"id\",\"mnbv1lk87jhy0utrd\" );//Markup clone for a final removing\n ku[0].removeAttribute( \"width\" );\n ku[0].removeAttribute( \"height\" );\n //Now we still get 0\n alert(\"There are still 0 before a clone appending to document: \"+ $(ku)[0].width+\"/\"+$(ku)[0].height);\n //Hide a clone\n ku.css({\"visibility\" : \"hidden\",'position':'absolute','left':'-9999px'}); \n //A clone appending\n $(document.body).append (ku[0]);\n alert(\"We get right dimensions: \"+ $(ku)[0].width+\"/\"+$(ku)[0].height);\n //Remove a clone\n $(\"#mnbv1lk87jhy0utrd\").remove();\n\n //But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.\n alert(\"But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.\");\n imgcopy=$('<img src=\"'+ $(this, 'img').attr('src') +'\" />');//new object \n imgcopy.attr( \"id\",\"mnbv1lk87jhy0aaa\" );//Markup for a final removing\n imgcopy.css({\"visibility\" : \"hidden\",'position':'absolute','left':'-9999px'});//hide copy \n $(document.body).append (imgcopy);//append to document \n alert(\"We get right dimensions: \"+ imgcopy.width()+\"/\"+imgcopy.height());\n $(\"#mnbv1lk87jhy0aaa\").remove();\n\n\n }\n})( jQuery );\n\n$(document).ready(function(){\n\n $(\"img.toreaddimensions\").click(function(){$(this).getDimensions();});\n});\n" }, { "answer_id": 4437832, "author": "drublic", "author_id": 541740, "author_profile": "https://Stackoverflow.com/users/541740", "pm_score": 0, "selected": false, "text": "$('#image').fadeIn(10,function () {var tmpW = $(this).width(); var tmpH = $(this).height(); });" }, { "answer_id": 4469435, "author": "damijanc", "author_id": 545911, "author_profile": "https://Stackoverflow.com/users/545911", "pm_score": 0, "selected": false, "text": "//make json call to server to get image size\n$.getJSON(\"http://server/getimagesize.php\",\n{\"src\":url},\nSetImageWidth\n);\n\n//callback function\nfunction SetImageWidth(data) {\n\n var wrap = $(\"div#image_gallery #image_wrap\");\n\n //remove height\n wrap.find(\"img\").removeAttr('height');\n //remove height\n wrap.find(\"img\").removeAttr('width');\n\n //set image width\n if (data.width > 635) {\n wrap.find(\"img\").width(635);\n }\n else {\n wrap.find(\"img\").width(data.width);\n }\n}\n <?php\n\n$image_width = 0;\n$image_height = 0;\n\nif (isset ($_REQUEST['src']) && is_file($_SERVER['DOCUMENT_ROOT'] . $_REQUEST['src'])) {\n\n $imageinfo = getimagesize($_SERVER['DOCUMENT_ROOT'].$_REQUEST['src']);\n if ($imageinfo) {\n $image_width= $imageinfo[0];\n $image_height= $imageinfo[1];\n }\n}\n\n$arr = array ('width'=>$image_width,'height'=>$image_height);\n\necho json_encode($arr);\n\n?>\n" }, { "answer_id": 4807788, "author": "SDemonUA", "author_id": 591020, "author_profile": "https://Stackoverflow.com/users/591020", "pm_score": 1, "selected": false, "text": " graph= $('<img/>', {\"src\":'mySRC', id:'graph-img'});\n graph.bind('load', function (){\n wid = graph.attr('width');\n hei = graph.attr('height');\n\n graph.dialog({ autoOpen: false, title: 'MyGraphTitle', height:hei, width:wid })\n })\n" }, { "answer_id": 4909227, "author": "JKS", "author_id": 144149, "author_profile": "https://Stackoverflow.com/users/144149", "pm_score": 4, "selected": false, "text": "onload onload setTimeout $(\"img\").one(\"load\", function(){\n var img = this;\n setTimeout(function(){\n // do something based on img.width and/or img.height\n }, 0);\n});\n onload var src = img.src; img.src = \"\"; img.src = src;" }, { "answer_id": 6413645, "author": "sandstrom", "author_id": 118007, "author_profile": "https://Stackoverflow.com/users/118007", "pm_score": 8, "selected": false, "text": "naturalHeight naturalWidth var h = document.querySelector('img').naturalHeight;\n" }, { "answer_id": 7573016, "author": "xmarcos", "author_id": 296609, "author_profile": "https://Stackoverflow.com/users/296609", "pm_score": 2, "selected": false, "text": "window.load window.load $(window).load(function(){\n\n //these all work\n\n $('img#someId').css('width');\n $('img#someId').width();\n $('img#someId').get(0).style.width;\n $('img#someId').get(0).width; \n\n});\n var pic_real_width = 0,\n img_src_no_cache = $('img#someId').attr('src') + '?cache=' + Date.now();\n\n$('<img/>').attr('src', img_src_no_cache).load(function(){\n\n pic_real_width = this.width;\n\n});\n img.src" }, { "answer_id": 8456052, "author": "Gadelkareem", "author_id": 280512, "author_profile": "https://Stackoverflow.com/users/280512", "pm_score": 0, "selected": false, "text": "$(\"img\").imagesLoaded(function(){\nalert( $(this).width() );\nalert( $(this).height() );\n});\n" }, { "answer_id": 8708244, "author": "foxybagga", "author_id": 95350, "author_profile": "https://Stackoverflow.com/users/95350", "pm_score": 0, "selected": false, "text": "var img = new Image();\n$(img).bind('load error', function(e)\n{\n $.data(img, 'dimensions', { 'width': img.width, 'height': img.height }); \n});\nimg.src = imgs[i]; \n $(this).data('dimensions').width;\n$(this).data('dimensions').height;\n" }, { "answer_id": 8717189, "author": "Andrew Mackenzie", "author_id": 573149, "author_profile": "https://Stackoverflow.com/users/573149", "pm_score": 3, "selected": false, "text": "image.naturalHeight image.naturalWidth" }, { "answer_id": 9361340, "author": "CheeseSucker", "author_id": 975552, "author_profile": "https://Stackoverflow.com/users/975552", "pm_score": 1, "selected": false, "text": "function LoadImage(imgSrc, callback){\n var image = new Image();\n image.src = imgSrc;\n if (image.complete) {\n callback(image);\n image.onload=function(){};\n } else {\n image.onload = function() {\n callback(image);\n // clear onLoad, IE behaves erratically with animated gifs otherwise\n image.onload=function(){};\n }\n image.onerror = function() {\n alert(\"Could not load image.\");\n }\n }\n}\n function AlertImageSize(image) {\n alert(\"Image size: \" + image.width + \"x\" + image.height);\n}\nLoadImage(\"http://example.org/image.png\", AlertImageSize);\n" }, { "answer_id": 10223973, "author": "Zdeněk Mlčoch", "author_id": 1084149, "author_profile": "https://Stackoverflow.com/users/1084149", "pm_score": 1, "selected": false, "text": " function waitForImageSize(src, func, ctx){\n if(!ctx)ctx = window;\n var img = new Image();\n img.src = src;\n $(img).imagesLoaded($.proxy(function(){\n var w = this.img.innerWidth||this.img.naturalWidth;\n var h = this.img.innerHeight||this.img.naturalHeight;\n this.func.call(this.ctx, w, h, this.img);\n },{img: img, func: func, ctx: ctx}));\n },\n waitForImageSize(\"image.png\", function(w,h){alert(w+\",\"+h)},this)\n" }, { "answer_id": 10841401, "author": "Yëco", "author_id": 339034, "author_profile": "https://Stackoverflow.com/users/339034", "pm_score": 3, "selected": false, "text": "var img = new Image();\nimg.onload = function() {\n console.log(this.width + 'x' + this.height);\n}\nimg.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';\n" }, { "answer_id": 11789619, "author": "Eranda", "author_id": 1181127, "author_profile": "https://Stackoverflow.com/users/1181127", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){\n var image = $(\"#fix_img\");\n var w = image.width();\n var h = image.height();\n var mr = 274/200;\n var ir = w/h\n if(ir > mr){\n image.height(200);\n image.width(200*ir);\n } else{\n image.width(274);\n image.height(274/ir);\n }\n }); \n" }, { "answer_id": 13169581, "author": "Duane Comeaux", "author_id": 1790109, "author_profile": "https://Stackoverflow.com/users/1790109", "pm_score": 2, "selected": false, "text": "// Hack for Safari and others\n// clone the image and add it to the DOM\n// to get the actual width and height\n// of the newly loaded image\n\nvar cloned, \n o_width, \n o_height, \n src = 'my_image.jpg', \n img = [some existing image object];\n\n$(img)\n.load(function()\n{\n $(this).removeAttr('height').removeAttr('width');\n cloned = $(this).clone().css({visibility:'hidden'});\n $('body').append(cloned);\n o_width = cloned.get(0).width; // I prefer to use native javascript for this\n o_height = cloned.get(0).height; // I prefer to use native javascript for this\n cloned.remove();\n $(this).attr({width:o_width, height:o_height});\n})\n.attr(src:src);\n" }, { "answer_id": 18750728, "author": "Stephen Synowsky", "author_id": 2768997, "author_profile": "https://Stackoverflow.com/users/2768997", "pm_score": 0, "selected": false, "text": "tempObject.image = $('<img />').attr({ 'src':\"images/prod-\" + tempObject.id + \".png\", load:preloader });\nxmlProjectInfo.push(tempObject);\n\nfunction preloader() {\n imagesLoaded++;\n if (imagesLoaded >= itemsToLoad) { //itemsToLoad gets set elsewhere in code\n DetachEvent(this, 'load', preloader); //function that removes event listener\n drawItems();\n } \n}\n\nfunction drawItems() {\n for(var i = 1; i <= xmlProjectInfo.length; i++)\n alert(xmlProjectInfo[i - 1].image[0].width);\n}\n" }, { "answer_id": 31776277, "author": "Samuel Santos", "author_id": 4909287, "author_profile": "https://Stackoverflow.com/users/4909287", "pm_score": 3, "selected": false, "text": "$('.my-img')[0].naturalWidth \n$('.my-img')[0].naturalHeight\n" }, { "answer_id": 33993570, "author": "Abdulaziz Alkharashi", "author_id": 5518977, "author_profile": "https://Stackoverflow.com/users/5518977", "pm_score": 0, "selected": false, "text": " function CheckImageSize(){\nvar image = document.getElementById(\"Image\").files[0];\n createReader(image, function (w, h) {\n\n alert(\"Width is: \" + w + \" And Height is: \"+h);\n}); \n}\n\n\n function createReader(file, whenReady) {\n var reader = new FileReader;\n reader.onload = function (evt) {\n var image = new Image();\n image.onload = function (evt) {\n var width = this.width;\n var height = this.height;\n if (whenReady) whenReady(width, height);\n };\n image.src = evt.target.result;\n };\n reader.readAsDataURL(file);\n }\n <html>\n<head>\n<title>Image Real Size</title>\n<script src=\"ImageSize.js\"></script>\n</head>\n<body>\n<input type=\"file\" id=\"Image\"/>\n<input type=\"button\" value=\"Find the dimensions\" onclick=\"CheckImageSize()\"/>\n</body>\n<html>\n" }, { "answer_id": 47823258, "author": "Jair Reina", "author_id": 1993956, "author_profile": "https://Stackoverflow.com/users/1993956", "pm_score": 1, "selected": false, "text": "//you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method\nvar pic = $(\"img\")[0];\nvar pic_real_width = pic.naturalWidth;\nvar pic_real_height = pic.naturalHeight;\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27623/" ]
318,632
<p>I'm running into a problem trying to anchor a textbox to a form on all 4 sides. I added a textbox to a form and set the Multiline property to True and the Anchor property to Left, Right, Up, and Down so that the textbox will expand and shrink with the form at run time. I also have a few other controls above and below the textbox. </p> <p>The anchoring works correctly in Visual Studio 2005 (i.e. I can resize the form and have the controls expand and shrink as expected), but when I run the project, the bottom of the textbox is extended to the bottom of the form, behind the other controls that would normally appear beneath it. This problem occurs when the form loads, before any resizing is attempted. The anchoring of the textbox is correct for the top, left, and right sides; only the bottom is malfunctioning. </p> <p>Has anybody heard of this and if so, were you able to find a solution?</p> <p>Thanks!</p> <p>UPDATE:</p> <p>Here is some of the designer code as per Greg D's request (I am only including the stuff that had to do with the textbox itself, not the other controls):</p> <pre><code>Friend WithEvents txtRecommendationText1 As System.Windows.Forms.TextBox &lt;System.Diagnostics.DebuggerStepThrough()&gt; _ Private Sub InitializeComponent() Me.txtRecommendationText1 = New System.Windows.Forms.TextBox ' ...snip... 'txtRecommendationText1 Me.txtRecommendationText1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtRecommendationText1.Location = New System.Drawing.Point(4, 127) Me.txtRecommendationText1.Multiline = True Me.txtRecommendationText1.Name = "txtRecommendationText1" Me.txtRecommendationText1.Size = New System.Drawing.Size(223, 149) Me.txtRecommendationText1.TabIndex = 10 End Sub </code></pre> <p>ANOTHER UPDATE:</p> <p>The textbox I originally posted about was not inherited from a baseclass form (although it was added to a custom User Control class; I probably should have mentioned that earlier), but I recently ran into the same problem on a totally unrelated set of controls that were inherited from a baseclass form. It's easy to blame these problems on possible bugs in the .NET framework, but it's really starting to look that way to me. </p>
[ { "answer_id": 318745, "author": "Vincent Van Den Berghe", "author_id": 39259, "author_profile": "https://Stackoverflow.com/users/39259", "pm_score": 2, "selected": false, "text": "Form Textbox.Size Form Textbox Textbox Textbox.MinimumSize MaximumSize" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22392/" ]
318,644
<p>I am new with Linq and I would like to sort some data that are in the BindingList. Once I did my Linq query, I need to use back the BindingList collection to bind my data.</p> <pre><code> var orderedList = //Here is linq query return (BindingList&lt;MyObject&gt;)orderedList; </code></pre> <p>This compiled but fails in execution, what is the trick?</p>
[ { "answer_id": 318650, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": true, "text": "new BindingList<MyObject>(orderedList.ToList())\n" }, { "answer_id": 538957, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var result = (from x in MyObjects\n where (wherePredicate( x ))\n select new MyObject {\n Prop1 = x.Prop1,\n Prop2 = x.Prop2\n }).ToList();\nreturn new BindingList<MyObject>( result );\n var result = from x in db.MyObjects\n where(Predicate(x))\n select new {\n Prop1 = x.Prop1\n Prop2 = x.Prop2\n };\nreturn new BindingList<MyObject>(result.ToList())\n//creates the error: CS0030 \"Cannot convert type 'AnonymousType#1' to 'MyObject'\n" }, { "answer_id": 22105102, "author": "KyleMit", "author_id": 1366033, "author_profile": "https://Stackoverflow.com/users/1366033", "pm_score": 3, "selected": false, "text": "BindingList static class ExtensionMethods\n{\n public static BindingList<T> ToBindingList<T>(this IEnumerable<T> range)\n {\n return new BindingList<T>(range.ToList());\n }\n}\n\n//use like this:\nvar newBindingList = (from i in new[]{1,2,3,4} select i).ToBindingList();\n Module ExtensionMethods\n <Extension()> _\n Public Function ToBindingList(Of T)(ByVal range As IEnumerable(Of T)) As BindingList(Of T)\n Return New BindingList(Of T)(range.ToList())\n End Function\nEnd Module\n\n'use like this:\nDim newBindingList = (From i In {1, 2, 3, 4}).ToBindingList()\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
318,647
<p>We have a server (written in C and C++) that currently catches a SEGV and dumps some internal info to a file. I would like to generate a core file and write it to disk at the time we catch the SEGV, so our support reps and customers don't have to fuss with ulimit and then wait for the crash to happen again in order to get a core file. We have used the abort function in the past, but it is subject to the ulimit rules and doesn't help.</p> <p>We have some legacy code that reads /proc/pid/map and manually generates a core file, but it is out of date, and doesn't seem very portable (for example, I'm guessing it would not work in our 64 bit builds). What is the best way to generate and dump a core file in a Linux process?</p>
[ { "answer_id": 327744, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "gdb --pid=4049 --batch -ex gcore" }, { "answer_id": 7339557, "author": "Jay Haynberg", "author_id": 933474, "author_profile": "https://Stackoverflow.com/users/933474", "pm_score": 2, "selected": false, "text": "void my_handler(int sig)\n{\n ...\n if (wantCore_ && !fork()) {\n setrlimit(...); // ulimit -Sc unlimited\n sigset(sig, SIG_DFL); // reset default handler\n raise(sig); // doesn't return, generates a core file\n }\n _exit(1);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7893/" ]
318,649
<p>Ok, so after spending a good portion of a day debugging a stupid typing mistake inside a piece of code I am curious as to why the specific actions occured rather than an exception.</p> <p>First of all the problem code.</p> <pre><code>Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn Dim hl As New HyperLink AddHandler hl.DataBinding, AddressOf Me.BindData container.Controls.Add(container) End Sub </code></pre> <p>The obvious problem is that we are trying to add the container to itself, which I would have expected to cause an exception. However, instead it caused the page to prompt the user for their login credentials (Windows authentication in the browser).</p> <p>Does anyone have an idea why this is the case, and why an exception or something else didn't happen?</p> <p><strong>EDIT</strong></p> <p>The reason for the question is that due to this mistake, the page is rendered useless, and prompts for Windows Login, and NOT giving stack overflow exceptions or any other exception.</p>
[ { "answer_id": 327744, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "gdb --pid=4049 --batch -ex gcore" }, { "answer_id": 7339557, "author": "Jay Haynberg", "author_id": 933474, "author_profile": "https://Stackoverflow.com/users/933474", "pm_score": 2, "selected": false, "text": "void my_handler(int sig)\n{\n ...\n if (wantCore_ && !fork()) {\n setrlimit(...); // ulimit -Sc unlimited\n sigset(sig, SIG_DFL); // reset default handler\n raise(sig); // doesn't return, generates a core file\n }\n _exit(1);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
318,657
<p>I recently watched <a href="http://www.youtube.com/watch?v=hp1Y9bhail8" rel="nofollow noreferrer">this youtube tutorial</a> on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn't do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that can be null have getters, and are used in your code? How do you know which value to return by default? Or should I implement this pattern inside all the objects? What if I need to return strings or primitives? I'm talking from a Java perspective.</p> <p><strong>EDIT</strong>: won't I be trading null objects testing for default value testing ? If not , why not ? </p>
[ { "answer_id": 318683, "author": "P Arrayah", "author_id": 33459, "author_profile": "https://Stackoverflow.com/users/33459", "pm_score": 3, "selected": true, "text": "Collections.EMPTY_SET EMPTY_MAP EMPTY_LIST" }, { "answer_id": 318711, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "driveCar Car SlowCar FastCar NullCar NullCar.speed null NullCar.getSpeed" }, { "answer_id": 34315678, "author": "shawnhcorey", "author_id": 604642, "author_profile": "https://Stackoverflow.com/users/604642", "pm_score": 0, "selected": false, "text": "A B NullA NullB" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
318,666
<p>I understand that any init... method initializes a new object and that NSString stringWithString makes a copy of the parameter string as a new object. I also understand that being the objects' owner, I can control the release/deallocation of any objects that I allocate. What I don't understand is when would I use the stringWithString method since any local variable assigned that way would have it's memory "owned" by NSString instead of the local class.</p> <p>The "Programming in Objective C" book by Kochan (1st ed) uses the following code (see pages 342-344) to explain that the initWithString is preferable to stringWithString because the AddressCard class would own the name variable contents. Also, I don't get any errors making repeated calls to the setName version with the stringWithString method. TIA!!</p> <pre><code>//header file has appropriate declarations but not included here: #import "AddressCard.h" @implementation AddressCard; -(NSString *) name { return name; } //Recommended code: -(void) setName: (NSString *) theName { [name release] name = [[NSString alloc] initWthString: theName]; } //Incorrect code according to Kochan: -(void) setName: (NSString *) theName { [name release] name = [NSString stringWthString: theName]; } //rest of class implementation code snipped @end </code></pre>
[ { "answer_id": 318702, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 0, "selected": false, "text": "name = [[NSString stringWithString: theName] retain];\n" }, { "answer_id": 318704, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 6, "selected": true, "text": "alloc copy copyWithZone new retain release autorelease release stringWithString: copy alloc retain new setName: alloc initWithString: copy" }, { "answer_id": 318784, "author": "Boaz Stuller", "author_id": 1464654, "author_profile": "https://Stackoverflow.com/users/1464654", "pm_score": 3, "selected": false, "text": "-(void) setName: (NSString *) theName\n{\n if (theName == name) return; // if they're equal, no need to do anything further\n [name release];\n name = [theName copy]; // sets name to nil if theName is nil\n}\n" }, { "answer_id": 319087, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 0, "selected": false, "text": "stringWithString: NSString NSAutoreleasePool retain stringWithString: release retain name name NSString retain NSString initWithString:" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9711/" ]
318,673
<p>I use Thunderbird to receive email using POP3. I have Thurnderbird configured to leave email on the server. Lets say one day I uses POP3 to retrieve (<code>RETR</code>) 10 email messages, then I logout for the night. Overnight 10 more messages are sent to my mailbox. When I fire up Thunderbird the next morning, the <code>STAT</code> command should show 20 messages. However, Thunderbird should not download the first 10 messages; it should start at message 11 (or the unique identifier or UID for message 11). Thunderbird will send a POP3 <code>UIDL</code> command, then compare the UID's to the UID of the last message Thunderbird retrieved yesterday. It will find that the last UID matches the UIDL list for message 10, then Thunderbird will <code>RETR 11</code>, <code>RETR 12</code>, and so on.</p> <p>In my case, the POP3 <code>STAT</code> command shows that I have 5379 messages on the POP server. I have already received about 5000 of them. For some reason Thunderbird wants to download all 5379 messages instead of starting at 5001. I am trying to debug this and was looking for the UID that Thunderbird thinks was the last message retrieved.</p> <p>Does anyone know where Thunderbird (on Windows) stores the last UID, which it will use to compare to the UIDL (list)?</p> <p>Is there a way to manually set it so I can force Thunderbird to start retrieving somewhere close to 5001?</p>
[ { "answer_id": 554844, "author": "Pauld", "author_id": 31241, "author_profile": "https://Stackoverflow.com/users/31241", "pm_score": 3, "selected": true, "text": "UIDL popstate.dat popstate.dat RETR popstate.dat d f popstate.dat popstate.dat popstate.dat popstate.dat popstate.dat" }, { "answer_id": 67317250, "author": "Magentron", "author_id": 832620, "author_profile": "https://Stackoverflow.com/users/832620", "pm_score": 0, "selected": false, "text": "usage: rebuild_popstate.php [-d] [-i n] [-s] [-v] [-f file] server [ port ]\n -c CRLF flag, use when talking to Windows servers\n -d debug flag\n -f output filename (if popstate.dat, Thunderbird needs to be closed!)\n -i ignore the last n messages (for if you don't have them yet)\n -s use for secure POP3 (SSL/TLS)\n -v verbose flag\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31241/" ]
318,675
<p>Is there a way to allow a flex application to have a dynamic height while embedded in an HTML wrapper?</p> <p>I want the Flex application to grow in height in a way that it will not cause vertical scroll bars.</p>
[ { "answer_id": 320606, "author": "ianmjones", "author_id": 3023, "author_profile": "https://Stackoverflow.com/users/3023", "pm_score": 2, "selected": false, "text": "percentWidth=\"100\"\npercentHeight=\"100\"\n" }, { "answer_id": 901669, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "private var _lastMeasuredHeight:int;\n\noverride protected function measure():void\n{\n super.measure();\n if (measuredHeight != _lastMeasuredHeight)\n {\n _lastMeasuredHeight = measuredHeight;\n if (ExternalInterface.available)\n {\n ExternalInterface.call(\"setFlashHeight\", measuredHeight);\n }\n }\n}\n function setFlashHeight(newHeight){\n //assuming flashDiv is the name of the div contains flex app.\n var flashContentHolderDiv = document.getElementById('flashDiv'); \n flashContentHolderDiv.style.height = newHeight;\n}\n" }, { "answer_id": 4198570, "author": "Khaled", "author_id": 510012, "author_profile": "https://Stackoverflow.com/users/510012", "pm_score": 0, "selected": false, "text": "<mx:Application xmlns:fx=\"http://ns.adobe.com/mxml/2009\" >\n\n</mx:Application>\n <s:Application xmlns:fx=\"http://ns.adobe.com/mxml/2009\" >\n\n</s:Application>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
318,677
<p>Let's say I create a website like StackOverFlow and decide to use OpenID. What's to prevent me, or anyone else for that matter, from phishing the ID's? That is, how can you truly know that any website is using OpenID and not pretending to? And how do you protect myself against this?</p> <p>Expanding on this, let's say one site did compromise your openID credentials, couldn't they use it on every other site using openID (a global password hack)? Wouldn't then the security of your openID then only be as strong as the weakest website/provider? </p>
[ { "answer_id": 318688, "author": "phihag", "author_id": 35070, "author_profile": "https://Stackoverflow.com/users/35070", "pm_score": 3, "selected": false, "text": "https://www.google.com/accounts/o8/id" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,700
<p>I am working with a set of data that I have converted to a list of dictionaries</p> <p>For example one item in my list is </p> <pre><code>{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} </code></pre> <p>Per request </p> <p>The second item in my list could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006', 'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'} </code></pre> <p>The third item could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005', 'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'} </code></pre> <p>The fourth item could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'} </code></pre> <p>The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be)</p> <p>I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way?</p> <p>I don't want to put this into a database because it is not permanent. </p> <p>I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.</p>
[ { "answer_id": 318719, "author": "rebra", "author_id": 2282296, "author_profile": "https://Stackoverflow.com/users/2282296", "pm_score": 1, "selected": false, "text": "[('reportDate', u'R20080501'), ('idnum', u'1078099'), ...etc]\n dict()" }, { "answer_id": 318722, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 1, "selected": false, "text": "data = {'reportDate': u'R20070501', 'idnum': u'1078099', \n 'columnLabel': u'2005', 'actionDate': u'C20070627', \n 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}\ndataOrder = ['reportDate', 'idnum', 'columnLabel', \n 'actionDate', 'data', 'rowLabel']\n\nfor key in dataOrder:\n print key, data[key]\n" }, { "answer_id": 318864, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 4, "selected": true, "text": ">>> import pickle\n>>> d1 = {1:'one', 2:'two', 3:'three'}\n>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}\n>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'}\n>>> data = [d1, d2, d3]\n>>> out = open('data.pickle', 'wb')\n>>> pickle.dump(data, out)\n>>> out.close()\n>>> input = open('data.pickle') \n>>> data2 = pickle.load(input)\n>>> data == data2\nTrue\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30105/" ]
318,707
<p>I have one java program that has to be compiled as 1.4, and another program that could be anything (so, 1.4 or 1.6), and the two need to pass serialized objects back and forth. If I define a serializable class in a place where both programs can see it, will java's serialization still work, or do I need 1.6-1.6 or 1.4-1.4 only?</p>
[ { "answer_id": 318720, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "static final long serialVersionUID" }, { "answer_id": 318735, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "serialVersionUID" }, { "answer_id": 318806, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 2, "selected": false, "text": "serialVersionUID myjar.mypackage.myclass myjar.mypackage.myclass Serializable serialVersionUID" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
318,715
<p>My webpage is suffering from two IE6 rendering bugs. Each of them have workarounds, but unfortunately said workarounds are incompatible with each other.</p> <p><a href="http://www.control-v.net/stackoverflow/318715.html" rel="nofollow noreferrer">Here's a minimized test case</a>. The behavior in Firefox/Safari is the desired/correct one. IE7 is unknown, since I don't have access to it right now.</p> <p>First bug: #content has overflow: auto and contains a relatively-positioned div. <a href="http://rowanw.com/bugs/overflow_relative.htm" rel="nofollow noreferrer">IE6 incorrectly gives the relatively-positioned div a 'fixed' appearance.</a> Workaround: Set position: relative on #content.</p> <p>Second bug: The page sometimes shows a modal popup. The z-index on the popup and background are set really high to stop anything behind them from being interacted with. This works fine until I set position:relative on #content, which makes IE6 <a href="http://www.last-child.com/conflicting-z-index-in-ie6/" rel="nofollow noreferrer">treat the z-index property completely wrong</a>.</p> <p>How can I make these bugs play nicely with each other? (Note: Remotely formatting the hard drives of users still running IE6 is not an option, much to my dismay.)</p> <p><b>Edit:</b> <a href="http://www.control-v.net/stackoverflow/318715-2.html" rel="nofollow noreferrer">Here's a second test case</a> that shows what happens when I apply position: relative to content. The first bug ('fixed' appearance of #content-header) is solved, but it causes the z-index bug to kick in and mess up the modal background.</p>
[ { "answer_id": 320641, "author": "Chrysaor", "author_id": 40992, "author_profile": "https://Stackoverflow.com/users/40992", "pm_score": 0, "selected": false, "text": "<!--[if lt IE 8]><script src=\"http://ie7-js.googlecode.com/svn/version/2.0(beta)/IE7.js\" type=\"text/javascript\"></script><![endif]-->\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160/" ]
318,716
<p>I just launched my <a href="http://www.dudlers.com" rel="noreferrer">tiny webapp</a> on my humble dedicated server (Win2003)... running ASP.NET MVC, LINQ2SQL, SQL Express 2005, and IIS6 (setup with <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true" rel="noreferrer">wildcard mapping</a>)</p> <p>The website runs smoothly 90% of the times. However, on <em>relatively</em> high traffic, LINQ2SQL throws the error: Specified cast is not valid</p> <p>This error is ONLY thrown at high traffic. I have <strong>NO IDEA</strong> how or exactly why this happens. Caching did not remove this problem entirely.</p> <p>Anyone seen this problem before? are there any secret SQL Server tweaking I should've done? Or at least, <strong>any ideas on how to diagnose this issue?</strong> because i'm out!</p> <p>Naimi</p> <p>Stacktrace (from Event Log):</p> <pre> at System.Data.SqlClient.SqlBuffer.get_SqlGuid() at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i) at Read_Friend(ObjectMaterializer`1 ) at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext() at Dudlers.Web.Models.DudlersDataContext.GetFriendRequests(Guid userId) in C:\Web\Models\DudlersDataContext.cs:line 562 at Dudlers.Web.Controllers.BaseController.View(String viewName, String masterName, Object viewData) in C:\Web\Controllers\BaseController.cs:line 39 at System.Web.Mvc.Controller.View(String viewName) at Dudlers.Web.Controllers.CatController.Index() in C:\Web\Controllers\CatController.cs:line 25 at lambda_method(ExecutionScope , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(MethodInfo methodInfo, IDictionary`2 parameters) at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.b__8() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.c__DisplayClassd.b__a() at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(MethodInfo methodInfo, IDictionary`2 parameters, IList`1 filters) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) </pre>
[ { "answer_id": 780421, "author": "Atle", "author_id": 58170, "author_profile": "https://Stackoverflow.com/users/58170", "pm_score": 4, "selected": true, "text": "System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.\n at System.Data.SqlClient.SqlBuffer.get_String()\n at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)\n at Read_Person(ObjectMaterializer`1 )\n at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\n at RF.Ias.Services.Person.BusinessLogic.PersonTransactionScripts.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)\n at CompositionAopProxy_5b0727341ad64f29b816c1b73d11dd44.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)\n at RF.Ias.Services.Person.ServiceImplementation.PersonService.GetPersons(GetPersonRequest request)\n\n\nSystem.InvalidCastException: Specified cast is not valid.\n at System.Data.SqlClient.SqlBuffer.get_Int32()\n at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)\n at Read_GetRolesForOrganisationResult(ObjectMaterializer`1 )\n at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\n at RF.Ias.Services.Role.DataAccess.RoleDataAccess.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)\n at RF.Ias.Services.Role.BusinessLogic.RoleTransactionScripts.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)\n at CompositionAopProxy_4bd29c6074f54d10a2c09bd4ab27ca66.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)\n at RF.Ias.Services.Role.ServiceImplementation.RoleService.GetRolesForOrganisation(GetRolesForOrganisationRequest request)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2721/" ]
318,742
<p>I was using jQuery plugins to create a rounded corner for my <code>&lt;li&gt;</code>, but it was not working on a lot of browsers and didn't support mouse over.</p> <p>I am wondering what is the best way to use two images (left corner and right corner) as the left and right side with using <code>&lt;li&gt;</code>.</p>
[ { "answer_id": 318754, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": -1, "selected": true, "text": "<li>\n <div class=\"lefcorner\"></div>\n <div class='liContent'>Foo</div>\n <div class='rightcorner'></div>\n</li>\n" }, { "answer_id": 318771, "author": "seanb", "author_id": 3354, "author_profile": "https://Stackoverflow.com/users/3354", "pm_score": 1, "selected": false, "text": "<li><a><span>Your text here</span></a></li> \n a:hover{some rules here} \na:hover span{some more rules here} \n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,756
<p>Lets say you have a:</p> <pre><code>List&lt;string&gt; los = new List&lt;string&gt;(); </code></pre> <p>In this crazy functional world we live in these days which one of these would be best for creating one string by concatenating these:</p> <pre><code>String.Join(String.Empty, los.ToArray()); StringBuilder builder = new StringBuilder(); los.ForEach(s =&gt; builder.Append(s)); string disp = los.Aggregate&lt;string&gt;((a, b) =&gt; a + b); </code></pre> <p>or Plain old StringBuilder foreach</p> <p>OR is there a better way?</p>
[ { "answer_id": 318773, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 8, "selected": false, "text": "String.Join(String.Empty, los.ToArray());\n .ToArray() String.Join(String.Empty, los);\n" }, { "answer_id": 319545, "author": "Pent Ploompuu", "author_id": 17122, "author_profile": "https://Stackoverflow.com/users/17122", "pm_score": 6, "selected": false, "text": "string.Concat(los.ToArray());\n" }, { "answer_id": 7403919, "author": "mnieto", "author_id": 777551, "author_profile": "https://Stackoverflow.com/users/777551", "pm_score": 4, "selected": false, "text": "String.Join<string>(String.Empty, los);\n" }, { "answer_id": 30381350, "author": "landrady", "author_id": 3183484, "author_profile": "https://Stackoverflow.com/users/3183484", "pm_score": 3, "selected": false, "text": "los.Aggregate((current, next) => current + \",\" + next);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28717/" ]
318,761
<p>As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.</p> <p><strong>My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism?</strong> That way, the list gets populated dynamically as we add new types.</p> <p>Here is an <strong>example</strong>. <em>Please no comment about how loading images can be done other ways, we know</em>.</p> <p>Suppose we have the following IImageFileFormat interface:</p> <pre><code>public interface IImageFileFormat { string[] SupportedFormats { get; }; Image Load(string fileName); void Save(Image image, string fileName); } </code></pre> <p>Different classes will implement this interface:</p> <pre><code>[FileFormat] public class BmpFileFormat : IImageFileFormat { ... } [FileFormat] public class JpegFileFormat : IImageFileFormat { ... } </code></pre> <p>When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.</p> <pre><code>class ImageLoader { public Image Load(string fileName) { return FindFormat(fileName).Load(fileName); } public void Save(Image image, string fileName) { FindFormat(fileName).Save(image, fileName); } IImageFileFormat FindFormat(string fileName) { string extension = Path.GetExtension(fileName); return formats.First(f =&gt; f.SupportedExtensions.Contains(extension)); } private List&lt;IImageFileFormat&gt; formats; } </code></pre> <p>I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.</p> <p>By hand:</p> <pre><code>public ImageLoader() { formats = new List&lt;IImageFileFormat&gt;(); formats.Add(new BmpFileFormat()); formats.Add(new JpegFileFormat()); } </code></pre> <p>By reflection:</p> <pre><code>public ImageLoader() { formats = new List&lt;IImageFileFormat&gt;(); foreach(Type type in Assembly.GetExecutingAssembly().GetTypes()) { if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length &gt; 0) { formats.Add(Activator.CreateInstance(type)) } } } </code></pre> <p>I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.</p> <p>Please discuss.</p>
[ { "answer_id": 319234, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 1, "selected": false, "text": "<interface>" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42/" ]
318,766
<p>Here's the purpose of my console program: Make a web request > Save results from web request > Use QueryString to get next page from web request > Save those results > Use QueryString to get next page from web request, etc.</p> <p>So here's some pseudocode for how I set the code up.</p> <pre><code> for (int i = 0; i &lt; 3; i++) { strPageNo = Convert.ToString(i); //creates the url I want, with incrementing pages strURL = "http://www.website.com/results.aspx?page=" + strPageNo; //makes the web request wrGETURL = WebRequest.Create(strURL); //gets the web page for me objStream = wrGETURL.GetResponse().GetResponseStream(); //for reading web page objReader = new StreamReader(objStream); //-------- // -snip- code that saves it to file, etc. //-------- objStream.Close(); objReader.Close(); //so the server doesn't get hammered System.Threading.Thread.Sleep(1000); } </code></pre> <p>Pretty simple, right? <b>The problem is</b>, even though it increments the page number to get a different web page, I'm getting the <em>exact same results page</em> each time the loop runs. </p> <p><code>i</code> IS incrementing correctly, and I can cut/paste the url <code>strURL</code> creates into a web browser and it works just fine.</p> <p>I can manually type in <code>&amp;page=1</code>, <code>&amp;page=2</code>, <code>&amp;page=3</code>, and it'll return the correct pages. Somehow putting the increment in there screws it up.</p> <p>Does it have anything to do with sessions, or what? I make sure I close both the stream and the reader before it loops again...</p>
[ { "answer_id": 318824, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 0, "selected": false, "text": "http://www.website.com/results.aspx&page=\n http://www.website.com/results.aspx?page=\n" }, { "answer_id": 318961, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 2, "selected": false, "text": "var urls = new [] { \"http://www.google.com\", \"http://www.yahoo.com\", \"http://www.live.com\" };\n\nforeach (var url in urls)\n{\n WebRequest request = WebRequest.Create(url);\n using (Stream responseStream = request.GetResponse().GetResponseStream())\n using (Stream outputStream = new FileStream(\"file\" + DateTime.Now.Ticks.ToString(), FileMode.Create, FileAccess.Write, FileShare.None))\n {\n const int chunkSize = 1024;\n byte[] buffer = new byte[chunkSize];\n int bytesRead;\n while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)\n {\n byte[] actual = new byte[bytesRead];\n Buffer.BlockCopy(buffer, 0, actual, 0, bytesRead);\n outputStream.Write(actual, 0, actual.Length);\n }\n }\n Thread.Sleep(1000);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557/" ]
318,775
<p>Are there any good reasons not to use \u0000 as a delimiter within a Java String? I would be encoding and decoding the string myself.</p> <p>This is for saving a list of user-inputted (I'm expecting input to be typed?) strings to an Eclipse preference and reading it back. The list may be variable size so I don't think I can save each item to its own preference.</p>
[ { "answer_id": 318797, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "ArrayList<String> \\u0000" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40443/" ]
318,776
<p>I have following POJOs:</p> <pre><code>class Month { long id; String description; List&lt;Day&gt; days; // always contains 29, 30 or 31 elements } class Day { byte nr; // possible values are 1-31 String info; } </code></pre> <p>Is there a way to store these objects into following DB structure using JPA+Hibernate:</p> <p>Table MONTHS:</p> <pre>id;description;</pre> <p>Table DAYS:</p> <pre>id-of-month;nr-of-day;info;</pre> <p>Any better solution for this situation?</p>
[ { "answer_id": 340018, "author": "Vilmantas Baranauskas", "author_id": 11662, "author_profile": "https://Stackoverflow.com/users/11662", "pm_score": 0, "selected": false, "text": "class Month {\n long id;\n String description;\n\n @CollectionOfElements(fetch = FetchType.EAGER)\n @IndexColumn(name = \"nr-of-day\")\n List<Day> days; // always contains 29, 30 or 31 elements\n}\n\n@Embeddable\nclass Day {\n byte nr; // possible values are 1-31\n String info;\n}\n" }, { "answer_id": 504660, "author": "mxc", "author_id": 61636, "author_profile": "https://Stackoverflow.com/users/61636", "pm_score": 1, "selected": false, "text": "class Month {\n @Id\n private long id;\n private String description;\n @OneToMany(mappedBy=\"month\",fetchType=Lazy)\n private List<Day> days;\n\n}\n class Day {\n @Id\n private int id;\n private Month month;\n private byte nr; // possible values are 1-31\n private String info;\n}\n" }, { "answer_id": 1025772, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "@Id\n@GeneratedValue\nprivate Integer id;\n\n\n// one way relationship\n@OneToMany(cascade=CascadeType.PERSIST)\n@JoinColumn(name=\"MONTH_ID\")\n@IndexColumn(name=\"childIndex\")\nprivate List<Day> dayList = new ArrayList<Day>();\n @EmbeddedId // composed by month foreign key and index column\nprivate DayId id;\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662/" ]
318,777
<p>I am trying to map a virtual keycode to a char.</p> <p>My code uses ProcessCmdKey to listen to WM_KEYDOWN which gives me access to the key pressed. For example, when I press single quote I get a key of 222 which I want to have it mapped to keychar 39 which represents... you guessed it... single quote.</p> <p>My dev context is: - .net Framework 2.0 - UserControl placed in a lot of places</p> <p>Do you know the answer to the question?</p>
[ { "answer_id": 320878, "author": "Horas", "author_id": 12333, "author_profile": "https://Stackoverflow.com/users/12333", "pm_score": 5, "selected": false, "text": "MapVirtualKey DllImport enum [DllImport(\"user32.dll\")]\nstatic extern int MapVirtualKey(uint uCode, uint uMapType);\n protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n {\n const int WM_KEYDOWN = 0x100;\n\n if (msg.Msg == WM_KEYDOWN)\n { \n // 2 is used to translate into an unshifted character value \n int nonVirtualKey = MapVirtualKey((uint)keyData, 2);\n\n char mappedChar = Convert.ToChar(nonVirtualKey);\n }\n\n return base.ProcessCmdKey(ref msg, keyData);\n }\n" }, { "answer_id": 320914, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 6, "selected": false, "text": "KeysConverter kc = new KeysConverter();\nstring keyChar = kc.ConvertToString(keyData);\n" }, { "answer_id": 28760963, "author": "SongWithoutWords", "author_id": 4476886, "author_profile": "https://Stackoverflow.com/users/4476886", "pm_score": 3, "selected": false, "text": "public static char ToChar(this Keys key)\n{\n char c = '\\0';\n if((key >= Keys.A) && (key <= Keys.Z))\n {\n c = (char)((int)'a' + (int)(key - Keys.A));\n }\n\n else if((key >= Keys.D0) && (key <= Keys.D9))\n {\n c = (char)((int)'0' + (int)(key - Keys.D0));\n }\n\n return c;\n}\n" }, { "answer_id": 38787314, "author": "Ivan Petrov", "author_id": 925308, "author_profile": "https://Stackoverflow.com/users/925308", "pm_score": 5, "selected": false, "text": "\n public string KeyCodeToUnicode(Keys key)\n {\n byte[] keyboardState = new byte[255];\n bool keyboardStateStatus = GetKeyboardState(keyboardState);\n\n if (!keyboardStateStatus)\n {\n return \"\";\n }\n\n uint virtualKeyCode = (uint)key;\n uint scanCode = MapVirtualKey(virtualKeyCode, 0);\n IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);\n\n StringBuilder result = new StringBuilder();\n ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, (uint)0, inputLocaleIdentifier);\n\n return result.ToString();\n }\n\n [DllImport(\"user32.dll\")]\n static extern bool GetKeyboardState(byte[] lpKeyState);\n\n [DllImport(\"user32.dll\")]\n static extern uint MapVirtualKey(uint uCode, uint uMapType);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr GetKeyboardLayout(uint idThread);\n\n [DllImport(\"user32.dll\")]\n static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl);\n\n" }, { "answer_id": 45055627, "author": "edupeux", "author_id": 8295201, "author_profile": "https://Stackoverflow.com/users/8295201", "pm_score": 3, "selected": false, "text": "public static string GetKeyString(Key key, ModifierKeys modifiers)\n{\n string result = \"\";\n if (key != Key.None)\n {\n // Setup modifiers\n if (modifiers.HasFlag(ModifierKeys.Control))\n result += \"Ctrl + \";\n if (modifiers.HasFlag(ModifierKeys.Alt))\n result += \"Alt + \";\n if (modifiers.HasFlag(ModifierKeys.Shift))\n result += \"Shift + \";\n // Get string representation\n string keyStr = key.ToString();\n int keyInt = (int)key;\n // Numeric keys are returned without the 'D'\n if (key >= Key.D0 && key <= Key.D9)\n keyStr = char.ToString((char)(key - Key.D0 + '0'));\n // Char keys are returned directly\n else if (key >= Key.A && key <= Key.Z)\n keyStr = char.ToString((char)(key - Key.A + 'A'));\n // If the key is a keypad operation (Add, Multiply, ...) or an 'Oem' key, P/Invoke\n else if ((keyInt >= 84 && keyInt <= 89) || keyInt >= 140)\n keyStr = KeyCodeToUnicode(key);\n result += keyStr;\n }\n return result;\n}\n\nprivate static string KeyCodeToUnicode(Key key)\n{\n byte[] keyboardState = new byte[255];\n bool keyboardStateStatus = GetKeyboardState(keyboardState);\n\n if (!keyboardStateStatus)\n {\n return \"\";\n }\n\n uint virtualKeyCode = (uint)KeyInterop.VirtualKeyFromKey(key);\n uint scanCode = MapVirtualKey(virtualKeyCode, 0);\n IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);\n\n StringBuilder result = new StringBuilder();\n ToUnicodeEx(virtualKeyCode, scanCode, new byte[255], result, (int)5, (uint)0, inputLocaleIdentifier);\n\n return result.ToString();\n}\n\n[DllImport(\"user32.dll\")]\nstatic extern bool GetKeyboardState(byte[] lpKeyState);\n\n[DllImport(\"user32.dll\")]\nstatic extern uint MapVirtualKey(uint uCode, uint uMapType);\n\n[DllImport(\"user32.dll\")]\nstatic extern IntPtr GetKeyboardLayout(uint idThread);\n\n[DllImport(\"user32.dll\")]\nstatic extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl);\n" }, { "answer_id": 61772220, "author": "Francesco Bonizzi", "author_id": 1090403, "author_profile": "https://Stackoverflow.com/users/1090403", "pm_score": -1, "selected": false, "text": "public partial class MainWindow : Window\n{\n public MainWindow()\n {\n InitializeComponent();\n TextInput += MainWindow_TextInput;\n }\n\n private void MainWindow_TextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)\n {\n txtInput.Text += e.Text;\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12333/" ]
318,789
<p>Please note - I am not looking for the "right" way to open/read a file, or the way I should open/read a file every single time. I am just interested to find out what way most people use, and maybe learn a few new methods at the same time :)*</p> <p>A very common block of code in my Perl programs is opening a file and reading or writing to it. I have seen so many ways of doing this, and my style on performing this task has changed over the years a few times. I'm just wondering what the <em>best</em> (if there is a best way) method is to do this?</p> <p>I used to open a file like this:</p> <pre><code>my $input_file = "/path/to/my/file"; open INPUT_FILE, "&lt;$input_file" || die "Can't open $input_file: $!\n"; </code></pre> <p>But I think that has problems with error trapping.</p> <p>Adding a parenthesis seems to fix the error trapping:</p> <pre><code>open (INPUT_FILE, "&lt;$input_file") || die "Can't open $input_file: $!\n"; </code></pre> <p>I know you can also assign a filehandle to a variable, so instead of using "INPUT_FILE" like I did above, I could have used $input_filehandle - is that way better?</p> <p>For reading a file, if it is small, is there anything wrong with globbing, like this?</p> <pre><code>my @array = &lt;INPUT_FILE&gt;; </code></pre> <p>or</p> <pre><code>my $file_contents = join( "\n", &lt;INPUT_FILE&gt; ); </code></pre> <p>or should you always loop through, like this:</p> <pre><code>my @array; while (&lt;INPUT_FILE&gt;) { push(@array, $_); } </code></pre> <p>I know there are so many ways to accomplish things in perl, I'm just wondering if there are preferred/standard methods of opening and reading in a file?</p>
[ { "answer_id": 318822, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 7, "selected": true, "text": "open( my $input_fh, \"<\", $input_file ) || die \"Can't open $input_file: $!\";\n my @lines = <$input_fh>;\n my $text = join('', <$input_fh>);\n" }, { "answer_id": 318843, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": false, "text": "use strict;\nuse warnings;\nuse Carp;\nuse English qw( -no_match_vars );\nmy $data = q{};\n{\n local $RS = undef; # This makes it just read the whole thing,\n my $fh;\n croak \"Can't open $input_file: $!\\n\" if not open $fh, '<', $input_file;\n $data = <$fh>;\n croak 'Some Error During Close :/ ' if not close $fh;\n}\n perlcritic --brutal $input_file" }, { "answer_id": 319529, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 3, "selected": false, "text": "use FileHandle;\n...\nmy $handle = FileHandle->new( \"< $file_to_read\" );\ncroak( \"Could not open '$file_to_read'\" ) unless $handle;\n...\nmy $line1 = <$handle>;\nmy $line2 = $handle->getline;\nmy @lines = $handle->getlines;\n$handle->close;\n" }, { "answer_id": 319729, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "$files_in_the_known_universe * $perl_programmers\n use strict;\nuse warnings;\n\nuse IO::File;\n\nmy $file = shift @ARGV or die \"what file?\";\n\nmy $fh = IO::File->new( $file, '<' ) or die \"$file: $!\";\nmy $data = do { local $/; <$fh> };\n$fh->close();\n\n# If you didn't just run out of memory, you have:\nprintf \"%d characters (possibly bytes)\\n\", length($data);\n my $fh = IO::File->new( $file, '<' ) or die \"$file: $!\";\nwhile ( my $line = <$fh> ) {\n print \"Better than cat: $line\";\n}\n$fh->close();\n" }, { "answer_id": 320530, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 3, "selected": false, "text": "open (FILEIN, \"<\", $inputfile) or die \"...\";\nmy @FileContents = <FILEIN>;\nclose FILEIN;\n File::Slurp Tie::File" }, { "answer_id": 327489, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 4, "selected": false, "text": "use autodie;\n\nopen(my $image_fh, '<', $filename);\n or die ... < > | open strict _fh" }, { "answer_id": 328258, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$text = do {local(@ARGV, $/) = $file ; <>};\n $text = load_file($file);\nsub load_file {local(@ARGV, $/) = @_; <>}\n" }, { "answer_id": 330017, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 1, "selected": false, "text": "$data = readline!open(!((*{!$_},$/)=\\$_)) for \"filename\";\n" }, { "answer_id": 330465, "author": "Ape-inago", "author_id": 42082, "author_profile": "https://Stackoverflow.com/users/42082", "pm_score": 2, "selected": false, "text": "|| open INPUT_FILE, \"<$input_file\"\n or die \"Can't open $input_file: $!\\n\";\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40619/" ]
318,793
<p>Here are the errors:</p> <pre> $ perl ftper.pl Use of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. </pre> <p>Here is the Perl/Tk code:</p> <pre><code>#! /usr/bin/perl -w use strict; use Tk; use Tk::Scale; use File::DosGlob 'glob'; ##################################################################### # Define variables # ##################################################################### my $UserID; my $Password; my $BnsNode; my $Status_msg = "BUILD SCRIPT!"; ##################################################################### # Window variables # ##################################################################### my $mw; my $frmUserID; my $lblUserID; my $frmPassword; my $lblPassword; my $edtUserID; my $edtPassword; my $frmTop; my $frmBig; my $frmButtonLine; my $btnExit; my $btnSubmit; my $lblStatus; my $lblUnixNode; my $frmUnixNode; my $edtUnixNode; ################################################################# # Main Logic # ################################################################# init_mainwindow(); MainLoop; ################################################################# # init_mainwindow # ################################################################# sub init_mainwindow { $mw = MainWindow-&gt;new; $mw-&gt;title("BUILD"); $mw-&gt;resizable(100, 100); $mw-&gt;geometry("+175+100"); # Top Level frame for top section of form. $frmTop = $mw-&gt;Frame(-bd =&gt; 2, -relief =&gt; 'ridge') -&gt;pack(-side =&gt; 'top', -fill =&gt; 'x', -pady =&gt; 3); $frmUserID = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblUserID = $frmUserID-&gt;Label(-text =&gt; "Unix User ID:") -&gt;pack(-side =&gt; 'left'); $edtUserID = $frmUserID-&gt;Entry(-textvariable =&gt; \$UserID, -background =&gt; 'white')-&gt;pack(-side =&gt; 'left'); $frmUnixNode = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblUnixNode = $frmUserID-&gt;Label(-text =&gt; "BNS Number") -&gt;pack(-side =&gt; 'left'); $edtUnixNode = $frmUserID-&gt;Entry(-textvariable =&gt; \$BnsNode, -background =&gt; 'white')-&gt;pack(-side =&gt; 'left'); $frmPassword = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblPassword = $frmPassword-&gt;Label( -text =&gt; "Password: ")-&gt;pack(-side =&gt; 'left'); $edtPassword = $frmPassword-&gt;Entry(-textvariable =&gt; \$Password, -background =&gt; 'white', -show =&gt; "*") -&gt;pack(-side =&gt; 'left'); # Top Level frame for bottom section of form. $frmButtonLine = $mw-&gt;Frame(-bd =&gt; 2, -relief =&gt; 'ridge') -&gt;pack(-side =&gt; 'top', -fill =&gt; 'x', -pady =&gt; 3); $btnExit = $frmButtonLine-&gt;Button(-text =&gt; "Exit", -command =&gt; \&amp;close_mw, -width =&gt; 6)-&gt;pack( -side =&gt; 'right', -padx =&gt; 1); $btnSubmit = $frmButtonLine-&gt;Button(-text =&gt; "Run Script", -command =&gt; \&amp;execute_script, -width =&gt; 6)-&gt;pack( -side =&gt; 'right', -padx =&gt; 1); $lblStatus = $mw-&gt;Label(-textvariable =&gt; \$Status_msg, -borderwidth =&gt; 2, -relief =&gt; 'groove') -&gt;pack(-fill =&gt; 'x', -side =&gt; 'bottom'); $edtUserID-&gt;focus; } ##################################################################### # excute_script # ##################################################################### sub execute_script { unless (defined($UserID)) { update_status("Must enter a user id!"); $edtUserID-&gt;focus; return 0; } unless (defined($Password)) { update_status("Must enter a password!"); $edtPassword-&gt;focus; return 0; } update_status("$BnsNode ,$UserID "); } ##################################################################### # close_mw # ##################################################################### sub close_mw { $mw-&gt;destroy; } ##################################################################### # update_status # ##################################################################### sub update_status { my ($msg) = @_; $Status_msg = $msg; $lblStatus -&gt; update; } </code></pre>
[ { "answer_id": 318929, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "undef $id $h{$id} delete $h{$id} $id" }, { "answer_id": 318932, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 2, "selected": false, "text": "-w use warnings;" }, { "answer_id": 318937, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "$id $id" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34531/" ]
318,816
<p>How would I go about setting different authentication tags for different parts of my web app? Say I have:</p> <pre><code>/ /folder1/ /folder2/ </code></pre> <p>Would it be possible to specify different <code>&lt;authentication/&gt;</code> tags for each folder?</p> <p>I want folder1 to use Windows authentication but folder2 use Forms authentication. </p> <p>I tried doing in a <code>&lt;location/&gt;</code> tag but it doesn't look like you can have <code>&lt;authentication/&gt;</code> tags in a <code>&lt;location/&gt;</code> tags, at least not via VS 2008 with it's built in webserver.</p> <p>This errors out saying - Error 3 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. </p> <pre><code>&lt;location path="/folder1"&gt; &lt;system.web&gt; &lt;authentication mode="Forms" /&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre>
[ { "answer_id": 319035, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 1, "selected": false, "text": "<allow users=\"*\" />\n" }, { "answer_id": 320259, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 5, "selected": true, "text": "<authentication /> web.config" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ]
318,818
<p>I just had to add a checkbox to an application that was written before I got here, and it was way more difficult than it had to be because the app uses some third-party LayoutManager that attempts to do pseudo-absolute, gridlike positioning. The API was terrible, it takes position-designating strings that are comma-delimited lists of two, four, or six parameters (I still don't know why this varies), and I would much rather let the LayoutManager handle a lot of this grunt work, anyway. I've always felt like allowing Swing to position things itself led to better organization than anything I could generate. I felt the same way with CGI applications, where other than occasionally grouping checkboxes or radio boxes with tables I pretty much just let the browser flow and wrap things however the user wants.</p> <p>Are the LayoutManager implementations included with Swing adequate, or is it really necessary to incorporate this kind of absolute control to force the layout to be exactly what you want (and give you a million more decisions to make)?</p>
[ { "answer_id": 416082, "author": "tddmonkey", "author_id": 51577, "author_profile": "https://Stackoverflow.com/users/51577", "pm_score": 0, "selected": false, "text": "FormPanel panel = new FormPanel( \"myDialog.jfrm\" );\nadd(panel);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
318,831
<p>I'd like to programatically determine the encoding of a page via JavaScript, or some other API from a browser. The reason I want this information is because I am attempting to fuzz major browsers on what character encodings they support, and obviously just because I sent the appropriate "Content-Type" doesn't mean that the browser will do the right thing with the encoding. Any other possible methods would be welcome, but I would rather not click "Page Info" for 50+ character encodings.</p>
[ { "answer_id": 319577, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 6, "selected": true, "text": "document.inputEncoding document.characterSet document.charset document.defaultCharset testElement.innerHTML" }, { "answer_id": 42072440, "author": "ecc", "author_id": 1125171, "author_profile": "https://Stackoverflow.com/users/1125171", "pm_score": 3, "selected": false, "text": "document.characterSet >>> document.characterSet\n \"utf-8\"\n \"UTF-8\"\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
318,835
<p>When creating a new C++ header/source file, what information do you add to the top? For example, do you add the date, your name, a description of the file, etc.? Do you use a structured format for this information?</p> <p>e.g.</p> <pre><code>// Foo.cpp - Implementation of the Foo class // Date: 2008-25-11 // Created by: John Smith </code></pre> <p>One team I know embeds CVS commit messages to the foot of each file, but I'm not sure I want to go this far...</p>
[ { "answer_id": 318867, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 1, "selected": false, "text": "// $Id$\n" }, { "answer_id": 319505, "author": "Lodle", "author_id": 23339, "author_profile": "https://Stackoverflow.com/users/23339", "pm_score": 1, "selected": false, "text": "///////////// Copyright © 2008 DesuraNET. All rights reserved. /////////////\n//\n// Project : [project name]\n// File : [file name]\n// Description :\n// [TODO: Write the purpose of ... ]\n//\n// Created On: 11/12/2008 2:24:07 PM\n// Created By: [name] <mailto:[email]>\n////////////////////////////////////////////////////////////////////////////\n" }, { "answer_id": 319724, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$Id$\n$HeadURL$\n $HeadURL$" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
318,850
<p>I have a two part question</p> <p><strong>Best-Practice</strong></p> <ul> <li>I have an algorithm that performs some operation on a data structure using the public interface</li> <li>It is currently a module with numerous static methods, all private except for the one public interface method.</li> <li>There is one instance variable that needs to be shared among all the methods.</li> </ul> <p>These are the options I can see, which is the best?:</p> <ul> <li><strong>Module</strong> with static ('module' in ruby) methods </li> <li><strong>Class</strong> with static methods</li> <li><strong>Mixin</strong> module for inclusion into the data structure</li> <li><strong>Refactor</strong> out the part of the algorithm that modifies that data structure (very small) and make that a mixin that calls the static methods of the algorithm module</li> </ul> <p><strong>Technical part</strong></p> <p>Is there any way to make a <strong>private Module method</strong>?</p> <pre><code>module Thing def self.pub; puts "Public method"; end private def self.priv; puts "Private method"; end end </code></pre> <p><strong>The <code>private</code> in there doesn't seem to have any effect</strong>, I can still call <code>Thing.priv</code> without issue.</p>
[ { "answer_id": 318893, "author": "J Cooper", "author_id": 38803, "author_profile": "https://Stackoverflow.com/users/38803", "pm_score": 4, "selected": false, "text": "private class << self\n private\n\n def foo()\n ....\n end\nend\n" }, { "answer_id": 321407, "author": "Cameron Price", "author_id": 35526, "author_profile": "https://Stackoverflow.com/users/35526", "pm_score": 5, "selected": false, "text": "module Foo\n def self.included(base)\n class << base \n def public_method\n puts \"public method\"\n end\n def call_private\n private_method\n end\n private\n def private_method\n puts \"private\"\n end\n end\n end\nend\n\nclass Bar\n include Foo\nend\n\nBar.public_method\n\nbegin\n Bar.private_method\nrescue\n puts \"couldn't call private method\"\nend\n\nBar.call_private\n" }, { "answer_id": 418321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "Module.private_class_method module Foo\n def self.included(base)\n base.instance_eval do\n def method_name\n # ...\n end\n private_class_method :method_name\n end\n end\nend\n module Thing\n def self.pub; puts \"Public method\"; end\n def self.priv; puts \"Private method\"; end\n private_class_method :priv\nend\n module Thing\n def self.pub; puts \"Public method\"; end\n private_class_method def self.priv; puts \"Private method\"; end\nend\n" }, { "answer_id": 424569, "author": "ucron", "author_id": 45246, "author_profile": "https://Stackoverflow.com/users/45246", "pm_score": 8, "selected": true, "text": "module GTranslate\n class Translator\n def perform(text)\n translate(text)\n end\n\n private\n\n def translate(text)\n # do some private stuff here\n end\n end\n\n def self.translate(text)\n t = Translator.new\n t.perform(text)\n end\nend\n" }, { "answer_id": 12925407, "author": "Nakilon", "author_id": 322020, "author_profile": "https://Stackoverflow.com/users/322020", "pm_score": 1, "selected": false, "text": "module MyModule\n @@my_secret_method = lambda {\n # ...\n }\n # ...\nend\n d module A\n @@L = lambda{ \"@@L\" }\n def self.a ; @@L[] ; end\n def self.b ; a ; end\n\n class << self\n def c ; @@L[] ; end\n private\n def d ; @@L[] ; end\n end\n def self.e ; c ; end\n def self.f ; self.c ; end\n def self.g ; d ; end\n def self.h ; self.d ; end\n\n private\n def self.i ; @@L[] ; end\n class << self\n def j ; @@L[] ; end\n end\n\n public\n def self.k ; i ; end\n def self.l ; self.i ; end\n def self.m ; j ; end\n def self.n ; self.j ; end\nend\n\nfor expr in %w{ A.a A.b A.c A.d A.e A.f A.g A.h A.i A.j A.k A.l A.m A.n }\n puts \"#{expr} => #{begin ; eval expr ; rescue => e ; e ; end}\"\nend\n A.a => @@L\nA.b => @@L\nA.c => @@L\nA.d => private method `d' called for A:Module\nA.e => @@L\nA.f => @@L\nA.g => @@L\nA.h => private method `d' called for A:Module\nA.i => @@L\nA.j => @@L\nA.k => @@L\nA.l => @@L\nA.m => @@L\nA.n => @@L\n @@L class << self ; private ; def d self. private ; self. private ; class << self self." }, { "answer_id": 30854310, "author": "Tallak Tveide", "author_id": 1388584, "author_profile": "https://Stackoverflow.com/users/1388584", "pm_score": 2, "selected": false, "text": "module MyModule\n class << self\n def public_method\n # you may call the private method here\n tmp = private_method\n :public\n end\n\n private def private_method\n :private\n end\n end\nend\n\n# calling from outside the module\nputs MyModule::public_method\n" }, { "answer_id": 35012552, "author": "cdrev", "author_id": 1997733, "author_profile": "https://Stackoverflow.com/users/1997733", "pm_score": 6, "selected": false, "text": "module Writer\n class << self\n def output(s)\n puts upcase(s)\n end\n\n private\n\n def upcase(s)\n s.upcase\n end\n end\nend\n\nWriter.output \"Hello World\"\n# -> HELLO WORLD\n\nWriter.upcase \"Hello World\"\n# -> so.rb:16:in `<main>': private method `upcase' called for Writer:Module (NoMethodError)\n" }, { "answer_id": 40531791, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 0, "selected": false, "text": ":private_class_method module PublicModule\n def self.do_stuff(input)\n @private_implementation.do_stuff(input)\n end\n\n @private_implementation = Module.new do\n def self.do_stuff(input)\n input.upcase # or call other methods on module\n end\n end\nend\n PublicModule.do_stuff(\"whatever\") # => \"WHATEVER\"\n" }, { "answer_id": 62632216, "author": "Gerry Shaw", "author_id": 265940, "author_profile": "https://Stackoverflow.com/users/265940", "pm_score": 2, "selected": false, "text": "module Thing\n extend self\n\n def pub\n puts priv(123)\n end\n\n private\n \n def priv(value)\n puts \"Private method with value #{value}\"\n end\nend\n\nThing.pub\n# \"Private method with value 123\"\n\nThing.priv\n# NoMethodError (private method `priv' called for Thing:Module)\n" }, { "answer_id": 65894085, "author": "jeffdill2", "author_id": 2266827, "author_profile": "https://Stackoverflow.com/users/2266827", "pm_score": 0, "selected": false, "text": "extend module SomeModule\n\n class ClassThatDoesNotExtendTheModule\n class << self\n def random_class_method\n private_class_on_module\n end\n end\n end\n\n class ClassThatDoesExtendTheModule\n extend SomeModule\n \n class << self\n def random_class_method\n private_class_on_module\n end\n end\n end\n\n class AnotherClassThatDoesExtendTheModule\n extend SomeModule\n \n class << self\n def random_class_method\n private_class_on_module\n end\n end\n end\n\n private\n\n def private_class_on_module\n puts 'some private class was called'\n end\n \nend\n\n > SomeModule::ClassThatDoesNotExtendTheModule.random_class_method\n\nNameError: undefined local variable or method `private_class_on_module' for SomeModule::ClassThatDoesNotExtendTheModule:Class\n\n\n> SomeModule::ClassThatDoesExtendTheModule.random_class_method\n\nsome private class was called\n\n\n> SomeModule::ClassThatDoesExtendTheModule.private_class_on_module\n\nNoMethodError: private method `private_class_on_module' called for SomeModule::ClassThatDoesExtendTheModule:Class\n\n\n> SomeModule::AnotherClassThatDoesExtendTheModule.random_class_method\n\nsome private class was called\n\n\n> SomeModule::AnotherClassThatDoesExtendTheModule.random_class_method\n\nNoMethodError: private method `private_class_on_module' called for SomeModule::AnotherClassThatDoesExtendTheModule:Class\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13216/" ]
318,854
<p>I've often heard Ruby's inject method criticized as being "slow." As I rather like the function, and see equivalents in other languages, I'm curious if it's merely Ruby's <strong>implementation</strong> of the method that's slow, or if it is inherently a slow way to do things (e.g. should be avoided for non-small collections)?</p>
[ { "answer_id": 318885, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": true, "text": "inject fold fold_left" }, { "answer_id": 322267, "author": "dgtized", "author_id": 34450, "author_profile": "https://Stackoverflow.com/users/34450", "pm_score": 2, "selected": false, "text": "$ ruby -v\nruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]\n$ ruby exp/each_v_inject.rb \nRehearsal -----------------------------------------------------\nloop 0.000000 0.000000 0.000000 ( 0.000178)\nfixnums each 0.790000 0.280000 1.070000 ( 1.078589)\nfixnums each add 1.010000 0.290000 1.300000 ( 1.297733)\nEnumerable#inject 1.900000 0.430000 2.330000 ( 2.330083)\n-------------------------------------------- total: 4.700000sec\n\n user system total real\nloop 0.000000 0.000000 0.000000 ( 0.000178)\nfixnums each 0.760000 0.300000 1.060000 ( 1.079252)\nfixnums each add 1.030000 0.280000 1.310000 ( 1.305888)\nEnumerable#inject 1.850000 0.490000 2.340000 ( 2.340341)\n require 'benchmark'\n\ntotal = (ENV['TOTAL'] || 1_000).to_i\nfixnums = Array.new(total) {|x| x}\n\nBenchmark.bmbm do |x|\n x.report(\"loop\") do\n total.times { }\n end\n\n x.report(\"fixnums each\") do\n total.times do |i|\n fixnums.each {|x| x}\n end\n end\n\n x.report(\"fixnums each add\") do\n total.times do |i|\n v = 0\n fixnums.each {|x| v += x}\n end\n end \n\n x.report(\"Enumerable#inject\") do\n total.times do |i|\n fixnums.inject(0) {|a,x| a + x }\n end\n end \nend\n" }, { "answer_id": 6396515, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 0, "selected": false, "text": "each_with_object inject" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38803/" ]
318,871
<p>Due to current limitations on getting DIV tags to work well across browser platforms for the particular liquid layout I desire, I have opted to use a combination of Tables and DIVs for layout. That being said, a couple of issues remain. </p> <p>The FIRST issue is that in Firefox, my table row height for my footer is being rendered differently than it is being rendered in IE when using a table with a height of 100%. What happens is that in Firefox the footer row for the table has a height that is greater than the height specified for the table row. This, in turn, throws off my footer layout. </p> <p>Here is the code for the page:</p> <hr> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta NAME="DESCRIPTION" CONTENT="Cold Fusion Applications and Development"&gt; &lt;meta NAME="keywords" CONTENT="cold fusion, coldfusion, sql server, graphic design, houston, texas, tx, web developer, web development, e-commerce, survey, surveys, web applications, php, mysql, access, foxpro, sql, perl, shopping cart, web programming, macromedia, webmaster, html, cfml, xml, 77057, cfware, cfware.com, www.cfware.com, hosting, dhtml, dynamic html, web programmer, graphic designer, website, resume"&gt; &lt;link href="style.css" rel="stylesheet" type="text/css"&gt; &lt;/head&gt; &lt;!-- BODY --&gt; &lt;body topmargin="0" bottommargin="0" rightmargin="0" leftmargin="0"&gt; &lt;!--TABLE I --&gt; &lt;table class="fullheight" width="100%" height="100%" min-height="100%" border="1" align="center" cellpadding="0" cellspacing="0"&gt; &lt;tr&gt;&lt;td height="116" align="center" valign="top"&gt; &lt;!-- HEADER --&gt; &lt;div class="header"&gt; &lt;div class="lfc"&gt;Cornerstone&lt;/div&gt; &lt;div class="rfl"&gt;&lt;img src="c4sqlogo.gif" width="295" height="68"&gt;&lt;/div&gt; &lt;div class="lf4"&gt;Foursquare&lt;/div&gt; &lt;/div&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;!-- HEADER END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td align="center" valign="center" bgcolor="#FFFFFF"&gt; &lt;!-- CONTENT --&gt; &lt;div class="content"&gt; &lt;table class="fullheight" width="100%" height="100%"&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td align="center" valign="middle"&gt; &lt;h1 class="font-black"&gt;Cornerstone Foursquare Church&lt;/h1&gt; &lt;br&gt; &lt;h2&gt;7791 Hillbarn Dr. Houston, TX 77040&lt;/h2&gt; &lt;br&gt; &lt;h2&gt;(713) 856 - 7773&lt;/h2&gt; &lt;br&gt; &lt;br&gt; &lt;h3&gt;Service Times:&lt;br&gt;Sunday Morning Worship 10:30AM&lt;br&gt;Sunday Evening Bible Study 6:00PM &lt;br&gt;Wednesday Evening Bible Study and Prayer 7:00PM&lt;/h3&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;!-- CONTENT END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tfoot height="28"&gt;&lt;td height="28" align="center" valign="middle" bgcolor="#FFFFFF"&gt; &lt;!-- FOOTER --&gt; &lt;div class="clearspacer"&gt;&lt;img src="1.gif" height="10" width="1"&gt;&lt;/div&gt; &lt;div class="footer"&gt;&lt;div class="footertext"&gt;&lt;a href="http://www.c4sq.org"&gt; w w w . c 4 s q . o r g &lt;/a&gt;&lt;/div&gt;&lt;/div&gt; &lt;!-- FOOTER END --&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;!-- TABLE I END --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>And here is the code for the sytle sheet:</p> <pre><code>html, body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11px; color: :#a02f1d; height: 100%; width: 100%; } a { color: #ffffff; text-decoration: none; font-size: 12; font-weight: 500; } .header { color: #ff0000; margin: 0 auto; width: 760px; height: 116px; background-image: url(stripe.gif); background-repeat: repeat-x; } .fullheight { height:100%;} .lf4 { float: left; margin-top: 0px; clear: left; width: 240px; margin-left: 190px; color: #a02f1d; font-size: 26px; font-weight: semi-bold; font-style: italic; } .lfc { float: left; margin-top: 8px; margin-left: 20px; color: #a02f1d; font-size: 48px; font-weight: semi-bold; font-style: italic; } .rfl { float: right; margin-top: 24px; margin-right: 20px; clear: right; } .content { margin: 0 auto; width: 760px; overflow: hidden; color: :#a02f1d; } .spacer { background-color:#a02f1d; margin: 0 auto; width: 760px; height: 4px; overflow: hidden; } .clearspacer { background-color:#000000; } .footer { color: #ffffff; background-color:#a02f1d; margin: 0 auto; width: 760px; height: 30px; clear: both; } .footertext { color:#ffffff; margin-top: 6px; font-size: 12px; } </code></pre> <hr> <p>The SECOND issue has to do with modifying the existing layout so that there is a centered vertical area of 760px in width that displays in a shade of color different from the surrounding viewport. The primary difficulty is that in order to get my footer to stick to the bottom in both browsers and resize with the viewport, I had to re-adopt a table layout. The current strategy, however, is to use as few nests as possible in order to benefit from the speed and clarity from using DIVs. I would opt to use a DIV layout to the exclusion of a TABLE layout if it were not for the apparently, currently insoluble problem of getting a working sticky-footer to work with a DIV liquid layout.</p>
[ { "answer_id": 319022, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "<tfoot height=\"28\"><td height=\"28\" align=\"center\" valign=\"middle\" bgcolor=\"#FFFFFF\">\n <!-- FOOTER --> \n <div class=\"clearspacer\"><img src=\"1.gif\" height=\"10\" width=\"1\"></div>\n <div class=\"footer\"><div class=\"footertext\"><a href=\"http://www.c4sq.org\"> w w w . c 4 s q . o r g </a></div></div>\n <!-- FOOTER END -->\n </td>\n</tr>\n</table>\n <tfoot> \n <tr> \n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40810/" ]
318,875
<p>Is this right for When 4 &lt; 5 and 1 &lt; 2 ?</p> <pre><code>&lt;xsl:when test="4 &amp;lt; 5 AND 1 &amp;lt; 2" &gt; &lt;!-- do something --&gt; &lt;/xsl:when&gt; </code></pre>
[ { "answer_id": 318907, "author": "phihag", "author_id": 35070, "author_profile": "https://Stackoverflow.com/users/35070", "pm_score": 9, "selected": true, "text": "<xsl:when test=\"4 &lt; 5 and 1 &lt; 2\">\n<!-- do something -->\n</xsl:when>\n" }, { "answer_id": 318912, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 5, "selected": false, "text": "<xsl:choose>\n <xsl:when test=\"4 &lt; 5 and 1 &lt; 2\" >\n <!-- do something -->\n </xsl:when>\n <xsl:otherwise>\n <!-- do something else -->\n </xsl:otherwise>\n</xsl:choose>\n" }, { "answer_id": 22374268, "author": "Ted", "author_id": 3414617, "author_profile": "https://Stackoverflow.com/users/3414617", "pm_score": 3, "selected": false, "text": "<xsl:when test=\"responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999\"> \n <xsl:when test=\"number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999\">\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
318,876
<p>I have TFS installed on a single server and am running out of space on the disk. (We've been using the instance for about 2 years now.) </p> <p>Looking at the tables in SQL Server what seems to be culprit is the tbl_content table, it is at 70 GB. If I do a get on the entire source tree for all projects it is only about 8 GB of data.</p> <p>Is this just all the histories of the files? It seems like a 10:1 ratio just the histories...since I would think the deltas would be very small. </p> <p>Does anyone know if that is a reasonable size given 8 GB of source (and 2 yrs of activity)? And if not what to look at to 'fix' this?</p> <p>Thanks</p>
[ { "answer_id": 319777, "author": "JB Brown", "author_id": 21360, "author_profile": "https://Stackoverflow.com/users/21360", "pm_score": 2, "selected": false, "text": "SELECT name ,size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS AvailableSpaceInMB\nFROM sys.database_files;\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
318,880
<p>I have a table with a binary column which stores files of a number of different possible filetypes (PDF, BMP, JPEG, WAV, MP3, DOC, MPEG, AVI etc.), but no columns that store either the name or the type of the original file. Is there any easy way for me to process these rows and determine the type of each file stored in the binary column? Preferably it would be a utility that only reads the file headers, so that I don't have to fully extract each file to determine its type.</p> <p><strong>Clarification</strong>: I know that the approach here involves reading just the beginning of each file. I'm looking for a good resource (aka links) that can do this for me without too much fuss. Thanks.</p> <p>Also, <strong>just C#/.NET on Windows, please</strong>. I'm not using Linux and can't use Cygwin (doesn't work on Windows CE, among other reasons).</p>
[ { "answer_id": 318889, "author": "Paul Fisher", "author_id": 39808, "author_profile": "https://Stackoverflow.com/users/39808", "pm_score": 3, "selected": false, "text": "file" }, { "answer_id": 318897, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 1, "selected": false, "text": "$ file visitors.*\nvisitors.html: HTML document text\nvisitors.png: PNG image data, 5360 x 2819, 8-bit colormap, non-interlaced\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
318,886
<p>I can't seem to figure this out. I'm experimenting with MVC Beta and am trying to implement a catchall route such that if the user enters mysite.com/blah instead of mysite.com/home/index it will hit the "Error" route. </p> <p>Unfortunately it seems that the "Default" route always catches "blah" first. In fact the only route I've been able to get to the "Error" route with is blah/blah/blah/blah.</p> <p>Is this the way it's supposed to work, because I've seen other examples that have the "Default" and "Error" route set up just like this and it seems that if they were to type in a controller that doesn't exist it would hit the "Error" route.</p> <p>Is there something I'm missing (very possible) or will I just have to create a specific route for each controller?</p> <p>Code I'm using:</p> <pre><code> routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "Error", "{*catchall}", new { controller = "Base", action = "Error", id = "404" } ); </code></pre> <p>Thank you, Jeff</p>
[ { "answer_id": 319090, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 3, "selected": false, "text": "protected void Application_Error(object sender, EventArgs e)\n{\n Exception exception = Server.GetLastError();\n HttpException httpException = exception as HttpException;\n if (httpException != null)\n {\n RouteData routeData = new RouteData();\n routeData.Values.Add(\"controller\", \"Error\");\n routeData.Values.Add(\"action\", \"HttpError500\");\n\n if (httpException.GetHttpCode() == 404)\n {\n routeData.Values[\"action\"] = \"HttpError404\";\n }\n\n Server.ClearError();\n Response.Clear();\n IController errorController = new ErrorController();\n errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));\n }\n}\n" }, { "answer_id": 11184688, "author": "Chris Moschini", "author_id": 176877, "author_profile": "https://Stackoverflow.com/users/176877", "pm_score": 0, "selected": false, "text": "routes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{*id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n);\n {id} {*id}" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40814/" ]
318,888
<p>Edit: this puzzle is also known as "Einstein's Riddle"</p> <p>The <a href="https://en.wikipedia.org/wiki/Zebra_Puzzle" rel="noreferrer">Who owns the Zebra</a> (you can <a href="https://www.brainzilla.com/logic/zebra/einsteins-riddle/" rel="noreferrer" title="Einstein&#39;s Riddle">try the online version here</a>) is an example of a classic set of puzzles and I bet that most people on Stack Overflow can solve it with pen and paper. But what would a programmatic solution look like?</p> <p>Based on the clues listed below...</p> <ul> <li>There are five houses.</li> <li>Each house has its own unique color.</li> <li>All house owners are of different nationalities.</li> <li>They all have different pets.</li> <li>They all drink different drinks.</li> <li>They all smoke different cigarettes.</li> <li>The English man lives in the red house.</li> <li>The Swede has a dog.</li> <li>The Dane drinks tea.</li> <li>The green house is on the left side of the white house.</li> <li>They drink coffee in the green house.</li> <li>The man who smokes Pall Mall has birds.</li> <li>In the yellow house they smoke Dunhill.</li> <li>In the middle house they drink milk.</li> <li>The Norwegian lives in the first house.</li> <li>The man who smokes Blend lives in the house next to the house with cats.</li> <li>In the house next to the house where they have a horse, they smoke Dunhill.</li> <li>The man who smokes Blue Master drinks beer.</li> <li>The German smokes Prince.</li> <li>The Norwegian lives next to the blue house.</li> <li>They drink water in the house next to the house where they smoke Blend. </li> </ul> <p>...who owns the Zebra?</p>
[ { "answer_id": 318922, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 3, "selected": false, "text": "// The green house's owner drinks coffee\nPost(greenHouse.Eq(coffee));\n// The person who smokes Pall Mall rears birds \nPost(pallMall.Eq(birds));\n// The owner of the yellow house smokes Dunhill \nPost(yellowHouse.Eq(dunhill));\n" }, { "answer_id": 318989, "author": "Chris", "author_id": 8415, "author_profile": "https://Stackoverflow.com/users/8415", "pm_score": 4, "selected": false, "text": "(housenumber, color, nationality, pet, drink, smoke)\n" }, { "answer_id": 320981, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "from constraint import AllDifferentConstraint, InSetConstraint, Problem\n\n# variables\ncolors = \"blue red green white yellow\".split()\nnationalities = \"Norwegian German Dane Swede English\".split()\npets = \"birds dog cats horse zebra\".split()\ndrinks = \"tea coffee milk beer water\".split()\ncigarettes = \"Blend, Prince, Blue Master, Dunhill, Pall Mall\".split(\", \")\n\n# There are five houses.\nminn, maxn = 1, 5\nproblem = Problem()\n# value of a variable is the number of a house with corresponding property\nvariables = colors + nationalities + pets + drinks + cigarettes\nproblem.addVariables(variables, range(minn, maxn+1))\n\n# Each house has its own unique color.\n# All house owners are of different nationalities.\n# They all have different pets.\n# They all drink different drinks.\n# They all smoke different cigarettes.\nfor vars_ in (colors, nationalities, pets, drinks, cigarettes):\n problem.addConstraint(AllDifferentConstraint(), vars_)\n\n# In the middle house they drink milk.\n#NOTE: interpret \"middle\" in a numerical sense (not geometrical)\nproblem.addConstraint(InSetConstraint([(minn + maxn) // 2]), [\"milk\"])\n# The Norwegian lives in the first house.\n#NOTE: interpret \"the first\" as a house number\nproblem.addConstraint(InSetConstraint([minn]), [\"Norwegian\"])\n# The green house is on the left side of the white house.\n#XXX: what is \"the left side\"? (linear, circular, two sides, 2D house arrangment)\n#NOTE: interpret it as 'green house number' + 1 == 'white house number'\nproblem.addConstraint(lambda a,b: a+1 == b, [\"green\", \"white\"])\n\ndef add_constraints(constraint, statements, variables=variables, problem=problem):\n for stmt in (line for line in statements if line.strip()):\n problem.addConstraint(constraint, [v for v in variables if v in stmt])\n\nand_statements = \"\"\"\nThey drink coffee in the green house.\nThe man who smokes Pall Mall has birds.\nThe English man lives in the red house.\nThe Dane drinks tea.\nIn the yellow house they smoke Dunhill.\nThe man who smokes Blue Master drinks beer.\nThe German smokes Prince.\nThe Swede has a dog.\n\"\"\".split(\"\\n\")\nadd_constraints(lambda a,b: a == b, and_statements)\n\nnextto_statements = \"\"\"\nThe man who smokes Blend lives in the house next to the house with cats.\nIn the house next to the house where they have a horse, they smoke Dunhill.\nThe Norwegian lives next to the blue house.\nThey drink water in the house next to the house where they smoke Blend.\n\"\"\".split(\"\\n\")\n#XXX: what is \"next to\"? (linear, circular, two sides, 2D house arrangment)\nadd_constraints(lambda a,b: abs(a - b) == 1, nextto_statements)\n\ndef solve(variables=variables, problem=problem):\n from itertools import groupby\n from operator import itemgetter\n\n # find & print solutions\n for solution in problem.getSolutionIter():\n for key, group in groupby(sorted(solution.iteritems(), key=itemgetter(1)), key=itemgetter(1)):\n print key, \n for v in sorted(dict(group).keys(), key=variables.index):\n print v.ljust(9),\n print\n\nif __name__ == '__main__':\n solve()\n 1 yellow Norwegian cats water Dunhill \n2 blue Dane horse tea Blend \n3 red English birds milk Pall Mall\n4 green German zebra coffee Prince \n5 white Swede dog beer Blue Master\n constraint pip" }, { "answer_id": 7961892, "author": "new123456", "author_id": 144734, "author_profile": "https://Stackoverflow.com/users/144734", "pm_score": 4, "selected": false, "text": "% NOTE - This may or may not be more efficent. A bit verbose, though.\nleft_side(L, R, [L, R, _, _, _]).\nleft_side(L, R, [_, L, R, _, _]).\nleft_side(L, R, [_, _, L, R, _]).\nleft_side(L, R, [_, _, _, L, R]).\n\nnext_to(X, Y, Street) :- left_side(X, Y, Street).\nnext_to(X, Y, Street) :- left_side(Y, X, Street).\n\nm(X, Y) :- member(X, Y).\n\nget_zebra(Street, Who) :- \n Street = [[C1, N1, P1, D1, S1],\n [C2, N2, P2, D2, S2],\n [C3, N3, P3, D3, S3],\n [C4, N4, P4, D4, S4],\n [C5, N5, P5, D5, S5]],\n m([red, english, _, _, _], Street),\n m([_, swede, dog, _, _], Street),\n m([_, dane, _, tea, _], Street),\n left_side([green, _, _, _, _], [white, _, _, _, _], Street),\n m([green, _, _, coffee, _], Street),\n m([_, _, birds, _, pallmall], Street),\n m([yellow, _, _, _, dunhill], Street),\n D3 = milk,\n N1 = norwegian,\n next_to([_, _, _, _, blend], [_, _, cats, _, _], Street),\n next_to([_, _, horse, _, _], [_, _, _, _, dunhill], Street),\n m([_, _, _, beer, bluemaster], Street),\n m([_, german, _, _, prince], Street),\n next_to([_, norwegian, _, _, _], [blue, _, _, _, _], Street),\n next_to([_, _, _, water, _], [_, _, _, _, blend], Street),\n m([_, Who, zebra, _, _], Street).\n ?- get_zebra(Street, Who).\nStreet = ...\nWho = german\n" }, { "answer_id": 8270393, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 6, "selected": false, "text": "select([A|As],S):- select(A,S,S1),select(As,S1).\nselect([],_). \n\nleft_of(A,B,C):- append(_,[A,B|_],C). \nnext_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C).\n\nzebra(Owns, HS):- % (* house: color,nation,pet,drink,smokes *)\n HS = [ h(_,norwegian,_,_,_), h(blue,_,_,_,_), h(_,_,_,milk,_), _, _], \n select([ h(red,brit,_,_,_), h(_,swede,dog,_,_), \n h(_,dane,_,tea,_), h(_,german,_,_,prince)], HS),\n select([ h(_,_,birds,_,pallmall), h(yellow,_,_,_,dunhill),\n h(_,_,_,beer,bluemaster)], HS), \n left_of( h(green,_,_,coffee,_), h(white,_,_,_,_), HS),\n next_to( h(_,_,_,_,dunhill), h(_,_,horse,_,_), HS),\n next_to( h(_,_,_,_,blend), h(_,_,cats, _,_), HS),\n next_to( h(_,_,_,_,blend), h(_,_,_,water,_), HS),\n member( h(_,Owns,zebra,_,_), HS).\n ?- time( (zebra(Who,HS), writeln(Who), nl, maplist(writeln,HS), nl, false \n ; writeln(\"no more solutions!\") )).\ngerman\n\nh( yellow, norwegian, cats, water, dunhill )\nh( blue, dane, horse, tea, blend )\nh( red, brit, birds, milk, pallmall )\nh( green, german, zebra, coffee, prince ) % (* formatted by hand *)\nh( white, swede, dog, beer, bluemaster)\n\nno more solutions!\n% (* 1,706 inferences, 0.000 CPU in 0.070 seconds (0% CPU, Infinite Lips) *)\ntrue.\n" }, { "answer_id": 20102528, "author": "CapelliC", "author_id": 874024, "author_profile": "https://Stackoverflow.com/users/874024", "pm_score": 3, "selected": false, "text": ":- use_module(library(clpfd)).\n\nsolve(ZebraOwner) :-\n maplist( init_dom(1..5), \n [[British, Swedish, Danish, Norwegian, German], % Nationalities\n [Red, Green, Blue, White, Yellow], % Houses\n [Tea, Coffee, Milk, Beer, Water], % Beverages\n [PallMall, Blend, Prince, Dunhill, BlueMaster], % Cigarettes\n [Dog, Birds, Cats, Horse, Zebra]]), % Pets\n British #= Red, % Hint 1\n Swedish #= Dog, % Hint 2\n Danish #= Tea, % Hint 3\n Green #= White - 1 , % Hint 4\n Green #= Coffee, % Hint 5\n PallMall #= Birds, % Hint 6\n Yellow #= Dunhill, % Hint 7\n Milk #= 3, % Hint 8\n Norwegian #= 1, % Hint 9\n neighbor(Blend, Cats), % Hint 10\n neighbor(Horse, Dunhill), % Hint 11\n BlueMaster #= Beer, % Hint 12\n German #= Prince, % Hint 13\n neighbor(Norwegian, Blue), % Hint 14\n neighbor(Blend, Water), % Hint 15\n memberchk(Zebra-ZebraOwner, [British-british, Swedish-swedish, Danish-danish,\n Norwegian-norwegian, German-german]).\n\ninit_dom(R, L) :-\n all_distinct(L),\n L ins R.\n\nneighbor(X, Y) :-\n (X #= (Y - 1)) #\\/ (X #= (Y + 1)).\n" }, { "answer_id": 24113528, "author": "DreadPirateShawn", "author_id": 128977, "author_profile": "https://Stackoverflow.com/users/128977", "pm_score": 3, "selected": false, "text": "categories( POSITION, 1, 2, 3, 4, 5 ) # There are five houses.\ncategories( HOUSE_COLOR, blue, red, green, white, yellow ) # Each house has its own unique color.\ncategories( NATIONALITY, Norwegian, German, Dane, Swede, English ) # All house owners are of different nationalities.\ncategories( PET, birds, dog, cats, horse, zebra ) # They all have different pets.\ncategories( DRINK, tea, coffee, milk, beer, water ) # They all drink different drinks.\ncategories( SMOKE, Blend, Prince, 'Blue Master', Dunhill, 'Pall Mall' ) # They all smoke different cigarettes.\n\nrelated( NATIONALITY, English, HOUSE_COLOR, red ) # The English man lives in the red house.\nrelated( NATIONALITY, Swede, PET, dog ) # The Swede has a dog.\nrelated( NATIONALITY, Dane, DRINK, tea ) # The Dane drinks tea.\nleft_of( HOUSE_COLOR, green, HOUSE_COLOR, white ) # The green house is on the left side of the white house.\nrelated( DRINK, coffee, HOUSE_COLOR, green ) # They drink coffee in the green house.\nrelated( SMOKE, 'Pall Mall', PET, birds ) # The man who smokes Pall Mall has birds.\nrelated( SMOKE, Dunhill, HOUSE_COLOR, yellow ) # In the yellow house they smoke Dunhill.\nrelated( POSITION, 3, DRINK, milk ) # In the middle house they drink milk.\nrelated( NATIONALITY, Norwegian, POSITION, 1 ) # The Norwegian lives in the first house.\nnext_to( SMOKE, Blend, PET, cats ) # The man who smokes Blend lives in the house next to the house with cats.\nnext_to( SMOKE, Dunhill, PET, horse ) # In the house next to the house where they have a horse, they smoke Dunhill.\nrelated( SMOKE, 'Blue Master', DRINK, beer ) # The man who smokes Blue Master drinks beer.\nrelated( NATIONALITY, German, SMOKE, Prince ) # The German smokes Prince.\nnext_to( NATIONALITY, Norwegian, HOUSE_COLOR, blue ) # The Norwegian lives next to the blue house.\nnext_to( DRINK, water, SMOKE, Blend ) # They drink water in the house next to the house where they smoke Blend.\n #############\n# Categories\n\n# Foreach set of categories, assert each type\ncategories\n foreach\n clues.categories($category, $thing1, $thing2, $thing3, $thing4, $thing5)\n assert\n clues.is_category($category, $thing1)\n clues.is_category($category, $thing2)\n clues.is_category($category, $thing3)\n clues.is_category($category, $thing4)\n clues.is_category($category, $thing5)\n\n\n#########################\n# Inverse Relationships\n\n# Foreach A=1, assert 1=A\ninverse_relationship_positive\n foreach\n clues.related($category1, $thing1, $category2, $thing2)\n assert\n clues.related($category2, $thing2, $category1, $thing1)\n\n# Foreach A!1, assert 1!A\ninverse_relationship_negative\n foreach\n clues.not_related($category1, $thing1, $category2, $thing2)\n assert\n clues.not_related($category2, $thing2, $category1, $thing1)\n\n# Foreach \"A beside B\", assert \"B beside A\"\ninverse_relationship_beside\n foreach\n clues.next_to($category1, $thing1, $category2, $thing2)\n assert\n clues.next_to($category2, $thing2, $category1, $thing1)\n\n\n###########################\n# Transitive Relationships\n\n# Foreach A=1 and 1=a, assert A=a\ntransitive_positive\n foreach\n clues.related($category1, $thing1, $category2, $thing2)\n clues.related($category2, $thing2, $category3, $thing3)\n\n check unique($thing1, $thing2, $thing3) \\\n and unique($category1, $category2, $category3)\n assert\n clues.related($category1, $thing1, $category3, $thing3)\n\n# Foreach A=1 and 1!a, assert A!a\ntransitive_negative\n foreach\n clues.related($category1, $thing1, $category2, $thing2)\n clues.not_related($category2, $thing2, $category3, $thing3)\n\n check unique($thing1, $thing2, $thing3) \\\n and unique($category1, $category2, $category3)\n assert\n clues.not_related($category1, $thing1, $category3, $thing3)\n\n\n##########################\n# Exclusive Relationships\n\n# Foreach A=1, assert A!2 and A!3 and A!4 and A!5\nif_one_related_then_others_unrelated\n foreach\n clues.related($category, $thing, $category_other, $thing_other)\n check unique($category, $category_other)\n\n clues.is_category($category_other, $thing_not_other)\n check unique($thing, $thing_other, $thing_not_other)\n assert\n clues.not_related($category, $thing, $category_other, $thing_not_other)\n\n# Foreach A!1 and A!2 and A!3 and A!4, assert A=5\nif_four_unrelated_then_other_is_related\n foreach\n clues.not_related($category, $thing, $category_other, $thingA)\n clues.not_related($category, $thing, $category_other, $thingB)\n check unique($thingA, $thingB)\n\n clues.not_related($category, $thing, $category_other, $thingC)\n check unique($thingA, $thingB, $thingC)\n\n clues.not_related($category, $thing, $category_other, $thingD)\n check unique($thingA, $thingB, $thingC, $thingD)\n\n # Find the fifth variation of category_other.\n clues.is_category($category_other, $thingE)\n check unique($thingA, $thingB, $thingC, $thingD, $thingE)\n assert\n clues.related($category, $thing, $category_other, $thingE)\n\n\n###################\n# Neighbors: Basic\n\n# Foreach \"A left of 1\", assert \"A beside 1\"\nexpanded_relationship_beside_left\n foreach\n clues.left_of($category1, $thing1, $category2, $thing2)\n assert\n clues.next_to($category1, $thing1, $category2, $thing2)\n\n# Foreach \"A beside 1\", assert A!1\nunrelated_to_beside\n foreach\n clues.next_to($category1, $thing1, $category2, $thing2)\n check unique($category1, $category2)\n assert\n clues.not_related($category1, $thing1, $category2, $thing2)\n\n\n###################################\n# Neighbors: Spatial Relationships\n\n# Foreach \"A beside B\" and \"A=(at-edge)\", assert \"B=(near-edge)\"\ncheck_next_to_either_edge\n foreach\n clues.related(POSITION, $position_known, $category, $thing)\n check is_edge($position_known)\n\n clues.next_to($category, $thing, $category_other, $thing_other)\n\n clues.is_category(POSITION, $position_other)\n check is_beside($position_known, $position_other)\n assert\n clues.related(POSITION, $position_other, $category_other, $thing_other)\n\n# Foreach \"A beside B\" and \"A!(near-edge)\" and \"B!(near-edge)\", assert \"A!(at-edge)\"\ncheck_too_close_to_edge\n foreach\n clues.next_to($category, $thing, $category_other, $thing_other)\n\n clues.is_category(POSITION, $position_edge)\n clues.is_category(POSITION, $position_near_edge)\n check is_edge($position_edge) and is_beside($position_edge, $position_near_edge)\n\n clues.not_related(POSITION, $position_near_edge, $category, $thing)\n clues.not_related(POSITION, $position_near_edge, $category_other, $thing_other)\n assert\n clues.not_related(POSITION, $position_edge, $category, $thing)\n\n# Foreach \"A beside B\" and \"A!(one-side)\", assert \"A=(other-side)\"\ncheck_next_to_with_other_side_impossible\n foreach\n clues.next_to($category, $thing, $category_other, $thing_other)\n\n clues.related(POSITION, $position_known, $category_other, $thing_other)\n check not is_edge($position_known)\n\n clues.not_related($category, $thing, POSITION, $position_one_side)\n check is_beside($position_known, $position_one_side)\n\n clues.is_category(POSITION, $position_other_side)\n check is_beside($position_known, $position_other_side) \\\n and unique($position_known, $position_one_side, $position_other_side)\n assert\n clues.related($category, $thing, POSITION, $position_other_side)\n\n# Foreach \"A left of B\"...\n# ... and \"C=(position1)\" and \"D=(position2)\" and \"E=(position3)\"\n# ~> assert \"A=(other-position)\" and \"B=(other-position)+1\"\nleft_of_and_only_two_slots_remaining\n foreach\n clues.left_of($category_left, $thing_left, $category_right, $thing_right)\n\n clues.related($category_left, $thing_left_other1, POSITION, $position1)\n clues.related($category_left, $thing_left_other2, POSITION, $position2)\n clues.related($category_left, $thing_left_other3, POSITION, $position3)\n check unique($thing_left, $thing_left_other1, $thing_left_other2, $thing_left_other3)\n\n clues.related($category_right, $thing_right_other1, POSITION, $position1)\n clues.related($category_right, $thing_right_other2, POSITION, $position2)\n clues.related($category_right, $thing_right_other3, POSITION, $position3)\n check unique($thing_right, $thing_right_other1, $thing_right_other2, $thing_right_other3)\n\n clues.is_category(POSITION, $position4)\n clues.is_category(POSITION, $position5)\n\n check is_left_right($position4, $position5) \\\n and unique($position1, $position2, $position3, $position4, $position5)\n assert\n clues.related(POSITION, $position4, $category_left, $thing_left)\n clues.related(POSITION, $position5, $category_right, $thing_right)\n\n\n#########################\n\nfc_extras\n\n def unique(*args):\n return len(args) == len(set(args))\n\n def is_edge(pos):\n return (pos == 1) or (pos == 5)\n\n def is_beside(pos1, pos2):\n diff = (pos1 - pos2)\n return (diff == 1) or (diff == -1)\n\n def is_left_right(pos_left, pos_right):\n return (pos_right - pos_left == 1)\n from pyke import knowledge_engine\n\nengine = knowledge_engine.engine(__file__)\nengine.activate('relations')\n\ntry:\n natl = engine.prove_1_goal('clues.related(PET, zebra, NATIONALITY, $nationality)')[0].get('nationality')\nexcept Exception, e:\n natl = \"Unknown\"\nprint \"== Who owns the zebra? %s ==\" % natl\n $ python driver.py\n\n== Who owns the zebra? German ==\n\n# Color Nationality Pet Drink Smoke \n=======================================================\n1 yellow Norwegian cats water Dunhill \n2 blue Dane horse tea Blend \n3 red English birds milk Pall Mall \n4 green German zebra coffee Prince \n5 white Swede dog beer Blue Master \n\nCalculated in 1.19 seconds.\n" }, { "answer_id": 32543279, "author": "mik01aj", "author_id": 115493, "author_profile": "https://Stackoverflow.com/users/115493", "pm_score": 3, "selected": false, "text": "var _ = require('lodash');\n\nfunction canBe(house, criteria) {\n for (const key of Object.keys(criteria))\n if (house[key] && house[key] !== criteria[key])\n return false;\n return true;\n}\n\nfunction* thereShouldBe(criteria, street) {\n for (const i of _.range(street.length))\n yield* thereShouldBeAtIndex(criteria, i, street);\n}\n\nfunction* thereShouldBeAtIndex(criteria, index, street) {\n if (canBe(street[index], criteria)) {\n const newStreet = _.cloneDeep(street);\n newStreet[index] = _.assign({}, street[index], criteria);\n yield newStreet;\n }\n}\n\nfunction* leftOf(critA, critB, street) {\n for (const i of _.range(street.length - 1)) {\n if (canBe(street[i], critA) && canBe(street[i+1], critB)) {\n const newStreet = _.cloneDeep(street);\n newStreet[i ] = _.assign({}, street[i ], critA);\n newStreet[i+1] = _.assign({}, street[i+1], critB);\n yield newStreet;\n }\n }\n}\nfunction* nextTo(critA, critB, street) {\n yield* leftOf(critA, critB, street);\n yield* leftOf(critB, critA, street);\n}\n\nconst street = [{}, {}, {}, {}, {}]; // five houses\n\n// Btw: it turns out we don't need uniqueness constraint.\n\nconst constraints = [\n s => thereShouldBe({nation: 'English', color: 'red'}, s),\n s => thereShouldBe({nation: 'Swede', animal: 'dog'}, s),\n s => thereShouldBe({nation: 'Dane', drink: 'tea'}, s),\n s => leftOf({color: 'green'}, {color: 'white'}, s),\n s => thereShouldBe({drink: 'coffee', color: 'green'}, s),\n s => thereShouldBe({cigarettes: 'PallMall', animal: 'birds'}, s),\n s => thereShouldBe({color: 'yellow', cigarettes: 'Dunhill'}, s),\n s => thereShouldBeAtIndex({drink: 'milk'}, 2, s),\n s => thereShouldBeAtIndex({nation: 'Norwegian'}, 0, s),\n s => nextTo({cigarettes: 'Blend'}, {animal: 'cats'}, s),\n s => nextTo({animal: 'horse'}, {cigarettes: 'Dunhill'}, s),\n s => thereShouldBe({cigarettes: 'BlueMaster', drink: 'beer'}, s),\n s => thereShouldBe({nation: 'German', cigarettes: 'Prince'}, s),\n s => nextTo({nation: 'Norwegian'}, {color: 'blue'}, s),\n s => nextTo({drink: 'water'}, {cigarettes: 'Blend'}, s),\n\n s => thereShouldBe({animal: 'zebra'}, s), // should be somewhere\n];\n\nfunction* findSolution(remainingConstraints, street) {\n if (remainingConstraints.length === 0)\n yield street;\n else\n for (const newStreet of _.head(remainingConstraints)(street))\n yield* findSolution(_.tail(remainingConstraints), newStreet);\n}\n\nfor (const streetSolution of findSolution(constraints, street)) {\n console.log(streetSolution);\n}\n [ { color: 'yellow',\n cigarettes: 'Dunhill',\n nation: 'Norwegian',\n animal: 'cats',\n drink: 'water' },\n { nation: 'Dane',\n drink: 'tea',\n cigarettes: 'Blend',\n animal: 'horse',\n color: 'blue' },\n { nation: 'English',\n color: 'red',\n cigarettes: 'PallMall',\n animal: 'birds',\n drink: 'milk' },\n { color: 'green',\n drink: 'coffee',\n nation: 'German',\n cigarettes: 'Prince',\n animal: 'zebra' },\n { nation: 'Swede',\n animal: 'dog',\n color: 'white',\n cigarettes: 'BlueMaster',\n drink: 'beer' } ]\n" }, { "answer_id": 34190142, "author": "b_levitt", "author_id": 852208, "author_profile": "https://Stackoverflow.com/users/852208", "pm_score": 1, "selected": false, "text": "delegate CspTerm NamedTerm(string name);\n\npublic static void Zebra() {\n ConstraintSystem S = ConstraintSystem.CreateSolver();\n var termList = new List<KeyValuePair<CspTerm, string>>();\n\n NamedTerm House = delegate(string name) {\n CspTerm x = S.CreateVariable(S.CreateIntegerInterval(1, 5), name);\n termList.Add(new KeyValuePair<CspTerm, string>(x, name));\n return x;\n };\n\n CspTerm English = House(\"English\"), Spanish = House(\"Spanish\"),\n Japanese = House(\"Japanese\"), Italian = House(\"Italian\"),\n Norwegian = House(\"Norwegian\");\n CspTerm red = House(\"red\"), green = House(\"green\"),\n white = House(\"white\"),\n blue = House(\"blue\"), yellow = House(\"yellow\");\n CspTerm dog = House(\"dog\"), snails = House(\"snails\"),\n fox = House(\"fox\"),\n horse = House(\"horse\"), zebra = House(\"zebra\");\n CspTerm painter = House(\"painter\"), sculptor = House(\"sculptor\"),\n diplomat = House(\"diplomat\"), violinist = House(\"violinist\"),\n doctor = House(\"doctor\");\n CspTerm tea = House(\"tea\"), coffee = House(\"coffee\"),\n milk = House(\"milk\"),\n juice = House(\"juice\"), water = House(\"water\");\n\n S.AddConstraints(\n S.Unequal(English, Spanish, Japanese, Italian, Norwegian),\n S.Unequal(red, green, white, blue, yellow),\n S.Unequal(dog, snails, fox, horse, zebra),\n S.Unequal(painter, sculptor, diplomat, violinist, doctor),\n S.Unequal(tea, coffee, milk, juice, water),\n S.Equal(English, red),\n S.Equal(Spanish, dog),\n S.Equal(Japanese, painter),\n S.Equal(Italian, tea),\n S.Equal(1, Norwegian),\n S.Equal(green, coffee),\n S.Equal(1, green - white),\n S.Equal(sculptor, snails),\n S.Equal(diplomat, yellow),\n S.Equal(3, milk),\n S.Equal(1, S.Abs(Norwegian - blue)),\n S.Equal(violinist, juice),\n S.Equal(1, S.Abs(fox - doctor)),\n S.Equal(1, S.Abs(horse - diplomat))\n );\n bool unsolved = true;\n ConstraintSolverSolution soln = S.Solve();\n\n while (soln.HasFoundSolution) {\n unsolved = false;\n System.Console.WriteLine(\"solved.\");\n StringBuilder[] houses = new StringBuilder[5];\n for (int i = 0; i < 5; i++)\n houses[i] = new StringBuilder(i.ToString());\n foreach (KeyValuePair<CspTerm, string> kvp in termList) {\n string item = kvp.Value;\n object house;\n if (!soln.TryGetValue(kvp.Key, out house))\n throw new InvalidProgramException(\n \"can't find a Term in the solution: \" + item);\n houses[(int)house - 1].Append(\", \");\n houses[(int)house - 1].Append(item);\n }\n foreach (StringBuilder house in houses) {\n System.Console.WriteLine(house);\n }\n soln.GetNext();\n }\n if (unsolved)\n System.Console.WriteLine(\"No solution found.\");\n else\n System.Console.WriteLine(\n\"Expected: the Norwegian drinking water and the Japanese with the zebra.\");\n}\n" }, { "answer_id": 38027486, "author": "Tarik", "author_id": 990750, "author_profile": "https://Stackoverflow.com/users/990750", "pm_score": 2, "selected": false, "text": "include \"globals.mzn\";\n\n% Zebra puzzle\nint: nc = 5;\n\n% Colors\nint: red = 1;\nint: green = 2;\nint: ivory = 3;\nint: yellow = 4;\nint: blue = 5;\narray[1..nc] of var 1..nc:color;\nconstraint alldifferent([color[i] | i in 1..nc]);\n\n% Nationalities\nint: eng = 1;\nint: spa = 2;\nint: ukr = 3;\nint: nor = 4;\nint: jap = 5;\narray[1..nc] of var 1..nc:nationality;\nconstraint alldifferent([nationality[i] | i in 1..nc]);\n\n% Pets\nint: dog = 1;\nint: snail = 2;\nint: fox = 3;\nint: horse = 4;\nint: zebra = 5;\narray[1..nc] of var 1..nc:pet;\nconstraint alldifferent([pet[i] | i in 1..nc]);\n\n% Drinks\nint: coffee = 1;\nint: tea = 2;\nint: milk = 3;\nint: orange = 4;\nint: water = 5;\narray[1..nc] of var 1..nc:drink;\nconstraint alldifferent([drink[i] | i in 1..nc]);\n\n% Smokes\nint: oldgold = 1;\nint: kools = 2;\nint: chesterfields = 3;\nint: luckystrike = 4;\nint: parliaments = 5;\narray[1..nc] of var 1..nc:smoke;\nconstraint alldifferent([smoke[i] | i in 1..nc]);\n\n% The Englishman lives in the red house.\nconstraint forall ([nationality[i] == eng <-> color[i] == red | i in 1..nc]);\n\n% The Spaniard owns the dog.\nconstraint forall ([nationality[i] == spa <-> pet[i] == dog | i in 1..nc]);\n\n% Coffee is drunk in the green house.\nconstraint forall ([color[i] == green <-> drink[i] == coffee | i in 1..nc]);\n\n% The Ukrainian drinks tea.\nconstraint forall ([nationality[i] == ukr <-> drink[i] == tea | i in 1..nc]);\n\n% The green house is immediately to the right of the ivory house.\nconstraint forall ([color[i] == ivory -> if i<nc then color[i+1] == green else false endif | i in 1..nc]);\n\n% The Old Gold smoker owns snails.\nconstraint forall ([smoke[i] == oldgold <-> pet[i] == snail | i in 1..nc]);\n\n% Kools are smoked in the yellow house.\nconstraint forall ([smoke[i] == kools <-> color[i] == yellow | i in 1..nc]);\n\n% Milk is drunk in the middle house.\nconstraint drink[3] == milk;\n\n% The Norwegian lives in the first house.\nconstraint nationality[1] == nor;\n\n% The man who smokes Chesterfields lives in the house next to the man with the fox.\nconstraint forall ([smoke[i] == chesterfields -> (if i>1 then pet[i-1] == fox else false endif \\/ if i<nc then pet[i+1] == fox else false endif) | i in 1..nc]);\n\n% Kools are smoked in the house next to the house where the horse is kept.\nconstraint forall ([smoke[i] == kools -> (if i>1 then pet[i-1] == horse else false endif \\/ if i<nc then pet[i+1] == horse else false endif)| i in 1..nc]);\n\n%The Lucky Strike smoker drinks orange juice.\nconstraint forall ([smoke[i] == luckystrike <-> drink[i] == orange | i in 1..nc]);\n\n% The Japanese smokes Parliaments.\nconstraint forall ([nationality[i] == jap <-> smoke[i] == parliaments | i in 1..nc]);\n\n% The Norwegian lives next to the blue house.\nconstraint forall ([color[i] == blue -> (if i > 1 then nationality[i-1] == nor else false endif \\/ if i<nc then nationality[i+1] == nor else false endif) | i in 1..nc]);\n\nsolve satisfy;\n Compiling zebra.mzn\nRunning zebra.mzn\ncolor = array1d(1..5 ,[4, 5, 1, 3, 2]);\nnationality = array1d(1..5 ,[4, 3, 1, 2, 5]);\npet = array1d(1..5 ,[3, 4, 2, 1, 5]);\ndrink = array1d(1..5 ,[5, 2, 3, 4, 1]);\nsmoke = array1d(1..5 ,[2, 3, 1, 4, 5]);\n----------\nFinished in 47msec\n" }, { "answer_id": 42184547, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 2, "selected": false, "text": "let rec distribute y xs =\n match xs with\n | [] -> [[y]]\n | x::xs -> (y::x::xs)::[for xs in distribute y xs -> x::xs]\n\nlet rec permute xs =\n match xs with\n | [] | [_] as xs -> [xs]\n | x::xs -> List.collect (distribute x) (permute xs)\n\nlet find xs x = List.findIndex ((=) x) xs + 1\n\nlet eq xs x ys y = find xs x = find ys y\n\nlet nextTo xs x ys y = abs(find xs x - find ys y) = 1\n\nlet nations = [\"British\"; \"Swedish\"; \"Danish\"; \"Norwegian\"; \"German\"]\n\nlet houses = [\"Red\"; \"Green\"; \"Blue\"; \"White\"; \"Yellow\"]\n\nlet drinks = [\"Milk\"; \"Coffee\"; \"Water\"; \"Beer\"; \"Tea\"]\n\nlet smokes = [\"Blend\"; \"Prince\"; \"Blue Master\"; \"Dunhill\"; \"Pall Mall\"]\n\nlet pets = [\"Dog\"; \"Cat\"; \"Zebra\"; \"Horse\"; \"Bird\"]\n\n[ for nations in permute nations do\n if find nations \"Norwegian\" = 1 then\n for houses in permute houses do\n if eq nations \"British\" houses \"Red\" &&\n find houses \"Green\" = find houses \"White\"-1 &&\n nextTo nations \"Norwegian\" houses \"Blue\" then\n for drinks in permute drinks do\n if eq nations \"Danish\" drinks \"Tea\" &&\n eq houses \"Green\" drinks \"Coffee\" &&\n 3 = find drinks \"Milk\" then\n for smokes in permute smokes do\n if eq houses \"Yellow\" smokes \"Dunhill\" &&\n eq smokes \"Blue Master\" drinks \"Beer\" &&\n eq nations \"German\" smokes \"Prince\" &&\n nextTo smokes \"Blend\" drinks \"Water\" then\n for pets in permute pets do\n if eq nations \"Swedish\" pets \"Dog\" &&\n eq smokes \"Pall Mall\" pets \"Bird\" &&\n nextTo pets \"Cat\" smokes \"Blend\" &&\n nextTo pets \"Horse\" smokes \"Dunhill\" then\n yield nations, houses, drinks, smokes, pets ]\n val it :\n (string list * string list * string list * string list * string list) list =\n [([\"Norwegian\"; \"Danish\"; \"British\"; \"German\"; \"Swedish\"],\n [\"Yellow\"; \"Blue\"; \"Red\"; \"Green\"; \"White\"],\n [\"Water\"; \"Tea\"; \"Milk\"; \"Coffee\"; \"Beer\"],\n [\"Dunhill\"; \"Blend\"; \"Pall Mall\"; \"Prince\"; \"Blue Master\"],\n [\"Cat\"; \"Horse\"; \"Bird\"; \"Zebra\"; \"Dog\"])]\n" }, { "answer_id": 70651335, "author": "Mad Physicist", "author_id": 2988730, "author_profile": "https://Stackoverflow.com/users/2988730", "pm_score": 0, "selected": false, "text": "Solver adjecent_to match positions = [1, 2, 3, 4, 5]\nnationalities = [\n 'Englishman', 'Spaniard', 'Ukrainian', 'Norwegian', 'Japanese'\n]\ncolors = ['red', 'green', 'ivory', 'yellow', 'blue']\npets = ['dog', 'snails', 'fox', 'horse', 'ZEBRA']\ndrinks = ['coffee', 'tea', 'milk', 'orange juice', 'WATER']\ncigarettes = [\n 'Old Gold', 'Kools', 'Chesterfields', 'Lucky Strikes', 'Parliaments'\n]\n\nproblem = {\n 'position': positions,\n 'nationality': nationalities,\n 'color': colors,\n 'pet': pets,\n 'drink': drinks,\n 'cigarette': cigarettes,\n}\n\n\nsolver = Solver(problem)\n\n\nif __name__ == '__main__':\n solver.match('Englishman', 'red')\n solver.match('Spaniard', 'dog')\n solver.match('coffee', 'green')\n solver.match('Ukrainian', 'tea')\n solver.greater_than('green', 'ivory', 'position', 1)\n solver.match('Old Gold', 'snails')\n solver.match('Kools', 'yellow')\n solver.match('milk', 3)\n solver.match('Norwegian', 1)\n solver.adjacent_to('Chesterfields', 'fox', 'position')\n solver.adjacent_to('Kools', 'horse', 'position')\n solver.match('Lucky Strikes', 'orange juice')\n solver.match('Japanese', 'Parliaments')\n solver.adjacent_to('Norwegian', 'blue', 'position')\n\n solver.draw(show=False, title=f'After Rules: {solver.edges} Edges')\n\n print(f'Solved? {solver.solved}')\n print(f'{solver.category_for(\"ZEBRA\", \"nationality\")} owns the ZEBRA')\n print(f'{solver.category_for(\"WATER\", \"nationality\")} drinks WATER')\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444/" ]
318,906
<p>I'm having some problems with a datagridview element I'm using in VS2008. This DataGridView is actually a tab in a TabControl element.</p> <p>I gave it 5 colums which need to be filled up with elements from a costum Object i made.</p> <p>It's basically a small library application which contains a main class and several classed derived from it. They all have a ToString() method which represents the data as a string of keywords containing the values needed for me to fill up the datagridview.</p> <p>I only need the first 5 though, some objects will have up to 12 keywords. Currently, Whenever I add an object, the datagrid doesn't fill itself, instead it adds an amount of columns equall to the amount of keywords the specific object has.</p> <p>What i'm currently doing is this:</p> <pre><code>public void libDataGrid_Click(object sender, EventArgs e) { if(this.manager.Lib.LibList[0] != null) { libDataGrid.DataSource = this.manager.Lib.LibList; libDataGrid.Refresh(); } } </code></pre> <p><code>this.manager.Lib.LibList</code> returns and ArrayList, in which all objects are stored. The ArrayList can contain elements of all derived classes, but since they are all connected, the string representation will always contain the elements I need to fill up the grid.</p> <p>I don't see how I can filter only the first five and them have them put in the correct colums.</p> <p>And another thing. Currently I can only refresh the DataGridView by clicking it. It should change on when I switch to it switch to its specific tab on the Tabcontrol I mean.</p> <p>I tried adding an argument for SelectedIndexChanged, but that does nothing really... Or at least, it doesn't appear to do anything.</p> <p>What I mean is I commented out the code above and added this instead:</p> <pre><code>public void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { libDataGrid.DataSource = this.manager.Lib.LibList; libDataGrid.Refresh(); } </code></pre> <p>This refreshes it everytime the tab is changed, no matter to which one. I had to remove the if-statement, since it gave me an Exception. Probably because the length of the ArrayList isn't set on initialisation.</p>
[ { "answer_id": 318928, "author": "dragonjujo", "author_id": 37344, "author_profile": "https://Stackoverflow.com/users/37344", "pm_score": 0, "selected": false, "text": "public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)\n {\n libDataGrid.DataSource = this.manager.Lib.LibList;\n libDataGrid.Refresh();\n }\n tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);\n" }, { "answer_id": 318935, "author": "Pretzel", "author_id": 21244, "author_profile": "https://Stackoverflow.com/users/21244", "pm_score": 0, "selected": false, "text": "libDataGrid.Invalidate();\n" }, { "answer_id": 319300, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "DataGridView AutoGenerateColumn DataPropertyName DataGridView TypeDescriptor List<T> T object ArrayList ArrayList" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
318,915
<p>I'm using the following code</p> <pre><code>System::Diagnostics::Process^ p = gcnew System::Diagnostics::Process(); p-&gt;StartInfo-&gt;FileName = "tnccmd.exe"; p-&gt;StartInfo-&gt;UseShellExecute = false; p-&gt;StartInfo-&gt;RedirectStandardInput = true; p-&gt;StartInfo-&gt;RedirectStandardOutput = true; p-&gt;Start(); System::IO::StreamWriter^ tnc_stdin = p-&gt;StandardInput; System::IO::StreamReader^ tnc_stdout = p-&gt;StandardOutput; tnc_stdin-&gt;WriteLine("connect i 127.0.0.1"); String^ prg_output = tnc_stdout-&gt;ReadToEnd(); </code></pre> <p>My problem is that I cannot read <code>stdout</code> correctly. I can easily write to <code>stdin</code> however, but now I'm trying to implement some error checking code and it doesn't work.</p> <p>The program I'm using doesn't seem to write to <code>stdout</code> even if it is made to run in command line. I can reproduce the <code>bug</code> with <code>ftp.exe</code> which comes with <code>Windows XP</code> by default. If you change the <code>-&gt;FileName</code> with <code>ftp.exe</code> the command prompt <code>ftp.exe</code> usually gives <code>ftp&gt;</code> will not show up in <code>prg_output</code>.</p> <p>Now I know that the prompt must use some kind of <code>windows shell curses</code> and I may be mixing up problems.</p> <p>Normaly just after the <code>connect i 127.0.0.1</code> instruction I'm supposed to received <code>connecting to 127.0.0.1...</code> but I receive nothing.</p> <p>Any hint on what I'm doing wrong? Is there another kind of <code>stdout</code> that I'm not aware of?</p> <p>EDIT</p> <p>I cannot use arguments because I have multiple lines to write, much like with <code>ftp.exe</code>. Also, <code>ftp.exe</code> does output when you type commands like dir. At least it outputs when you write unknown commands, it complains about <code>Invalid command</code>.</p>
[ { "answer_id": 318928, "author": "dragonjujo", "author_id": 37344, "author_profile": "https://Stackoverflow.com/users/37344", "pm_score": 0, "selected": false, "text": "public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)\n {\n libDataGrid.DataSource = this.manager.Lib.LibList;\n libDataGrid.Refresh();\n }\n tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);\n" }, { "answer_id": 318935, "author": "Pretzel", "author_id": 21244, "author_profile": "https://Stackoverflow.com/users/21244", "pm_score": 0, "selected": false, "text": "libDataGrid.Invalidate();\n" }, { "answer_id": 319300, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "DataGridView AutoGenerateColumn DataPropertyName DataGridView TypeDescriptor List<T> T object ArrayList ArrayList" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
318,918
<p>Is there a way to set a maximum size for files that can be check in into source control under Team Foundation Server 2005 or 2008?</p> <p>In the past, when we worked with SourceSafe there were several cases were developers decided to checkin a 500mb data file to source control. </p> <p>I don't know what such a thing will do to TFS - and actually, I don't want to find out.</p> <p><strong>Edit:</strong> Custom checkin policy is not a viable solution for two reasons:</p> <ol> <li><p>it is done in the client side - I want the server to protect itself from such an abuse</p></li> <li><p>custom checkin policy can be overridden by the user.</p></li> </ol>
[ { "answer_id": 318928, "author": "dragonjujo", "author_id": 37344, "author_profile": "https://Stackoverflow.com/users/37344", "pm_score": 0, "selected": false, "text": "public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)\n {\n libDataGrid.DataSource = this.manager.Lib.LibList;\n libDataGrid.Refresh();\n }\n tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);\n" }, { "answer_id": 318935, "author": "Pretzel", "author_id": 21244, "author_profile": "https://Stackoverflow.com/users/21244", "pm_score": 0, "selected": false, "text": "libDataGrid.Invalidate();\n" }, { "answer_id": 319300, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "DataGridView AutoGenerateColumn DataPropertyName DataGridView TypeDescriptor List<T> T object ArrayList ArrayList" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38265/" ]
318,923
<p>I'd like to <strong>indent a block of text</strong>.</p> <p>I am able to do this in the <strong>Linux</strong> build of gVim.</p> <p>I do this in the <strong>state</strong> of gVim where I'm not in the insert or visual mode. The bar at the bottom is blank on the left, and the line number and percentage are showing on the right hand side.</p> <p>Then I perform the following <strong>procedure</strong>: I select a block of text via click and drag. Then I hit <kbd>Shift</kbd> + <kbd>.</kbd>. After that, I hit <kbd>Esc</kbd> and the block of text will move over a tab.</p> <p>If I do this in <strong>Windows</strong> however, it just replaces the block with <code>&gt;</code>.</p> <p>I am just running the stock Windows <strong>rc file</strong> and version 7.1 of gVim.</p>
[ { "answer_id": 318941, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 1, "selected": false, "text": "behave mswin behave xterm" }, { "answer_id": 321442, "author": "csexton", "author_id": 19839, "author_profile": "https://Stackoverflow.com/users/19839", "pm_score": 3, "selected": false, "text": "\" Pressing < or > will let you indent/unident selected lines\nvnoremap < <gv\nvnoremap > >gv\n" }, { "answer_id": 322055, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 1, "selected": false, "text": ">ap >aB :h text-objects" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21906/" ]
318,926
<p>i've populated a dropdownlist control with different text properties but each text properties had THE SAME value (text property was A, value properties is blah,text property was B, value properties is blahblah, etc... )</p> <p>ASP.net only checks value properties on postback and because ALL values were the same (for testing reason) this little annoying behavior happened. Is there a work around? does this mean you can't never have the value to be the same? </p>
[ { "answer_id": 318948, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "AutoPostBack True <asp:DropDownList ID=\"myDDL\" runat=\"server\" AutoPostBack=\"True\">\n </asp:DropDownList>\n <asp:Label ID=\"lblSelItem\" runat=\"server\"Text=\"Currently Selected Item: 0\"></asp:Label>\n <asp:Label ID=\"lblSelVal\" runat=\"server\" Text=\"Currently Selected Value: X\"></asp:Label>\n List<string> MyData()\n {\n List<string> rtn = new List<string>();\n rtn.Add(\"I am the same value!\");\n rtn.Add(\"I am the same value!\");\n rtn.Add(\"I am the same value!\");\n rtn.Add(\"I am the same value!2\");\n return rtn;\n }\n\n protected void Page_Init()\n {\n if (!Page.IsPostBack)\n {\n // Load the Data for the DDL.\n myDDL.DataSource = MyData();\n myDDL.DataBind();\n }\n }\n\n protected void Page_Load(object sender, EventArgs e)\n {\n // Display the Currently Selected Item/Value.\n lblSelItem.Text = \"Currently Selected Item: \" + myDDL.SelectedIndex.ToString();\n lblSelVal.Text = \"Currently Selected Value: \" + myDDL.SelectedValue;\n }\n value <option> Dictionary<string, string> MyTwoColData()\n {\n Dictionary<string, string> rtn = new Dictionary<string, string>();\n rtn.Add(\"1\", \"I am the same value!\");\n rtn.Add(\"2\", \"I am the same value!\");\n rtn.Add(\"3\", \"I am the same value!\");\n return rtn;\n }\n\n protected void Page_Init()\n {\n if (!Page.IsPostBack)\n {\n // Load the Data for the DDL.\n Dictionary<string, string> data = MyTwoColData();\n\n foreach (KeyValuePair<string, string> pair in MyTwoColData())\n {\n myDDL.Items.Add(new ListItem(pair.Value, pair.Key));\n }\n\n myDDL.DataBind();\n }\n }\n i SelectedItem SelectedValue" }, { "answer_id": 320179, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 0, "selected": false, "text": "<SELECT> VALUE <OPTION>" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
318,938
<p>Testing:</p> <pre><code>return request.getCookies() == null; </code></pre> <p>is not an appropriate way test. Is there another way?</p>
[ { "answer_id": 319091, "author": "digitalsanctum", "author_id": 22436, "author_profile": "https://Stackoverflow.com/users/22436", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\">\nvar cookieEnabled=(navigator.cookieEnabled)? true : false\n\n//if not IE4+ nor NS6+\nif (typeof navigator.cookieEnabled==\"undefined\" && !cookieEnabled){ \ndocument.cookie=\"testcookie\"\ncookieEnabled=(document.cookie.indexOf(\"testcookie\")!=-1)? true : false\n}\n\n//if (cookieEnabled) //if cookies are enabled on client's browser\n//do whatever\n\n</script>\n" }, { "answer_id": 319102, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 3, "selected": false, "text": "import javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class Test4Cookies extends HttpServlet {\n\n private static final Cookie cookie = new Cookie( \"hello\" , \"world\" );\n private static final String paramName = \"foo\";\n private static final String successURI = \"/success.htm\";\n private static final String failureURI = \"/failure.htm\";\n\n public void doPost(HttpServletRequest req, HttpServletResponse res) {\n if ( req.getParameter( paramName ) == null ) {\n res.addCookie( cookie );\n res.sendRedirect(req.getRequestURI() +\"?\"+ paramName +\"=bar\" );\n } \n else {\n res.sendRedirect\n (( req.getCookies().length == 0 ) ? failureURI : successURI \n )\n }\n\n public void doGet(HttpServletRequest req, HttpServletResponse res) {\n doPost(req, res);\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39371/" ]
318,940
<p>I can't find a good way of putting Eclipse windows on two monitors. Currently I just detached (clicked on a header and dragged) a few windows to a secondary monitor (package explorer, console, and outline) while leaving primary monitor with maximized source editing window. </p> <p>It works pretty well except few annoying issues. Detached windows are not in focus while you are editing your code. Which means that, for example, last build shortcut (<kbd>Alt</kbd>-<kbd>Shift</kbd>-<kbd>X</kbd>, <kbd>Q</kbd>) doesn't work because it can't find build file (because package explorer is not in focus). Also "Selected resources" option in a file search menu is not picking up current package selection.</p> <p>So I was wondering is detaching windows a right way to go? Do you have any better solutions so at least package explorer stays in focus?</p> <p>Thanks.</p> <p>PS. Btw "unable to find build" error started showing up only in 3.4 ver for some reason.</p>
[ { "answer_id": 28252174, "author": "azerafati", "author_id": 3160597, "author_profile": "https://Stackoverflow.com/users/3160597", "pm_score": 2, "selected": false, "text": "P cntrl+{ normal dual monitor" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
318,942
<p>I know what PermGen is, what it's used for, why it fails, how to increase it etc.</p> <p>What I don't know is what PermGen actually stands for. Permanent... Gen... something?</p> <p>Does anyone know what PermGen actually stands for?</p>
[ { "answer_id": 320469, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 7, "selected": true, "text": "classes.jsa" }, { "answer_id": 320901, "author": "bajafresh4life", "author_id": 21339, "author_profile": "https://Stackoverflow.com/users/21339", "pm_score": 6, "selected": false, "text": "-XX:MaxPermSize=384m" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
318,952
<p>How do I convert a string into the corresponding code in PLT Scheme (which does not contain the <code>string-&gt;input-port</code> method)? For example, I want to convert this string:</p> <pre><code>"(1 (0) 1 (0) 0)" </code></pre> <p>into this list:</p> <pre><code>'(1 (0) 1 (0) 0) </code></pre> <p>Is it possible to do this without opening a file?</p>
[ { "answer_id": 318978, "author": "Brian Gianforcaro", "author_id": 3415, "author_profile": "https://Stackoverflow.com/users/3415", "pm_score": 2, "selected": false, "text": "(let ((my-port (open-output-file \"Foo\")))\n (display \"(1 (0) 1 (0) 0)\" my-port)\n (close-output-port my-port))\n\n(let* ((my-port (open-input-file \"Foo\"))\n (answer (read my-port)))\n (close-input-port my-port)\n answer)\n" }, { "answer_id": 319029, "author": "Juha Autero", "author_id": 6363, "author_profile": "https://Stackoverflow.com/users/6363", "pm_score": 4, "selected": true, "text": "read string->input-port (read (string->input-port \"(1 (0) 1 (0) 0)\"))\n" }, { "answer_id": 320468, "author": "Anton Nazarov", "author_id": 38204, "author_profile": "https://Stackoverflow.com/users/38204", "pm_score": 3, "selected": false, "text": "(open-input-string string [name-v]) name-v 'string" }, { "answer_id": 320533, "author": "Joel Borggrén-Franck", "author_id": 38222, "author_profile": "https://Stackoverflow.com/users/38222", "pm_score": 1, "selected": false, "text": "with-input-from-string str thunk thunk str (with-input-from-string \"(foo bar)\"\n (lambda () (read))) (foo bar) thunk" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7648/" ]
318,964
<p>I'm building a new app that is using NHibernate to generate the database schema but i can see a possible problem in the future.</p> <p>Obviously you use all the data from your database is cleared when you update the schema but what stratagies do people use to restore any data to the new database. I am aware that massive changes to the schema will make this hard but was wondering how other people have dealt with this problem.</p> <p>Cheers Colin G</p> <p>PS I will not be doing this against the live database only using it to restore test data for integration test and continuous integration</p>
[ { "answer_id": 323495, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 4, "selected": true, "text": "public class CustomerBuilder : Builder<Customer>\n{\n string firstName;\n string lastName;\n Guid id = Guid.Empty;\n\n public override Customer Build()\n {\n return new Customer() { Id = id, FirstName = firstName, LastName = }\n }\n\n public CustomerBuilder WithId(Guid newId)\n {\n id= newId;\n return this;\n }\n\n public CustomerBuilder WithFirstName(string newFirstName)\n {\n firstName = newFirstName;\n return this;\n }\n\n public CustomerBuilder WithLastName(string newLastName)\n {\n lastName = newLastName;\n return this;\n }\n}\n var customer = new CustomerBuilder().WithFirstName(\"John\").WithLastName(\"Doe\").Build();\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1213936/" ]
318,969
<p>i have a basic ruby class:</p> <pre><code>class LogEntry end </code></pre> <p>and what i would like to do is be able to define a hash with a few values like so:</p> <pre><code>EntryType = { :error =&gt; 0, :warning =&gt; 1, :info =&gt; 2 } </code></pre> <p>so that i can access the values like this (or something similar):</p> <pre><code>LogEntry.EntryType[:error] </code></pre> <p>is this even possible in Ruby? am i going about this the right way?</p>
[ { "answer_id": 318981, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 4, "selected": true, "text": "class LogEntry\n EntryType = { :error => 0, :warning => 1, :info => 2 }\nend\n LogEntry::EntryType[:error]\n" }, { "answer_id": 318994, "author": "Chris Lloyd", "author_id": 42413, "author_profile": "https://Stackoverflow.com/users/42413", "pm_score": 1, "selected": false, "text": "class LogEntry\n\n def self.types\n { :error => 0, :warning => 1, :info => 2 }\n end\n\nend\n\n# And a simple test\nLogEntry.types[:error].should be_an_instance_of(Hash)\n" }, { "answer_id": 319076, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 0, "selected": false, "text": "class LogEntry\n @@ErrorType = 0\nEnd\n\nLogEntry.ErrorType\n" }, { "answer_id": 324494, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 0, "selected": false, "text": "class LogEntry\n attr_reader :type\n ERROR_RANKING = [ :error, :warning, :info, ]\n include Comparable\n\n def initialize( type )\n @type = type\n end\n\n def <=>( other )\n ERROR_RANKING.index( @type ) <=> ERROR_RANKING.index( other.type )\n end\nend\n\nentry1 = LogEntry.new( :error )\nentry2 = LogEntry.new( :warning )\n\nputs entry1.type.inspect\n#=> :error\nputs entry2.type.inspect\n#=> :warning\nputs( ( entry1 > entry2 ).inspect )\n#=> false\nputs( ( entry1 < entry2 ).inspect )\n#=> true\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
318,988
<p>Let's say I have a table like this:</p> <pre><code>name | score_a | score_b -----+---------+-------- Joe | 100 | 24 Sam | 96 | 438 Bob | 76 | 101 ... | ... | ... </code></pre> <p>I'd like to select the minimum of score_a and score_b. In other words, something like:</p> <pre><code>SELECT name, MIN(score_a, score_b) FROM table </code></pre> <p>The results, of course, would be:</p> <pre><code>name | min -----+----- Joe | 24 Sam | 96 Bob | 76 ... | ... </code></pre> <p>However, when I try this in Postgres, I get, "No function matches the given name and argument types. You may need to add explicit type casts." MAX() and MIN() appear to work across <em>rows</em> rather than <em>columns.</em></p> <p>Is it possible to do what I'm attempting?</p>
[ { "answer_id": 318993, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 10, "selected": true, "text": "GREATEST LEAST GREATEST LEAST" }, { "answer_id": 319092, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": false, "text": "LEAST()" }, { "answer_id": 43567578, "author": "Mohamed Aamir", "author_id": 7516331, "author_profile": "https://Stackoverflow.com/users/7516331", "pm_score": -1, "selected": false, "text": "SELECT name, MIN(score_a, score_b) as minimum_score\nFROM table\n score_a score_b minimum_score" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91385/" ]
318,998
<p>I am currently building a .Net userform using C# and I am populating it with custom user controls. The controls each have an accessor that gets and sets the object that contains the data that the control will be populated with.</p> <p>At runtime, everything works great, but at design time I will get errors in the form designer. The errors are always along the lines of "Cannot convert an object of type [ObjectA] to an object of type [ObjectA]"</p> <p>At this point, I can go into the resx file and delete the row that references the object of type ObjectA and then go into the designer.cs file and delete the line in InitializeComponent that sets the accessor of the control to the data from the resx file.</p> <p>Once I've done that, the form will display in the designer until it rebuilds the InitializeComponet and reinserts the lines / data into the resx and InitializeComponent.</p> <p>What am I missing in my control and class design that will end this cycle? I've tried using the Liscence Usage mode and the Designer runtime mode with mixed results and I would prefer it if I could solve this in my design.</p> <p>Thanks for any help that you can provide.</p> <p>Update: I added the attribute... </p> <pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] </code></pre> <p>To the property and I got an error in the designer "ObjectA is null, this is not allowed!", so I changed the line to ... </p> <pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] </code></pre> <p>and the issue went away. Since I don't need to set any of these properties at design time, the hidden attribute is probably more appropriate.</p> <p>Thanks.</p>
[ { "answer_id": 319019, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "protected override void OnPaintBackground(PaintEventArgs e)\n{\n if (this.DesignMode)\n {\n base.OnPaintBackground(e);\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5239/" ]
318,999
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/174968/how-many-parameters-are-too-many">How many parameters are too many?</a> </p> </blockquote> <p>I was just writing a function that took in several values and it got me thinking. When is the number number of arguments to a function / method too many? When (if) does it signal a flawed design? Do you design / refactor the function to take in structs, arrays, pointers, etc to decrease the amount of arguments? Do you refactor the data coming in just to decrease the number of arguments? It seems that this could be a little less applicable in OOP designs, though. Just curious to see how others view the issue.</p> <p>EDIT: For reference the function I just wrote took in 5 parameters. I use the definition of several that my AP Econ teacher gave me. More than 2; less than 7.</p>
[ { "answer_id": 319191, "author": "user35978", "author_id": 35978, "author_profile": "https://Stackoverflow.com/users/35978", "pm_score": 0, "selected": false, "text": "// In C \n draw_dot(x, y, size, red, green, blue, alpha)\n\n// In C# \n Point point(x,y);\n Color color(red,green,blue,alpha);\n\n Tool.DrawDot(point, color);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/318999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28714/" ]
319,002
<p>I use custom Attributes in a project and I would like to integrate them in my unit-tests.</p> <p>Now I use Rhino Mocks to create my mocks but I don't see a way to add my attributes (and there parameters) to them.</p> <p>Did I miss something, or is it not possible? Other mocking framework? Or do I have to create dummy implementations with my attributes?</p> <p>example: I have an interface in a plugin-architecture (IPlugin) and there is an attribute to add meta info to a property. Then I look for properties with this attribute in the plugin implementation for extra processing (storing its value, mark as gui read-only...)</p> <p>Now when I create a mock can I add easily an attribute to a property or the object instance itself?</p> <p>EDIT: I found a post with the same question -> <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=68&amp;t=001581" rel="nofollow noreferrer">link</a>. The answer there is not 100% and it is Java...</p> <p>EDIT 2: It can be done... searched some more (on SO) and found 2 related questions (+ answers)</p> <p><a href="https://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c">here</a> and <a href="https://stackoverflow.com/questions/268426/how-do-i-add-attributes-to-a-method-at-runtime">here</a></p> <p>Now, is this already implemented in one or another mocking framework?</p>
[ { "answer_id": 319219, "author": "Joseph Anderson", "author_id": 18102, "author_profile": "https://Stackoverflow.com/users/18102", "pm_score": 1, "selected": false, "text": "[TestFixture] public class SomeRandomAttributeTest\n{\n [SomeRandom(RestrictionType.Local)]\n public void PlaceholderMethodForAttribute() {throw new ApplicationException(this.ToString());}\n\n [Test]public void BlahBlahIsBlahTheBlah()\n {\n object[] attributes = this.GetType().GetMethod(\"PlaceholderMethodForAttribute\").GetCustomAttributes(false);\n Assert.AreEqual(1, attributes.Length);\n Assert.IsInstanceOfType(typeof(SomeRandomAttribute), attributes[0]);\n\n Assert.AreEqual(\"Yada yada yada\", ((SomeRandomAttribute) attributes[0]).Yada);\n\n }\n}\n" }, { "answer_id": 656453, "author": "Bas Bossink", "author_id": 74198, "author_profile": "https://Stackoverflow.com/users/74198", "pm_score": 1, "selected": false, "text": "var sut = new SomeRandomAttribute(RestrictionType.Local);\nAssert.AreEqual(\"Yada yada yada\", sut.Yada);\n SomeRandomAttribute" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23805/" ]
319,038
<p>I've added a jpg file to the App_localResources folder and in the document properites specified the photo in the Background propery. In the designer it shows up as the background but when i run the page i still get the white page background.</p>
[ { "answer_id": 319161, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 3, "selected": false, "text": "body { background-image: url('background.jpg'); }\n runat=\"server\"" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,057
<p>trying to implement a dialog-box style behaviour using a separate div section with all the stuff inside it.</p> <p>When the "dialog box" needs to be shown, it has to display at the center of the WINDOW, not in the center of the page, that is, REGARDLESS of the scroling position. Furthermore, the correct solution will not move the "dialog box" if the user scrolls the page.</p> <p>In Chrome and FF this works using position='fixed' and centering the div in the intuitive way.</p> <p>This does not seem to work in IE6 (apparently fixed is not supported there). </p> <p>Any ideas?</p>
[ { "answer_id": 319166, "author": "Perpetualcoder", "author_id": 37494, "author_profile": "https://Stackoverflow.com/users/37494", "pm_score": 3, "selected": true, "text": "body { \n font: 80% verdana, arial, helvetica, sans-serif; \n text-align: center; /* for IE */ \n} \n\n#container { \n margin: 0 auto; /* align for good browsers */ \n text-align: left; /* counter the body center */\n border: 2px solid #000; \n width: 80%; \n}\n" }, { "answer_id": 8797742, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 0, "selected": false, "text": "overflow-y html {overflow-y: } body{overflow-y: } body { margin:0; height:100% } top:50%; left:50%; position:relative <!DOCTYPE html>\n<html>\n <head>\n <style>\n body { margin:0; margin-left: 14em; }\n\n #fixedbox { position: fixed; top: 1em; left: 1em; width: 10em; }\n\n #fixedbox { padding: 0.5em; border: 1px solid #000; }\n\n #container { height: 2000px; }\n\n @media,\n {\n html { _overflow-y: visible; *overflow-y: auto; }\n body { _overflow-y: auto; _height: 100%; }\n #container { _position: relative; }\n #fixedbox { _position: absolute; _top:50%; _left: 50%; }\n }\n </style>\n </head>\n <body>\n <div id=\"container\">\n Fixed box\n </div>\n\n <div id=\"fixedbox\">\n Homer\n </div>\n </body>\n</html>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19584/" ]
319,095
<p>I have several files that are in several different languages. I thought they were all encoded UTF-8, but now I'm not so sure. Some characters look fine, some do not. Is there a way that I can break out the strings and try to identify the character sets? Perhaps split on white space then identify each word? Finally, is there an easy way to translate characters from one set to UTF-8?</p>
[ { "answer_id": 319144, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "n n n - 1" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,108
<p>I have a list of items in a hierarchy, and I'm attempting to parse this list out into an actual hierarchy of objects. I'm using <a href="http://www.sitepoint.com/article/hierarchical-data-database/2/" rel="noreferrer">modified pre-order tree traversal</a> to store/iterate through this list, and so what I have is a subset of the tree, including all children, ordered by their "left" value.</p> <p>For example, given the tree:</p> <ul> <li>Item A <ul> <li>Item A.1</li> <li>Item A.2 <ul> <li>Item A.2.2</li> </ul></li> </ul></li> <li>Item B <ul> <li>Item B.1</li> </ul></li> <li>Item C</li> </ul> <p>I get the list:</p> <ul> <li>Item A, Item A.1, Item A.2, Item A.2.2, Item B, Item B.1, Item C</li> </ul> <p>(This is in order of the "left" value from the modified pre-order tree setup).</p> <p>What I want to do is parse this into objects that contain the actual structure of the tree, eg:</p> <pre><code>Class TreeObject { String Name; Guid ID; Guid ParentID; List&lt;TreeObject&gt; Children; } </code></pre> <p>The flat list is returned as a List of TreeObjects - and each TreeObject has properties for ID, ParentID, Left, and Right. What I'm looking for is a function:</p> <pre><code>List&lt;TreeObject&gt; FlatToHeirarchy(List&lt;TreeObject&gt; list); </code></pre> <p>which takes the flat list in, and returns a nested list.</p> <p>In other words:</p> <pre><code>List&lt;TreeObject&gt; flatSet = LoadTreeObjectsFromDatabase(); // flatSet.count == 7; flatSet(0).Children == null List&lt;TreeObject&gt; nestedSet = FlatToHeirarchy(flatSet); // nestedSet.count == 3; nestedSet(0).Children.count == 2 </code></pre> <p>I'm at a loss how to do this - keeping track of parents, and being able to deal with a bigger jump (eg, Item A.2.2 -> Item B).</p> <hr> <p>Edit: I'm looking for a non-brute-force solution here (eg, not looping several times, moving items into child nodes, until there are only the top-level parents left). I'm guessing there is an elegant method that can loop once, and just place items as needed.</p> <p>Remember, they are always in a hierarchal order (since I'm using MPTT), so a given item is going to always be a child or sibling of the previous item, or at least share a parent with the previous item. It is never going to come somewhere else in the tree.</p>
[ { "answer_id": 319127, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 2, "selected": false, "text": "foreach Item item in flatlist\n if item.Parent != null\n Add item to item.Parent.ChildrenList\n Remove item from flatlist\n end if\nend for\n" }, { "answer_id": 319239, "author": "Rohan West", "author_id": 38686, "author_profile": "https://Stackoverflow.com/users/38686", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n TreeObject a = new TreeObject() { Name = \"Item A\" };\n a.Children.Add( new TreeObject() { Name = \"Item A.1\" });\n a.Children.Add( new TreeObject() { Name = \"Item A.2\" });\n\n TreeObject b = new TreeObject() { Name = \"Item B\" };\n b.Children.Add(new TreeObject() { Name = \"Item B.1\" });\n b.Children.Add(new TreeObject() { Name = \"Item B.2\" });\n\n TreeObject c = new TreeObject() { Name = \"Item C\" };\n\n List<TreeObject> nodes = new List<TreeObject>(new[] { a, b, c });\n\n string list = BuildList(nodes);\n Console.WriteLine(list); // Item A,Item A.1,Item A.2,Item B,Item B.1,Item B.2,Item C\n\n List<TreeObject> newlist = new List<TreeObject>();\n TreeObject temp = null;\n\n foreach (string s in list.Split(','))\n {\n if (temp == null || !s.Contains(temp.Name) || temp.Name.Length != s.Length)\n {\n temp = new TreeObject() { Name = s };\n newlist.Add(temp);\n }\n else\n {\n temp.Children.Add(new TreeObject() { Name = s });\n } \n }\n\n Console.WriteLine(BuildList(newlist)); // Item A,Item A.1,Item A.2,Item B,Item B.1,Item B.2,Item C\n }\n\n static string BuildList(List<TreeObject> nodes)\n {\n StringBuilder output = new StringBuilder();\n BuildList(output, nodes);\n return output.Remove(output.Length - 1, 1).ToString();\n }\n\n static void BuildList(StringBuilder output, List<TreeObject> nodes)\n {\n foreach (var node in nodes)\n {\n output.AppendFormat(\"{0},\", node.Name);\n BuildList(output, node.Children);\n }\n }\n}\n\npublic class TreeObject\n{\n private List<TreeObject> _children = new List<TreeObject>();\n\n public string Name { get; set; }\n public Guid Id { get; set; }\n public List<TreeObject> Children { get { return _children; } }\n}\n" }, { "answer_id": 444556, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 6, "selected": true, "text": "public class TreeObject\n{\n public int Id { get; set; }\n public int ParentId { get; set; }\n public string Name { get; set; }\n public IList<TreeObject> Children { get; set; } = new List<TreeObject>();\n}\n\npublic IEnumerable<TreeObject> FlatToHierarchy(List<TreeObject> list)\n{\n // hashtable lookup that allows us to grab references to containers based on id\n var lookup = new Dictionary<int, TreeObject>();\n // actual nested collection to return\n var nested = new List<TreeObject>();\n\n foreach (TreeObject item in list)\n {\n if (lookup.ContainsKey(item.ParentId))\n {\n // add to the parent's child list \n lookup[item.ParentId].Children.Add(item);\n }\n else\n {\n // no parent added yet (or this is the first time)\n nested.Add(item);\n }\n lookup.Add(item.Id, item);\n }\n\n return nested;\n}\n void Main()\n{\n var list = new List<TreeObject>() {\n new TreeObject() { Id = 1, ParentId = 0, Name = \"A\" },\n new TreeObject() { Id = 2, ParentId = 1, Name = \"A.1\" },\n new TreeObject() { Id = 3, ParentId = 1, Name = \"A.2\" },\n new TreeObject() { Id = 4, ParentId = 3, Name = \"A.2.i\" },\n new TreeObject() { Id = 5, ParentId = 3, Name = \"A.2.ii\" }\n };\n\n FlatToHierarchy(list).Dump();\n}\n public IList<TreeObject> FlatToHierarchy(IEnumerable<TreeObject> list, int parentId = 0) {\n return (from i in list \n where i.ParentId == parentId \n select new TreeObject {\n Id = i.Id, \n ParentId = i.ParentId,\n Name = i.Name,\n Children = FlatToHierarchy(list, i.Id)\n }).ToList();\n}\n" }, { "answer_id": 7313557, "author": "Chris Barry", "author_id": 6822, "author_profile": "https://Stackoverflow.com/users/6822", "pm_score": 1, "selected": false, "text": "private List<Page> FlatToHierarchy(List<Page> list) {\n // hashtable lookup that allows us to grab references to the parent containers, based on id\n Dictionary<int, Page> lookup = new Dictionary<int, Page>();\n // actual nested collection to return\n List<Page> nested = new List<Page>();\n\n foreach(Page item in list) {\n if (lookup.ContainsKey(item.parentId)) {\n // add to the parent's child list \n lookup[item.parentId].children.Add(item); //add item to parent's childs list\n lookup.Add(item.pageId, item); //add reference to page in lookup table\n } else {\n // no parent added yet (or this is the first time)\n nested.Add(item); //add item directly to nested list \n lookup.Add(item.pageId, item); //add reference to page in lookup table\n }\n }\n return nested;\n }\n" }, { "answer_id": 22102203, "author": "Paulo Vj", "author_id": 1313042, "author_profile": "https://Stackoverflow.com/users/1313042", "pm_score": 0, "selected": false, "text": "IList<TreeObject> FlatToHierarchy(IQueryable<lcc_classe> list, int? parentId)\n {\n var q = (from i in list\n where i.parent_id == parentId\n select new\n {\n id = i.id,\n parent_id = i.parent_id,\n kks = i.kks,\n nome = i.nome\n }).ToList();\n return q.Select(x => new TreeObject\n {\n children = FlatToHierarchy(list, x.id)\n }).ToList();\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7913/" ]
319,113
<p>I have a JavaScript request going to a ASP.Net (2.0) HTTP handler which passes the request to a java web service. In this system special characters, such as those with an accent do not get passed on correctly.</p> <p>E.G.</p> <ul> <li>Human input: <code>Düsseldorf</code></li> <li>becomes a JavaScript asynch request to <code>http://site/serviceproxy.ashx?q=D%FCsseldorf</code>, which is valid in ISO-8859-1 as well as in UTF-8 as far as I can tell. (unless it's %c3%bc in UTF-8)</li> <li><code>HttpContext.Current.Request.QueryString.Get("q")</code> returns <code>D�sseldorf</code> which is where trouble begins.</li> <li>but <code>HttpUtility.UrlEncode(HttpContext.Current.Request.QueryString.Get("q"), Encoding.GetEncoding("ISO-8859-1"))</code> returns <code>D%3fsseldorf</code> (a '?')</li> <li>and <code>HttpUtility.UrlEncode(HttpContext.Current.Request.QueryString.Get("q"), Encoding.UTF8)</code> returns <code>D%ef%bfsseldorf</code></li> </ul> <p>So it the value doesn't get decoded nor re-encoded correctly to be passed on to the java service.</p> <ul> <li>Notice <code>HttpContext.Current.Request.Url.Query</code> is <code>?q=D%FCsseldorf&amp;output=json&amp;from=1&amp;to=10</code></li> <li>while <code>HttpContext.Current.Request.QueryString.ToString()</code> is <code>q=D%ufffdsseldorf&amp;output=json&amp;from=1&amp;to=10</code></li> </ul> <p>Why is this, and how can I tell the <code>HttpContext</code> to honor the request headers which include:</p> <pre><code>Content-Type=application/x-www-form-urlencoded;+charset=UTF-8 </code></pre> <p>and decode the URL's <code>QueryString</code> using the UTF-8 charset.</p> <p>Addendum: As the answer notes, the trouble lies not so much in the decoding as the encoding; using <code>escape()</code> in JavaScript does not escape according to UTF-8, while using <code>encodeURIComponent()</code> does.</p>
[ { "answer_id": 319412, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "%3f http://site/serviceproxy.ashx?q=D%C3%BCsseldorf encodeURI encodeURIComponent escape" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
319,120
<p>I would like to apply a transformation (rotation) to a <code>UIImageView</code>. I could just set the <code>transform</code> property of the view, but wouldn't setting the layer's <code>transform</code> make it faster? If so, how can I achieve this?</p> <p>Assuming I have a <code>UIImageView</code> initialized with an image, can anyone help? Wouldn't it be better to have a <code>UIVIew</code> with a <code>UIImageView</code> in it?</p>
[ { "answer_id": 319147, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 1, "selected": false, "text": "view.layer view.layer.affineTransform = newTranform; " } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,124
<p>In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don't mind doing p/invokes to Win32 dlls.</p> <p>Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized?</p>
[ { "answer_id": 319139, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 3, "selected": false, "text": "form.MinimizeBox = false;\n MinimizeBox = false;\n" }, { "answer_id": 319195, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 1, "selected": false, "text": "if (this.WindowState == FormWindowState.Minimized)\n{\n this.WindowState = FormWindowState.Normal;\n}\n" }, { "answer_id": 320145, "author": "Rob", "author_id": 34224, "author_profile": "https://Stackoverflow.com/users/34224", "pm_score": 5, "selected": true, "text": "\nusing System;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace NoMinimizeTest\n{\n public class MinimizeControlForm : Form\n {\n private const int WM_SYSCOMMAND = 0x0112;\n private const int SC_MINIMIZE = 0xf020;\n\n protected MinimizeControlForm()\n {\n AllowMinimize = true;\n }\n\n protected override void WndProc(ref Message m)\n {\n if (!AllowMinimize)\n {\n if (m.Msg == WM_SYSCOMMAND)\n {\n if (m.WParam.ToInt32() == SC_MINIMIZE)\n {\n m.Result = IntPtr.Zero;\n return;\n }\n }\n }\n base.WndProc(ref m);\n }\n\n [Browsable(true)]\n [Category(\"Behavior\")]\n [Description(\"Specifies whether to allow the window to minimize when the minimize button and command are enabled.\")]\n [DefaultValue(true)]\n public bool AllowMinimize\n {\n get;\n set;\n }\n }\n}\n \nusing System;\nusing System.Windows.Forms;\nusing System.ComponentModel;\n\nnamespace NoMinimizeTest\n{\n public class MinimizeControlForm : Form\n {\n private const int WM_SYSCOMMAND = 0x0112;\n private const int SC_MINIMIZE = 0xf020;\n\n protected MinimizeControlForm()\n {\n\n }\n\n protected override void WndProc(ref Message m)\n {\n if (m.Msg == WM_SYSCOMMAND)\n {\n if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed())\n {\n m.Result = IntPtr.Zero;\n return;\n }\n }\n base.WndProc(ref m);\n }\n\n private bool CheckMinimizingAllowed()\n {\n CancelEventArgs args = new CancelEventArgs(false);\n OnMinimizing(args);\n return !args.Cancel;\n }\n\n [Browsable(true)]\n [Category(\"Behavior\")]\n [Description(\"Allows a listener to prevent a window from being minimized.\")]\n public event CancelEventHandler Minimizing;\n\n protected virtual void OnMinimizing(CancelEventArgs e)\n {\n if (Minimizing != null)\n Minimizing(this, e);\n }\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21704/" ]
319,132
<p>Is there an easy way write to a file asynchronously in Python?</p> <p>I know the <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="noreferrer">file io that comes with Python</a> is blocking; which is fine in most cases. For this particular case, I need writes not to block the application at all, or at least as minimally as possible.</p>
[ { "answer_id": 983764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "read() EWOULDBLOCK EAGAIN select() poll() epoll() aio_read()" }, { "answer_id": 50511280, "author": "Guillaume Lebreton", "author_id": 5823489, "author_profile": "https://Stackoverflow.com/users/5823489", "pm_score": 2, "selected": false, "text": "Thread from threading import Thread\n\nfor file in list_file:\n tr = Thread(target=file.write, args=(data,))\n tr.start()\n join()" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30089/" ]
319,154
<p>I want <code>boost::any_cast&lt;T&gt;</code> to only throw an exception when the type of the <code>any</code> doesn't have an implicit conversion to <code>T</code>. The normal behaviour seems to be to throw an exception if the type of the <code>any</code> is not <code>T</code>, regardless of implicit conversions.</p> <p>Example:</p> <pre><code>boost::any a = 1; boost::any_cast&lt;int&gt;(a); // This succeeds, and rightfully so boost::any_cast&lt;long&gt;(a); // I don't want this to throw boost::any_cast&lt;Widget&gt;(a); // I want this to throw </code></pre> <p>Could anyone tell me if there's a simple way to get the functionality I want, or better yet give me a good reason for why the existing behaviour is the way it is?</p>
[ { "answer_id": 319196, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "any struct base {\n virtual ~base() { }\n};\n\ntemplate<typename T>\nstruct concrete_base : base {\n T t;\n concrete_base(T t):t(t) { }\n};\n\nstruct my_any {\n base * b;\n\n template<typename T>\n my_any(T t):b(new concrete_base<T>(t)) { }\n\n template<typename T>\n T any_cast() { \n concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b);\n if(!t) throw bad_any_cast();\n return t->t;\n }\n};\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40834/" ]
319,155
<p>I'm working on a project where I am using a script.aculo.us Sortable object.</p> <p>It works nice and fast in Firefox and Chrome, but in IE it is incredibly slow whenever I drop an element.</p> <p>I've done a little checking, and it turns out that in IE, the "onUpdate" callback function gets called about 8 times every time I drop. Normally it is supposed to only get called one time per sortable container (destination and origin).</p> <p>Since my callback function resizes some elements and draws graphs in those elements, the computation involved for each call is considerable.</p> <p>Does anyone know what could be causing this problem in IE, or how to fix it?</p> <p>EDIT: I've noticed that the problem isn't that it triggers many many times when it is dragged, the problem is that the <code>onUpdate</code> function gets fired when the order of a sortable changes, even if the drag hasn't ended. It seems that <code>onUpdate</code> is actually working like the <code>onChange</code> callback, but only IE.</p>
[ { "answer_id": 319196, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "any struct base {\n virtual ~base() { }\n};\n\ntemplate<typename T>\nstruct concrete_base : base {\n T t;\n concrete_base(T t):t(t) { }\n};\n\nstruct my_any {\n base * b;\n\n template<typename T>\n my_any(T t):b(new concrete_base<T>(t)) { }\n\n template<typename T>\n T any_cast() { \n concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b);\n if(!t) throw bad_any_cast();\n return t->t;\n }\n};\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12983/" ]
319,159
<p>I have an XML definition that contains an element with child elements. For example:</p> <pre><code>&lt;a&gt; &lt;b&gt; &lt;c&gt;C&lt;/c&gt; &lt;d&gt;D&lt;/d&gt; &lt;/b&gt; &lt;/a&gt; </code></pre> <p>I have an XSLT with an output of text. For example:</p> <pre><code>&lt;xsl...&gt; &lt;xsl:output method="text" indent="yes"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:copy-of select="/a/b" /&gt; ... </code></pre> <p>I want to copy the entire b element and its children into a whitespace-removed string so that I can generate a SQL query. For example:</p> <pre><code>select * from some-table where xml = '&lt;b&gt;&lt;c&gt;C&lt;/c&gt;&lt;d&gt;D&lt;/d&gt;&lt;/b&gt;' </code></pre> <p>At the moment copy-of is finding the b element but dropping off all element and attribute information leaving only the text content within each. I think this might be to do with the output type.</p> <p>Any ideas?</p>
[ { "answer_id": 319402, "author": "Scott McKenzie", "author_id": 26625, "author_profile": "https://Stackoverflow.com/users/26625", "pm_score": 1, "selected": false, "text": " <xsl:template match=\"b//*|node()\">\n <xsl:copy>\n <xsl:text>&lt;</xsl:text>\n <xsl:value-of select=\"name()\"/>\n <xsl:text>&gt;</xsl:text>\n <xsl:value-of select=\"text()\"/>\n <xsl:apply-templates select=\"*\"/>\n <xsl:text>&lt;/</xsl:text>\n <xsl:value-of select=\"name()\"/>\n <xsl:text>&gt;</xsl:text>\n </xsl:copy>\n </xsl:template>\n <xsl:apply-templates select=\"/a/b/self::*\"/>\n <b>\n <c>C</c>\n <d>D</d>\n </b>\n" }, { "answer_id": 320349, "author": "Maxim Kulkin", "author_id": 1142754, "author_profile": "https://Stackoverflow.com/users/1142754", "pm_score": -1, "selected": true, "text": "<xsl:output method=\"xml\" />\n\n<xsl:template match=\"/\"><xsl:apply-templates select=\"/a/b\" mode=\"normalize-space\" /></xsl:template>\n\n<xsl:template match=\"text()\" mode=\"normalize-space\"><xsl:value-of select=\"normalize-space(.)\" /></xsl:template>\n<xsl:template match=\"@*|node()\" mode=\"normalize-space\"><xsl:copy><xsl:apply-templates select=\"@*|node()\" mode=\"normalize-space\" /></xsl:copy></xsl:template>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26625/" ]
319,168
<p>I'm working on +1M LOC C/C++ project on Solaris (remote, via VNC or SSH). I have a daily updated copy of source code on my local machine too (Windows, just for browsing code).</p> <p>I use VIM and ctags combo (on both Solaris and Windows) but I'm not happy with results / speed. What settings for ctags would you recommend? There are a lot of options what should be tagged and how. Should I use single tag file per project, per dir or perhaps just one for everything?</p>
[ { "answer_id": 319402, "author": "Scott McKenzie", "author_id": 26625, "author_profile": "https://Stackoverflow.com/users/26625", "pm_score": 1, "selected": false, "text": " <xsl:template match=\"b//*|node()\">\n <xsl:copy>\n <xsl:text>&lt;</xsl:text>\n <xsl:value-of select=\"name()\"/>\n <xsl:text>&gt;</xsl:text>\n <xsl:value-of select=\"text()\"/>\n <xsl:apply-templates select=\"*\"/>\n <xsl:text>&lt;/</xsl:text>\n <xsl:value-of select=\"name()\"/>\n <xsl:text>&gt;</xsl:text>\n </xsl:copy>\n </xsl:template>\n <xsl:apply-templates select=\"/a/b/self::*\"/>\n <b>\n <c>C</c>\n <d>D</d>\n </b>\n" }, { "answer_id": 320349, "author": "Maxim Kulkin", "author_id": 1142754, "author_profile": "https://Stackoverflow.com/users/1142754", "pm_score": -1, "selected": true, "text": "<xsl:output method=\"xml\" />\n\n<xsl:template match=\"/\"><xsl:apply-templates select=\"/a/b\" mode=\"normalize-space\" /></xsl:template>\n\n<xsl:template match=\"text()\" mode=\"normalize-space\"><xsl:value-of select=\"normalize-space(.)\" /></xsl:template>\n<xsl:template match=\"@*|node()\" mode=\"normalize-space\"><xsl:copy><xsl:apply-templates select=\"@*|node()\" mode=\"normalize-space\" /></xsl:copy></xsl:template>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3579/" ]
319,171
<p>I understand the first argument must be the result of GetFileVersionInfo().</p> <p>The third and forth are target buffer and size</p> <p>What is the second argument, lpSubBlock?</p> <p>Thanks In Advance</p>
[ { "answer_id": 324903, "author": "Greg Domjan", "author_id": 37558, "author_profile": "https://Stackoverflow.com/users/37558", "pm_score": 3, "selected": true, "text": "VS_VERSION_INFO VERSIONINFO\n FILEVERSION 5,0,0,0\n PRODUCTVERSION 5,0,0,0\n FILEFLAGSMASK 0x3fL\n#ifdef _DEBUG\n FILEFLAGS 0x1L\n#else\n FILEFLAGS 0x0L\n#endif\n FILEOS 0x40004L\n FILETYPE 0x2L\n FILESUBTYPE 0x0L\nBEGIN\n BLOCK \"StringFileInfo\"\n BEGIN\n BLOCK \"040904b0\"\n BEGIN\n VALUE \"CompanyName\", \"\"\n VALUE \"FileVersion\", \"5, 0, 0, 0\"\n VALUE \"ProductName\", \"\"\n VALUE \"ProductVersion\", \"5, 0, 0, 0\"\n END\n BLOCK \"000004b0\"\n BEGIN\n VALUE \"CompanyName\", \"\"\n VALUE \"FileVersion\", \"5, 0, 0, 0\"\n VALUE \"ProductName\", \"\"\n VALUE \"ProductVersion\", \"5, 0, 0, 0\"\n END\n END\n BLOCK \"VarFileInfo\"\n BEGIN\n VALUE \"Translation\", 0x0, 1200, 0x409, 1200\n END\nEND\n VS_FIXEDFILEINFO *versionInfo;\nPUINT versionInfoSize;\nVerQueryValue(buffer.get(), TEXT(\"\\\\\"), (void**) &versionInfo, &versionInfoSize))\n Var *translationsInfo;\nPUINT transaltionInfoSize;\nVerQueryValue(buffer.get(), TEXT(\"\\\\VarFileInfo\\\\Translation\"), (void**) &translationsInfo, &transaltionInfoSize))\n StringTable *stringTable;\nPUINT stringTableSize;\nstd::wstring path( L\"\\\\StringFileInfo\\\\\" );\npath += L\"040904b0\"; // get this value from the language support list\npath += L\"\\\\FileVersion\";\nVerQueryValue(buffer.get(), path.c_str(), (void**) &stringTable, &stringTableSize))\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2167252/" ]
319,178
<p>I'm not sure how to ask the question, for I don't know what I don't know, and therefore I don't know the proper terminology for what I'm trying to get the answer to. I will explain my scenario, in hopes that it will help:</p> <p>I've got three tables, a Book table, a Tag table and a BookTag lookup table.</p> <p>Each book has an ID, a Title (for starters) Each tag has an ID, and a Title Each BookTag has an ID, a BookID, and a TagID.</p> <p>A book can be tagged with multiple tags, and a tag can be used on more than one BookID.</p> <p>I've got my objects setup in this fashion:</p> <pre><code>Book.cs int BookID string Title List&lt;BookTag&gt; Tags Tag.cs int TagID string Title BookTag.cs int ID int BookID int TagID </code></pre> <p>I would like the Books.cs class to have a collection of Tags, and not BookTags, but I cannot seem to get the mapping right in NHibernate. This is what I've got for the Book.hbm.xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainModel" namespace="DomainModel.Books"&gt; &lt;class name="DomainModel.Books.Book" table="Books"&gt; &lt;id name="BookID" type="Int32" unsaved-value="0"&gt; &lt;generator class="native"/&gt; &lt;/id&gt; &lt;property name="Title" type="String" not-null="true"/&gt; &lt;set lazy="true" name="Tags" table="BookTags" generic="true" inverse="true" cascade="delete"&gt; &lt;key column="BookID"/&gt; &lt;one-to-many class="DomainModel.Books.BookTag, DomainModel"/&gt; &lt;/set&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>And this is my BookTag.hbm.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DomainModel" namespace="DomainModel.Books"&gt; &lt;class name="DomainModel.Books.BookTag" table="BookTags"&gt; &lt;id column="BookTagID" name="BookTagID" type="Int32" unsaved-value="0"&gt; &lt;generator class="native"/&gt; &lt;/id&gt; &lt;many-to-one name="Tag"&gt; &lt;column not-null="true" name="TagID"/&gt; &lt;/many-to-one&gt; &lt;many-to-one name="Book"&gt; &lt;column not-null="true" name="BookID"/&gt; &lt;/many-to-one&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>Under this model, I can get to the tag I want by using my object model: Book.Tags[0].Tag, but that just seems inefficient. Can I use NHibernate to map out the BookTags.TagID with the Tags.TagID in the database so that I can get Book.Tags[0] to return a Tag object, instead of a BookTags object? I didn't know of a better way to associate Books to tags so that a tag used on Book1 can be used on Book2 without adding a new entry to the Tags table.</p> <p>I hope this makes at least some sense. Let me know if you need further clarification. I'll post my solution here if I figure it out before someone answers.</p>
[ { "answer_id": 319528, "author": "Carl", "author_id": 38375, "author_profile": "https://Stackoverflow.com/users/38375", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" assembly=\"DomainModel\" namespace=\"DomainModel.Books\">\n <class name=\"DomainModel.Books.Book\" table=\"Books\">\n <id name=\"BookID\" type=\"Int32\" unsaved-value=\"0\">\n <generator class=\"native\"/>\n </id>\n <property name=\"Title\" type=\"String\" not-null=\"true\"/>\n <bag name=\"Tags\" table=\"BookTag\" generic=\"true\">\n <key column=\"BookID\" on-delete=\"noaction\"></key>\n <many-to-many class=\"Tag\" column=\"TagID\"></many-to-many>\n </bag>\n </class>\n</hibernate-mapping>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38375/" ]
319,199
<p>An integer's max value in Java is 2147483647, since Java integers are signed, right?</p> <p>0xff000000 has a numeric value of 4278190080.</p> <p>Yet I see Java code like this:</p> <pre><code>int ALPHA_MASK = 0xff000000; </code></pre> <p>Can anyone enlighten me please?</p>
[ { "answer_id": 319283, "author": "balu", "author_id": 36253, "author_profile": "https://Stackoverflow.com/users/36253", "pm_score": 5, "selected": false, "text": " 000\n 111 001 \n110 010\n 101 011 \n 100 \n 000 (0)\n 111 001 (-1 / 1)\n110 010 (-2 / 2)\n 101 011 (-3 / 3)\n 100 (-4)\n 1111 1111 0000 0000 0000 0000 0000 0000\n 0000 0000 1111 1111 1111 1111 1111 1111\n 0000 0000 0000 0000 0000 0000 0000 0001\n 0000 0001 0000 0000 0000 0000 0000 0000 = 16777216\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
319,204
<p>How would you take an arbitrary list of strings (of the form "%[text]%") and a database column, and turn them into a SQL query that does a LIKE comparison for each string in the list?</p> <p>An example: I have three strings in my list, "%bc%", "%def%" and "%ab%". This builds the query:</p> <pre><code>([ColumnName] LIKE "%bc" AND [ColumnName] LIKE "%def%") AND [ColumnName] LIKE "%ab%" </code></pre> <p>A C# example would be excellent, but feel free to write it in the language of your choice.</p>
[ { "answer_id": 319240, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 0, "selected": false, "text": ">>> los=['ab', 'cd', 'ef']\n>>> ' and '.join((\"somecolumn like '%%%s%%'\" % s) for s in los)\n\"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'\"\n >>> ' and '.join((\"somecolumn like '%\" + s + \"%'\") for s in los)\n\"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'\"\n" }, { "answer_id": 319244, "author": "Rob", "author_id": 34224, "author_profile": "https://Stackoverflow.com/users/34224", "pm_score": 0, "selected": false, "text": "\nStringBuilder sql = new StringBuilder();\nif (list.Count > 0)\n sql.AppendFormat(CultureInfo.InvariantCulture, \"([{0}] LIKE \\\"{1}\\\"\", columnName, list[0]);\n\nfor (int i = 1; i < list.Count; i++)\n{\n sql.AppendFormat(CultureInfo.InvariantCulture, \" AND [{0}] LIKE \\\"{1}\\\"\", columnName, list[i]);\n}\n\nif (list.Count > 0)\n sql.Append(\")\");\n" }, { "answer_id": 319261, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 2, "selected": false, "text": "string.join(\" and \", \n (new[] { \"%bc%\", \"%def%\", \"%ab%\" })\n .Select(x => string.Format(\"[{0}] LIKE '{1}'\",columnName, x))\n .ToArray());\n select * from table\nwhere FREETEXT(\"bc def ab\")\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
319,210
<p>Would someone explain how to get LINQ working with Sqlite.</p>
[ { "answer_id": 319381, "author": "Luke Foust", "author_id": 646, "author_profile": "https://Stackoverflow.com/users/646", "pm_score": 2, "selected": false, "text": "select top 1 * from table where ...\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]