qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
240,242
<p>I have a main window (#1) on my webpage from which I open a new browser window (#2) from which I open a new window (#3).</p> <p>Now if my user closes window#2 before window#3, I have the problem that window#3 no longer can call function in its window.opener since it has gone away.</p> <p>What I would like to do is to set window#3.opener to window#1 when window#2 closes.</p> <p>I've tried to do this i window#2 (by the way I use jquery):</p> <pre><code>var children = []; $(window).unload( function( ) { $.each( children, function( p, win ) { if ( win ) { win.opener = window.opener; } } ); } ); </code></pre> <p>When window#3 is loaded I add the window to the array children in window#2.</p> <p>But still when window#2 is closed before window#3, windows#3's window.opener doesn't point to window#1.</p> <p>How do I make sure that my grand child window (window#3), can still call the main window (window#1) after window#2 is closed?</p>
[ { "answer_id": 240275, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "window.opener function onLoad() {\n window.grandparent = window.opener.opener;\n}\n" }, { "answer_id": 240288, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\">\n var grandMother = null;\n window.onload = function(){\n grandMother = window.opener.opener;\n }\n</script>\n if(grandMother)\n grandMother.document.getElementById(\"myDiv\").firstChild.nodeValue =\"Greetings from your grandchild !-\";\n" }, { "answer_id": 240302, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "parent = window.opener.opener\n" }, { "answer_id": 40490753, "author": "JayB", "author_id": 2022103, "author_profile": "https://Stackoverflow.com/users/2022103", "pm_score": 1, "selected": false, "text": "var main_window = get_main_window();\nfunction get_main_window(){\n var w = window;\n while(w.opener !== null){\n w = w.opener;\n }\n return w;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441556/" ]
240,244
<p>I want to read line n1->n2 from file foo.c into the current buffer.</p> <p>I tried: <code>147,227r /path/to/foo/foo.c</code></p> <p>But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.</p>
[ { "answer_id": 240262, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 5, "selected": false, "text": ":147,227r /path/to/foo/foo.c\n /path/to/foo/foo.c" }, { "answer_id": 240274, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 8, "selected": true, "text": ":r! sed -n 147,227p /path/to/foo/foo.c\n" }, { "answer_id": 240286, "author": "PaulB", "author_id": 4460, "author_profile": "https://Stackoverflow.com/users/4460", "pm_score": 2, "selected": false, "text": ":r /path/to/foo/foo.c\n:d 228,$\n:d 1,146\n" }, { "answer_id": 21130304, "author": "DigitalAce69", "author_id": 3196849, "author_profile": "https://Stackoverflow.com/users/3196849", "pm_score": 2, "selected": false, "text": "/path/to/foo/foo.c :147,227w export.txt\n :r export.txt\n g/<search_criteria/:.w >> export.txt" }, { "answer_id": 21277670, "author": "joeytwiddle", "author_id": 99777, "author_profile": "https://Stackoverflow.com/users/99777", "pm_score": 5, "selected": false, "text": ":put =readfile('/path/to/foo/foo.c')[146:226]\n" }, { "answer_id": 45011363, "author": "raj", "author_id": 8283538, "author_profile": "https://Stackoverflow.com/users/8283538", "pm_score": 4, "selected": false, "text": ":r !head -20 xyz.xml\n :r !tail -10 xyz.xml \n :r !head -700030 xyz.xml| tail -30\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
240,258
<p>Ok, I am reading in dat files into a byte array. For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file. Anybody know a quick way to trim these off the end?</p> <p>First thought was to start at the end of the array and iterate backwards until I found something other than a null, then copy everything up to that point, but I wonder if there isn't a better way.</p> <p>To answer some questions: Are you sure the 0 bytes are definitely in the file, rather than there being a bug in the file reading code? Yes, I am certain of that.</p> <p>Can you definitely trim all trailing 0s? Yes.</p> <p>Can there be any 0s in the rest of the file? Yes, there can be 0's other places, so, no, I can't start at the beginning and stop at the first 0.</p>
[ { "answer_id": 240289, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Buffer.BlockCopy" }, { "answer_id": 240315, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "[Test]\npublic void Test()\n{\n var chars = new [] {'a', 'b', '\\0', 'c', '\\0', '\\0'};\n\n File.WriteAllBytes(\"test.dat\", Encoding.ASCII.GetBytes(chars));\n\n var content = File.ReadAllText(\"test.dat\");\n\n Assert.AreEqual(6, content.Length); // includes the null bytes at the end\n\n content = content.Trim('\\0');\n\n Assert.AreEqual(4, content.Length); // no more null bytes at the end\n // but still has the one in the middle\n}\n" }, { "answer_id": 240543, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 0, "selected": false, "text": "byte[] data = new byte[] { 0x01, 0x02, 0x00, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00 };\nbool data_found = false;\nbyte[] new_data = data.Reverse().SkipWhile(point =>\n{\n if (data_found) return false;\n if (point == 0x00) return true; else { data_found = true; return false; }\n}).Reverse().ToArray();\n" }, { "answer_id": 240745, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 5, "selected": false, "text": "byte[] foo;\n// populate foo\nint i = foo.Length - 1;\nwhile(foo[i] == 0)\n --i;\n// now foo[i] is the last non-zero byte\nbyte[] bar = new byte[i+1];\nArray.Copy(foo, bar, i+1);\n" }, { "answer_id": 240752, "author": "Brian J Cardiff", "author_id": 30948, "author_profile": "https://Stackoverflow.com/users/30948", "pm_score": 3, "selected": false, "text": "var data = new byte[] { 0x01, 0x02, 0x00, 0x03, 0x04, 0x00, 0x00, 0x00, 0x00 };\nvar new_data = data.TakeWhile((v, index) => data.Skip(index).Any(w => w != 0x00)).ToArray();\n" }, { "answer_id": 240814, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 0, "selected": false, "text": "var data = (byte array of file data...);\nvar index = data.length / 2;\nvar jmpsize = data.length/2;\nwhile(true)\n{\n jmpsize /= 2;//integer division\n if( jmpsize == 0) break;\n byte b1 = data[index];\n byte b2 = data[index + 1];\n if(b1 == 0 && b2 == 0) //too close to the end, go left\n index -=jmpsize;\n else\n index += jmpsize;\n}\n\nif(index == data.length - 1) return data.length;\nbyte b1 = data[index];\nbyte b2 = data[index + 1];\nif(b2 == 0)\n{\n if(b1 == 0) return index;\n else return index + 1;\n}\nelse return index + 2;\n" }, { "answer_id": 2216275, "author": "A.Yaqin", "author_id": 268052, "author_profile": "https://Stackoverflow.com/users/268052", "pm_score": 1, "selected": false, "text": " private byte[] trimByte(byte[] input)\n {\n if (input.Length > 1)\n {\n int byteCounter = input.Length - 1;\n while (input[byteCounter] == 0x00)\n {\n byteCounter--;\n }\n byte[] rv = new byte[(byteCounter + 1)];\n for (int byteCounter1 = 0; byteCounter1 < (byteCounter + 1); byteCounter1++)\n {\n rv[byteCounter1] = input[byteCounter1];\n }\n return rv;\n }\n" }, { "answer_id": 2725479, "author": "Kirill", "author_id": 207063, "author_profile": "https://Stackoverflow.com/users/207063", "pm_score": -1, "selected": false, "text": " /// <summary>\n /// Gets array of bytes from memory stream.\n /// </summary>\n /// <param name=\"stream\">Memory stream.</param>\n public static byte[] GetAllBytes(this MemoryStream stream)\n {\n byte[] result = new byte[stream.Length];\n Array.Copy(stream.GetBuffer(), result, stream.Length);\n\n return result;\n }\n" }, { "answer_id": 68319969, "author": "Fidel", "author_id": 171846, "author_profile": "https://Stackoverflow.com/users/171846", "pm_score": 0, "selected": false, "text": "static void RemoveTrailingNulls(string inputFilename, string outputFilename)\n{\n int bufferSize = 100 * 1024 * 1024;\n long totalTrailingNulls = 0;\n byte[] emptyArray = new byte[bufferSize];\n\n using (var inputFile = File.OpenRead(inputFilename))\n using (var inputFileReversed = new ReverseStream(inputFile))\n {\n var buffer = new byte[bufferSize];\n\n while (true)\n {\n var start = DateTime.Now;\n\n var bytesRead = inputFileReversed.Read(buffer, 0, buffer.Length);\n\n if (bytesRead == emptyArray.Length && Enumerable.SequenceEqual(emptyArray, buffer))\n {\n totalTrailingNulls += buffer.Length;\n }\n else\n {\n var nulls = buffer.Take(bytesRead).TakeWhile(b => b == 0).Count();\n totalTrailingNulls += nulls;\n\n if (nulls < bytesRead)\n {\n //found the last non-null byte\n break;\n }\n }\n\n var duration = DateTime.Now - start;\n var mbPerSec = (bytesRead / (1024 * 1024D)) / duration.TotalSeconds;\n Console.WriteLine($\"{mbPerSec:N2} MB/seconds\");\n }\n\n var lastNonNull = inputFile.Length - totalTrailingNulls;\n\n using (var outputFile = File.Open(outputFilename, FileMode.Create, FileAccess.Write))\n {\n inputFile.Seek(0, SeekOrigin.Begin);\n inputFile.CopyTo(outputFile, lastNonNull, bufferSize);\n }\n }\n}\n public static class Extensions\n{\n public static long CopyTo(this Stream input, Stream output, long count, int bufferSize)\n {\n byte[] buffer = new byte[bufferSize];\n long totalRead = 0;\n while (true)\n {\n if (count == 0) break;\n\n int read = input.Read(buffer, 0, (int)Math.Min(bufferSize, count));\n\n if (read == 0) break;\n totalRead += read;\n\n output.Write(buffer, 0, read);\n count -= read;\n }\n\n return totalRead;\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
240,263
<p>I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.</p> <p>I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:</p> <pre><code>selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/"); </code></pre> <p>How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?</p> <p>For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.</p> <p>I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.</p> <p>Many thanks if anyone can help.</p>
[ { "answer_id": 446606, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 1, "selected": false, "text": " [FixtureSetUp]\n public virtual void TestFixtureSetup ()\n {\n BrowserType = (BrowserType) Enum.Parse (typeof (BrowserType),\n System.Configuration.ConfigurationManager.AppSettings[\"BrowserType\"],\n true);\n testMachine = System.Configuration.ConfigurationManager.AppSettings[\"TestMachine\"];\n seleniumPort = int.Parse (System.Configuration.ConfigurationManager.AppSettings[\"SeleniumPort\"],\n System.Globalization.CultureInfo.InvariantCulture);\n seleniumSpeed = System.Configuration.ConfigurationManager.AppSettings[\"SeleniumSpeed\"];\n browserUrl = System.Configuration.ConfigurationManager.AppSettings[\"BrowserUrl\"];\n targetUrl = new Uri (System.Configuration.ConfigurationManager.AppSettings[\"TargetUrl\"]);\n\n string browserExe;\n switch (BrowserType)\n {\n case BrowserType.InternetExplorer:\n browserExe = \"*iexplore\";\n break;\n case BrowserType.Firefox:\n browserExe = \"*firefox\";\n break;\n\n default:\n throw new NotSupportedException ();\n }\n\n selenium = new DefaultSelenium (testMachine, seleniumPort, browserExe, browserUrl);\n selenium.Start ();\n\n System.Console.WriteLine (\"Started Selenium session (browser type={0})\",\n browserType);\n\n // sets the speed of execution of GUI commands\n if (false == String.IsNullOrEmpty (seleniumSpeed))\n selenium.SetSpeed (seleniumSpeed);\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31412/" ]
240,269
<p>I'm hitting this error and I'm not really sure why. I have a minified version of excanvas.js and something is breaking in IE, specifically on:</p> <p><code> var b=a.createStyleSheet(); </code></p> <p>I'm not sure why. Does anyone have any insight? I can provide more information, I'm just not sure what information will help.</p>
[ { "answer_id": 652627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<html>\n<head>\n<title></title>\n<script>\nfor(var i=0;i<32;i++) {\ndocument.createStyleSheet();\n}\n</script>\n</head>\n<body>\n</body>\n</html>\n" }, { "answer_id": 7975820, "author": "bburrier", "author_id": 352311, "author_profile": "https://Stackoverflow.com/users/352311", "pm_score": 1, "selected": false, "text": " var ss = null;\n var cssText = 'canvas{display:inline-block;overflow:hidden;' +\n // default size is 300x150 in Gecko and Opera\n 'text-align:left;width:300px;height:150px}';\n try{\n ss = doc.createStyleSheet();\n ss.owningElement.id = 'ex_canvas_';\n ss.cssText = cssText;\n } catch(e) {\n ss = document.styleSheets[document.styleSheets.length - 1];\n ss.cssText += \"\\r\\n\" + cssText;\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
240,293
<p>How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.</p> <pre><code>If ABS(billeddate – getdate) &gt; 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”. if (txtDate &amp;&amp; txtDate.value == "") { txtDate.focus(); alert("Please enter a date in the 'Date' field.") return false; } </code></pre>
[ { "answer_id": 240337, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": " var myDate = new Date(yearno, monthno-1, dayno);\n //you could put hour, minute, second and milliseconds in this too\n //today (right now !-) can be constructed by an empty constructor\nvar today = new Date();\nvar olddate = new Date(2008,9,2);\nvar diff = today.getTime() - olddate.getTime();\nvar diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds\n\nalert(diffInDays);\n alert(Math.floor(diffInDays));\n" }, { "answer_id": 240350, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "var billeddate = Date.parse(\"2008/10/27\");\nvar getdate = Date.parse(\"2008/09/25\");\n\nvar differenceInDays = (billeddate - getdate)/(1000*60*60*24)\n // What date is next thrusday?\nDate.today().next().thursday();\n//or\nDate.parse('next thursday');\n\n// Add 3 days to Today\nDate.today().add(3).days();\n\n// Is today Friday?\nDate.today().is().friday();\n\n// Number fun\n(3).days().ago();\n" }, { "answer_id": 240358, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "function IsDate(testValue) {\n\n var returnValue = false;\n var testDate;\n try {\n testDate = new Date(testValue);\n if (!isNaN(testDate)) {\n returnValue = true; \n }\n else {\n returnValue = false;\n }\n }\n catch (e) {\n returnValue = false;\n }\n return returnValue;\n }\n function IsMoreThan31Days(dateToTest) {\n\n if(IsDate(futureDate)) {\n var futureDateObj = new Date();\n var enteredDateObj = new Date(dateToTest);\n\n futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.\n //adds hours and minutes to dateToTest so that the test for 31 days is more accurate.\n enteredDateObj.setHours(futureDateObj.getHours()); \n enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);\n\n if(enteredDateObj >= futureDateObj) {\n return true;\n }\n else {\n return false;\n }\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
240,294
<p>I'd like something like a generic, re-usable <code>getPosition()</code> method that will tell me the number of bytes read from the starting point of the stream. Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.</p> <p>Does such a beast exist? If not, can anyone recommend an existing implementation of a counting <code>InputStream</code>?</p>
[ { "answer_id": 240312, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "InputStream" }, { "answer_id": 240431, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "java.io import java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic final class PositionInputStream\n extends FilterInputStream\n{\n\n private long pos = 0;\n\n private long mark = 0;\n\n public PositionInputStream(InputStream in)\n {\n super(in);\n }\n\n /**\n * <p>Get the stream position.</p>\n *\n * <p>Eventually, the position will roll over to a negative number.\n * Reading 1 Tb per second, this would occur after approximately three \n * months. Applications should account for this possibility in their \n * design.</p>\n *\n * @return the current stream position.\n */\n public synchronized long getPosition()\n {\n return pos;\n }\n\n @Override\n public synchronized int read()\n throws IOException\n {\n int b = super.read();\n if (b >= 0)\n pos += 1;\n return b;\n }\n\n @Override\n public synchronized int read(byte[] b, int off, int len)\n throws IOException\n {\n int n = super.read(b, off, len);\n if (n > 0)\n pos += n;\n return n;\n }\n\n @Override\n public synchronized long skip(long skip)\n throws IOException\n {\n long n = super.skip(skip);\n if (n > 0)\n pos += n;\n return n;\n }\n\n @Override\n public synchronized void mark(int readlimit)\n {\n super.mark(readlimit);\n mark = pos;\n }\n\n @Override\n public synchronized void reset()\n throws IOException\n {\n /* A call to reset can still succeed if mark is not supported, but the \n * resulting stream position is undefined, so it's not allowed here. */\n if (!markSupported())\n throw new IOException(\"Mark not supported.\");\n super.reset();\n pos = mark;\n }\n\n}\n volatile AtomicLong PositionInputStream is = …\nsynchronized (is) {\n is.read(buf);\n pos = is.getPosition();\n}\n" }, { "answer_id": 32625738, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 2, "selected": false, "text": "CountingInputStream" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23309/" ]
240,314
<p>I use Struts v1.3 and have following input form:</p> <p>In struts-config.xml:</p> <pre><code> &lt;form-bean name="testForm" type="org.apache.struts.validator.DynaValidatorForm"&gt; &lt;form-property name="displayName" type="java.lang.String" /&gt; &lt;/form-bean&gt; </code></pre> <p>In validation.xml:</p> <pre><code> &lt;form name="testForm"&gt; &lt;field property="displayName" depends="required"&gt; &lt;arg key="input.displayName" /&gt; &lt;/field&gt; &lt;/form&gt; </code></pre> <p>How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?</p>
[ { "answer_id": 263444, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 2, "selected": false, "text": "public void setDisplayName(String displayName) {\n this.displayName = displayName.trim();\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662/" ]
240,320
<p>I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.</p> <p>I'm using Java.</p> <p>to illustrate:</p> <pre><code>logger.info("sequentially executing all batches..."); for (TestExecutor executor : builder.getExecutors()) { logger.info("executing batch..."); executor.execute(); } </code></pre> <p>I figure the <code>TestExecutor</code> class should <code>implement Callable</code> and continue in that direction.</p> <p>But all i want to be able to do is stop <code>executor.execute()</code> if it's taking too long.</p> <p>Suggestions...?</p> <p><strong>EDIT</strong></p> <p>Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked. However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.</p>
[ { "answer_id": 240396, "author": "krakatoa", "author_id": 12223, "author_profile": "https://Stackoverflow.com/users/12223", "pm_score": 2, "selected": false, "text": "public void testStop(Runnable r) {\n Thread t = new Thread(r);\n t.start();\n try {\n t.join(2000);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n\n if (!t.isAlive()) {\n System.err.println(\"Finished on time.\");\n return;\n }\n\n try {\n t.interrupt();\n t.join(2000);\n if (!t.isAlive()) {\n System.err.println(\"cooperative stop\");\n return;\n }\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n System.err.println(\"non-cooperative stop\");\n StackTraceElement[] trace = Thread.getAllStackTraces().get(t);\n if (null != trace) {\n Throwable temp = new Throwable();\n temp.setStackTrace(trace);\n temp.printStackTrace();\n }\n t.stop();\n System.err.println(\"stopped non-cooperative thread\");\n}\n public void cooperative() {\n try {\n for (;;) {\n Thread.sleep(500);\n }\n } catch (InterruptedException e) {\n System.err.println(\"cooperative() interrupted\");\n } finally {\n System.err.println(\"cooperative() finally\");\n }\n}\n\npublic void noncooperative() {\n try {\n for (;;) {\n Thread.yield();\n }\n } finally {\n System.err.println(\"noncooperative() finally\");\n }\n}\n @Test\npublic void testStopCooperative() {\n testStop(new Runnable() {\n @Override\n public void run() {\n cooperative();\n }\n });\n}\n\n@Test\npublic void testStopNoncooperative() {\n testStop(new Runnable() {\n @Override\n public void run() {\n noncooperative();\n }\n });\n}\n" }, { "answer_id": 240689, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 1, "selected": false, "text": "void myMethod()\n{\n methodTakingAllTheTime();\n}\n void myMethod()\n{\n Thread t = new Thread(new Runnable()\n {\n public void run()\n {\n methodTakingAllTheTime(); // modify the internals of this method to check for interruption\n }\n });\n t.join(5000); // 5 seconds\n t.interrupt();\n}\n" }, { "answer_id": 241534, "author": "Alex", "author_id": 20634, "author_profile": "https://Stackoverflow.com/users/20634", "pm_score": 4, "selected": false, "text": "public class TimeoutExample {\n public static Object myMethod() {\n // does your thing and taking a long time to execute\n return someResult;\n }\n\n public static void main(final String[] args) {\n Callable<Object> callable = new Callable<Object>() {\n public Object call() throws Exception {\n return myMethod();\n }\n };\n ExecutorService executorService = Executors.newCachedThreadPool();\n\n Future<Object> task = executorService.submit(callable);\n try {\n // ok, wait for 30 seconds max\n Object result = task.get(30, TimeUnit.SECONDS);\n System.out.println(\"Finished with result: \" + result);\n } catch (ExecutionException e) {\n throw new RuntimeException(e);\n } catch (TimeoutException e) {\n System.out.println(\"timeout...\");\n } catch (InterruptedException e) {\n System.out.println(\"interrupted\");\n }\n }\n}\n" }, { "answer_id": 16096955, "author": "davidswelt", "author_id": 2297678, "author_profile": "https://Stackoverflow.com/users/2297678", "pm_score": 0, "selected": false, "text": "double x = 2.0; \nwhile(true) {x = x*x}; // do not terminate\nSystem.out.print(x); // prevent optimization\n" }, { "answer_id": 23493730, "author": "WVrock", "author_id": 3009607, "author_profile": "https://Stackoverflow.com/users/3009607", "pm_score": 0, "selected": false, "text": " Method(){\n //task1\nif (tooMuchTime == true) return;\n //task2\nif (tooMuchTime == true) return;\n //task3\nif (tooMuchTime == true) return;\n//task4\nif (tooMuchTime == true) return;\n//task5\nif (tooMuchTime == true) return;\n//final task\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
240,333
<p>I am trying to quantify "site slowness". In the olden days you just made sure that your HTML was lightweight, images optimized and servers not overloaded. In high end sites built on top of modern content management systems there are a lot more variables: third party advertising, trackers and various other callouts, the performance of CDN (interestingly enough sometimes content delivery networks make things worse), javascript execution, css overload, as well as all kinds of server side issues like long queries.</p> <p>The obvious answer is for every developer to clear the cache and continuously look at the "net" section of the Firebug plugin. What other ways to measure "site dragging ass" have you used?</p>
[ { "answer_id": 241518, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 0, "selected": false, "text": "ab -c <number of CPUs on server> -n 1000 url" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
240,341
<p>I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date).</p> <p>I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week. I'd like to not have to type in the dates when i run the reports each week. </p> <p>The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.</p>
[ { "answer_id": 240368, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "SELECT \n DateColumn,\n DateColumn - CASE DATEPART(dw, DateColumn) \n WHEN 1 THEN 6\n ELSE DATEPART(dw, DateColumn) - 2\n END MondayOfDateColumn\nFROM \n TheTable\n DATEADD(dd, 0, DATEDIFF(dd, 0, DateColumn)) - CASE DATEPART(dw, /* etc. etc. */\n" }, { "answer_id": 240372, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "SELECT (DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))\n" }, { "answer_id": 240392, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": -1, "selected": false, "text": "SELECT\nDATEADD(dy, DATEPART(dw, GETDATE()) - 9, GETDATE())\n" }, { "answer_id": 240407, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "SET DateFirst 7\n\nDECLARE @Today datetime\n\nSET @Today = '2008-10-22'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-23'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-24'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-25'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\n\nSET @Today = '2008-10-26'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-27'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-28'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-29'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\n SELECT\n DateDiff(wk, 0, '2008-10-25') as SatWeek, --5677\n DateDiff(wk, 0, '2008-10-26') as SunWeek, --5688\n DateDiff(wk, 0, '2008-10-27') as MonWeek --5688\n\nSELECT\n DatePart(dw, '2008-10-25') as SatPart, --7\n DatePart(dw, '2008-10-26') as SunPart, --1\n DatePart(dw, '2008-10-27') as MonPart, --2\n convert(datetime,'2008-10-25') - (DatePart(dw, '2008-10-25') - 2) as SatMonday,\n --'2008-10-20'\n convert(datetime,'2008-10-26') - (-1) as SunMonday,\n --'2008-10-27'\n convert(datetime,'2008-10-27') - (DatePart(dw, '2008-10-27') - 2) as MonMonday\n --'2008-10-27'\n" }, { "answer_id": 240542, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "select\n case when 2 = to_char(sysdate-1,'D') then sysdate - 1\n when 2 = to_char(sysdate-2,'D') then sysdate - 2\n when 2 = to_char(sysdate-3,'D') then sysdate - 3\n when 2 = to_char(sysdate-4,'D') then sysdate - 4\n when 2 = to_char(sysdate-5,'D') then sysdate - 5\n when 2 = to_char(sysdate-6,'D') then sysdate - 6\n when 2 = to_char(sysdate-7,'D') then sysdate - 7\n end as last_monday\nfrom dual\n" }, { "answer_id": 240747, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": false, "text": "select sysdate - 5 - to_number(to_char(sysdate,'D')) from dual\n SELECT sysdate - 6 - to_number(to_char(sysdate,'D')) LastSunday FROM dual;\nSELECT sysdate - 5 - to_number(to_char(sysdate,'D')) LastMonday FROM dual;\nSELECT sysdate - 4 - to_number(to_char(sysdate,'D')) LastTuesday FROM dual;\nSELECT sysdate - 3 - to_number(to_char(sysdate,'D')) LastWednesday FROM dual;\nSELECT sysdate - 2 - to_number(to_char(sysdate,'D')) LastThursday FROM dual;\nSELECT sysdate - 1 - to_number(to_char(sysdate,'D')) LastFriday FROM dual;\nSELECT sysdate - 0 - to_number(to_char(sysdate,'D')) LastSaturday FROM dual;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
240,345
<p>I have a ClickOnce deployed application I want to launch from VBScript, similar to launching Microsoft Word in the following example:</p> <pre><code>Dim word Set word = CreateObject("Word.Application") word.Visible = True </code></pre> <p>The problem is I don't know what parameter to pass into the <code>CreateObject</code> function to launch my application. Where would I find the master list of applications installed on my PC/the shortcut to call to launch them?</p>
[ { "answer_id": 265911, "author": "Jeff", "author_id": 13338, "author_profile": "https://Stackoverflow.com/users/13338", "pm_score": 1, "selected": false, "text": " Dim program As New Process\n\n 'Try to run a .Net click-once application\n Try\n Dim shortcut As String = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)\n shortcut = shortcut + \"specific\\shorctut\\path\\shortcut.appref-ms\"\n program .StartInfo.FileName = lpsShortcut\n program .Start()\n Catch\n 'If not go to the web site for a fresh install\n Try\n .Diagnostics.Process.Start(\"IExplore.exe\", \"http://url/program.application\")\n Catch ex As Exception\n 'Log or Email alert here...\n End Try\n End Try\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13338/" ]
240,353
<p>I'm looking for a way to convert a preprocessor token to a string.</p> <p>Specifically, I've somewhere got:</p> <pre><code>#define MAX_LEN 16 </code></pre> <p>and I want to use it to prevent buffer overrun:</p> <pre><code>char val[MAX_LEN+1]; // room for \0 sscanf(buf, "%"MAX_LEN"s", val); </code></pre> <p>I'm open to other ways to accomplish the same thing, but standard library only.</p>
[ { "answer_id": 240361, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": false, "text": "#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define VERSION_STRING \"v\" #VERSION_MAJOR \".\" #VERSION_MINOR\n #define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define STRINGIZE2(s) #s\n#define STRINGIZE(s) STRINGIZE2(s)\n#define VERSION_STRING \"v\" STRINGIZE(VERSION_MAJOR) \\\n\".\" STRINGIZE(VERSION_MINOR)\n\n#include <stdio.h>\nint main() {\n printf (\"%s\\n\", VERSION_STRING);\n return 0;\n}\n" }, { "answer_id": 240365, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": " sscanf(buf, \"%\" #MAX_LEN \"s\", val);\n #define STR1(x) #x\n #define STR(x) STR1(x)\n sscanf(buf, \"%\" STR(MAX_LEN) \"s\", val);\n" }, { "answer_id": 240370, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 8, "selected": true, "text": "#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n#define AT __FILE__ \":\" TOSTRING(__LINE__)\n sscanf(buf, \"%\" TOSTRING(MAX_LEN) \"s\", val);" }, { "answer_id": 241286, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "#define MAX_LEN 16\n#define MAX_LEN_S \"16\"\n\nchar val[MAX_LEN+1];\nsscanf(buf, \"%\"MAX_LEN_S\"s\", val);\n strncpy strncpy(val, buf, MAX_LEN);\nval[MAX_LEN] = '\\0';\n printf sprintf(buf, \"%.*s\", MAX_LEN, val);\n" }, { "answer_id": 61806583, "author": "Joma", "author_id": 3158594, "author_profile": "https://Stackoverflow.com/users/3158594", "pm_score": 1, "selected": false, "text": "%16s%16s%d #include <iostream>\n\n#define MAX_LEN 16\n\n#define AUX(x) #x\n#define STRINGIFY(x) AUX(x)\n\nint main() {\n char buffer[] = \"Hello World 25\";\n char val[MAX_LEN+1]; \n char val2[MAX_LEN+1];\n int val3;\n\n char format[] = \"%\" STRINGIFY(MAX_LEN) \"s\" \"%\" STRINGIFY(MAX_LEN) \"s\" \"%d\";\n int result = sscanf(buffer, format, val, val2, &val3);\n std::cout<< val << std::endl;\n std::cout<< val2 << std::endl;\n std::cout<< val3 << std::endl;\n std::cout<<\"Filled: \" << result << \" variables\" << std::endl;\n std::cout << \"Format: \" << format << std::endl;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
240,354
<p>We have a POST to a PL/SQL database procedure that (a) does some database operations based on the POST parameters and (b) redirects the user to a page showing the results.</p> <p>The problem is, when the user does a browser "refresh" of the results page, that still has the original request, so it calls the database procedure and resends the parameters. </p> <p>There are things we can do with saving state so bad things don't happen if the request gets sent in again. But that got me wondering. </p> <p>Is there a way to tell the browser to set the url to the redirect call, not the original user request? This would probably be in either the redirect itself, or in Javascript on the target page. </p>
[ { "answer_id": 240361, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": false, "text": "#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define VERSION_STRING \"v\" #VERSION_MAJOR \".\" #VERSION_MINOR\n #define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define STRINGIZE2(s) #s\n#define STRINGIZE(s) STRINGIZE2(s)\n#define VERSION_STRING \"v\" STRINGIZE(VERSION_MAJOR) \\\n\".\" STRINGIZE(VERSION_MINOR)\n\n#include <stdio.h>\nint main() {\n printf (\"%s\\n\", VERSION_STRING);\n return 0;\n}\n" }, { "answer_id": 240365, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": " sscanf(buf, \"%\" #MAX_LEN \"s\", val);\n #define STR1(x) #x\n #define STR(x) STR1(x)\n sscanf(buf, \"%\" STR(MAX_LEN) \"s\", val);\n" }, { "answer_id": 240370, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 8, "selected": true, "text": "#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n#define AT __FILE__ \":\" TOSTRING(__LINE__)\n sscanf(buf, \"%\" TOSTRING(MAX_LEN) \"s\", val);" }, { "answer_id": 241286, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "#define MAX_LEN 16\n#define MAX_LEN_S \"16\"\n\nchar val[MAX_LEN+1];\nsscanf(buf, \"%\"MAX_LEN_S\"s\", val);\n strncpy strncpy(val, buf, MAX_LEN);\nval[MAX_LEN] = '\\0';\n printf sprintf(buf, \"%.*s\", MAX_LEN, val);\n" }, { "answer_id": 61806583, "author": "Joma", "author_id": 3158594, "author_profile": "https://Stackoverflow.com/users/3158594", "pm_score": 1, "selected": false, "text": "%16s%16s%d #include <iostream>\n\n#define MAX_LEN 16\n\n#define AUX(x) #x\n#define STRINGIFY(x) AUX(x)\n\nint main() {\n char buffer[] = \"Hello World 25\";\n char val[MAX_LEN+1]; \n char val2[MAX_LEN+1];\n int val3;\n\n char format[] = \"%\" STRINGIFY(MAX_LEN) \"s\" \"%\" STRINGIFY(MAX_LEN) \"s\" \"%d\";\n int result = sscanf(buffer, format, val, val2, &val3);\n std::cout<< val << std::endl;\n std::cout<< val2 << std::endl;\n std::cout<< val3 << std::endl;\n std::cout<<\"Filled: \" << result << \" variables\" << std::endl;\n std::cout << \"Format: \" << format << std::endl;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8051/" ]
240,382
<p>I need my .net application to use the .html extension instead of .aspx </p> <p>I'm converting a php app and there are external applications which depend on that extension to function.</p> <p>What is the best way to do this?</p> <p>Thanks</p>
[ { "answer_id": 240441, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 5, "selected": true, "text": "<httpHandlers>\n <remove verb=\"*\" path=\"*.html\" />\n <add verb=\"*\" path=\"*.html\" type=\"System.Web.UI.PageHandlerFactory\" />\n</httpHandlers>\n<compilation>\n <buildProviders>\n <buildProvider \n extension=\".html\" \n type=\"System.Web.Compilation.PageBuildProvider\" />\n </buildProviders>\n</compilation>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
240,393
<p>I have the following SQL-statement:</p> <pre><code>SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; </code></pre> <p>It works fine on Postgres (returns all different names from log, which aren't empty and contain the string '.EDIT'). But on Oracle this statement doesn't work. Any idea why?</p>
[ { "answer_id": 240418, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 2, "selected": false, "text": " SELECT DISTINCT name \n FROM log\n WHERE name LIKE '%.EDIT%';\n" }, { "answer_id": 240430, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": true, "text": "SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%';\n SELECT DISTINCT name FROM log WHERE name LIKE '%.EDIT%';\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
240,394
<p>In normal WebForms scenario, any root-relative URLs (e.g. ~/folder/file.txt) <strong>inside</strong> CSS files such as:</p> <pre><code>.form { background-image: url(~/Content/Images/form_bg.gif); } </code></pre> <p>will automatically get resolved during runtime if I specify</p> <pre><code>&lt;head runat="server"&gt; </code></pre> <p>In the referencing page.</p> <p>However, that is no longer happening on an ASP.NET MVC Beta1 website.</p> <p>Is there a way I could enable this functionality without resorting to hacks or CSS-loader file? Like maybe HttpModules or something?</p> <p>Or am I not desigining my website correctly? What is supposed to be a good design?</p> <p>Since original ASP.NET WebForms already has this feature, I'd prefer to utilize any existing functionality if possible. But I don't have much clue.</p> <p>This web application will be deployed in several environments where the ~ root folder might not be obvious.</p> <hr> <p><strong>EDIT:</strong> I mean the url in the file's CONTENT not the file's url itself.</p>
[ { "answer_id": 243765, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "<link href=\"<%=PathHelper.CssUrl(\"FormulaIndex.css\")%>\" rel=\"Stylesheet\" type=\"text/css\"/>\n" }, { "answer_id": 269977, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 1, "selected": false, "text": "public class StringParsingFilter : MemoryStream {\n\n public Stream OriginalStream {\n get { return this.m_OriginalStream; }\n set { this.m_OriginalStream = value; }\n }\n private System.IO.Stream m_OriginalStream;\n\n public StringParsingFilter() : base() {\n this.m_OriginalStream = null;\n }\n\n public override void Flush() {\n this.m_OriginalStream.Flush();\n }\n\n public override void Write(byte[] buffer, int offset, int count) {\n\n //otherwise, parse for the correct content\n string value = System.Text.Encoding.Default.GetString(buffer);\n string contentType = HttpContext.Current.Response.ContentType;\n\n //Do any parsing here\n ...\n\n //write the new bytes to the stream\n byte[] bytes = System.Text.Encoding.Default.GetBytes(value);\n this.m_OriginalStream.Write(bytes, offset, count + (bytes.Length - buffer.Length));\n\n }\n\n}\n public class FilterControlModule : IHttpModule {\n\n public void Init(HttpApplication context) {\n HttpApplication oAppContext = context;\n oAppContext.BeginRequest += new EventHandler(_HandleSettingFilter); \n }\n\n private void _HandleSettingFilter(object sender, EventArgs e) {\n\n //You might check the file at this part to make sure\n //it is a file type you want to parse\n //if (!CurrentFile.isStyleSheet()) { return; }\n ...\n\n //assign the new filter\n StringParsingFilter filter = new StringParsingFilter();\n filter.OriginalStream = HttpContext.Current.Response.Filter;\n HttpContext.Current.Response.Filter = (Stream)filter;\n\n }\n\n}\n" }, { "answer_id": 269985, "author": "David Kolar", "author_id": 3283, "author_profile": "https://Stackoverflow.com/users/3283", "pm_score": 7, "selected": true, "text": "~ ~/Content/Images ~/Content/Stylesheets background-image: url(../Images/form_bg.gif);" }, { "answer_id": 274425, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 3, "selected": false, "text": "<%@ Page Language=\"C#\" ContentType=\"text/css\" %>\n\nbody {\n margin: 0;\n padding: 0;\n background: #C32605 url(<%= ResolveUrl(\"~/Content/themes/base/images/BodyBackground.png\") %>) repeat-x;\n font-family: Verdana, Arial, sans-serif;\n font-size: small;\n color: #d7f9ff;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055/" ]
240,411
<p>In a class diagram, is there a way of specifying that a class is an internal class of another class ? </p> <p>Or is it considered as a pure implementation choice ? </p>
[ { "answer_id": 240460, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": false, "text": "OuterClass vs OuterClass::InnerClass\n InnerClass::OuterClass" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
240,419
<p>I've got a VB.NET class that is invoked with a context menu extension in Internet Explorer. </p> <p>The code has access to the object model of the page, and reading data is not a problem. This is the code of a test function...it changes the status bar text (OK), prints the page HTML (OK), changes the HTML by adding a text and prints again the page HTML (OK, in the second pop-up my added text is in the HTML)</p> <p>But the Internet Explorer window doesn't show it. Where am I doing wrong?</p> <pre><code>Public Sub CallingTest(ByRef Source As Object) Dim D As mshtml.HTMLDocument = Source.document Source.status = "Working..." Dim H As String = D.documentElement.innerHTML() MsgBox(H) D.documentElement.insertAdjacentText("beforeEnd", "ThisIsATest") H = D.documentElement.outerHTML() MsgBox(H) Source.status = "" End Sub </code></pre> <p>The function is called like this from JavaScript: </p> <pre><code>&lt;script&gt; var EB = new ActiveXObject("MyObject.MyClass"); EB.CallingTest(external.menuArguments); &lt;/script&gt; </code></pre>
[ { "answer_id": 240460, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": false, "text": "OuterClass vs OuterClass::InnerClass\n InnerClass::OuterClass" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22108/" ]
240,425
<p>When I merge the trunk into a feature-branch, a delete that occurred on the trunk will not be replicated to my working copy.</p> <p>Why will a delete on trunk not delete the same file on a branch when merging? I'm using subversion 1.5 client and server.</p> <p>I'm assuming that changes to the file in the branch will be skipped when reintegrating the branch?</p> <p>What's the best way to redeem the file on trunk, as a colleague deleted the file from trunk only because it was not "ready".</p> <p>Situation:</p> <pre><code>cd project; svn copy trunk branches/f1; svn ci -m "branching out" branches f1; echo "modifying a file on branch." &gt;&gt; branches/f1/file1; svn ci branches/f1 -m "Branch modified"; echo "Above modify is not even needed to state the case"; svn rm trunk/file1; svn ci trunk -m "creating (conflicting) delete on trunk"; cd branches/f1; svn merge svn+ssh://repos/trunk . [ -f file1 ] &amp;&amp; echo "file f1 does exist while it should have been deleted by merge."; </code></pre> <p>So, the file still exists in my working copy even though I'm merging in trunk where the file has been actively deleted. Highly unexpected. In my case I haven't even made any changes to the file, which is the only reason i can think of why svn would save the file.</p>
[ { "answer_id": 242636, "author": "JXG", "author_id": 15456, "author_profile": "https://Stackoverflow.com/users/15456", "pm_score": 1, "selected": false, "text": "svn status svn status" }, { "answer_id": 4337918, "author": "RjOllos", "author_id": 121694, "author_profile": "https://Stackoverflow.com/users/121694", "pm_score": 0, "selected": false, "text": "svn status" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972/" ]
240,428
<p>What is people's prefered method of storing application configuration data in a database. From having done this in the past myself, I've utilised two ways of doing it.</p> <ol> <li>You can create a table where you store key/value pairs, where key is the name of the config option and value is its value. Pro's of this is adding new values is easy and you can use the same routines to set/get data. Downsides are you have untyped data as the value.</li> <li>Alternatively, you can hardcode a configuration table, with each column being the name of the value and its datatype. The downside to this is more maintenance setting up new values, but it allows you to have typed data.</li> </ol> <p>Having used both, my preferences lie with the first option as its quicker to set things up, however its also riskier and can reduce performance (slightly) when looking up data. Does anyone have any alternative methods?</p> <p><strong>Update</strong></p> <p>It's necessary to store the information in a database because as noted below, there may be multiple instances of the program that require configuring the same way, as well as stored procedures potentially using the same values.</p>
[ { "answer_id": 241703, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 0, "selected": false, "text": "CREATE TABLE [dbo].[MyOption] (\n [GUID] uniqueidentifier CONSTRAINT [dfMyOptions_GUID] DEFAULT newsequentialid() ROWGUIDCOL NOT NULL,\n [Logo] varbinary(max) NULL,\n [X] char(1) CONSTRAINT [dfMyOptions_X] DEFAULT 'X' NOT NULL,\n CONSTRAINT [MyOptions_pk] PRIMARY KEY CLUSTERED ([GUID]),\n CONSTRAINT [MyOptions_ck] CHECK ([X]='X')\n)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29086/" ]
240,467
<p>Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (<code>p</code>) into an <code>address</code> element. My current method is (more-or-less):</p> <pre><code>var p = $('p#test'); p.replaceWith('&lt;address&gt;' + p.html() + '&lt;/address&gt;'); </code></pre> <p>but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (<code>&lt;address/&gt;</code>) has been added to the document, for some reason.</p> <p>Can anyone spot the bug or suggest an alternative method?</p>
[ { "answer_id": 240494, "author": "Daniel Cassidy", "author_id": 31662, "author_profile": "https://Stackoverflow.com/users/31662", "pm_score": 4, "selected": true, "text": "var p = $('p#test');\nvar a = $('<address>').\n append(p.contents());\np.replaceWith(a);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5058/" ]
240,470
<p>I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.</p>
[ { "answer_id": 240503, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<?php\nsession_start();\n\nif (isset($_POST['username'], $_POST['password']) {\n $_SESSION['username'] = $_POST['username'];\n $_SESSION['password'] = $_POST['password'];\n echo '<a href=\"nextpage.php\">Click to continue.</a>';\n} else {\n // form\n}\n?>\n <?php\nsession_start();\n\nif (isset($_SESSION['username'])) {\n echo $_SESSION['username'];\n} else {\n header('Location: index.php');\n}\n?>\n" }, { "answer_id": 240507, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "//page1.php\nsession_start();\n$_SESSION['user']='user';\n$_SESSION['password']='password';\n\n//page2.php\nsession_start();\necho $_SESSION['user'] . ' ' . $_SESSION['password'];\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
240,473
<p>I have an unsorted list of noisy X, Y points. They do, however, form a path through the world. I would like an algorithm to draw an approximation of this data using line segments.</p> <p>This is similar to how you would use a line -fitting algorithm to pick an approximation of linear data. My problem is only harder because the path bends and winds around the world. <a href="http://www.praeclarum.org/so/pathfinder.png">alt text http://www.praeclarum.org/so/pathfinder.png</a></p> <p>Does anyone know of any standard / robust / easy to comprehend algorithms to accomplish this?</p> <p><strong>Q&amp;A</strong>:</p> <p><strong>What do you mean by noisy?</strong> If I had an ideal realization of the path, then my set of points would be sampled from that ideal path with gaussian noise added to the X and Y elements. I do not know the mean or standard deviation of that noise. I may be able to guess at the std dev...</p> <p><strong>Do the points lie near, but not on, some ideal but complicated path which you seek to approximate?</strong> Yes.</p> <p><strong>Do you have any a priori information about he shape of the path? Any other way to get such information?</strong> Unfortunately not.</p>
[ { "answer_id": 274079, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 1, "selected": false, "text": "#lang scheme\n\n(require (only-in srfi/1 iota))\n\n; a bunch of trig\n(define (deg->rad d)\n (* pi (/ d 180)))\n\n(define (rad->deg r)\n (* 180 (/ r pi)))\n\n(define (euclidean-length v)\n (sqrt (apply + (map (lambda (x) (expt x 2)) v))))\n\n(define (dot a b)\n (apply + (map * a b)))\n\n(define (angle-ratio a b)\n (/ (dot a b)\n (* (euclidean-length a) (euclidean-length b))))\n\n; given a list of 3 points, calculate the likelihood of the\n; angle they represent. straight is better.\n(define (probability-triple a b c)\n (let ([av (map - a b)]\n [bv (map - c b)])\n (cos (/ (- pi (abs (acos (angle-ratio av bv)))) 2))))\n\n; makes a random 2d point. uncomment the bit for a 3d point\n(define (random-point . x)\n (list (/ (random 1000) 100)\n (/ (random 1000) 100)\n #;(/ (random 1000) 100)))\n\n; calculate the likelihood of an entire list of points\n(define (point-order-likelihood lst)\n (if (null? (cdddr lst))\n 1\n (* (probability-triple (car lst)\n (cadr lst)\n (caddr lst))\n (point-order-likelihood (cdr lst)))))\n\n; just print a list of points\n(define (print-points lst)\n (for ([p (in-list lst)])\n (printf \"~a~n\"\n (string-join (map number->string\n (map exact->inexact p))\n \" \"))))\n\n; attempts to improve upon a list\n(define (find-better-arrangement start\n ; by default, try only 10 times to find something better\n [tries 10]\n ; if we find an arrangement that is as good as one where\n ; every segment bends by 22.5 degrees (which would be\n ; reasonably gentle) then call it good enough. higher\n ; cut offs are more demanding.\n [cut-off (expt (cos (/ pi 8))\n (- (length start) 2))])\n (let ([vec (list->vector start)]\n ; evaluate what we've started with\n [eval (point-order-likelihood start)])\n (let/ec done\n ; if the current list exceeds the cut off, we're done\n (when (> eval cut-off)\n (done start))\n ; otherwise, try no more than 'tries' times...\n (for ([x (in-range tries)])\n ; pick two random points in the list\n (let ([ai (random (vector-length vec))]\n [bi (random (vector-length vec))])\n ; if they're the same...\n (when (= ai bi)\n ; increment the second by 1, wrapping around the list if necessary\n (set! bi (modulo (add1 bi) (vector-length vec))))\n ; take the values from the two positions...\n (let ([a (vector-ref vec ai)]\n [b (vector-ref vec bi)])\n ; swap them\n (vector-set! vec bi a)\n (vector-set! vec ai b)\n ; make a list out of the vector\n (let ([new (vector->list vec)])\n ; if it evaluates to better\n (when (> (point-order-likelihood new) eval)\n ; start over with it\n (done (find-better-arrangement new tries cut-off)))))))\n ; we fell out the bottom of the search. just give back what we started with\n start)))\n\n; evaluate, display, and improve a list of points, five times\n(define points (map random-point (iota 10)))\n(define tmp points)\n(printf \"~a~n\" (point-order-likelihood tmp))\n(print-points tmp)\n(set! tmp (find-better-arrangement tmp 10))\n(printf \"~a~n\" (point-order-likelihood tmp))\n(print-points tmp)\n(set! tmp (find-better-arrangement tmp 100))\n(printf \"~a~n\" (point-order-likelihood tmp))\n(print-points tmp)\n(set! tmp (find-better-arrangement tmp 1000))\n(printf \"~a~n\" (point-order-likelihood tmp))\n(print-points tmp)\n(set! tmp (find-better-arrangement tmp 10000))\n(printf \"~a~n\" (point-order-likelihood tmp))\n(print-points tmp)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
240,510
<p>I have a string from an email header, like <code>Date: Mon, 27 Oct 2008 08:33:29 -0700</code>. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?</p> <p>And for the fastest ones -- this is <strong>not</strong> going to work properly:</p> <pre><code>SimpleDateFormat format = ... // whatever you want Date date = format.parse(myString) GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date) </code></pre> <p>because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return <code>-7 * milisInAnHour</code>.</p>
[ { "answer_id": 240565, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 5, "selected": true, "text": "DateTimeFormatter formatter =\n DateTimeFormat.forPattern(\"your pattern\").withOffsetParsed();\nDateTime dateTime = formatter.parseDateTime(\"your input\");\nGregorianCalendar cal = dateTime.toGregorianCalendar();\n" }, { "answer_id": 240734, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "String dateString = \"Mon, 27 Oct 2008 08:33:29 -0700\";\nDateFormat df = new SimpleDateFormat(\"E, dd MMM yyyy hh:mm:ss Z\");\nDate parsed = df.parse(dateString);\nSystem.out.println(\"parsed date: \" + parsed);\n\nCalendar newCalendar = Calendar.getInstance();\nnewCalendar.setTime(parsed);\n Date" }, { "answer_id": 67472622, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": false, "text": "java.time OffsetDateTime Instant Instant +00:00 Z Instant#toEpochMilli GregorianCalendar import java.time.Instant;\nimport java.time.OffsetDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.Locale;\n\npublic class Main {\n public static void main(String[] args) {\n String strDateTime = \"Mon, 27 Oct 2008 08:33:29 -0700\";\n OffsetDateTime odt = OffsetDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);\n System.out.println(odt);\n \n // In case you want a time zone neutral object, convert to Instant\n Instant instant = odt.toInstant();\n System.out.println(instant);\n \n // Edit: If the requirement is a GregorianCalendar having the offset from\n // the string — typically for an old API not yet upgraded to java.time: \n ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);\n GregorianCalendar gc = GregorianCalendar.from(zdt);\n \n System.out.println(\"As Date: \" + gc.getTime());\n System.out.println(\"Time zone ID: \" + gc.getTimeZone().getID());\n System.out.println(\"Hour of day: \" + gc.get(Calendar.HOUR_OF_DAY));\n // ...\n }\n}\n 2008-10-27T08:33:29-07:00\n2008-10-27T15:33:29Z\nAs Date: Mon Oct 27 15:33:29 GMT 2008\nTime zone ID: GMT-07:00\nHour of day: 8\n getTime() GregorianCalendar Date GregorianCalendar" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105/" ]
240,531
<p>I have a weird date rounding problem that hopefully someone can solve. My client uses a work week that runs from Monday through Sunday. Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date).</p> <p>One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.</p> <p>So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above. Thanks for your help. I have a solution that works, but I'm too embarassed to post it.</p> <p>Oh, and I can't use LINQ.</p>
[ { "answer_id": 240560, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "public DateTime WeekNum(DateTime now)\n{\n DateTime NewNow = now.AddHours(-11).AddDays(6);\n\n return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);\n}\n\npublic void Code(params string[] args)\n{\n\n Console.WriteLine(WeekNum(DateTime.Now)); \n Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,28)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,25)));\n\n\n}\n" }, { "answer_id": 240605, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "[Test]\npublic void Test()\n{\n DateTime sunday = DateTime.Parse(\"10/26/2008\");\n DateTime nextSunday = DateTime.Parse(\"11/2/2008\");\n\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/21/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/22/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/23/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/24/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/25/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/26/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/27/2008 10:59 AM\")));\n Assert.AreEqual(nextSunday, GetSunday(DateTime.Parse(\"10/27/2008 11:00 AM\")));\n}\n\nprivate DateTime GetSunday(DateTime date)\n{\n if (date.DayOfWeek == DayOfWeek.Monday && date.Hour < 11)\n return date.Date.AddDays(-1);\n\n while (date.DayOfWeek != DayOfWeek.Sunday)\n date = date.AddDays(1);\n\n return date.Date;\n}\n" }, { "answer_id": 240940, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 1, "selected": false, "text": "DateTime GetMidnightFollowingSunday()\n{\n DateTime now = DateTime.Now;\n return now.AddDays(7 - (int)now.DayOfWeek).Date;\n}\n DateTime GetRecordDate()\n{\n DateTime nowMinusOffset = DateTime.Now.AddHours(-11);\n return nowMinusOffset.AddDays(7-(int)nowMinusOffset.DayOfWeek).Date;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
240,537
<p>Does anyone know of a simple web app that supports running ant tasks? Alternatively it could run command line programs. I need to allow the user to choose parameters for running the ant task. I effectively want a web interface to run the ant task and provide any parameters.</p> <p>I can write one but this is generic enough that it seems like there should already be a few standard packages that do this.</p>
[ { "answer_id": 240558, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 0, "selected": false, "text": "echo shell_exec('ant');\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
240,544
<p>I have the following rails migration:</p> <pre><code>create_table :articles do |t| t.integer :user_id, :allow_null =&gt; false t.integer :genre_id, :allow_null =&gt; false t.string :url, :limit =&gt; 255, :allow_null =&gt; false t.string :title, :limit =&gt; 60, :allow_null =&gt; false t.text :summary, :limit =&gt; 350, :allow_null =&gt; false t.integer :votes_count, :default =&gt; 0 t.datetime :published_at, :default =&gt; nil t.timestamps end </code></pre> <p>All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.</p>
[ { "answer_id": 240556, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": true, "text": "NULL" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31810/" ]
240,546
<p>Is there a good way to remove HTML from a Java string? A simple regex like</p> <pre class="lang-js prettyprint-override"><code>replaceAll(&quot;\\&lt;.*?&gt;&quot;, &quot;&quot;) </code></pre> <p>will work, but some things like <code>&amp;amp;</code> won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the <code>.*?</code> in the regex will disappear).</p>
[ { "answer_id": 240630, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 7, "selected": false, "text": "<b>hey!</b> <b>hey!</b> hey! replaceAll(\"\\\\<[^>]*>\",\"\")\n <bhey!</b>" }, { "answer_id": 241757, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": false, "text": "<br/> </p> replaceAll(\"\\\\<[\\s]*tag[^>]*>\",\"\")\n &amp;" }, { "answer_id": 454511, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "static public String getUrlContentsAsText(String url) {\n String content = \"\";\n StringBean stringBean = new StringBean();\n stringBean.setURL(url);\n content = stringBean.getStrings();\n return content;\n}\n" }, { "answer_id": 455196, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 5, "selected": false, "text": "import java.io.*;\nimport javax.swing.text.html.*;\nimport javax.swing.text.html.parser.*;\n\npublic class Html2Text extends HTMLEditorKit.ParserCallback {\n StringBuffer s;\n\n public Html2Text() {\n }\n\n public void parse(Reader in) throws IOException {\n s = new StringBuffer();\n ParserDelegator delegator = new ParserDelegator();\n // the third parameter is TRUE to ignore charset directive\n delegator.parse(in, this, Boolean.TRUE);\n }\n\n public void handleText(char[] text, int pos) {\n s.append(text);\n }\n\n public String getText() {\n return s.toString();\n }\n\n public static void main(String[] args) {\n try {\n // the HTML to convert\n FileReader in = new FileReader(\"java-new.html\");\n Html2Text parser = new Html2Text();\n parser.parse(in);\n in.close();\n System.out.println(parser.getText());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n" }, { "answer_id": 2702056, "author": "Mike", "author_id": 324610, "author_profile": "https://Stackoverflow.com/users/324610", "pm_score": 3, "selected": false, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.util.Stack;\nimport java.util.logging.Logger;\n\nimport javax.swing.text.MutableAttributeSet;\nimport javax.swing.text.html.HTML;\nimport javax.swing.text.html.HTMLEditorKit;\nimport javax.swing.text.html.parser.ParserDelegator;\n\npublic class HTML2Text extends HTMLEditorKit.ParserCallback {\n private static final Logger log = Logger\n .getLogger(Logger.GLOBAL_LOGGER_NAME);\n\n private StringBuffer stringBuffer;\n\n private Stack<IndexType> indentStack;\n\n public static class IndexType {\n public String type;\n public int counter; // used for ordered lists\n\n public IndexType(String type) {\n this.type = type;\n counter = 0;\n }\n }\n\n public HTML2Text() {\n stringBuffer = new StringBuffer();\n indentStack = new Stack<IndexType>();\n }\n\n public static String convert(String html) {\n HTML2Text parser = new HTML2Text();\n Reader in = new StringReader(html);\n try {\n // the HTML to convert\n parser.parse(in);\n } catch (Exception e) {\n log.severe(e.getMessage());\n } finally {\n try {\n in.close();\n } catch (IOException ioe) {\n // this should never happen\n }\n }\n return parser.getText();\n }\n\n public void parse(Reader in) throws IOException {\n ParserDelegator delegator = new ParserDelegator();\n // the third parameter is TRUE to ignore charset directive\n delegator.parse(in, this, Boolean.TRUE);\n }\n\n public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {\n log.info(\"StartTag:\" + t.toString());\n if (t.toString().equals(\"p\")) {\n if (stringBuffer.length() > 0\n && !stringBuffer.substring(stringBuffer.length() - 1)\n .equals(\"\\n\")) {\n newLine();\n }\n newLine();\n } else if (t.toString().equals(\"ol\")) {\n indentStack.push(new IndexType(\"ol\"));\n newLine();\n } else if (t.toString().equals(\"ul\")) {\n indentStack.push(new IndexType(\"ul\"));\n newLine();\n } else if (t.toString().equals(\"li\")) {\n IndexType parent = indentStack.peek();\n if (parent.type.equals(\"ol\")) {\n String numberString = \"\" + (++parent.counter) + \".\";\n stringBuffer.append(numberString);\n for (int i = 0; i < (4 - numberString.length()); i++) {\n stringBuffer.append(\" \");\n }\n } else {\n stringBuffer.append(\"* \");\n }\n indentStack.push(new IndexType(\"li\"));\n } else if (t.toString().equals(\"dl\")) {\n newLine();\n } else if (t.toString().equals(\"dt\")) {\n newLine();\n } else if (t.toString().equals(\"dd\")) {\n indentStack.push(new IndexType(\"dd\"));\n newLine();\n }\n }\n\n private void newLine() {\n stringBuffer.append(\"\\n\");\n for (int i = 0; i < indentStack.size(); i++) {\n stringBuffer.append(\" \");\n }\n }\n\n public void handleEndTag(HTML.Tag t, int pos) {\n log.info(\"EndTag:\" + t.toString());\n if (t.toString().equals(\"p\")) {\n newLine();\n } else if (t.toString().equals(\"ol\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"ul\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"li\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"dd\")) {\n indentStack.pop();\n ;\n }\n }\n\n public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {\n log.info(\"SimpleTag:\" + t.toString());\n if (t.toString().equals(\"br\")) {\n newLine();\n }\n }\n\n public void handleText(char[] text, int pos) {\n log.info(\"Text:\" + new String(text));\n stringBuffer.append(text);\n }\n\n public String getText() {\n return stringBuffer.toString();\n }\n\n public static void main(String args[]) {\n String html = \"<html><body><p>paragraph at start</p>hello<br />What is happening?<p>this is a<br />mutiline paragraph</p><ol> <li>This</li> <li>is</li> <li>an</li> <li>ordered</li> <li>list <p>with</p> <ul> <li>another</li> <li>list <dl> <dt>This</dt> <dt>is</dt> <dd>sdasd</dd> <dd>sdasda</dd> <dd>asda <p>aasdas</p> </dd> <dd>sdada</dd> <dt>fsdfsdfsd</dt> </dl> <dl> <dt>vbcvcvbcvb</dt> <dt>cvbcvbc</dt> <dd>vbcbcvbcvb</dd> <dt>cvbcv</dt> <dt></dt> </dl> <dl> <dt></dt> </dl></li> <li>cool</li> </ul> <p>stuff</p> </li> <li>cool</li></ol><p></p></body></html>\";\n System.out.println(convert(html));\n }\n}\n" }, { "answer_id": 3149645, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 10, "selected": true, "text": "public static String html2text(String html) {\n return Jsoup.parse(html).text();\n}\n <b> <i> <u>" }, { "answer_id": 3426610, "author": "rjha94", "author_id": 262376, "author_profile": "https://Stackoverflow.com/users/262376", "pm_score": 3, "selected": false, "text": "MyWriter.toConsole(HtmlToText.htmlToPlainText(htmlResponse));\n" }, { "answer_id": 3472783, "author": "dfrankow", "author_id": 34935, "author_profile": "https://Stackoverflow.com/users/34935", "pm_score": 3, "selected": false, "text": "import java.io.IOException;\nimport java.io.StringReader;\nimport java.util.logging.Logger;\n\nimport org.ccil.cowan.tagsoup.Parser;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.ContentHandler;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.Locator;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\n\n/**\n * Take HTML and give back the text part while dropping the HTML tags.\n *\n * There is some risk that using TagSoup means we'll permute non-HTML text.\n * However, it seems to work the best so far in test cases.\n *\n * @author dan\n * @see <a href=\"http://home.ccil.org/~cowan/XML/tagsoup/\">TagSoup</a> \n */\npublic class Html2Text2 implements ContentHandler {\nprivate StringBuffer sb;\n\npublic Html2Text2() {\n}\n\npublic void parse(String str) throws IOException, SAXException {\n XMLReader reader = new Parser();\n reader.setContentHandler(this);\n sb = new StringBuffer();\n reader.parse(new InputSource(new StringReader(str)));\n}\n\npublic String getText() {\n return sb.toString();\n}\n\n@Override\npublic void characters(char[] ch, int start, int length)\n throws SAXException {\n for (int idx = 0; idx < length; idx++) {\n sb.append(ch[idx+start]);\n }\n}\n\n@Override\npublic void ignorableWhitespace(char[] ch, int start, int length)\n throws SAXException {\n sb.append(ch);\n}\n\n// The methods below do not contribute to the text\n@Override\npublic void endDocument() throws SAXException {\n}\n\n@Override\npublic void endElement(String uri, String localName, String qName)\n throws SAXException {\n}\n\n@Override\npublic void endPrefixMapping(String prefix) throws SAXException {\n}\n\n\n@Override\npublic void processingInstruction(String target, String data)\n throws SAXException {\n}\n\n@Override\npublic void setDocumentLocator(Locator locator) {\n}\n\n@Override\npublic void skippedEntity(String name) throws SAXException {\n}\n\n@Override\npublic void startDocument() throws SAXException {\n}\n\n@Override\npublic void startElement(String uri, String localName, String qName,\n Attributes atts) throws SAXException {\n}\n\n@Override\npublic void startPrefixMapping(String prefix, String uri)\n throws SAXException {\n}\n}\n" }, { "answer_id": 4095615, "author": "Serge", "author_id": 395815, "author_profile": "https://Stackoverflow.com/users/395815", "pm_score": 5, "selected": false, "text": "private static final Pattern REMOVE_TAGS = Pattern.compile(\"<.+?>\");\n\npublic static String removeTags(String string) {\n if (string == null || string.length() == 0) {\n return string;\n }\n\n Matcher m = REMOVE_TAGS.matcher(string);\n return m.replaceAll(\"\");\n}\n" }, { "answer_id": 4200787, "author": "Rizwan", "author_id": 507112, "author_profile": "https://Stackoverflow.com/users/507112", "pm_score": -1, "selected": false, "text": "String RemoveTag(String html){\n html = html.replaceAll(\"\\\\<.*?>\",\"\")\n html = html.replaceAll(\"&nbsp;\",\"\");\n html = html.replaceAll(\"&amp;\".\"\");\n ----------\n ----------\n return html;\n}\n" }, { "answer_id": 6266528, "author": "rqualis", "author_id": 787614, "author_profile": "https://Stackoverflow.com/users/787614", "pm_score": 2, "selected": false, "text": "noHTMLString.replaceAll(\"\\\\&.*?\\\\;\", \"\");\n html = html.replaceAll(\"&nbsp;\",\"\");\nhtml = html.replaceAll(\"&amp;\".\"\");\n" }, { "answer_id": 6962693, "author": "Josh", "author_id": 881338, "author_profile": "https://Stackoverflow.com/users/881338", "pm_score": 4, "selected": false, "text": " Source htmlSource = new Source(htmlText);\n Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());\n Renderer htmlRend = new Renderer(htmlSeg);\n System.out.println(htmlRend.toString());\n" }, { "answer_id": 6997978, "author": "Alexander", "author_id": 698723, "author_profile": "https://Stackoverflow.com/users/698723", "pm_score": 0, "selected": false, "text": "String[] temp = yourString.split(\"&amp;\");\nString tmp = \"\";\nif (temp.length > 1) {\n\n for (int i = 0; i < temp.length; i++) {\n tmp += temp[i] + \"&\";\n }\n yourString = tmp.substring(0, tmp.length() - 1);\n}\n" }, { "answer_id": 7784001, "author": "blackStar", "author_id": 941748, "author_profile": "https://Stackoverflow.com/users/941748", "pm_score": 2, "selected": false, "text": "public static String removeHTML(String input) {\n int i = 0;\n String[] str = input.split(\"\");\n\n String s = \"\";\n boolean inTag = false;\n\n for (i = input.indexOf(\"<\"); i < input.indexOf(\">\"); i++) {\n inTag = true;\n }\n if (!inTag) {\n for (i = 0; i < str.length; i++) {\n s = s + str[i];\n }\n }\n return s;\n}\n" }, { "answer_id": 12259801, "author": "Maksim Sorokin", "author_id": 417297, "author_profile": "https://Stackoverflow.com/users/417297", "pm_score": 2, "selected": false, "text": "InputStream htmlInputStream = ..\nHtmlParser htmlParser = new HtmlParser();\nHtmlContentHandler htmlContentHandler = new HtmlContentHandler();\nhtmlParser.parse(htmlInputStream, htmlContentHandler, new Metadata())\nSystem.out.println(htmlContentHandler.getBodyText().trim())\n" }, { "answer_id": 16220579, "author": "surfealokesea", "author_id": 1773233, "author_profile": "https://Stackoverflow.com/users/1773233", "pm_score": 0, "selected": false, "text": "String BR_ESCAPED = \"&lt;br/&gt;\";\nElement el=Jsoup.parse(html).select(\"body\");\nel.select(\"br\").append(BR_ESCAPED);\nel.select(\"p\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h1\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h2\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h3\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h4\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h5\").append(BR_ESCAPED+BR_ESCAPED);\nString nodeValue=el.text();\nnodeValue=nodeValue.replaceAll(BR_ESCAPED, \"<br/>\");\nnodeValue=nodeValue.replaceAll(\"(\\\\s*<br[^>]*>){3,}\", \"<br/><br/>\");\n nodeValue=nodeValue.replaceAll(\"(\\\\s*\\n){3,}\", \"<br/><br/>\");\n" }, { "answer_id": 21838532, "author": "Stephan", "author_id": 363573, "author_profile": "https://Stackoverflow.com/users/363573", "pm_score": 3, "selected": false, "text": "private CharSequence removeHtmlFrom(String html) {\n return new HtmlCleaner().clean(html).getText();\n}\n" }, { "answer_id": 23622675, "author": "Damien", "author_id": 271887, "author_profile": "https://Stackoverflow.com/users/271887", "pm_score": 4, "selected": false, "text": "Jsoup.parse(html).text() &lt;script&gt; <script> // breaks multi-level of escaping, preventing &amp;lt;script&amp;gt; to be rendered as <script>\nString replace = input.replace(\"&amp;\", \"\");\n// decode any encoded html, preventing &lt;script&gt; to be rendered as <script>\nString html = StringEscapeUtils.unescapeHtml(replace);\n// remove all html tags, but maintain line breaks\nString clean = Jsoup.clean(html, \"\", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));\n// decode html again to convert character entities back into text\nreturn StringEscapeUtils.unescapeHtml(clean);\n {\"regular string\", \"regular string\"},\n{\"<a href=\\\"link\\\">A link</a>\", \"A link\"},\n{\"<script src=\\\"http://evil.url.com\\\"/>\", \"\"},\n{\"&lt;script&gt;\", \"\"},\n{\"&amp;lt;script&amp;gt;\", \"lt;scriptgt;\"}, // best effort\n{\"\\\" ' > < \\n \\\\ é å à ü and & preserved\", \"\\\" ' > < \\n \\\\ é å à ü and & preserved\"}\n" }, { "answer_id": 25648860, "author": "Satya Prakash", "author_id": 2934974, "author_profile": "https://Stackoverflow.com/users/2934974", "pm_score": -1, "selected": false, "text": " // sample text with tags\n\n string str = \"<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>\";\n\n\n\n // regex which match tags\n\n System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(\"<[^>]*>\");\n\n\n\n // replace all matches with empty strin\n\n str = rx.Replace(str, \"\");\n\n\n\n //now str contains string without html tags\n" }, { "answer_id": 30022636, "author": "Ameen Maheen", "author_id": 3836137, "author_profile": "https://Stackoverflow.com/users/3836137", "pm_score": 4, "selected": false, "text": "String result = Html.fromHtml(html).toString();\n" }, { "answer_id": 32406442, "author": "RobMen", "author_id": 5302242, "author_profile": "https://Stackoverflow.com/users/5302242", "pm_score": 1, "selected": false, "text": "String html = \"<p>Line one</p><p>Line two</p>Line three<br/>etc.\";\nString NEW_LINE_MARK = \"NEWLINESTART1234567890NEWLINEEND\";\nfor (String tag: new String[]{\"</p>\",\"<br/>\",\"</h1>\",\"</h2>\",\"</h3>\",\"</h4>\",\"</h5>\",\"</h6>\",\"</li>\"}) {\n html = html.replace(tag, NEW_LINE_MARK+tag);\n}\n\nString text = Jsoup.parse(html).text();\n\ntext = text.replace(NEW_LINE_MARK + \" \", \"\\n\\n\");\ntext = text.replace(NEW_LINE_MARK, \"\\n\\n\");\n" }, { "answer_id": 33870804, "author": "IntelliJ Amiya", "author_id": 3395198, "author_profile": "https://Stackoverflow.com/users/3395198", "pm_score": 3, "selected": false, "text": "Html.fromHtml <a href=”…”> <b>, <big>, <blockquote>, <br>, <cite>, <dfn>\n<div align=”…”>, <em>, <font size=”…” color=”…” face=”…”>\n<h1>, <h2>, <h3>, <h4>, <h5>, <h6>\n<i>, <p>, <small>\n<strike>, <strong>, <sub>, <sup>, <tt>, <u>\n Html.formHtml Html.TagHandler String Str_Html=\" <p>This is about me text that the user can put into their profile</p> \";\n Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());\n" }, { "answer_id": 44845644, "author": "Sandeep1699", "author_id": 8237054, "author_profile": "https://Stackoverflow.com/users/8237054", "pm_score": 4, "selected": false, "text": " text.replaceAll('<.*?>' , \" \") -> This will replace all the html tags with a space.\n text.replaceAll('&.*?;' , \"\")-> this will replace all the tags which starts with \"&\" and ends with \";\" like &nbsp;, &amp;, &gt; etc.\n" }, { "answer_id": 48461365, "author": "Guilherme Oliveira", "author_id": 8115060, "author_profile": "https://Stackoverflow.com/users/8115060", "pm_score": 1, "selected": false, "text": "classeString.replaceAll(\"\\\\<(/?[^\\\\>]+)\\\\>\", \"\\\\ \").replaceAll(\"\\\\s+\", \" \").trim() \n" }, { "answer_id": 50942752, "author": "silentsudo", "author_id": 1752366, "author_profile": "https://Stackoverflow.com/users/1752366", "pm_score": 2, "selected": false, "text": "content.replaceAll(\"(<.*?>)|(&.*?;)|([ ]{2,})\", \"\");" }, { "answer_id": 55413383, "author": "Anuraganu Punalur", "author_id": 9385470, "author_profile": "https://Stackoverflow.com/users/9385470", "pm_score": 3, "selected": false, "text": " public String htmlToStringFilter(String textToFilter){\n\n return Html.fromHtml(textToFilter).toString();\n\n }\n" }, { "answer_id": 62001289, "author": "Itay Sasson", "author_id": 13612863, "author_profile": "https://Stackoverflow.com/users/13612863", "pm_score": 0, "selected": false, "text": "Pattern REMOVE_TAGS = Pattern.compile(\"<.+?>\");\n Source source= new Source(htmlAsString);\n Matcher m = REMOVE_TAGS.matcher(sourceStep.getTextExtractor().toString());\n String clearedHtml= m.replaceAll(\"\");\n" }, { "answer_id": 62920964, "author": "Jared Beach", "author_id": 1834329, "author_profile": "https://Stackoverflow.com/users/1834329", "pm_score": 0, "selected": false, "text": "using ServiceStack.Text;\n// ...\n\"The <b>quick</b> brown <p> fox </p> jumps over the lazy dog\".StripHtml();\n" }, { "answer_id": 63552068, "author": "Parker", "author_id": 2074605, "author_profile": "https://Stackoverflow.com/users/2074605", "pm_score": 0, "selected": false, "text": "// delete all comments\nresponse = response.replaceAll(\"<!--[^>]*-->\", \"\");\n// delete all script elements\nresponse = response.replaceAll(\"<(script|SCRIPT)[^+]*?>[^>]*?<(/script|SCRIPT)>\", \"\");\n" }, { "answer_id": 63720307, "author": "jiamo", "author_id": 976371, "author_profile": "https://Stackoverflow.com/users/976371", "pm_score": 1, "selected": false, "text": "&lt Document doc = Jsoup.parse(htmlstrl);\nWhitelist wl = Whitelist.none();\nString plain = Jsoup.clean(doc.text(), wl);\n Jsoup.parse(htmlstrl).text()" }, { "answer_id": 63832019, "author": "Muneeb Ahmed", "author_id": 9533811, "author_profile": "https://Stackoverflow.com/users/9533811", "pm_score": 1, "selected": false, "text": "const strippedString = htmlString.replace(/(<([^>]+)>)/gi, \"\");\nconsole.log(strippedString);\n" }, { "answer_id": 66425176, "author": "Arefe", "author_id": 2746110, "author_profile": "https://Stackoverflow.com/users/2746110", "pm_score": 1, "selected": false, "text": "public static String stripHtmlTags(String html) {\n\n return html.replaceAll(\"<.*?>\", \"\");\n\n}\n" }, { "answer_id": 69073444, "author": "Ahmad Nabeel Butt", "author_id": 11709551, "author_profile": "https://Stackoverflow.com/users/11709551", "pm_score": 0, "selected": false, "text": "function remove_html_tags(html) {\n html = html.replace(/<div>/g, \"\").replace(/<\\/div>/g, \"<br>\");\n html = html.replace(/<br>/g, \"$br$\");\n html = html.replace(/(?:\\r\\n|\\r|\\n)/g, '$br$');\n var tmp = document.createElement(\"DIV\");\n tmp.innerHTML = html;\n html = tmp.textContent || tmp.innerText;\n html = html.replace(/\\$br\\$/g, \"\\n\");\n return html;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973/" ]
240,582
<p>I have tried the following two statements:</p> <ul> <li><code>SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num</code> results in a syntax error</li> <li><code>SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num</code> results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned.</li> </ul> <p>I figured one of the two statements would work, but they aren't.</p>
[ { "answer_id": 240585, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 7, "selected": true, "text": "SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num\n" }, { "answer_id": 240589, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = ...\n" }, { "answer_id": 240591, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "WHERE ((page LIKE 'str1') OR (page LIKE 'str2'))" }, { "answer_id": 240612, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "page LIKE ('str1' OR 'str2')\n page LIKE TRUE" }, { "answer_id": 41220435, "author": "Developer", "author_id": 6516777, "author_profile": "https://Stackoverflow.com/users/6516777", "pm_score": 3, "selected": false, "text": "% SELECT col FROM db.tbl WHERE (col LIKE '%str1%' OR col LIKE '%str2%') AND col2 = num\n" }, { "answer_id": 62834101, "author": "AMF", "author_id": 6292891, "author_profile": "https://Stackoverflow.com/users/6292891", "pm_score": 0, "selected": false, "text": "IN SELECT col FROM db.tbl WHERE col IN('str1','str2') AND col2 = num\n" }, { "answer_id": 66513302, "author": "Dominic Flynn", "author_id": 12087633, "author_profile": "https://Stackoverflow.com/users/12087633", "pm_score": 2, "selected": false, "text": "SELECT col FROM db.tbl WHERE col LIKE '%str[12]%' AND col2 = num\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
240,592
<p>I'm working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options from other parts of the form. Whenever those options change the new values are noted in a "registry" type object and the other sections re-populate accordingly.</p> <p>Having event listeners on the many form fields is starting to slow things down, and refreshing the whole form for each change would be too heavy/slow for the user.</p> <p>I'm wondering whether its possible to add listeners to the registry object's attributes rather than the form elements to speed things up a bit? And, if so, could you provide/point me to some sample code?</p> <p>Further information:</p> <ul> <li>This is a plug-in for jQuery, so any functionality I can build-on from that library would be helpful but not essential.</li> <li>Our users are using IE6/7, Safari and FF2/3, so if it is possible but only for "modern" browsers I'll have to find a different solution.</li> </ul>
[ { "answer_id": 240663, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "$('body').change(function(event){\n /* do whatever you want with event.target here */\n console.debug(event.target); /* assuming firebug */\n });\n" }, { "answer_id": 240700, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "Object.watch $(form).observe('change', function(e) {\n // To identify changed field, in Proto use e.element()\n // but I think in jQuery it's e.target (as it should be)\n});\n input keyup paste input form keyup paste textarea input textarea keyup paste form change form select keyup paste value defaultValue" }, { "answer_id": 240722, "author": "Brian J Cardiff", "author_id": 30948, "author_profile": "https://Stackoverflow.com/users/30948", "pm_score": 0, "selected": false, "text": "var o = { foo: \"Change this string\" };\n\nSys.Observer.observe(o);\n\no.add_propertyChanged(function(sender, args) {\n var name = args.get_propertyName();\n alert(\"Property '\" + name + \"' was changed to '\" + sender[name] + \"'.\");\n});\n\no.setValue(\"foo\", \"New string value.\");\n" }, { "answer_id": 242873, "author": "Phillip B Oldham", "author_id": 30478, "author_profile": "https://Stackoverflow.com/users/30478", "pm_score": 4, "selected": true, "text": "var EntriesRegistry = (function(){\n\n var instance = null;\n\n function __constructor() {\n\n var\n self = this,\n observations = {};\n\n this.set = function(n,v)\n {\n self[n] = v;\n\n if( observations[n] )\n for( var i=0; i < observations[n].length; i++ )\n observations[n][i].apply(null, [v, n]);\n\n }\n\n this.get = function(n)\n {\n return self[n];\n }\n\n this.observe = function(n,f)\n {\n\n if(observations[n] == undefined)\n observations[n] = [];\n\n observations[n].push(f);\n }\n\n }\n\n return new function(){\n this.getInstance = function(){\n if (instance == null)\n {\n instance = new __constructor();\n instance.constructor = null;\n }\n return instance;\n }\n }\n})();\n\nvar entries = EntriesRegistry.getInstance();\n\nvar test = function(v){ alert(v); };\n\nentries.set('bob', 'meh');\n\nentries.get('bob');\n\nentries.observe('seth', test);\n\nentries.set('seth', 'dave');\n" }, { "answer_id": 15144909, "author": "rafaelcastrocouto", "author_id": 1242389, "author_profile": "https://Stackoverflow.com/users/1242389", "pm_score": 0, "selected": false, "text": "var ObservedObject = function(){\n this.customAttribute = 0\n this.events = {}\n // your code...\n}\nObservedObject.prototype.changeAttribute = function(v){\n this.customAttribute = v\n // your code...\n this.dispatchEvent('myEvent')\n}\nObservedObject.prototype.addEventListener = function(type, f){\n if(!this.events[type]) this.events[type] = []\n this.events[type].push({\n action: f,\n type: type,\n target: this\n })\n}\nObservedObject.prototype.dispatchEvent = function(type){\n for(var e = 0; e < this.events[type].length; ++e){\n this.events[type][e].action(this.events[type][e])\n }\n}\nObservedObject.prototype.removeEventListener = function(type, f){\n if(this.events[type]) {\n for(var e = 0; e < this.events[type].length; ++e){\n if(this.events[type][e].action == f)\n this.events[type].splice(e, 1)\n }\n }\n}\n\nvar myObj = new ObservedObject()\n\nmyObj.addEventListener('myEvent', function(e){// your code...})\n" }, { "answer_id": 32336310, "author": "Sumi Straessle", "author_id": 2012120, "author_profile": "https://Stackoverflow.com/users/2012120", "pm_score": 1, "selected": false, "text": "ObservableProperties = {\n events : {},\n on : function(type, f)\n {\n if(!this.events[type]) this.events[type] = [];\n this.events[type].push({\n action: f,\n type: type,\n target: this\n });\n },\n trigger : function(type)\n {\n if (this.events[type]!==undefined)\n {\n for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)\n {\n this.events[type][e].action(this.events[type][e]);\n }\n }\n },\n removeEventListener : function(type, f)\n {\n if(this.events[type])\n {\n for(var e = 0, imax = this.events[type].length ; e < imax ; ++e)\n {\n if(this.events[type][e].action == f)\n this.events[type].splice(e, 1);\n }\n }\n }\n};\nObject.freeze(ObservableProperties);\n\nvar SomeBusinessObject = function (){\n self = $.extend(true,{},ObservableProperties);\n self.someAttr = 1000\n self.someMethod = function(){\n // some code\n }\n return self;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
240,648
<p>I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.</p> <p>I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing <code>static</code> and not containing <code>final</code>, and not ending in a <code>{</code>?</p> <p>The last part about not ending with a <code>{</code> will eliminate static methods.</p> <p>An example:</p> <pre><code>public class FlagOffendingStatics { private static String shouldBeFlagged = "not ok"; private static final String ok = "this is fine"; public static void methodsAreOK() { } } </code></pre>
[ { "answer_id": 240687, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": "grep -r static . | grep -v final final" }, { "answer_id": 240848, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": true, "text": "[^(final)] static [^(final)][^(\\})]*$\n $ cat test.txt\nprivate int x = \"3\";\nprivate static x = \"3\";\nprivate final static String x = \"3\";\nprivate static final String x = \"3\";\nprivate static String x = \"3\";\npublic static void main(String args[]) {\n blah;\n}\n\n$ grep \"[^(final)] static [^(final)][^(\\})]*$\" test.txt\nprivate static x = \"3\";\nprivate static String x = \"3\";\n private static x = \"3\"; final static [^(final)] static [^(final)] [^(\\})]*$ { private static void blah()\n{\n //hi!\n}\n" }, { "answer_id": 241324, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": false, "text": "^(?![ \\t]*import\\b)(?!.*\\bfinal\\b).*\\bstatic\\b.*;[ \\t]*$\n" }, { "answer_id": 23958544, "author": "SynteZZZ", "author_id": 175221, "author_profile": "https://Stackoverflow.com/users/175221", "pm_score": 2, "selected": false, "text": "[^(final|import)] static [^(final|class|{|enum)][^(\\})]*$\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31837/" ]
240,659
<p>I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?</p>
[ { "answer_id": 241430, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "post_save post_delete Article Question User Question from django.contrib.auth.models import User\nfrom django.db import connection, models, transaction\nfrom django.db.models.signals import post_delete, post_save\n\nclass Question(models.Model):\n # ...\n favourite_count = models.PositiveIntegerField(default=0)\n\nclass FavouriteQuestion(models.Model):\n question = models.ForeignKey(Question)\n user = models.ForeignKey(User)\n\ndef update_question_favourite_count(instance, **kwargs):\n \"\"\"\n Updates the favourite count for the Question related to the given\n FavouriteQuestion.\n \"\"\"\n if kwargs.get('raw', False):\n return\n cursor = connection.cursor()\n cursor.execute(\n 'UPDATE soclone_question SET favourite_count = ('\n 'SELECT COUNT(*) from soclone_favouritequestion '\n 'WHERE soclone_favouritequestion.question_id = soclone_question.id'\n ') '\n 'WHERE id = %s', [instance.question_id])\n transaction.commit_unless_managed()\n\npost_save.connect(update_question_favourite_count, sender=FavouriteQuestion)\npost_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)\n\n# Very, very naughty\nUser.add_to_class('favourite_questions',\n models.ManyToManyField(Question, through=FavouriteQuestion,\n related_name='favourited_by'))\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437/" ]
240,660
<p>I have an associative array in the form <code>key =&gt; value</code> where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.</p> <p>I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?</p>
[ { "answer_id": 240673, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 4, "selected": false, "text": "echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];\n" }, { "answer_id": 240676, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 10, "selected": true, "text": "$arr[$newkey] = $arr[$oldkey];\nunset($arr[$oldkey]);\n" }, { "answer_id": 4196760, "author": "Simon Franco", "author_id": 509808, "author_profile": "https://Stackoverflow.com/users/509808", "pm_score": 6, "selected": false, "text": "array mysql \"select ´id´ from ´tablename´...\"\n \"select ´id´ **as NEWNAME** from ´tablename´...\"\n" }, { "answer_id": 4533033, "author": "kjg", "author_id": 547306, "author_profile": "https://Stackoverflow.com/users/547306", "pm_score": 4, "selected": false, "text": "$newarr[$newkey] = $oldarr[$oldkey];\n$oldarr=$newarr;\nunset($newarr);\n" }, { "answer_id": 5227417, "author": "kingjeffrey", "author_id": 315010, "author_profile": "https://Stackoverflow.com/users/315010", "pm_score": 3, "selected": false, "text": "function swapKeys( &$arr, $origKey, $newKey, &$pendingKeys ) {\n if( !isset( $arr[$newKey] ) ) {\n $arr[$newKey] = $arr[$origKey];\n unset( $arr[$origKey] );\n if( isset( $pendingKeys[$origKey] ) ) {\n // recursion to handle conflicting keys with conflicting keys\n swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );\n unset( $pendingKeys[$origKey] );\n }\n } elseif( $newKey != $origKey ) {\n $pendingKeys[$newKey] = $origKey;\n }\n}\n $myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );\n$pendingKeys = array();\nforeach( $myArray as $key => $myArrayValue ) {\n // NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)\n $timestamp = strtotime( $myArrayValue );\n swapKeys( $myArray, $key, $timestamp, $pendingKeys );\n}\n// RESULT: $myArray == array( 1=>'1970-01-01 00:00:01', 60=>'1970-01-01 00:01:00' )\n" }, { "answer_id": 13062010, "author": "pajafumo", "author_id": 1746058, "author_profile": "https://Stackoverflow.com/users/1746058", "pm_score": 3, "selected": false, "text": " $datos = array\n (\n '0' => array\n (\n 'no' => 1,\n 'id_maquina' => 1,\n 'id_transaccion' => 1276316093,\n 'ultimo_cambio' => 'asdfsaf',\n 'fecha_ultimo_mantenimiento' => 1275804000,\n 'mecanico_ultimo_mantenimiento' =>'asdfas',\n 'fecha_ultima_reparacion' => 1275804000,\n 'mecanico_ultima_reparacion' => 'sadfasf',\n 'fecha_siguiente_mantenimiento' => 1275804000,\n 'fecha_ultima_falla' => 0,\n 'total_fallas' => 0,\n ),\n\n '1' => array\n (\n 'no' => 2,\n 'id_maquina' => 2,\n 'id_transaccion' => 1276494575,\n 'ultimo_cambio' => 'xx',\n 'fecha_ultimo_mantenimiento' => 1275372000,\n 'mecanico_ultimo_mantenimiento' => 'xx',\n 'fecha_ultima_reparacion' => 1275458400,\n 'mecanico_ultima_reparacion' => 'xx',\n 'fecha_siguiente_mantenimiento' => 1275372000,\n 'fecha_ultima_falla' => 0,\n 'total_fallas' => 0,\n )\n );\n function changekeyname($array, $newkey, $oldkey)\n{\n foreach ($array as $key => $value) \n {\n if (is_array($value))\n $array[$key] = changekeyname($value,$newkey,$oldkey);\n else\n {\n $array[$newkey] = $array[$oldkey]; \n }\n\n }\n unset($array[$oldkey]); \n return $array; \n}\n" }, { "answer_id": 21299719, "author": "DiverseAndRemote.com", "author_id": 1681414, "author_profile": "https://Stackoverflow.com/users/1681414", "pm_score": 7, "selected": false, "text": "function change_key( $array, $old_key, $new_key ) {\n\n if( ! array_key_exists( $old_key, $array ) )\n return $array;\n\n $keys = array_keys( $array );\n $keys[ array_search( $old_key, $keys ) ] = $new_key;\n\n return array_combine( $keys, $array );\n}\n" }, { "answer_id": 28168537, "author": "spreadzz", "author_id": 4287410, "author_profile": "https://Stackoverflow.com/users/4287410", "pm_score": 4, "selected": false, "text": "function change_array_key( $array, $old_key, $new_key) {\n if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; }\n if(!array_key_exists($old_key, $array)){\n return $array;\n }\n\n $key_pos = array_search($old_key, array_keys($array));\n $arr_before = array_slice($array, 0, $key_pos);\n $arr_after = array_slice($array, $key_pos + 1);\n $arr_renamed = array($new_key => $array[$old_key]);\n\n return $arr_before + $arr_renamed + $arr_after;\n}\n" }, { "answer_id": 30974058, "author": "Karthikeyan Ganesan", "author_id": 3462686, "author_profile": "https://Stackoverflow.com/users/3462686", "pm_score": 2, "selected": false, "text": "$i = 0;\n$keys_array=array(\"0\"=>\"one\",\"1\"=>\"two\");\n\n$keys = array_keys($keys_array);\n\nfor($i=0;$i<count($keys);$i++) {\n $keys_array[$keys_array[$i]]=$keys_array[$i];\n unset($keys_array[$i]);\n}\nprint_r($keys_array);\n $keys_array=array(\"one\"=>\"one\",\"two\"=>\"two\");\n" }, { "answer_id": 31508993, "author": "Nadir", "author_id": 1641763, "author_profile": "https://Stackoverflow.com/users/1641763", "pm_score": 2, "selected": false, "text": "function keyRename(array $hash, array $replacements) {\n $new=array();\n foreach($hash as $k=>$v)\n {\n if($ok=array_search($k,$replacements))\n $k=$ok;\n $new[$k]=$v;\n }\n return $new; \n}\n function keyRename(array $hash, array $replacements) {\n\n foreach($hash as $k=>$v)\n if($ok=array_search($k,$replacements))\n {\n $hash[$ok]=$v;\n unset($hash[$k]);\n }\n\n return $hash; \n}\n" }, { "answer_id": 34005346, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "/**\n * Helper function to rename array keys.\n */\nfunction _rename_arr_key($oldkey, $newkey, array &$arr) {\n if (array_key_exists($oldkey, $arr)) {\n $arr[$newkey] = $arr[$oldkey];\n unset($arr[$oldkey]);\n return TRUE;\n } else {\n return FALSE;\n }\n}\n _rename_arr_key('oldkey', 'newkey', $my_array);\n" }, { "answer_id": 36435888, "author": "temuri", "author_id": 84626, "author_profile": "https://Stackoverflow.com/users/84626", "pm_score": 4, "selected": false, "text": "$array = [\n 'old1' => 1\n 'old2' => 2\n];\n\n$renameMap = [\n 'old1' => 'new1', \n 'old2' => 'new2'\n];\n\n$array = array_combine(array_map(function($el) use ($renameMap) {\n return $renameMap[$el];\n}, array_keys($array)), array_values($array));\n\n/*\n$array = [\n 'new1' => 1\n 'new2' => 2\n];\n*/\n" }, { "answer_id": 37243759, "author": "wmmso", "author_id": 3930840, "author_profile": "https://Stackoverflow.com/users/3930840", "pm_score": 1, "selected": false, "text": "$a = ['catine' => 'cat', 'canine' => 'dog'];\n$tmpa['feline'] = $a['catine'];\nunset($a['catine']);\n$a = $tmpa + $a;\n Array\n(\n [feline] => cat\n [canine] => dog\n)\n $a = ['canine' => 'dog', 'catine' => 'cat', 'porcine' => 'pig']\n$af = array_flip($a)\n$af['cat'] = 'feline';\n$a = array_flip($af)\n Array\n(\n [canine] => dog\n [feline] => cat\n [porcine] => pig\n)\n function renameKey($oldkey, $newkey, $array) {\n $val = $array[$oldkey];\n $tmp_A = array_flip($array);\n $tmp_A[$val] = $newkey;\n\n return array_flip($tmp_A);\n}\n" }, { "answer_id": 38341525, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 2, "selected": false, "text": "/**\n * Rename keys of an array\n * @param array $array (asoc)\n * @param array $replacement_keys (indexed)\n * @return array\n */\nfunction rename_keys($array, $replacement_keys) {\n return array_combine($replacement_keys, array_values($array));\n}\n $myarr = array(\"a\" => 22, \"b\" => 144, \"c\" => 43);\n$newkeys = array(\"x\",\"y\",\"z\");\nprint_r(rename_keys($myarr, $newkeys));\n//must return: array(\"x\" => 22, \"y\" => 144, \"z\" => 43);\n" }, { "answer_id": 41669197, "author": "Frank Vu", "author_id": 2924678, "author_profile": "https://Stackoverflow.com/users/2924678", "pm_score": -1, "selected": false, "text": "function replace_array_key($data) {\n $mapping = [\n 'old_key_1' => 'new_key_1',\n 'old_key_2' => 'new_key_2',\n ];\n\n $data = json_encode($data);\n foreach ($mapping as $needed => $replace) {\n $data = str_replace('\"'.$needed.'\":', '\"'.$replace.'\":', $data);\n }\n\n return json_decode($data, true);\n}\n" }, { "answer_id": 43061290, "author": "Kristoffer Bohmann", "author_id": 169224, "author_profile": "https://Stackoverflow.com/users/169224", "pm_score": 1, "selected": false, "text": "<?php\n$arr = [\n 'foo',\n 'bar'=>'alfa',\n 'baz'=>['a'=>'hello', 'b'=>'world'],\n];\n\nforeach($arr as $k=>$v) {\n $kk = is_numeric($k) ? $v : $k;\n $vv = is_numeric($k) ? null : $v;\n $arr2[$kk] = $vv;\n}\n\nprint_r($arr2);\n Array (\n [foo] => \n [bar] => alfa\n [baz] => Array (\n [a] => hello\n [b] => world\n )\n)\n" }, { "answer_id": 51857398, "author": "Andrew", "author_id": 2035501, "author_profile": "https://Stackoverflow.com/users/2035501", "pm_score": 0, "selected": false, "text": "function rename_array_key(array $array, $old_key, $new_key) {\n if (!array_key_exists($old_key, $array)) {\n return $array;\n }\n $new_array = [];\n foreach ($array as $key => $value) {\n $new_key = $old_key === $key\n ? $new_key\n : $key;\n $new_array[$new_key] = $value;\n }\n return $new_array;\n}\n" }, { "answer_id": 52248296, "author": "Alekzander", "author_id": 1331420, "author_profile": "https://Stackoverflow.com/users/1331420", "pm_score": 2, "selected": false, "text": "function mapToIDs($array, $id_field_name = 'id')\n{\n $result = [];\n array_walk($array, \n function(&$value, $key) use (&$result, $id_field_name)\n {\n $result[$value[$id_field_name]] = $value;\n }\n );\n return $result;\n}\n\n$arr = [0 => ['id' => 'one', 'fruit' => 'apple'], 1 => ['id' => 'two', 'fruit' => 'banana']];\nprint_r($arr);\nprint_r(mapToIDs($arr));\n Array(\n [0] => Array(\n [id] => one\n [fruit] => apple\n )\n [1] => Array(\n [id] => two\n [fruit] => banana\n )\n)\n\nArray(\n [one] => Array(\n [id] => one\n [fruit] => apple\n )\n [two] => Array(\n [id] => two\n [fruit] => banana\n )\n)\n" }, { "answer_id": 56388222, "author": "Kamil Dąbrowski", "author_id": 1088058, "author_profile": "https://Stackoverflow.com/users/1088058", "pm_score": 1, "selected": false, "text": "$tab = ['two' => [] ];\n $tab['newname'] = & $tab['two'];\n foreach($tab as $key=> & $value) {\n if($key=='two') { \n $newtab[\"newname\"] = & $tab[$key];\n } else {\n $newtab[$key] = & $tab[$key];\n }\n}\n" }, { "answer_id": 56800416, "author": "vardius", "author_id": 2160958, "author_profile": "https://Stackoverflow.com/users/2160958", "pm_score": -1, "selected": false, "text": "<?php\nfunction array_map_keys(callable $callback, array $array) {\n return array_merge([], ...array_map(\n function ($key, $value) use ($callback) { return [$callback($key) => $value]; },\n array_keys($array),\n $array\n ));\n}\n\n$array = ['a' => 1, 'b' => 'test', 'c' => ['x' => 1, 'y' => 2]];\n$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);\n\necho json_encode($array); // {\"a\":1,\"b\":\"test\",\"c\":{\"x\":1,\"y\":2}}\necho json_encode($newArray); // {\"newA\":1,\"newB\":\"test\",\"newC\":{\"x\":1,\"y\":2}}\n" }, { "answer_id": 58619985, "author": "Léo Benoist", "author_id": 1617857, "author_profile": "https://Stackoverflow.com/users/1617857", "pm_score": 4, "selected": false, "text": "<?php\n$array = ['test' => 'value', ['etc...']];\n\n$array['test2'] = $array['test'];\nunset($array['test']);\n <?php\n$array = ['test' => 'value', ['etc...']];\n\n$keys = array_keys( $array );\n$keys[array_search('test', $keys, true)] = 'test2';\narray_combine( $keys, $array );\n <?php\n$array = ['test' => 'value', ['etc...']];\n\n\nfor ($i =0; $i < 100000000; $i++){\n // Solution 1\n}\n\n\nfor ($i =0; $i < 100000000; $i++){\n // Solution 2\n}\n php solution1.php 6.33s user 0.02s system 99% cpu 6.356 total\nphp solution1.php 6.37s user 0.01s system 99% cpu 6.390 total\nphp solution2.php 12.14s user 0.01s system 99% cpu 12.164 total\nphp solution2.php 12.57s user 0.03s system 99% cpu 12.612 total\n" }, { "answer_id": 58630444, "author": "MikeyJ", "author_id": 1665124, "author_profile": "https://Stackoverflow.com/users/1665124", "pm_score": 2, "selected": false, "text": "public function keySwap(array $resource, array $keys)\n{\n $newResource = [];\n\n foreach($resource as $k => $r){\n if(array_key_exists($k,$keys)){\n $newResource[$keys[$k]] = $r;\n }else{\n $newResource[$k] = $r;\n }\n }\n\n return $newResource;\n}\n $inputs = [\n 0 => ['a'=>'1','b'=>'2'],\n 1 => ['a'=>'3','b'=>'4']\n]\n\n$keySwap = ['a'=>'z'];\n\nforeach($inputs as $k=>$i){\n $inputs[$k] = $this->keySwap($i,$keySwap);\n}\n" }, { "answer_id": 60765547, "author": "Grant", "author_id": 4582132, "author_profile": "https://Stackoverflow.com/users/4582132", "pm_score": 2, "selected": false, "text": "function renameArrKey($arr, $oldKey, $newKey){\n if(!isset($arr[$oldKey])) return $arr; // Failsafe\n $keys = array_keys($arr);\n $keys[array_search($oldKey, $keys)] = $newKey;\n $newArr = array_combine($keys, $arr);\n return $newArr;\n}\n $arr = renameArrKey($arr, 'old_key', 'new_key');\n" }, { "answer_id": 71274431, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "array_search() unset() $idCounts = [\n 3 => 15,\n 7 => 12,\n 8 => 10,\n 9 => 4\n];\n\n$idNames = [\n 1 => 'Steve',\n 2 => 'Georgia',\n 3 => 'Elon',\n 4 => 'Fiona',\n 5 => 'Tim',\n 6 => 'Petra',\n 7 => 'Quentin',\n 8 => 'Raymond',\n 9 => 'Barb'\n];\n\n$result = [];\nforeach ($idCounts as $id => $count) {\n if (isset($idNames[$id])) {\n $result[$idNames[$id]] = $count;\n }\n}\nvar_export($result);\n array (\n 'Elon' => 15,\n 'Quentin' => 12,\n 'Raymond' => 10,\n 'Barb' => 4,\n)\n isset()" }, { "answer_id": 73508367, "author": "Andris", "author_id": 2118559, "author_profile": "https://Stackoverflow.com/users/2118559", "pm_score": 0, "selected": false, "text": "$some_array[] = '6110';//\n$some_array[] = '6111';//\n$some_array[] = '6210';//\n human_readable15 human_readable16 human_readable17 $some_array lastInsertId $first_id_of_inserted = 7;//lastInsertId\n$last_loop_for_some_array = count($some_array);\n\n\nfor ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {\n\n$some_array['human_readable'.($first_id_of_inserted + $current_loop)] = $some_array[$current_loop];//add new key for intial array\n\nunset( $some_array[$current_loop] );//remove already renamed key from array\n\n}\n echo '<pre>', print_r($some_array, true), '</pre>$some_array in '. basename(__FILE__, '.php'). '.php <br/>';\n human_readable15 human_readable16 human_readable17 $arr_with_key_names[] = 'human_readable';\n$arr_with_key_names[] = 'something_another';\n$arr_with_key_names[] = 'and_something_else';\n\n\nfor ($current_loop = 0; $current_loop < $last_loop_for_some_array ; $current_loop++) {\n\n $some_array[$arr_with_key_names[$current_loop]] = $some_array[$current_loop];//add new key for intial array\n\n unset( $some_array[$current_loop] );//remove already renamed key from array\n\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
240,661
<p>Do you think changing directories inside bash or Perl scripts is acceptable? Or should one avoid doing this at all costs?</p> <p>What is the best practice for this issue?</p>
[ { "answer_id": 240703, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 5, "selected": true, "text": "alias build-product1='(cd $working-copy/delivery; mvn package;)'\n" }, { "answer_id": 241489, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "use Cwd;\nsub foo {\n my $orig_cwd = cwd;\n chdir \"some/dir\";\n\n ...do some work...\n\n chdir $orig_cwd;\n}\n some/dir chdir use File::chdir;\nsub foo {\n local $CWD = 'some/dir';\n\n ...do some work...\n}\n $CWD $CWD chdir" }, { "answer_id": 241531, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 2, "selected": false, "text": " use File::pushd;\n\n chdir $ENV{HOME};\n\n # change directory again for a limited scope\n {\n my $dir = pushd( '/tmp' );\n # working directory changed to /tmp\n }\n # working directory has reverted to $ENV{HOME}\n\n # tempd() is equivalent to pushd( File::Temp::tempdir )\n {\n my $dir = tempd();\n }\n\n # object stringifies naturally as an absolute path\n {\n my $dir = pushd( '/tmp' );\n my $filename = File::Spec->catfile( $dir, \"somefile.txt\" );\n # gives /tmp/somefile.txt\n }\n" }, { "answer_id": 242235, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 0, "selected": false, "text": "use FileHandle;\nuse FindBin qw($Bin);\n# ...\nmy $file = new FileHandle(\"< $Bin/somefile\");\n use FileHandle;\n# ...\nmy $file = new FileHandle(\"< somefile\");\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
240,692
<p>I am trying to download an xml.gz file from a remote server with HttpsURLConnection in java, but I am getting an empty response. Here is a sample of my code:</p> <pre><code>URL server = new URL("https://www.myurl.com/path/sample_file.xml.gz"); HttpsURLConnection connection = (HttpsURLConnection)server.openConnection(); connection.connect(); </code></pre> <p>When I try to get an InputStream from the connection, it is empty. (If I try connection.getInputStream().read() I get -1) The file I am expecting is approximately 50MB. </p> <p>To test my sanity, I aslo tried entering the exact same url in my browser, and it did return the file I needed. Am I missing something? Do I have to set some sort of parameter in the connection? Any help/direction is much appreciated. </p>
[ { "answer_id": 240871, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "response code connection.contentType" }, { "answer_id": 244318, "author": "Zakir Hemraj", "author_id": 29752, "author_profile": "https://Stackoverflow.com/users/29752", "pm_score": 1, "selected": false, "text": "if (connection.getResponseCode() == 302 && connection.getHeaderField(\"location\") != null){\n URL server2 = new URL(connection.getHeaderField(\"location\"));\n HttpURLConnection connection2 = (HttpURLConnection)server2.openConnection();\n connection2.connect();\n InputStream in = connection2.getInputStream();\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29752/" ]
240,704
<p>Does anyone have any suggestions for a good approach to finding all the CPAN dependencies that might have arisen in a bespoke development project. As tends to be the case your local development environment rarely matches your live one and as you build more and more projects you tend to build up a local library of installed modules. These then lead to you not necessarily noticing that your latest project has a requirement on a non-core module. As there is generally a requirement to package the entire project up for deployment to another group (in our case our operations team), it is important to know what modules should be included in the package. </p> <p>Does anyone have any insights into the problem.</p> <p>Thanks</p> <p>Peter</p>
[ { "answer_id": 240723, "author": "Vagnerr", "author_id": 3720, "author_profile": "https://Stackoverflow.com/users/3720", "pm_score": 3, "selected": false, "text": "perl -d:Modlist script.pl\n" }, { "answer_id": 240927, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 3, "selected": false, "text": "perl -d:Modlist" }, { "answer_id": 241081, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "package Bundle::Baz;\n$VERSION = '0.1';\n1;\n__END__\n=head1 NAME\nBundle::Baz\n=head1 SYNOPSIS\nperl -MCPAN -e 'install Bundle::Baz'\n=head1 CONTENTS\n# Baz's modules\nXML::Twig\nXML::Writer\nPerl6::Say\nMoose\n" }, { "answer_id": 241353, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": true, "text": "if ($some_condition) { require Some::Module }\n $some_condition Devel::Modlist Some::Module Some::Module my $module = \"Other::Module\";\neval \"use $module;\";\n #! /usr/bin/perl\n#---------------------------------------------------------------------\n# Copyright 2008 Christopher J. Madsen <perl at cjmweb.net>\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the same terms as Perl itself.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the\n# GNU General Public License or the Artistic License for more details.\n#\n# Recursively collect dependencies of Perl scripts\n#---------------------------------------------------------------------\n\nuse strict;\nuse warnings;\nuse File::Spec ();\nuse Module::CoreList ();\nuse Module::ExtractUse ();\n\nmy %need;\nmy $core = $Module::CoreList::version{'5.008'};\n\n# These modules have lots of dependencies. I don't need to see them now.\nmy %noRecurse = map { $_ => 1 } qw(\n Log::Log4perl\n XML::Twig\n);\n\nforeach my $file (@ARGV) {\n findDeps($file);\n}\n\nforeach my $module (sort keys %need) {\n print \" $module\\n\";\n}\n\n#---------------------------------------------------------------------\nsub findDeps\n{\n my ($file) = @_;\n\n my $p = Module::ExtractUse->new;\n\n $p->extract_use($file);\n\n foreach my $module ($p->array) {\n next if exists $core->{$module};\n next if $module =~ /^5[._\\d]+/; # Ignore \"use MIN-PERL-VERSION\"\n next if $module =~ /\\$/; # Run-time specified module\n\n if (++$need{$module} == 1 and not $noRecurse{$module}) {\n my $path = findModule($module);\n if ($path) { findDeps($path) }\n else { warn \"WARNING: Can't find $module\\n\" }\n } # end if first use of $module\n } # end foreach $module used\n} # end findDeps\n\n#---------------------------------------------------------------------\nsub findModule\n{\n my ($module) = @_;\n\n $module =~ s!::|\\'!/!g;\n $module .= '.pm';\n\n foreach my $dir (@INC) {\n my $path = File::Spec->catfile($dir, $module);\n return $path if -f $path;\n }\n\n return;\n} # end findModule\n perl finddeps.pl scriptToCheck.pl otherScriptToCheck.pl\n" }, { "answer_id": 245158, "author": "JDrago", "author_id": 29060, "author_profile": "https://Stackoverflow.com/users/29060", "pm_score": 2, "selected": false, "text": "use Acme::Magic::Pony;\n" }, { "answer_id": 245167, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 1, "selected": false, "text": "# find-perl-module-use <directory> (lib/ by default)\nfunction find-perl-module-use() {\n dir=${1:-lib}\n ack '^\\s*use\\s+.*;\\s*$' $dir | awk '{ print $2 }' | sed 's/();\\?$\\|;$//' | sort | uniq\n ack '^\\s*use\\s+base\\s+.*;\\s*$' $dir | awk '{ print $3 }' | sed 's/();\\?$\\|;$//' | sort | uniq\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
240,713
<p>I need to encrypt and decrypt a querystring in ASP.NET. </p> <p>The querystring might look something like this:</p> <blockquote> <p><a href="http://www.mysite.com/report.aspx?id=12345&amp;year=2008" rel="noreferrer">http://www.mysite.com/report.aspx?id=12345&amp;year=2008</a></p> </blockquote> <p>How do I go about encrypting the entire querystring so that it looks something like the following?</p> <blockquote> <p><a href="http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a" rel="noreferrer">http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a</a></p> </blockquote> <p>And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?</p>
[ { "answer_id": 240730, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 0, "selected": false, "text": "crypt" }, { "answer_id": 240751, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": true, "text": "Private _key as string = \"!#$a54?3\"\nPublic Function encryptQueryString(ByVal strQueryString As String) As String\n Dim oES As New ExtractAndSerialize.Encryption64()\n Return oES.Encrypt(strQueryString, _key)\nEnd Function\n\nPublic Function decryptQueryString(ByVal strQueryString As String) As String\n Dim oES As New ExtractAndSerialize.Encryption64()\n Return oES.Decrypt(strQueryString, _key)\nEnd Function\n Imports System\nImports System.IO\nImports System.Xml\nImports System.Text\nImports System.Security.Cryptography\n\nPublic Class Encryption64\n Private key() As Byte = {}\n Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}\n\n Public Function Decrypt(ByVal stringToDecrypt As String, _\n ByVal sEncryptionKey As String) As String\n Dim inputByteArray(stringToDecrypt.Length) As Byte\n Try\n key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))\n Dim des As New DESCryptoServiceProvider()\n inputByteArray = Convert.FromBase64String(stringToDecrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _\n CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8\n Return encoding.GetString(ms.ToArray())\n Catch e As Exception\n Return e.Message\n End Try\n End Function\n\n Public Function Encrypt(ByVal stringToEncrypt As String, _\n ByVal SEncryptionKey As String) As String\n Try\n key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))\n Dim des As New DESCryptoServiceProvider()\n Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _\n stringToEncrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _\n CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Return Convert.ToBase64String(ms.ToArray())\n Catch e As Exception\n Return e.Message\n End Try\n End Function\n\nEnd Class\n" }, { "answer_id": 240858, "author": "Brendan Kendrick", "author_id": 13473, "author_profile": "https://Stackoverflow.com/users/13473", "pm_score": 0, "selected": false, "text": "stringToDecrypt = stringToDecrypt.Replace(\" \", \"+\")\n Public Shared Function DecryptQueryString(ByVal stringToDecrypt As String, ByVal encryptionKey As String) As Collections.Specialized.NameValueCollection\n Dim inputByteArray(stringToDecrypt.Length) As Byte\n Try\n Dim key() As Byte = System.Text.Encoding.UTF8.GetBytes(encryptionKey.Substring(0, encryptionKey.Length))\n Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}\n Dim des As New DESCryptoServiceProvider()\n stringToDecrypt = stringToDecrypt.Replace(\" \", \"+\")\n inputByteArray = Convert.FromBase64String(stringToDecrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8\n Dim decryptedString As String = encoding.GetString(ms.ToArray())\n Dim nameVals() As String = decryptedString.Split(CChar(\"&\"))\n Dim queryString As New Collections.Specialized.NameValueCollection(nameVals.Length)\n For Each nameValPair As String In nameVals\n Dim pair() As String = nameValPair.Split(CChar(\"=\"))\n queryString.Add(pair(0), pair(1))\n Next\n Return queryString\n\n Catch e As Exception\n Throw New Exception(e.Message)\n End Try\nEnd Function\n" }, { "answer_id": 50232009, "author": "Ravindra Vairagi", "author_id": 6656918, "author_profile": "https://Stackoverflow.com/users/6656918", "pm_score": 3, "selected": false, "text": "protected void Submit(object sender, EventArgs e)\n{\n string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));\n string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));\n Response.Redirect(string.Format(\"~/CS2.aspx?name={0}&technology={1}\", name, technology));\n}\n private string Encrypt(string clearText)\n{\n string EncryptionKey = \"hyddhrii%2moi43Hd5%%\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n}\n\n\nprivate string Decrypt(string cipherText)\n{\n string EncryptionKey = \"hyddhrii%2moi43Hd5%%\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n}\n lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[\"name\"]));\nlblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[\"technology\"]));\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
240,719
<p>I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed. </p> <p>Is there a way to do that?</p> <p>maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the date it was extracted as a file header.</p> <p>thanks.</p>
[ { "answer_id": 1070447, "author": "eksortso", "author_id": 446456, "author_profile": "https://Stackoverflow.com/users/446456", "pm_score": 2, "selected": true, "text": "outExt # from __future__ import with_statement # Version 2.5 requires this.\nimport os, re\n\ndef dump_sql(infile, outExt=r'csv'):\n \"\"\"Parse a DTS package saved as a .bas file, and dump the SQL code.\n\n Pull out the SQL code and the filename for each task. This process\n depends on the way that DTS saves packages as VB modules.\n\n Keyword arguments:\n infile - The .bas file defining a DTS package.\n outExt - The extension (without a period) of the files exported by the\n data pumps in the DTS package. These are used to rename the\n extracted SQL scripts. If an extract file does not use this\n extension, then the whole name of the extract file is used to\n name the SQL script. (default: csv)\n\n The function produces a folder in the same folder that contains the\n .bas file. It's named like this: if the .bas file is \"DTS package.bas\",\n then the directory will be named \"DTS package_SQL\". The SQL scripts are\n stored in this folder.\n\n \"\"\"\n #Declare all of the RE's used in the script here.\n basExtRE = re.compile(r'\\.bas$', re.IGNORECASE)\n outExtRE = re.compile(r'\\.' + outExt + r'$', re.IGNORECASE)\n startTaskRE = re.compile(r'Set oCustomTask(\\d+) = oTask.CustomTask')\n startSqlRE = re.compile(\n r'oCustomTask(\\d+)\\.(?:Source)?SQLStatement = \"(.*)\"( & vbCrLf)?')\n nextSqlRE = re.compile(\n r'oCustomTask(\\d+)\\.(?:Source)?SQLStatement = oCustomTask\\1\\.'\n r'(?:Source)?SQLStatement & \"(.*)\"( & vbCrLf)?')\n filenameRE = re.compile(\n r'oCustomTask(\\d+)\\.DestinationObjectName = \"(.*)\"')\n descripRE = re.compile(r'oCustomTask(\\d+)\\.Description = \"(.*)\"')\n invalidCharsRE = re.compile(r'[][+/*?<>,.;:\"=\\\\|]')\n\n #Read the file\n with open(infile, 'r') as f:\n\n #Produce the directory for the SQL scripts.\n outfolder = '%s_SQL\\\\' % basExtRE.sub('', infile)\n if not os.path.exists(outfolder):\n os.makedirs(outfolder)\n\n taskNum = -1\n outfile = ''\n sql = []\n\n for line in f:\n line = line.rstrip().lstrip()\n\n if taskNum == -1:\n #Seek the beginning of a task.\n m = startTaskRE.match(line)\n if m is not None:\n taskNum = int(m.group(1))\n elif line == '' and outfile != '':\n #Save the SQL code to a file.\n if sql:\n if os.path.exists(outfile):\n os.unlink(outfile)\n with open(outfile, 'w') as fw:\n fw.writelines([\"%s\" % sqlQ for sqlQ in sql])\n print \"%2d - %s\" % (taskNum, outfile)\n else:\n print \"%2d > No SQL (%s)\" % (\n taskNum, os.path.basename(outfile))\n sql = []\n outfile = ''\n taskNum = -1\n else:\n #Acquire SQL code and filename\n m = startSqlRE.match(line)\n if m:\n #Start assembling the SQL query.\n tnum, sqlQ, lf = m.groups()\n assert int(tnum) == taskNum\n sql = [sqlQ.replace('\"\"', '\"')\n + ('\\n' if lf is not None else '')]\n continue\n m = nextSqlRE.match(line)\n if m:\n #Continue assembling the SQL query\n tnum, sqlQ, lf = m.groups()\n assert int(tnum) == taskNum\n sql.append(sqlQ.replace('\"\"', '\"')\n + ('\\n' if lf is not None else ''))\n continue\n m = descripRE.match(line)\n if m:\n # Get a SQL output filename from the task's\n # description. This always appears near the top of the\n # task's definition.\n tnum, outfile = m.groups()\n assert int(tnum) == taskNum\n outfile = invalidCharsRE.sub('_', outfile)\n outfile = \"%s%s.sql\" % (outfolder, outfile)\n continue\n m = filenameRE.match(line)\n if m:\n # Get a SQL output filename from the task's output\n # filename. This always appears near the bottom of the\n # task's definition, so we overwrite the description if\n # one was found earlier.\n tnum, outfile = m.groups()\n assert int(tnum) == taskNum\n outfile = os.path.basename(outfile)\n outfile = outExtRE.sub('', outfile)\n outfile = \"%s%s.sql\" % (outfolder, outfile)\n continue\n print 'Done.'\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
240,721
<p>Has anyone used jQuery to populate an autocomplete list on a textbox using ASP.NET webforms? If so, can anyone recommend a good method? From my reading so far, it seems like most people are using delimited lists rather than JSON to bring the items back. I'm open to any ideas that will get me up and running rather quickly. </p>
[ { "answer_id": 240882, "author": "Pablo", "author_id": 22696, "author_profile": "https://Stackoverflow.com/users/22696", "pm_score": 2, "selected": true, "text": "<BR/> > $(\"#input_box\").autocomplete(\"my_autocomplete_backend.php\");\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
240,725
<p>I have OS X 10.5 set up with the precompiled versions of PHP 5 and Apache 2. I'm trying to set up the Zend Debugger, but with no luck. Here's what I did:</p> <ul> <li>I downloaded <code>ZendDebugger-5.2.14-darwin8.6-uni.tar</code></li> <li>I created the directory <code>/Developer/Extras/PHP</code> and set the permissions to: <ul> <li>Permissions: <code>drwxrwxr-x</code></li> <li>Owner: <code>root:admin</code></li> </ul></li> <li>I copied <code>ZendDebugger.so</code> from the <code>5_2_x_comp</code> directory to <code>/Developer/Extras/PHP</code></li> <li><p>I updated <code>/etc/php.ini</code> file, adding the following lines:</p> <pre><code>zend_extension=/Developer/Extras/PHP/ZendDebugger.so zend_debugger.expose_remotely=always zend_debugger.connector_port=10013 zend_debugger.allow_hosts=127.0.0.1 </code></pre></li> <li><p>I restarted Apache via the System Preferences "Sharing" panel</p></li> </ul> <p>When I run <code>phpinfo()</code> within a PHP file, I get no mention of the Zend Debugger. When I run <code>php -m</code> from the command line, it shows the Zend Debugger is loaded. Both state that they're running the same version of PHP, and loading the same INI file.</p> <p>Anyone have another suggestion for me to try?</p>
[ { "answer_id": 270352, "author": "inxilpro", "author_id": 12549, "author_profile": "https://Stackoverflow.com/users/12549", "pm_score": 1, "selected": false, "text": "do shell script \"apachectl stop\" with administrator privileges\ndo shell script \"arch -i386 /usr/sbin/httpd\" with administrator privileges\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12549/" ]
240,755
<p>I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:</p> <pre><code>double i=1; double sinSoFar = 0; int term = 1; while(i &gt;= .000001) { i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1); sinSoFar=sinSoFar + i; term++; } </code></pre>
[ { "answer_id": 240859, "author": "Luiz Fernando Penkal", "author_id": 4355, "author_profile": "https://Stackoverflow.com/users/4355", "pm_score": 4, "selected": true, "text": "public static long factorial(long n) {\n if (n < 0) throw new RuntimeException(\"Underflow error in factorial\");\n else if (n > 20) throw new RuntimeException(\"Overflow error in factorial\");\n else if (n == 0) return 1;\n else return n * factorial(n-1);\n} \n" }, { "answer_id": 241006, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "// First, normalize argument angle (ang) to -PI to PI, \n// by adding/subtracting 2*PI until it's within range\nif ( ang > 1/2PI ) {\n sin = sin ( PI - ang );\n}\nelse if ( ang < 0 ) {\n sin = -1 * sin( -1 * ang );\n}\nelse {\n // your original code\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31665/" ]
240,764
<p>I have seen some websites use the following tag:</p> <pre><code>&lt;meta type="title" content="Title of the page" /&gt; </code></pre> <p>Is it needed when you have a <code>&lt;title&gt;</code>?</p> <p>Also, what's the best formatting for a page title? Some ideas:</p> <ul> <li>Page Description :: Company Name</li> <li>Page Description - Company Name</li> <li>Page Description &lt;> Company Name</li> <li>Company Name: Page Description</li> <li>...</li> </ul> <p>Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page? </p>
[ { "answer_id": 240867, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "<title>" }, { "answer_id": 404992, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 3, "selected": true, "text": "<meta type=\"title\"> <title> <title>\n Page Description - Company Name\n</title>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
240,765
<p>I've got a lot of similar oracle jobs I need to create, and I'd like to do it programatically. </p> <p>Where does the Oracle store the job library (schema/table)?</p> <p>(yes, I know I might be running with scissors)</p>
[ { "answer_id": 240943, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 4, "selected": true, "text": "dbms_job.submit(\nJOB OUT BINARY_INTEGER,\nWHAT IN VARCHAR2,\nNEXT_DATE IN DATE DEFAULT SYSDATE,\nINTERVAL IN VARCHAR2 DEFAULT 'NULL',\nNO_PARSE IN BOOLEAN DEFAULT FALSE,\nINSTANCE IN BINARY_INTEGER DEFAULT 0,\nFORCE IN BOOLEAN DEFAULT FALSE);\n dbms_scheduler.create_job(\njob_name IN VARCHAR2,\njob_type IN VARCHAR2,\njob_action IN VARCHAR2,\nnumber_of_arguments IN PLS_INTEGER DEFAULT 0,\nstart_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,\nrepeat_interval IN VARCHAR2 DEFAULT NULL,\nend_date IN TIMESTAMP WITH TIME ZONE DEFAULT NULL,\njob_class IN VARCHAR2 DEFAULT 'DEFAULT_JOB_CLASS',\nenabled IN BOOLEAN DEFAULT FALSE,\nauto_drop IN BOOLEAN DEFAULT TRUE,\ncomments IN VARCHAR2 DEFAULT NULL);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
240,774
<p>I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.</p> <p>I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).</p> <p>The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine.</p> <p>Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do).</p> <p>The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable.</p> <p>What should I do? I'm under the impression that "I'm doing it wrong"...</p> <p>Thanks,</p> <p>Guillaume.</p> <p>Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).</p>
[ { "answer_id": 240806, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "public Object clone() throws CloneNotSupportedException {\n return super.clone();\n}\n" }, { "answer_id": 240895, "author": "Sean Reilly", "author_id": 8313, "author_profile": "https://Stackoverflow.com/users/8313", "pm_score": 4, "selected": true, "text": "public interface Modifiable<T extends Modifiable<T>> extends Cloneable {\n T clone();\n}\n\npublic class Foo implements Modifiable<Foo> {\n public Foo clone() { //this is required\n return null; //todo: real work\n }\n}\n" }, { "answer_id": 388318, "author": "Hosam Aly", "author_id": 41283, "author_profile": "https://Stackoverflow.com/users/41283", "pm_score": 1, "selected": false, "text": "public interface Modifiable<T extends Modifiable<T>> extends Cloneable {\n T clone();\n}\npublic class Test implements Modifiable<Test> {\n @Override\n public Test clone() {\n System.out.println(\"clone\");\n return null;\n }\n public static void main(String[] args) {\n Test t = new Test().clone();\n }\n}\n" }, { "answer_id": 861381, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private LinkedList names = new LinkedList();\n\n\npublic CloningExample() {\n names.add(\"Alex\");\n names.add(\"Melody\");\n names.add(\"Jeff\");\n}\n\n\npublic String toString() {\n StringBuffer sb = new StringBuffer();\n Iterator i = names.iterator();\n while (i.hasNext()) {\n sb.append(\"\\n\\t\" + i.next());\n }\n return sb.toString();\n}\n\n\npublic Object clone() {\n try {\n return super.clone();\n } catch (CloneNotSupportedException e) {\n throw new Error(\"This should not occur since we implement Cloneable\");\n }\n}\n\n\npublic Object deepClone() {\n try {\n CloningExample copy = (CloningExample)super.clone();\n copy.names = (LinkedList)names.clone();\n return copy;\n } catch (CloneNotSupportedException e) {\n throw new Error(\"This should not occur since we implement Cloneable\");\n }\n}\n\npublic boolean equals(Object obj) {\n\n /* is obj reference this object being compared */\n if (obj == this) {\n return true;\n }\n\n /* is obj reference null */\n if (obj == null) {\n return false;\n }\n\n /* Make sure references are of same type */\n if (!(this.getClass() == obj.getClass())) {\n return false;\n } else {\n CloningExample tmp = (CloningExample)obj;\n if (this.names == tmp.names) {\n return true;\n } else {\n return false;\n }\n }\n\n}\n\n\npublic static void main(String[] args) {\n\n CloningExample ce1 = new CloningExample();\n System.out.println(\"\\nCloningExample[1]\\n\" + \n \"-----------------\" + ce1);\n\n CloningExample ce2 = (CloningExample)ce1.clone();\n System.out.println(\"\\nCloningExample[2]\\n\" +\n \"-----------------\" + ce2);\n\n System.out.println(\"\\nCompare Shallow Copy\\n\" +\n \"--------------------\\n\" +\n \" ce1 == ce2 : \" + (ce1 == ce2) + \"\\n\" +\n \" ce1.equals(ce2) : \" + ce1.equals(ce2));\n\n CloningExample ce3 = (CloningExample)ce1.deepClone();\n System.out.println(\"\\nCompare Deep Copy\\n\" +\n \"--------------------\\n\" +\n \" ce1 == ce3 : \" + (ce1 == ce3) + \"\\n\" +\n \" ce1.equals(ce3) : \" + ce1.equals(ce3));\n\n System.out.println();\n\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10687/" ]
240,777
<p>I've got a series of GIFs that I need to crop on the fly, I'm using a HTTP Handler in C# so I can better encapsulate the code - provide caching for the result etc.</p> <p>Currently, when I draw the existing image to a new <code>Image</code> via the <code>Graphics</code> object all the transparency is lost.</p> <p>I've tried various techniques to try and maintain the transparency, but to no avail.</p> <p>Things I've tried:</p> <ul> <li>Using the <code>MakeTransparent (Color)</code> method call</li> <li>Using the <code>ImageAttriutes</code> with a combination of <code>ColorMap</code> and <code>SetColorKey</code></li> </ul> <p>I don't really want to start using unsafe operators or Win32 calls.</p> <p>Any ideas?</p>
[ { "answer_id": 240939, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 0, "selected": false, "text": "Bitmap System.Drawing.Image SourceImage = System.Drawing.Image.FromFile(\"the.gif\");\nSystem.Drawing.Bitmap NewImage = new System.Drawing.Bitmap(SourceImage);\n// Do Processing\nNewImage.MakeTransparent();\n// Store changes\nNewImage.Save(..., System.Drawing.Imaging.ImageFormat.Png);\n Graphics" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]
240,778
<p>I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.</p> <p>If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred.</p> <p>Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.</p>
[ { "answer_id": 240790, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": true, "text": "u v p = A + (u * AB) + (v * AD)\n AB AD (a,b,c,d) a+b+c+d=1 P P = a A + b B + c C + d D\n u+v=1" }, { "answer_id": 240793, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "// public-domain code by Darel Rex Finley, 2007\n\nint nodes, nodeX[MAX_POLY_CORNERS], pixelX, pixelY, i, j, swap ;\n\n// Loop through the rows of the image.\nfor (pixelY=IMAGE_TOP; pixelY<IMAGE_BOT; pixelY++) {\n\n // Build a list of nodes.\n nodes=0; j=polyCorners-1;\n for (i=0; i<polyCorners; i++) {\n if (polyY[i]<(double) pixelY && polyY[j]>=(double) pixelY\n || polyY[j]<(double) pixelY && polyY[i]>=(double) pixelY) {\n nodeX[nodes++]=(int) (polyX[i]+(pixelY-polyY[i])/(polyY[j]-polyY[i])\n *(polyX[j]-polyX[i])); }\n j=i; }\n\n // Sort the nodes, via a simple “Bubble” sort.\n i=0;\n while (i<nodes-1) {\n if (nodeX[i]>nodeX[i+1]) {\n swap=nodeX[i]; nodeX[i]=nodeX[i+1]; nodeX[i+1]=swap; if (i) i--; }\n else {\n i++; }}\n\n // Fill the pixels between node pairs.\n // Code modified by SoloBold 27 Oct 2008\n // The flagPixel method below will flag a pixel as a possible choice.\n for (i=0; i<nodes; i+=2) {\n if (nodeX[i ]>=IMAGE_RIGHT) break;\n if (nodeX[i+1]> IMAGE_LEFT ) {\n if (nodeX[i ]< IMAGE_LEFT ) nodeX[i ]=IMAGE_LEFT ;\n if (nodeX[i+1]> IMAGE_RIGHT) nodeX[i+1]=IMAGE_RIGHT;\n for (j=nodeX[i]; j<nodeX[i+1]; j++) flagPixel(j,pixelY); }}}\n\n // TODO pick a flagged pixel randomly and fill it, then remove it from the list.\n // Repeat until no flagged pixels remain.\n" }, { "answer_id": 240896, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": ".BBBB.\nA C\nA C\n.DDDD.\n void GetRandomPoint(Polygon p, ref float x, ref float y) {\n\n float xrand = random();\n float yrand = random();\n\n float h0 = p.Vertices[0] + xrand * p.Vertices[1];\n float h1 = p.Vertices[2] + yrand * p.Vertices[3];\n\n float v0 = p.Vertices[0] + xrand * p.Vertices[2];\n float v1 = p.Vertices[1] + yrand * p.Vertices[3];\n\n GetLineIntersection(h0, h1, v0, v1, x, y);\n\n}\n" }, { "answer_id": 5648991, "author": "rapto", "author_id": 20545, "author_profile": "https://Stackoverflow.com/users/20545", "pm_score": 0, "selected": false, "text": "CREATE or replace FUNCTION random_point(geometry)\nRETURNS geometry\nAS $$\nDECLARE \n env geometry;\n corner1 geometry;\n corner2 geometry;\n minx real;\n miny real;\n maxx real;\n maxy real;\n x real;\n y real;\n ret geometry;\nbegin\n\nselect ST_Envelope($1) into env;\nselect ST_PointN(ST_ExteriorRing(env),1) into corner1;\nselect ST_PointN(ST_ExteriorRing(env),3) into corner2;\nselect st_x(corner1) into minx;\nselect st_x(corner2) into maxx;\nselect st_y(corner1) into miny;\nselect st_y(corner2) into maxy;\nloop\n select minx+random()*(maxx-minx) into x;\n select miny+random()*(maxy-miny) into y;\n select ST_SetSRID(st_point(x,y), st_srid($1)) into ret;\n if ST_Contains($1,ret) then\n return ret ;\n end if;\nend loop;\nend;\n$$\nLANGUAGE plpgsql\nvolatile\nRETURNS NULL ON NULL INPUT;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815/" ]
240,788
<p>Can I call a stored procedure in Oracle via a database link?</p> <p>The database link is functional so that syntax such as...</p> <pre><code>SELECT * FROM myTable@myRemoteDB </code></pre> <p>is functioning. But is there a syntax for...</p> <pre><code>EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB </code></pre>
[ { "answer_id": 240798, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 7, "selected": true, "text": "EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );\n" }, { "answer_id": 9313996, "author": "tptp", "author_id": 1214182, "author_profile": "https://Stackoverflow.com/users/1214182", "pm_score": 1, "selected": false, "text": "cmd.CommandText = \"BEGIN foo@v; END;\" \n" }, { "answer_id": 66373810, "author": "george fortech", "author_id": 11062891, "author_profile": "https://Stackoverflow.com/users/11062891", "pm_score": 0, "selected": false, "text": "exec utl_mail.send@myotherdb(\n sender => 'myfromemail@giggle.com',recipients => 'mytoemail@giggle.com, \n cc => null, subject => 'my subject', message => 'my message'\n); \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
240,836
<p>I'm currently working on a project where a section of the code looks like this:</p> <pre><code>Select Case oReader.Name Case &quot;NameExample1&quot; Me.Elements.NameExample1.Value = oReader.ReadString ' ... Case &quot;NameExampleN&quot; Me.Elements.NameExampleN.Value = oReader.ReadString ' ... End Select </code></pre> <p>It continues on for a while. The code is obviously verbose and it <em>feels</em> like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:</p> <pre><code>Dim sReadString As String = oReader.ReadString Me.Elements.InvokeProperty(sReadString).Value = sReadString </code></pre>
[ { "answer_id": 241143, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "Dictionary<string, PropertyInfo> GetProperty" }, { "answer_id": 15602458, "author": "Jet", "author_id": 1906044, "author_profile": "https://Stackoverflow.com/users/1906044", "pm_score": 4, "selected": false, "text": "CallByName(yourClassOrObjectName,\"NameExample1\",CallType.Set,oReader.ReadString)\n CallType.Get" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20/" ]
240,850
<p>I am having an issue when using <code>LoadControl( type, Params )</code>. Let me explain...</p> <p>I have a super simple user control (ascx)</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="True" Inherits="ErrorDisplay" Codebehind="ErrorDisplay.ascx.cs" EnableViewState="false" %&gt; &lt;asp:Label runat="server" ID="lblTitle" /&gt; &lt;asp:Label runat="server" ID="lblDescription" /&gt; </code></pre> <p>with code ( c# ) behind of:</p> <pre><code>public partial class ErrorDisplay : System.Web.UI.UserControl { private Message _ErrorMessage; public ErrorDisplay() { } public ErrorDisplay(Message ErrorMessage) { _ErrorMessage = ErrorMessage; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (_ErrorMessage != null) { lblTitle.Text = _ErrorMessage.Message; lblDescription.Text = _ErrorMessage.Description; } } } </code></pre> <p>Elsewhere in my web application I am adding an instance of the usercontrol to the page using the following code:</p> <pre><code>divValidationIssues.Controls.Add(LoadControl(typeof(ErrorDisplay), new object[] { MessageDetails })); </code></pre> <p>I am using the overloaded version of LoadControl because I want to pass the Message parameter to the constructor. All this <em>appears</em> to work ok.</p> <p>However, when the <code>OnPreRender()</code> is fired on the ErrorDisplay usercontrol the lblTitle and lblDescription variables are both <code>null</code>, despite them having a markup equivalent. The message variable has been correctly populated.</p> <p>Can anyone shed any light on why this may be happening?</p> <p>Thanks</p> <p><strong>EDIT:</strong></p> <p>Just for clarity I'll also add that the code which is programatically adding the usercontrol to the page is running in response to a button press, so the 'hosting page' has progressed through Init, Page_Load and is now processing the event handlers.</p> <p>I cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event.</p>
[ { "answer_id": 240998, "author": "Ash", "author_id": 31128, "author_profile": "https://Stackoverflow.com/users/31128", "pm_score": 6, "selected": true, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (_ErrorMessage != null)\n {\n lblTitle.Text = _ErrorMessage.Message;\n lblDescription.Text = _ErrorMessage.Description;\n }\n}\n LoadControl( type, params ) LoadControl( \"ascx path\" ) Control ErrorCntrl = LoadControl(\"ErrorDisplay.ascx\");\nErrorCntrl.ID = SomeID;\n(ErrorCntrl as ErrorDisplay).SetErrorMessage = MessageDetail;\ndivErrorContainer.Controls.Add(ErrorCntrl);\n" }, { "answer_id": 20220236, "author": "bflemi3", "author_id": 547071, "author_profile": "https://Stackoverflow.com/users/547071", "pm_score": 0, "selected": false, "text": "LoadControl LoadControl(Type, object[])" }, { "answer_id": 23184186, "author": "WebKing", "author_id": 3554213, "author_profile": "https://Stackoverflow.com/users/3554213", "pm_score": 0, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n\nEnd Sub\n\nPublic Sub Add(txt As String)\n Dim li As New ListItem(txt, txt)\n lstDay.Items.Add(li)\nEnd Sub\n Private Sub Calendar1_DayRender(sender As Object, e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender\n Dim div As CPCalendarCell = LoadControl(\"~/UserControls/CPCalendarCell.ascx\")\n div.ID = \"dv_\" & e.Day.Date.ToShortDateString.Replace(\" \", \"_\")\n\n **e.Cell.Controls.Add(div)**\n\n div.Add(e.Day.Date.Month.ToString & \"/\" & e.Day.Date.Day.ToString)\n div.Add(\"Item 1\")\n div.Add(\"Item 2\")\n e.Cell.Style.Add(\"background-color\", IIf(e.Day.IsWeekend, \"whitesmoke\", \"white\").ToString)\nEnd Sub\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
240,863
<p>So in a .NET app , i got about 2 million items that i need to hold them in memory for processing , 1 by 1, would holding these items in a Stack collection , is better than holding them in a List collection, assuming that the memory used by the stack object will be keep minimizing every time an item is poped out of the stack object , or the memory allocated by the stack will keep the same till the stack is set to null, or cleared.</p> <p>sorry if i couldn't express the question in the right way.. but here is another way, when a Stack collection is used, does the memory used by the stack get minimized every time an item is pulled out of the stack.</p> <p>Thanks in advance</p>
[ { "answer_id": 240870, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "Stack<T> List<T> Queue<T> List<T> List<T> Stack<T>" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20006/" ]
240,874
<p>When you have a derived class, is there an simpler way to refer to a variable from a method other than:</p> <pre><code>BaseClass::variable </code></pre> <p><strong>EDIT</strong> <br>As it so happens, I found a page that explained this issue using functions instead: <a href="http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19" rel="nofollow noreferrer">Template-Derived-Classes Errors</a>. Apparently it makes a difference when using templates classes.</p>
[ { "answer_id": 240881, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 4, "selected": true, "text": "\nclass Base\n{\nprotected:\n int a;\n\nprivate:\n int b;\n};\n\nclass Derived : public Base\n{\n void foo()\n {\n a = 5; // works\n b = 10; // error!\n }\n};\n \nclass Base\n{\npublic:\n int a;\n};\n\nclass Derived : public Base\n{\npublic:\n int a;\n};\n a Base Derived" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73/" ]
240,876
<p>I have this code</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(int argc,char **argv) { unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995LL; unsigned long long num2 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996LL; unsigned long long num3 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997LL; unsigned long long num4 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998LL; unsigned long long num5 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999LL; cout &lt;&lt; (unsigned long long)(num1 * num2 * num3 * num4 * num5) &lt;&lt; endl; return 0; } </code></pre> <p>As you can see the numbers are enormous, but when I do the math there I get this: 18446744073709551496</p> <p>At compile time I get these warnings:</p> <pre><code>warning: integer constant is too large for its type| In function `int main(int, char**)':| warning: this decimal constant is unsigned only in ISO C90| ... </code></pre>
[ { "answer_id": 241116, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "stringToBigUnsigned BigIntegerUtils.hh #include \"BigUnsigned.hh\"\n#include \"BigIntegerUtils.hh\" \n\n BigUnsigned num1 = stringToBigUnsigned (\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999999999999999999999999999999999999999999999999\"\n \"99999999999999999999999999999999999995\"\n );\n" }, { "answer_id": 12458092, "author": "Anshul garg", "author_id": 692846, "author_profile": "https://Stackoverflow.com/users/692846", "pm_score": 0, "selected": false, "text": "unsigned long long #include <cmath>\n#include <iostream>\nusing namespace std;\nint main()\n{\n unsigned int nd, nz; \n unsigned char *ca; \n unsigned int j, n=50, q, temp;\n int i;\n double p;\n p = 0.0;\n for(j = 2; j <= n; j++)\n {\n p += log10((double)j); \n }\n nd = (int)p + 1;\n\n ca = new unsigned char[nd+1];\n if (!ca)\n {\n cout << \"Could not allocate memory!!!\";\n exit(0);\n }\n for (i = 1; (unsigned)i < nd; i++)\n {\n ca[i] = 0;\n }\n ca[0] = 1;\n\n p = 0.0;\n for (j = 2; j <= n; j++)\n {\n p += log10((double)j); \n nz = (int)p + 1; \n q = 0; \n for (i = 0;(unsigned) i <= nz; i++)\n {\n temp = (ca[i] * j) + q;\n q = (temp / 10);\n ca[i] = (char)(temp % 10);\n }\n }\n\n cout << \"\\nThe Factorial of \" << n << \" is: \";\n for( i = nd - 1; i >= 0; i--)\n {\n cout << (int)ca[i];\n }\n // delete []ca; \n return 0;\n}\n" }, { "answer_id": 59005646, "author": "jav", "author_id": 972910, "author_profile": "https://Stackoverflow.com/users/972910", "pm_score": 0, "selected": false, "text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\nint main()\n{\n using namespace boost::multiprecision;\n// Repeat at arbitrary precision:\n cpp_int u = 1;\n for(unsigned i = 1; i <= 100; ++i)\n u *= i;\n\n // prints 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 (i.e. 100!)\n std::cout << u << std::endl;\n\n return 0;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8715/" ]
240,887
<p>I'm getting a whole bunch of linker errors in Visual studios for methods I'm not even calling directly. I'm a java developer by day, but I have a project I need to do in C++, intended to run on windows machines. Hence, I'm stuck messing about with Visual Studio.</p> <p>Bascally, I have an os project that I added an accessor method to. I compiled that project as a .lib file (compiles and links fine). </p> <p>I then have my own project that uses that lib. I've included the library under Project->Properties -> Linker -> Input, and set the appropriate directory in the General -> Additional Lib Directories. I've included the header in the appropriate file, and I'm simply calling the constructor of one of the classes...not even calling the method that I created yet.</p> <p>The code compiles, but I get the following mountain of linker errors -- mostly LNK2019 and LNK2001 errors. I've tried recompiling under different settings (lib, exe, etc.), and the linker errors only seem to multiply. When I switch back to the previous settings, the number of errors remain at their peak. Any ideas how to fix this?</p> <p>Build Log</p> <blockquote> <p>Build started: Project: SpamCapture, Configuration: Debug|Win32</p> </blockquote> <p>Command Lines:</p> <blockquote> <p>Creating temporary file "c:\SpamCapture\SpamCapture\SpamCapture\Debug\RSP0000103081740.rsp" with contents [ /VERBOSE:LIB /OUT:"C:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.exe" /INCREMENTAL /LIBPATH:"C:\SpamCapture\Config\Debug\" /MANIFEST /MANIFESTFILE:"Debug\SpamCapture.exe.intermediate.manifest" /NODEFAULTLIB:"libcmtd.lib" /NODEFAULTLIB:"nafxcwd.lib" /DEBUG /PDB:"c:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86 KeyCapture_Config.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib</p> <p>".\Debug\Interaction.obj"</p> <p>".\Debug\InteractionSet.obj"</p> <p>".\Debug\LogReader.obj"</p> <p>".\Debug\SpamCapture.obj"</p> <p>".\Debug\stdafx.obj"</p> <p>".\Debug\SpamCapture.res"</p> <p>".\Debug\SpamCapture.exe.embed.manifest.res" ] Creating command line "link.exe @c:\SpamCapture\SpamCapture\SpamCapture\Debug\RSP0000103081740.rsp /NOLOGO /ERRORREPORT:PROMPT"</p> </blockquote> <p>Output Window:</p> <blockquote> <p>Linking... LINK : warning LNK4067: ambiguous entry point; selected 'mainCRTStartup' Searching libraries Searching C:\SpamCapture\Config\Debug\KeyCapture_Config.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\MSVCRTD.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\OLDNAMES.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfc80ud.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfcs80ud.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\msimg32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comctl32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shlwapi.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\atlsd.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\wininet.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ws2_32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\mswsock.lib: Searching C:\SpamCapture\Config\Debug\KeyCapture_Config.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\MSVCRTD.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\OLDNAMES.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfc80ud.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfcs80ud.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\msimg32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comctl32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shlwapi.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\atlsd.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\wininet.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ws2_32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\mswsock.lib: Searching C:\SpamCapture\Config\Debug\KeyCapture_Config.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib: Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib: Finished searching libraries</p> </blockquote> <p>Linker Errors start here:</p> <blockquote> <p>KeyCapture_Config.lib(KeyCapture_ConfigDlg.obj) : error LNK2001: unresolved external symbol "public: virtual int __thiscall CWnd::Create(char const *,char const *,unsigned long,struct tagRECT const &amp;,class CWnd *,unsigned int,struct CCreateContext *)" (?Create@CWnd@@UAEHPBD0KABUtagRECT@@PAV1@IPAUCCreateContext@@@Z)</p> </blockquote> <p>... a bunch more like this</p> <blockquote> <p>KeyCapture_Config.lib(KeyCapture_ConfigDlg.obj) : error LNK2019: unresolved external symbol "public: struct HICON__ * <strong>thiscall CWinApp::LoadIconA(unsigned int)const " (?LoadIconA@CWinApp@@QBEPAUHICON</strong>@@I@Z) referenced in function "public: __thiscall CKeyCapture_ConfigDlg::CKeyCapture_ConfigDlg(class CWnd *)" (??0CKeyCapture_ConfigDlg@@QAE@PAVCWnd@@@Z)</p> </blockquote> <p>...a bunch more like this</p> <blockquote> <p>(?DoDataExchange@SetupDialog@@MAEXPAVCDataExchange@@@Z) C:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.exe : fatal error LNK1120: 34 unresolved externals</p> </blockquote> <p>Results:</p> <blockquote> <p>Build log was saved at "file://c:\SpamCapture\SpamCapture\SpamCapture\Debug\BuildLog.htm" SpamCapture - 44 error(s), 1 warning(s)</p> </blockquote>
[ { "answer_id": 241047, "author": "Rodney Schuler", "author_id": 6188, "author_profile": "https://Stackoverflow.com/users/6188", "pm_score": 0, "selected": false, "text": "#pragma comment(lib, \"nafxcwd.lib\")\n" }, { "answer_id": 241137, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": true, "text": "KeyCapture_Config.lib CWnd CWinApp /SUBSYSTEM:CONSOLE KeyCapture.lib" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13825/" ]
240,903
<p>I'm looking for a library that can deal with RDF and OWL data.</p> <p>So far I have found:</p> <ul> <li><a href="http://razor.occams.info/code/semweb/" rel="nofollow noreferrer">semweb</a> (no owl support for all I know)</li> <li><a href="http://rowlex.nc3a.nato.int/HowToUse.aspx" rel="nofollow noreferrer">rowlex</a> (more of a 'browser' application)</li> </ul> <p>Your recommendations:</p> <ul> <li><a href="https://code.google.com/p/linqtordf/" rel="nofollow noreferrer">LinqToRdf</a> (very interesting, thanks mark!)</li> </ul>
[ { "answer_id": 545739, "author": "Mr. Lame", "author_id": 24451, "author_profile": "https://Stackoverflow.com/users/24451", "pm_score": 5, "selected": true, "text": " RdfDocument rdfDoc = new RdfDocument();\n Car car = new Car(\"myCarUri\", rdfDoc);\n Vehicle vehicle = car; // implicit casting\n CompanyAsset companyAsset = car; // implicit casting \n vehicle.WheelCount = 4;\n companyAsset.MonetaryValue = 15000;\n Console.WriteLine(rdfDoc.ToN3());\n myCarUri typeOf Car \nmyCarUri WheelCount 4 \nmyCarUri MonetaryValue 15000\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
240,946
<p>I want my WPF ComboBox's ItemsSource property to be bound to MyListObject's MyList property. The problem is that when I update the MyList property in code, the WPF ComboBox is not reflecting the update. I am raising the PropertyChanged event after I perform the update, and I thought WPF was supposed to automatically respond by updating the UI. Am I missing something? </p> <p>Here's the CLR object:</p> <pre><code>Imports System.ComponentModel Public Class MyListObject Implements INotifyPropertyChanged Private _mylist As New List(Of String) Public Sub New() _mylist.Add("Joe") _mylist.Add("Steve") End Sub Public Property MyList() As List(Of String) Get Return _mylist End Get Set(ByVal value As List(Of String)) _mylist = value End Set End Property Public Sub AddName(ByVal name As String) _mylist.Add(name) NotifyPropertyChanged("MyList") End Sub Private Sub NotifyPropertyChanged(ByVal info As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info)) End Sub Public Event PropertyChanged(ByVal sender As Object, _ ByVal e As System.ComponentModel.PropertyChangedEventArgs) _ Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged End Class </code></pre> <p>Here is the XAML:</p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" xmlns:local="clr-namespace:WpfApplication1" &gt; &lt;Window.Resources&gt; &lt;ObjectDataProvider x:Key="MyListObject" ObjectType="{x:Type local:MyListObject}"/&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;ComboBox Height="23" Margin="24,91,53,0" Name="ComboBox1" VerticalAlignment="Top" ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}}" /&gt; &lt;TextBox Height="23" Margin="24,43,134,0" Name="TextBox1" VerticalAlignment="Top" /&gt; &lt;Button Height="23" HorizontalAlignment="Right" Margin="0,43,53,0" Name="btn_AddName" VerticalAlignment="Top" Width="75"&gt;Add&lt;/Button&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>And here's the simple code-behind:</p> <pre><code>Class Window1 Private obj As New MyListObject Private Sub btn_AddName_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) _ Handles btn_AddName.Click obj.AddName(TextBox1.Text) End Sub End Class </code></pre> <p>Thanks!</p>
[ { "answer_id": 240983, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 3, "selected": true, "text": "Private obj As New MyListObject\n" }, { "answer_id": 240991, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 0, "selected": false, "text": "Public Class MyListObject\n ...\n\n 'Private _mylist As New List(Of String)\n Private _mylist As New BindingList(Of String)\n\n ...\n\n 'Public Property MyList() As List(Of String)\n ' Get\n ' Return _mylist\n ' End Get\n ' Set(ByVal value As List(Of String))\n ' _mylist = value\n ' End Set\n 'End Property\n\n Public Property MyList() As BindingList(Of String)\n Get\n Return _mylist\n End Get\n Set(ByVal value As BindingList(Of String))\n _mylist = value\n End Set\n End Property\n\n ...\n\nEnd Class\n" }, { "answer_id": 241013, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "DirectCast(Me.FindResource(\"MyListObject\"), ObjectDataProvider).Source = _myList\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
240,948
<p>I'm working on a small app where I can generate a list of barcodes. I have the correct fonts installed on my computer. Right now I am printing them directly to a webpage and it works properly in Chrome and IE 7, but not Firefox. Does anyone know what Firefox would be doing differently than IE and Chrome?</p> <p>Here is my code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Barcode Font Test&lt;/title&gt; &lt;style type="text/css" media="screen"&gt; .barcode { font-family: "wasp 39 m", verdana, calibri; font-size: 36pt; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="barcode"&gt;*574656*&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>EDIT:</strong> I probably should have mentioned that this is more of a personal project at the moment and not meant to be released to the world. While I will take a solution that works, I would like something that does not involve Javascript/Flash/etc.</p>
[ { "answer_id": 241468, "author": "Doug L.", "author_id": 19179, "author_profile": "https://Stackoverflow.com/users/19179", "pm_score": 3, "selected": false, "text": "<IMG> <IMG> *574656* * 0 1 2 3 4 5 6 7 8 9 <html> \n <head> \n <title>Barcode Font Test</title> \n </head> \n <body> \n <img src=\"3o9cb_ast.png\" alt=\"*\"/> \n <img src=\"3o9cb_5.png\" alt=\"5\"/>\n <img src=\"3o9cb_7.png\" alt=\"7\"/>\n <img src=\"3o9cb_4.png\" alt=\"4\"/>\n <img src=\"3o9cb_6.png\" alt=\"6\"/>\n <img src=\"3o9cb_5.png\" alt=\"5\"/>\n <img src=\"3o9cb_6.png\" alt=\"6\"/>\n <img src=\"3o9cb_ast.png\" alt=\"*\"/>\n </body>\n</html>\n" }, { "answer_id": 61853068, "author": "broc.seib", "author_id": 516910, "author_profile": "https://Stackoverflow.com/users/516910", "pm_score": 2, "selected": false, "text": ".barcode39 {\n font-family: 'Libre Barcode 39 Extended Text', cursive;\n font-size: 40px;\n} <link href=\"https://fonts.googleapis.com/css2?family=Libre+Barcode+39+Extended+Text&display=swap\" rel=\"stylesheet\">\n\n<div class=\"barcode39\">\n *hello world*\n</div>" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444511/" ]
240,949
<p>I have a set of templates for emails that my app sends out. The templates have codes embedded in them that correspond to properties of my business object. </p> <p>Is there a more elegant way than calling </p> <pre><code>string.Replace("{!MyProperty!}", item.MyProperty.ToString()) </code></pre> <p>a zillion times? Maybe XMLTransform, regular expressions, or some other magic? I'm using C# 3.5 .</p>
[ { "answer_id": 240973, "author": "Wim", "author_id": 30874, "author_profile": "https://Stackoverflow.com/users/30874", "pm_score": 1, "selected": false, "text": "string.Replace foreach (string property in properties)\n{\n string.Replace(\"{!\"+property+\"!}\",ReflectionHelper.GetStringValue(item,property));\n}\n ReflectionHelper.GetStringValue" }, { "answer_id": 241170, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "public static string Translate(string pattern, object context)\n{\n return Regex.Replace(pattern, @\"\\{!(\\w+)!}\", match => {\n string tag = match.Groups[1].Value;\n if (context != null)\n {\n PropertyInfo prop = context.GetType().GetProperty(tag);\n if (prop != null)\n {\n object value = prop.GetValue(context);\n if (value != null)\n {\n return value.ToString();\n }\n }\n }\n return \"\";\n });\n}\n Translate(\"Hello {!User!}. Welcome to {!GroupName!}!\", new {\n User = \"John\",\n GroupName = \"The Community\"\n}); // -> \"Hello John. Welcome to The Community!\"\n" }, { "answer_id": 241433, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "var replacements = new Dictionary<string, object>() {\n { \"Property1\", obj.Property1 },\n { \"Property2\", obj.Property2 },\n { \"Property3\", obj.Property3 },\n { \"Property4\", obj.Property4 },\n}\n\nforeach (KeyValuePair<string, object> kvp in replacement) {\n body = Regex.Replace(body, kvp.Key, kvp.Value.ToString());\n}\n" }, { "answer_id": 53965013, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 0, "selected": false, "text": "//The guts of MailDefinition.CreateMailMessage\n//from https://github.com/Microsoft/referencesource/blob/master/System.Web/UI/WebControls/MailDefinition.cs\n\nif (replacements != null && !String.IsNullOrEmpty(body)) {\n foreach (object key in replacements.Keys) {\n string fromString = key as string;\nstring toString = replacements[key] as string;\n\n if ((fromString == null) || (toString == null)) {\n throw new ArgumentException(SR.GetString(SR.MailDefinition_InvalidReplacements));\n }\n // DevDiv 151177\n // According to http://msdn2.microsoft.com/en-us/library/ewy2t5e0.aspx, some special \n // constructs (starting with \"$\") are recognized in the replacement patterns. References of\n // these constructs will be replaced with predefined strings in the final output. To use the \n // character \"$\" as is in the replacement patterns, we need to replace all references of single \"$\"\n // with \"$$\", because \"$$\" in replacement patterns are replaced with a single \"$\" in the \n // final output. \n toString = toString.Replace(\"$\", \"$$\");\n body = Regex.Replace(body, fromString, toString, RegexOptions.IgnoreCase);\n }\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
241,003
<p>Is there some way to get a value from the last inserted row?</p> <p>I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.</p> <p>I am using Java with a JDBC and PostgreSQL.</p>
[ { "answer_id": 241016, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 3, "selected": false, "text": "currval(sequence)\n" }, { "answer_id": 241019, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 1, "selected": false, "text": "INSERT mytable(myid) VALUES (nextval('MySequence'));\n\nSELECT currval('MySequence');\n" }, { "answer_id": 241242, "author": "Luc M", "author_id": 14673, "author_profile": "https://Stackoverflow.com/users/14673", "pm_score": 7, "selected": true, "text": "INSERT INTO mytable( field_1, field_2,... )\nVALUES ( value_1, value_2 ) RETURNING anyfield\n ResultSet rs = statement.executeQuery(\"INSERT ... RETURNING ID\");\nrs.next();\nrs.getInt(1);\n" }, { "answer_id": 241377, "author": "Andrew Watt", "author_id": 31650, "author_profile": "https://Stackoverflow.com/users/31650", "pm_score": 5, "selected": false, "text": "executeUpdate() executeQuery() Statement.RETURN_GENERATED_KEYS getGeneratedKeys Statement stmt = conn.createStatement();\nstmt.execute(sql, Statement.RETURN_GENERATED_KEYS);\nResultSet keyset = stmt.getGeneratedKeys();\n" }, { "answer_id": 241573, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 4, "selected": false, "text": "Statement stmt = conn.createStatement();\n// Obtain the generated key that results from the query.\nstmt.executeUpdate(\"INSERT INTO authors \" +\n \"(first_name, last_name) \" +\n \"VALUES ('George', 'Orwell')\",\n Statement.RETURN_GENERATED_KEYS);\nResultSet rs = stmt.getGeneratedKeys();\nif ( rs.next() ) {\n // Retrieve the auto generated key(s).\n int key = rs.getInt(1);\n}\n" }, { "answer_id": 242966, "author": "eflles", "author_id": 26567, "author_profile": "https://Stackoverflow.com/users/26567", "pm_score": 3, "selected": false, "text": "Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.\nString sql = \"INSERT INTO \\\"TableName\\\"\" +\n \"(\\\"Column1\\\", \\\"Column2\\\",\\\"Column3\\\",\\\"Column4\\\")\" +\n \"VALUES ('value1',value2, 'value3', 'value4') RETURNING \n \\\"TableName\\\".\\\"TableId\\\"\";\nPreparedStatement prpState = conn.prepareStatement(sql);\nResultSet rs = prpState.executeQuery();\nif(rs.next()){\n System.out.println(rs.getInt(1));\n }\n" }, { "answer_id": 2953469, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 4, "selected": false, "text": "PreparedStatement#getGeneratedKeys() PreparedStatement statement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);\n" }, { "answer_id": 4623844, "author": "abdurrahim dagdelen", "author_id": 566630, "author_profile": "https://Stackoverflow.com/users/566630", "pm_score": 1, "selected": false, "text": "PreparedStatement stmt = getConnection(PROJECTDB + 2)\n .prepareStatement(\"INSERT INTO fonts (font_size) VALUES(?) RETURNING fonts.*\");\nstmt.setString(1, \"986\");\nResultSet res = stmt.executeQuery();\nwhile (res.next()) {\n System.out.println(\"Generated key: \" + res.getLong(1));\n System.out.println(\"Generated key: \" + res.getInt(2));\n System.out.println(\"Generated key: \" + res.getInt(3));\n}\nstmt.close();\n" }, { "answer_id": 5689400, "author": "emicklei", "author_id": 514308, "author_profile": "https://Stackoverflow.com/users/514308", "pm_score": 0, "selected": false, "text": "public interface ObjectiveMapper {\n\n@Select(\"insert into objectives\" +\n \" (code,title,description) values\" +\n \" (#{code}, #{title}, #{description}) returning id\")\nint insert(Objective anObjective);\n" }, { "answer_id": 6182585, "author": "fernando", "author_id": 549278, "author_profile": "https://Stackoverflow.com/users/549278", "pm_score": 0, "selected": false, "text": ",Statement.RETURN_GENERATED_KEYS);\"" }, { "answer_id": 11244794, "author": "danigonlinea", "author_id": 1196978, "author_profile": "https://Stackoverflow.com/users/1196978", "pm_score": 0, "selected": false, "text": "// Do your insert code\n\nmyDataBase.execSQL(\"INSERT INTO TABLE_NAME (FIELD_NAME1,FIELD_NAME2,...)VALUES (VALUE1,VALUE2,...)\");\n\n// Use the sqlite function \"last_insert_rowid\"\n\nCursor last_id_inserted = yourBD.rawQuery(\"SELECT last_insert_rowid()\", null);\n\n// Retrieve data from cursor.\n\nlast_id_inserted.moveToFirst(); // Don't forget that!\n\nultimo_id = last_id_inserted.getLong(0); // For Java, the result is returned on Long type (64)\n" }, { "answer_id": 16319938, "author": "Priyadharshani", "author_id": 2284850, "author_profile": "https://Stackoverflow.com/users/2284850", "pm_score": 2, "selected": false, "text": "Statement //MY_NUMBER is the column name in the database \nString generatedColumns[] = {\"MY_NUMBER\"};\nStatement stmt = conn.createStatement();\n\n//String sql holds the insert query\nstmt.executeUpdate(sql, generatedColumns);\n\nResultSet rs = stmt.getGeneratedKeys();\n\n// The generated id\n\nif(rs.next())\nlong key = rs.getLong(1);\n PreparedStatement String generatedColumns[] = {\"MY_NUMBER\"};\nPreparedStatement pstmt = conn.prepareStatement(sql,generatedColumns);\npstmt.setString(1, \"qwerty\");\n\npstmt.execute();\nResultSet rs = pstmt.getGeneratedKeys();\nif(rs.next())\nlong key = rs.getLong(1);\n" }, { "answer_id": 22832032, "author": "mihu86", "author_id": 1732450, "author_profile": "https://Stackoverflow.com/users/1732450", "pm_score": 0, "selected": false, "text": "SELECT lastval()" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
241,009
<p>In a Visual Basic project, I created a homemade TabControl in order to fix a visual bug. The control works properly, however whenever I modify the form using my tab, Visual Studio adds MyProject in front of the control in its declaration:</p> <pre><code>Me.tabMenu = New MyProject.MyClass 'Gives a BC30002 compile error </code></pre> <p>If I remove the <code>MyProject.</code>, the project compiles properly.</p> <p>MyClass is in a separate file MyClass.vb and looks mostly like this:</p> <pre><code>Public Class MyClass Inherits System.Windows.Forms.TabControl Public Sub New() InitializeComponent() MyBase.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed End Sub Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs) //OnDrawItem code End Sub Private Sub My_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles Me.DrawItem //My_DrawItem code End Sub End Class </code></pre> <p>I tried removing the file and adding it again, copy and pasting the class inside <code>MyForm.designer.vb</code>, adding <code>MyProject.</code> to the class name, but nothing stopped Visual Studio from adding this so-hated <code>MyProject</code>.</p> <p><strong>Edit regarding <a href="https://stackoverflow.com/questions/241009/myprojectmyclass-vbnet-custom-controls#241077">this answer</a>:</strong></p> <p>I understand the thing about the namespace, however my problem is mostly that the compiler does not recognize the class with the project name appended but still adds it everytime.</p>
[ { "answer_id": 241077, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "MyProject" }, { "answer_id": 270041, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 1, "selected": false, "text": "Me.tabMenu = New Global.MyProject.MyClass\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25818/" ]
241,015
<p>I have a backup server that automatically backs up my live site, both files and database.</p> <p>On the live site, the text looks fine, but when you view the mirrored version of it, it displays '?' within some of the text. This text is stored within the news database table.</p> <p>Here is a screenshot of it being on the live server and of it on the mirrored server.</p> <p>What could happen within the process of backing it up to the mirrored server?</p> <p><img src="https://i.stack.imgur.com/ftKNy.jpg" alt="Alt text" /></p> <p>The live server is <a href="https://en.wikipedia.org/wiki/Solaris_%28operating_system%29" rel="nofollow noreferrer">Solaris</a>, and the mirrored server is Linux <a href="https://en.wikipedia.org/wiki/Red_Hat_Linux" rel="nofollow noreferrer">Red Hat Linux</a> 5.</p>
[ { "answer_id": 241030, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 6, "selected": true, "text": "SET NAMES 'utf8';\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" }, { "answer_id": 241037, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "&mdash; &ndash;" }, { "answer_id": 241099, "author": "Nick Van Brunt", "author_id": 30470, "author_profile": "https://Stackoverflow.com/users/30470", "pm_score": 0, "selected": false, "text": "// Replace with path to a file that needs cleaning\nPATH = \"test.html\"\n\nvar go = WScript.CreateObject(\"Scripting.FileSystemObject\");\nvar content = go.GetFile(PATH).OpenAsTextStream().ReadAll();\nvar out = go.CreateTextFile(\"clean-\"+PATH, true);\n\n// Symbols\ncontent = content.replace(/“/g, '\"');\ncontent = content.replace(/”/g, '\"');\ncontent = content.replace(/’/g, \"'\");\ncontent = content.replace(/–/g, \"-\");\ncontent = content.replace(/©/g, \"&copy;\");\ncontent = content.replace(/®/g, \"&reg;\");\ncontent = content.replace(/°/g, \"&deg;\");\ncontent = content.replace(/¶/g, \"<p>\");\ncontent = content.replace(/¿/g, \"&iquest;\");\ncontent = content.replace(/¡/g, '&iexcl;');\ncontent = content.replace(/¢/g, '&cent;');\ncontent = content.replace(/£/g, '&pound;');\ncontent = content.replace(/¥/g, '&yen;');\n\nout.Write(content);\n" }, { "answer_id": 10265960, "author": "Dave Burton", "author_id": 562862, "author_profile": "https://Stackoverflow.com/users/562862", "pm_score": 4, "selected": false, "text": "AddDefaultCharset UTF-8\n service httpd restart\n <meta http-equiv=Content-Type content=\"text/html; charset=windows-1252\">\n <span style=\"mso-spacerun: yes\">ááá </span>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
241,034
<p>I have a very simple Java RMI Server that looks like the following:</p> <pre><code> import java.rmi.*; import java.rmi.server.*; public class CalculatorImpl extends UnicastRemoteObject implements Calculator { private String mServerName; public CalculatorImpl(String serverName) throws RemoteException { super(); mServerName = serverName; } public int calculate(int op1, int op2) throws RemoteException { return op1 + op2; } public void exit() throws RemoteException { try{ Naming.unbind(mServerName); System.out.println("CalculatorServer exiting."); } catch(Exception e){} System.exit(1); } public static void main(String args[]) throws Exception { System.out.println("Initializing CalculatorServer."); String serverObjName = "rmi://localhost/Calculator"; Calculator calc = new CalculatorImpl(serverObjName); Naming.rebind(serverObjName, calc); System.out.println("CalculatorServer running."); } } </code></pre> <p>When I call the exit method, System.exit(1) throws the following exception:</p> <pre><code>CalculatorServer exiting. java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is: java.io.EOFException at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:203) at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126) at CalculatorImpl_Stub.exit(Unknown Source) at CalculatorClient.&lt;init&gt;(CalculatorClient.java:17) at CalculatorClient.main(CalculatorClient.java:29) Caused by: java.io.EOFException at java.io.DataInputStream.readByte(DataInputStream.java:243) at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189) ... 4 more [2]+ Exit 1 java CalculatorImpl </code></pre> <p>What am I doing wrong in this method?</p>
[ { "answer_id": 241214, "author": "Clayton", "author_id": 1449, "author_profile": "https://Stackoverflow.com/users/1449", "pm_score": 5, "selected": true, "text": "public void exit() throws RemoteException\n{\n try{\n // Unregister ourself\n Naming.unbind(mServerName);\n\n // Unexport; this will also remove us from the RMI runtime\n UnicastRemoteObject.unexportObject(this, true);\n\n System.out.println(\"CalculatorServer exiting.\");\n }\n catch(Exception e){}\n}\n" }, { "answer_id": 1315814, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 2, "selected": false, "text": "public void quit() throws RemoteException {\n System.out.println(\"quit\");\n Registry registry = LocateRegistry.getRegistry();\n try {\n registry.unbind(_SERVICENAME);\n UnicastRemoteObject.unexportObject(this, false);\n } catch (NotBoundException e) {\n throw new RemoteException(\"Could not unregister service, quiting anyway\", e);\n }\n\n new Thread() {\n @Override\n public void run() {\n System.out.print(\"Shutting down...\");\n try {\n sleep(2000);\n } catch (InterruptedException e) {\n // I don't care\n }\n System.out.println(\"done\");\n System.exit(0);\n }\n\n }.start();\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449/" ]
241,051
<p>I have nant set up to build my ASP.NET MVC project and it works fine locally. I add nant to a tools folder and add it to version control. TeamCity picks up my changes and starts the build but it fails.</p> <p>I believe I'm using the latest version of Nant and I have added the .net framework 3.5 to the nant.exe.config. What am I missing on the server and yes the .net framework is installed on the server as the asp.net mvc app does work if I manually build and deploy there? </p> <p>The build file is as follows: </p> <pre><code>&lt;target name="compile" description="Compiles using the AutomatedDebug Configuration"&gt; &lt;msbuild project="Tolt.Sims.sln" /&gt; &lt;/target&gt; </code></pre> <p></p> <p>Here is the error:</p> <pre> BUILD FAILED Failed to initialize the 'Microsoft .NET Framework 2.0' (net-2.0) target framework. Property evaluation failed. Expression: ${path::combine(sdkInstallRoot, 'bin')} ^^^^^^^^^^^^^^ Property 'sdkInstallRoot' has not been set. For more information regarding the cause of the build failure, run the build again in debug mode. Try 'nant -help' for more information </pre>
[ { "answer_id": 3153659, "author": "Matt Scully", "author_id": 380555, "author_profile": "https://Stackoverflow.com/users/380555", "pm_score": 2, "selected": false, "text": "<directory name=\"${path::combine(sdkInstallRoot, 'bin')}\"" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
241,083
<p>I used to have a class in 1.1 for the Datagrid that inherited from the DataGridColumn class. This allowed me to create a check box column with a client-side un/check-all box in the header. Then as I designed my grid I would just add my custom column.</p> <p>I am currently on a project where I need similar functionality for the grid view, however, there does not seem to be a way to inherit or add functionality to a column.</p> <p>So my question is, Is there a way to override a column? or Does this code already exist, in a reusable way?</p> <p>Needs are simple: I would like for it to just register the JavaScript on the page and render a column of check boxes.</p> <p>I have come across the 4guys sample already, but they have just put all the code into the code behind, I am looking for something a little less copy/paste.</p>
[ { "answer_id": 241617, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 0, "selected": false, "text": "<asp:DataGrid id=\"DG1\" runat = \"server\" DataKeyField = \"ID\">\n<Columns>\n<asp:TemplateColumn HeaderText=\"ProductName\">\n<ItemTemplate>\n<asp:CheckBox id=\"chkBox1\" runat=\"server\" \nText =<%# DataBinder.Eval(Container.DataItem,\"yourDataToBind\") %>\nchecked='<%# DataBinder.Eval(Container.DataItem,\"yourBoolToBind\") %>'>\n</asp:CheckBox>\n</ItemTemplate>\n</asp:TemplateColumn>\n</Columns>\n</asp:DataGrid>\n" }, { "answer_id": 243395, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 1, "selected": true, "text": "<%@ register tagprefix=\"CAC\" namespace=\"UI.Controls\" assembly=\"UI.Controls\" %> \n<asp:gridview id=\"grdPrint\" runat=\"server\" autogeneratecolumns=\"False\">\n <columns>\n <cac:checkallcolumn />\n <asp:boundfield datafield=\"CompanyName\" headertext=\"Company Name\" />\n </columns>\n</asp:gridview>\n Imports system.Web.UI\nImports system.Web.UI.WebControls\n\nPublic Class CheckAllColumn\n Inherits BoundField\n\n Public Sub New()\n MyBase.New()\n End Sub\n\n Public ReadOnly Property SelectedIndexes() As List(Of Int32)\n Get\n Dim selectedIndexList As New List(Of Int32)\n Dim grdParent As GridView = CType(Me.Control, GridView)\n For Each item As GridViewRow In grdParent.Rows\n Dim chkBox As CheckBox = CType(item.FindControl(\"checkboxCol\"), CheckBox)\n If ((Not (chkBox) Is Nothing) _\n AndAlso chkBox.Checked) Then\n selectedIndexList.Add(item.DataItemIndex)\n End If\n Next\n Return selectedIndexList\n End Get\n End Property\n\n Public ReadOnly Property SelectedDataKeys() As Object()\n Get\n Dim dataKeyList As ArrayList = New ArrayList\n Dim grdParent As GridView = CType(Me.Control, GridView)\n If (grdParent.DataKeys.Count > 0) Then\n For Each selectedIndex As Int32 In SelectedIndexes\n Dim DataKey As Object = grdParent.DataKeys(selectedIndex).ToString\n dataKeyList.Add(DataKey)\n Next\n End If\n Return CType(dataKeyList.ToArray(GetType(System.Object)), Object())\n End Get\n End Property\n\n Public Overrides Sub InitializeCell(ByVal cell As DataControlFieldCell, ByVal cellType As DataControlCellType, ByVal rowState As DataControlRowState, ByVal rowIndex As Integer)\n If cell Is Nothing Then\n Throw New ArgumentNullException(\"cell\", \"cell is null.\")\n End If\n MyBase.InitializeCell(cell, cellType, rowState, rowIndex)\n If (cellType = DataControlCellType.Header) OrElse (cellType = DataControlCellType.DataCell) Then\n Dim checkbox As CheckBox = New CheckBox\n If cellType = DataControlCellType.Header Then\n checkbox.ID = \"checkboxHead\"\n Else\n checkbox.ID = \"checkboxCol\"\n End If\n cell.Controls.Add(checkbox)\n End If\n End Sub\n\n Public Shared Sub RegisterClientCheckEvents(ByVal pg As Page, ByVal formID As String)\n If pg Is Nothing Then\n Throw New ArgumentNullException(\"pg\", \"pg is null.\")\n End If\n If formID Is Nothing OrElse formID.Length = 0 Then\n Throw New ArgumentException(\"formID is null or empty.\", \"formID\")\n End If\n Dim strCol As String = GetCheckColScript()\n Dim strHead As String = GetCheckHeadScript()\n If Not pg.ClientScript.IsClientScriptBlockRegistered(\"clientScriptCheckAll\") Then\n pg.ClientScript.RegisterClientScriptBlock(pg.GetType, \"clientScriptCheckAll\", strHead.Replace(\"[frmID]\", formID))\n End If\n If Not pg.ClientScript.IsClientScriptBlockRegistered(\"clientScriptCheckChanged\") Then\n pg.ClientScript.RegisterClientScriptBlock(pg.GetType, \"clientScriptCheckChanged\", strCol.Replace(\"[frmID]\", formID))\n End If\n RegisterAttributes(pg)\n End Sub\n\n Private Shared Sub RegisterAttributes(ByVal ctrl As Control)\n For Each wc As Control In ctrl.Controls\n If wc.HasControls Then\n RegisterAttributes(wc)\n End If\n If TypeOf (wc) Is CheckBox Then\n Dim chk As CheckBox = DirectCast(wc, CheckBox)\n If Not chk Is Nothing AndAlso chk.ID = \"checkboxCol\" Then\n chk.Attributes.Add(\"onclick\", \"CheckChanged()\")\n ElseIf Not chk Is Nothing AndAlso chk.ID = \"checkboxHead\" Then\n chk.Attributes.Add(\"onclick\", \"CheckAll(this)\")\n End If\n End If\n Next\n End Sub\n\n Private Shared Function GetCheckColScript() As String\n Dim strScript As String\n strScript = \" <script language=JavaScript>\"\n strScript &= \" function CheckAll( checkAllBox )\"\n strScript &= \" {\"\n strScript &= \" var frm = document.[frmID];\"\n strScript &= \" var ChkState=checkAllBox.checked;\"\n strScript &= \" for(i=0;i< frm.length;i++)\"\n strScript &= \" {\"\n strScript &= \" e=frm.elements[i];\"\n strScript &= \" if(e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1)\"\n strScript &= \" e.checked= ChkState ;\"\n strScript &= \" }\"\n strScript &= \" }\"\n strScript &= \" </script>\"\n Return strScript\n End Function\n\n Private Shared Function GetCheckHeadScript() As String\n Dim strScript As String\n strScript = \"<script language=JavaScript>\"\n strScript &= \"function CheckChanged()\"\n strScript &= \"{\"\n strScript &= \" var frm = document.[frmID];\"\n strScript &= \" var boolAllChecked;\"\n strScript &= \" boolAllChecked=true;\"\n strScript &= \" for(i=0;i< frm.length;i++)\"\n strScript &= \" {\"\n strScript &= \" e=frm.elements[i];\"\n strScript &= \" if ( e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1 )\"\n strScript &= \" if(e.checked== false)\"\n strScript &= \" {\"\n strScript &= \" boolAllChecked=false;\"\n strScript &= \" break;\"\n strScript &= \" }\"\n strScript &= \" }\"\n strScript &= \" for(i=0;i< frm.length;i++)\"\n strScript &= \" {\"\n strScript &= \" e=frm.elements[i];\"\n strScript &= \" if ( e.type=='checkbox' && e.name.indexOf('checkboxHead') != -1 )\"\n strScript &= \" {\"\n strScript &= \" if( boolAllChecked==false)\"\n strScript &= \" e.checked= false ;\"\n strScript &= \" else\"\n strScript &= \" e.checked= true;\"\n strScript &= \" break;\"\n strScript &= \" }\"\n strScript &= \" }\"\n strScript &= \" }\"\n strScript &= \" </script>\"\n Return strScript\n End Function\nEnd Class\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30492/" ]
241,086
<p>I am setting up an Oracle connection for NHibernate for the first time. I have copied the Oracle.DataAccess.dll file into my bin folder. No matter what I try, I keep getting the same error:</p> <pre><code>Could not load type &gt;NHibernate.Driver.OracleDataClientDriver. Possible cause: no assembly name specified. </code></pre> <p>I am using the following configuration:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"&gt; &lt;session-factory name="DefaultSessionFactory"&gt; &lt;property name="connection.provider"&gt;NHibernate.Connection.DriverConnectionProvider&lt;/property&gt; &lt;property name="dialect"&gt;NHibernate.Dialect.Oracle9Dialect&lt;/property&gt; &lt;property name="connection.driver_class"&gt;&gt;NHibernate.Driver.OracleDataClientDriver&lt;/property&gt; &lt;property name="connection.connection_string"&gt;Data Source=DB;User ID=USERPassword=****;&lt;/property&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;mapping assembly="NHibernateExample.DataAccess"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>I have previously only set up NHibernate for SQL Server. Am I missing anything here?</p>
[ { "answer_id": 241154, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 0, "selected": false, "text": "hibernate <property name=\"hibernate.connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n<property name=\"hibernate.dialect\">NHibernate.Dialect.Oracle9Dialect</property>\n<property name=\"hibernate.connection.driver_class\">NHibernate.Driver.OracleDataClientDriver</property>\n<property name=\"hibernate.connection.connection_string\">Data Source=DB;User ID=USERPassword=****;</property> \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
241,088
<p>I have some Java code that uses curly braces in two ways</p> <pre><code>// Curly braces attached to an 'if' statement: if(node.getId() != null) { node.getId().apply(this); } // Curly braces by themselves: { List&lt;PExp&gt; copy = new ArrayList&lt;PExp&gt;(node.getArgs()); for(PExp e : copy) { e.apply(this); } } outAMethodExp(node); </code></pre> <p>What do those stand-alone curly braces after the first <code>if</code> statement mean?</p>
[ { "answer_id": 241097, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 8, "selected": true, "text": "List<PExp> copy List<PExp> copy" }, { "answer_id": 241182, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 0, "selected": false, "text": "if(a) int f; if(a) { int f; }" }, { "answer_id": 241950, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 5, "selected": false, "text": " List<String> names = new ArrayList<String>() {\n // I want to initialize this ArrayList instace in-line,\n // but I can't define a constructor for an anonymous class:\n {\n add(\"Adam\");\n add(\"Eve\");\n }\n\n };\n" }, { "answer_id": 29074419, "author": "Philipp", "author_id": 76024, "author_profile": "https://Stackoverflow.com/users/76024", "pm_score": 1, "selected": false, "text": "switch(foo) {\n case BAR:\n int i = ...\n ...\n case BAZ:\n int i = ... // error, \"i\" already defined in scope\n}\n switch(foo) {\n case BAR:{\n int i = ...\n ...\n }\n case BAZ:{\n int i = ... // OK\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
241,089
<p>I need to respond to the events of minimizing / maximizing Eclipse window. How do I do that?</p>
[ { "answer_id": 241097, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 8, "selected": true, "text": "List<PExp> copy List<PExp> copy" }, { "answer_id": 241182, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 0, "selected": false, "text": "if(a) int f; if(a) { int f; }" }, { "answer_id": 241950, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 5, "selected": false, "text": " List<String> names = new ArrayList<String>() {\n // I want to initialize this ArrayList instace in-line,\n // but I can't define a constructor for an anonymous class:\n {\n add(\"Adam\");\n add(\"Eve\");\n }\n\n };\n" }, { "answer_id": 29074419, "author": "Philipp", "author_id": 76024, "author_profile": "https://Stackoverflow.com/users/76024", "pm_score": 1, "selected": false, "text": "switch(foo) {\n case BAR:\n int i = ...\n ...\n case BAZ:\n int i = ... // error, \"i\" already defined in scope\n}\n switch(foo) {\n case BAR:{\n int i = ...\n ...\n }\n case BAZ:{\n int i = ... // OK\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431/" ]
241,100
<p>I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked.</p> <p>The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way?</p> <p>I am searching in Google and VS help, but I haven't found any information yet.</p> <p>Can anybody help please?</p>
[ { "answer_id": 241218, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 6, "selected": true, "text": " Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick\n DataGridView1.BeginEdit(True)\n If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then\n DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True\n End If\n End Sub\n" }, { "answer_id": 241275, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 4, "selected": false, "text": "DataGridView1.EditMode = DataGridViewEditMode.EditOnEnter\n" }, { "answer_id": 242760, "author": "user20353", "author_id": 20353, "author_profile": "https://Stackoverflow.com/users/20353", "pm_score": 4, "selected": false, "text": "private void dataGridViewWeighings_CellClick(object sender, DataGridViewCellEventArgs e) {\n if (e.RowIndex < 0) {\n return; // Header\n }\n if (e.ColumnIndex != 5) {\n return; // Filter out other columns\n }\n\n dataGridViewWeighings.BeginEdit(true);\n ComboBox comboBox = (ComboBox)dataGridViewWeighings.EditingControl;\n comboBox.DroppedDown = true;\n}\n" }, { "answer_id": 6752071, "author": "Sting", "author_id": 782991, "author_profile": "https://Stackoverflow.com/users/782991", "pm_score": 2, "selected": false, "text": "private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n string Weekdays = @\"MondayTuesdayWednesdayThursdayFridaySaturdaySunday\";\n if (Weekdays.IndexOf(dgv.Columns[e.ColumnIndex].Name) != -1)\n {\n dgv.BeginEdit(true);\n ComboBox comboBox = (ComboBox)dgv.EditingControl;\n comboBox.DroppedDown = true;\n }\n}\n" }, { "answer_id": 27793969, "author": "Paul Hitchcock", "author_id": 4308977, "author_profile": "https://Stackoverflow.com/users/4308977", "pm_score": 2, "selected": false, "text": "Private Sub SomeGrid_MouseClick(sender As Object, e As MouseEventArgs) Handles SomeGrid.MouseClick\n DGV_MouseClick(sender, e)\nEnd Sub\n Public Sub DGV_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)\n Try\n Dim dgv As DataGridView = sender\n Dim h As DataGridView.HitTestInfo = dgv.HitTest(e.X, e.Y)\n If h.RowIndex > -1 AndAlso h.ColumnIndex > -1 AndAlso dgv.Columns(h.ColumnIndex).CellType Is GetType(DataGridViewComboBoxCell) Then\n Dim cell As DataGridViewComboBoxCell = dgv.Rows(h.RowIndex).Cells(h.ColumnIndex)\n If Not dgv.CurrentCell Is cell Then dgv.CurrentCell = cell\n If Not dgv.IsCurrentCellInEditMode Then\n dgv.BeginEdit(True)\n CType(dgv.EditingControl, ComboBox).DroppedDown = True\n End If\n End If\n Catch ex As Exception\n End Try\nEnd Sub\n" }, { "answer_id": 32224097, "author": "nvivekgoyal", "author_id": 1005063, "author_profile": "https://Stackoverflow.com/users/1005063", "pm_score": 2, "selected": false, "text": "//to get the correct cell get value of row and column indexs of the cell\n ColIndex = 1;\n RowIndex = 1;\n\n DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();\n ComboBoxCell.Items.AddRange(\"XYZ\", \"ABC\", \"PQR\");\n ComboBoxCell.Value = \"XYZ\";\n datagridview1[ColIndex, RowIndex] = ComboBoxCell;\n private void datagridview1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n {\nComboBox ctrl = e.Control as ComboBox;\nctrl.Enter -= new EventHandler(ctrl_Enter);\nctrl.Enter += new EventHandler(ctrl_Enter); \n}\nvoid ctrl_Enter(object sender, EventArgs e)\n{\n(sender as ComboBox).DroppedDown = true;\n}\n" }, { "answer_id": 50277060, "author": "gridtrak", "author_id": 3519108, "author_profile": "https://Stackoverflow.com/users/3519108", "pm_score": 0, "selected": false, "text": "private void datagridview1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n{\n ComboBox ctrl = e.Control as ComboBox;\n ctrl.Enter -= new EventHandler(ctrl_Enter);\n ctrl.Enter += new EventHandler(ctrl_Enter);\n}\n\nvoid ctrl_Enter(object sender, EventArgs e)\n{\n (sender as ComboBox).DroppedDown = true;\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20353/" ]
241,102
<p>I have been working on a webpage. It is the first I have actually tried to design using an image and then use proper CSS layout rather than tables.</p> <p><a href="http://www.roccocammisola.com/proj/brunel/bgimage.html" rel="nofollow noreferrer">http://www.roccocammisola.com/proj/brunel/bgimage.html</a></p> <p>I have been having issues with the shadows on either side of the main content area. Of course these are only an issue in IE. As you can see the shadow has been cut down to about 10% of its actual height. </p> <p>With my relative inexperience how do I look for relevant fixes to this issue.</p> <p>Any help would be very much appreciated.</p>
[ { "answer_id": 241115, "author": "Larsenal", "author_id": 337, "author_profile": "https://Stackoverflow.com/users/337", "pm_score": 1, "selected": false, "text": ".mainShadowRight {\n*/ your other stuff */\nurl('images/mainShadowRight.gif');\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31866/" ]
241,131
<p>I've got a workspace with multiple RCP plugin projects.</p> <p>We've set the target platform, so we can build against a standard set of plugins, but are not able to see source code and Javadoc for all the platform plugins.</p> <p>The Windows -> Preferences -> Plug-in Development -> Target Platform -> Source Code Locations page doesn't seem to have any effect when I add the eclipse directory (it only allows you to add directories). </p> <p>Copying the source jars from the eclipse directory into the target platform has a similar effect.</p> <p>What am I doing wrong? How do I attach a set of Source jars to my target platform?</p>
[ { "answer_id": 241200, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": 0, "selected": false, "text": "-install" }, { "answer_id": 12535099, "author": "lueders", "author_id": 1689420, "author_profile": "https://Stackoverflow.com/users/1689420", "pm_score": 1, "selected": false, "text": "Eclipse for RCP/Plug-in Developers" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4737/" ]
241,134
<p>I was recently working with a <code>DateTime</code> object, and wrote something like this:</p> <pre><code>DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? </code></pre> <p>The intellisense documentation for <code>AddDays()</code> says it adds a day to the date, which it doesn't - it actually <em>returns</em> a date with a day added to it, so you have to write it like:</p> <pre><code>DateTime dt = DateTime.Now; dt = dt.AddDays(1); return dt; // tomorrow's date </code></pre> <p>This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.</p>
[ { "answer_id": 241138, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 6, "selected": false, "text": "int x = 0;\nx = x++;\nreturn x;\n" }, { "answer_id": 241155, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "mystring.Replace(\"x\",\"y\")\n" }, { "answer_id": 241180, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "Type.GetType(string) System.String System.Windows.Forms.Form mscorlib using System;\nusing System.Threading;\n\nclass Test\n{\n static void Main()\n {\n for (int i=0; i < 10; i++)\n {\n ThreadStart ts = delegate { Console.WriteLine(i); };\n new Thread(ts).Start();\n }\n }\n}\n i using System;\nusing System.Threading;\n\nclass Test\n{\n static void Main()\n {\n for (int i=0; i < 10; i++)\n {\n int copy = i;\n ThreadStart ts = delegate { Console.WriteLine(copy); };\n new Thread(ts).Start();\n }\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nclass Test\n{\n static IEnumerable<char> CapitalLetters(string input)\n {\n if (input == null)\n {\n throw new ArgumentNullException(input);\n }\n foreach (char c in input)\n {\n yield return char.ToUpper(c);\n }\n }\n \n static void Main()\n {\n // Test that null input is handled correctly\n try\n {\n CapitalLetters(null);\n Console.WriteLine(\"An exception should have been thrown!\");\n }\n catch (ArgumentNullException)\n {\n // Expected\n }\n }\n}\n CapitalLetters MoveNext()" }, { "answer_id": 241181, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 6, "selected": false, "text": "string my = \"my \";\nDebug.Assert(my+\"string\" == \"my string\"); //true\n\nvar a = new ArrayList();\na.Add(my+\"string\");\na.Add(\"my string\");\n\n// uses ==(object) instead of ==(string)\nDebug.Assert(a[1] == \"my string\"); // true, due to interning magic\nDebug.Assert(a[0] == \"my string\"); // false\n string.Equals(a, b) List<string>" }, { "answer_id": 241189, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 7, "selected": false, "text": "static void PrintHowLong(DateTime a, DateTime b)\n{\n TimeSpan span = a - b;\n Console.WriteLine(span.Seconds); // WRONG!\n Console.WriteLine(span.TotalSeconds); // RIGHT!\n}\n" }, { "answer_id": 241194, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 9, "selected": true, "text": "private int myVar;\npublic int MyVar\n{\n get { return MyVar; }\n}\n MyVar myVar" }, { "answer_id": 241307, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": " List<int> a = new List<int>();\n for (int i = 0; i < 10; i++)\n {\n a.Add(i);\n }\n\n var q1 = (from aa in a\n where aa == 2\n select aa).Single();\n\n var q2 = (from aa in a\n where aa == 2\n select aa).First();\n" }, { "answer_id": 241326, "author": "cciotti", "author_id": 16834, "author_profile": "https://Stackoverflow.com/users/16834", "pm_score": 3, "selected": false, "text": "SPSite oSiteCollection = SPContext.Current.Site;\n oSiteCollection.Dispose();\n" }, { "answer_id": 241406, "author": "Brian J Cardiff", "author_id": 30948, "author_profile": "https://Stackoverflow.com/users/30948", "pm_score": 4, "selected": false, "text": "var l = new List<Func<string>>();\nvar strings = new[] { \"Lorem\" , \"ipsum\", \"dolor\", \"sit\", \"amet\" };\nforeach (var s in strings)\n{\n l.Add(() => s);\n}\n\nforeach (var a in l)\n Console.WriteLine(a());\n var l = new List<Func<string>>();\nvar strings = new[] { \"Lorem\" , \"ipsum\", \"dolor\", \"sit\", \"amet\" };\nforeach (var s in strings)\n{\n var t = s;\n l.Add(() => t);\n}\n\nforeach (var a in l)\n Console.WriteLine(a());\n" }, { "answer_id": 241504, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 5, "selected": false, "text": "struct Point { ... }\nList<Point> mypoints = ...;\n\nmypoints[i].x = 10;\n mypoints[i] Point Cannot modify the return value of 'System.Collections.Generic.List<Foo>.this[int]' because it is not a variable\n" }, { "answer_id": 241849, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 8, "selected": false, "text": "catch(Exception e) \n{\n // Do stuff \n throw e; \n}\n catch(Exception)\n{\n throw;\n}\n catch(Exception e) \n{\n // Do stuff \n throw new MySpecialException(e); \n}\n" }, { "answer_id": 242207, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 1, "selected": false, "text": "private void button1_Click( object sender, EventArgs e ) {\n try {\n CallMe(234);\n } catch (Exception ex) {\n label1.Text = ex.Message.ToString();\n }\n}\nprivate void CallMe( Int32 x ) {\n CallMe(x);\n}\n" }, { "answer_id": 350782, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": false, "text": "MemoryStream.GetBuffer() MemoryStream.ToArray()" }, { "answer_id": 497149, "author": "GWLlosa", "author_id": 18071, "author_profile": "https://Stackoverflow.com/users/18071", "pm_score": 3, "selected": false, "text": "((MyObject)obj).Equals(this);\n ((MyObject)obj) == this;\n" }, { "answer_id": 640594, "author": "Matt Davis", "author_id": 51170, "author_profile": "https://Stackoverflow.com/users/51170", "pm_score": 5, "selected": false, "text": " class A\n {\n public:\n int i;\n };\n struct A\n {\n int i;\n };\n" }, { "answer_id": 1048056, "author": "Maltrap", "author_id": 10644, "author_profile": "https://Stackoverflow.com/users/10644", "pm_score": 6, "selected": false, "text": "DateTime.Parse(\"Tue, 06 Sep 2011 16:35:12 GMT\").ToString(\"r\")\n> \"Tue, 06 Sep 2011 17:35:12 GMT\"\n" }, { "answer_id": 1097354, "author": "softveda", "author_id": 11711, "author_profile": "https://Stackoverflow.com/users/11711", "pm_score": 4, "selected": false, "text": "class SomeGeneric<T>\n{\n public static int i = 0;\n}\n\nclass Test\n{\n public static void main(string[] args)\n {\n SomeGeneric<int>.i = 5;\n SomeGeneric<string>.i = 10;\n Console.WriteLine(SomeGeneric<int>.i);\n Console.WriteLine(SomeGeneric<string>.i);\n Console.WriteLine(SomeGeneric<int>.i);\n }\n}\n" }, { "answer_id": 1141114, "author": "Damovisa", "author_id": 77546, "author_profile": "https://Stackoverflow.com/users/77546", "pm_score": 5, "selected": false, "text": "long now = DateTime.Now.Ticks;\nfor (int i = 0; i < 10; i++)\n{\n System.Threading.Thread.Sleep(1);\n Console.WriteLine(DateTime.Now.Ticks - now);\n}\n 0\n0\n0\n0\n0\n0\n0\n156254\n156254\n156254\n \\ string prefix1 = \"C:\\\\MyFolder\\\\MySubFolder\";\nstring prefix2 = \"C:\\\\MyFolder\\\\MySubFolder\\\\\";\nstring suffix1 = \"log\\\\\";\nstring suffix2 = \"\\\\log\\\\\";\n\nConsole.WriteLine(Path.Combine(prefix1, suffix1));\nConsole.WriteLine(Path.Combine(prefix1, suffix2));\nConsole.WriteLine(Path.Combine(prefix2, suffix1));\nConsole.WriteLine(Path.Combine(prefix2, suffix2));\n C:\\MyFolder\\MySubFolder\\log\\\n\\log\\\nC:\\MyFolder\\MySubFolder\\log\\\n\\log\\\n" }, { "answer_id": 1394752, "author": "Nicolas Dorier", "author_id": 19803, "author_profile": "https://Stackoverflow.com/users/19803", "pm_score": 6, "selected": false, "text": "[Serializable]\nclass Hello\n{\n readonly object accountsLock = new object();\n}\n\n//Do stuff to deserialize Hello with BinaryFormatter\n//and now... accountsLock == null ;)\n" }, { "answer_id": 1404302, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "SubmitChanges() SubmitChanges()" }, { "answer_id": 1404311, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 4, "selected": false, "text": "DateTime.MinDate" }, { "answer_id": 1404987, "author": "Timothy Walters", "author_id": 14454, "author_profile": "https://Stackoverflow.com/users/14454", "pm_score": 6, "selected": false, "text": "timer.Tick -= TimerTickEventHandler;\n" }, { "answer_id": 1499314, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 4, "selected": false, "text": "ObjectTrackingEnabled" }, { "answer_id": 1571906, "author": "jdehaan", "author_id": 170443, "author_profile": "https://Stackoverflow.com/users/170443", "pm_score": 6, "selected": false, "text": "Image image = System.Drawing.Image.FromFile(\"nice.pic\");\n \"nice.pic\" FromFile() using (Stream fs = new FileStream(\"nice.pic\", FileMode.Open, FileAccess.Read))\n{\n image = System.Drawing.Image.FromStream(fs);\n}\n" }, { "answer_id": 1855090, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 5, "selected": false, "text": "|| &&" }, { "answer_id": 1969664, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 4, "selected": false, "text": "var files = Enumerable.Range(0, 5)\n .Select(i => Path.GetTempFileName());\n\nforeach (var file in files)\n File.WriteAllText(file, \"HELLO WORLD!\");\n\n/* ... many lines of codes later ... */\n\nforeach (var file in files)\n File.Delete(file);\n File.Delete(file) FileNotFound files Path.GetTempFilename() ToArray() ToList() var files = Enumerable.Range(0, 5)\n .Select(i => Path.GetTempFileName())\n .ToArray();\n foreach (var file in files)\n content = content + File.ReadAllText(file);\n content.Length" }, { "answer_id": 2172307, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 2, "selected": false, "text": "Thing Category var thing = CreateThing(); // does stuff to create a thing\nvar category = GetCategoryByID(123); // loads the Category with ID 123\nthing.Category = category;\nConsole.WriteLine(\"Category ID: {0}\", thing.CategoryID); \n Category ID: 0\n var thing = CreateThing();\nthing.CategoryID = 123;\nConsole.WriteLine(\"Category name: {0}\", order.Category.Name);\n NullReferenceException Category" }, { "answer_id": 2245370, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 8, "selected": false, "text": "private MyClass _myObj;\npublic MyClass MyObj {\n get {\n if (_myObj == null)\n _myObj = CreateMyObj(); // some other code to create my object\n return _myObj;\n }\n}\n // blah\n// blah\nMyObj.DoStuff(); // Line 3\n// blah\n CreateMyObj() _myObj = CreateMyObj(); CreateMyObj() _myObj return _myObj MyObj MyObj CreateMyObj()" }, { "answer_id": 2456832, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 1, "selected": false, "text": "Claim Amount decimal var sum = Claims.Where(c => c.ID < 0).Sum(c => c.Amount);\n InvalidOperationException var sum = Claims.Where(c => c.ID < 0).Sum(c => (decimal?)c.Amount);\n" }, { "answer_id": 2542277, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "return result = from o in table\n where o.column == null\n select o;\n//Returns all rows where column is null\n\nint? myNullInt = null;\nreturn result = from o in table\n where o.column == myNullInt\n select o;\n//Never returns anything!\n" }, { "answer_id": 2542285, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 3, "selected": false, "text": "TextInfo textInfo = Thread.CurrentThread.CurrentCulture.TextInfo;\n\ntextInfo.ToTitleCase(\"hello world!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"hElLo WoRld!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"Hello World!\"); //Returns \"Hello World!\"\ntextInfo.ToTitleCase(\"HELLO WORLD!\"); //Returns \"HELLO WORLD!\"\n" }, { "answer_id": 2556347, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 5, "selected": false, "text": "Angle" }, { "answer_id": 2731527, "author": "Will Vousden", "author_id": 58635, "author_profile": "https://Stackoverflow.com/users/58635", "pm_score": 3, "selected": false, "text": "base" }, { "answer_id": 2773292, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 0, "selected": false, "text": "DataContext.SubmitChanges() DataContext.GetChangeSet() .Equals()" }, { "answer_id": 2837357, "author": "BlueRaja - Danny Pflughoeft", "author_id": 238419, "author_profile": "https://Stackoverflow.com/users/238419", "pm_score": 5, "selected": false, "text": "abstract class Base\n{\n public virtual void foo(string s = \"base\") { Console.WriteLine(\"base \" + s); }\n}\n\nclass Derived : Base\n{\n public override void foo(string s = \"derived\") { Console.WriteLine(\"derived \" + s); }\n}\n\n...\n\nBase b = new Derived();\nb.foo();\n" }, { "answer_id": 3045173, "author": "Stefan Steinegger", "author_id": 2658202, "author_profile": "https://Stackoverflow.com/users/2658202", "pm_score": 4, "selected": false, "text": "IList IList<int> myList = new int[] { 1, 2, 4 };\nmyList.Add(5);\n" }, { "answer_id": 3045200, "author": "Stefan Steinegger", "author_id": 2658202, "author_profile": "https://Stackoverflow.com/users/2658202", "pm_score": 4, "selected": false, "text": "List<delegate>" }, { "answer_id": 3626947, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 2, "selected": false, "text": "base. public override bool IsRecursive\n {\n get { return IsRecursive; }\n set { IsRecursive = value; }\n }\n public bool IsRecursive\n{\n get { return IsRecursive; }\n set { IsRecursive = value; }\n}\n" }, { "answer_id": 3877065, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "BindByName OracleCommand true false DropDatabaseOnQueryExecution true" }, { "answer_id": 4638668, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 0, "selected": false, "text": "MyClass IHasDescription public interface IHasDescription {\n string Description { get; set; }\n}\n\npublic partial class MyClass : IHasDescription { }\n MyClass Description public static T GetByDescription<T>(System.Data.Linq.Table<T> table, string desc) \n where T : class, IHasDescription {\n return table.Where(t => t.Description == desc).FirstOrDefault();\n}\n NotSupportedException: The mapping of interface member IHasDescription.Description is not supported.\n == .Equals() return table.Where(t => t.Description.Equals(desc)).FirstOrDefault();\n" }, { "answer_id": 4833796, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "// Read 8 bytes and turn them into a ulong\nbyte[] data = new byte[8];\nstream.Read(data, 0, 8); // <-- WRONG!\nulong data = BitConverter.ToUInt64(data);\n Stream.Read Stream.Write /// <summary>\n /// Attempts to fill the buffer with the specified number of bytes from the\n /// stream. If there are fewer bytes left in the stream than requested then\n /// all available bytes will be read into the buffer.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"buffer\">Buffer to write the bytes to.</param>\n /// <param name=\"offset\">Offset at which to write the first byte read from\n /// the stream.</param>\n /// <param name=\"length\">Number of bytes to read from the stream.</param>\n /// <returns>Number of bytes read from the stream into buffer. This may be\n /// less than requested, but only if the stream ended before the\n /// required number of bytes were read.</returns>\n public static int FillBuffer(this Stream stream,\n byte[] buffer, int offset, int length)\n {\n int totalRead = 0;\n while (length > 0)\n {\n var read = stream.Read(buffer, offset, length);\n if (read == 0)\n return totalRead;\n offset += read;\n length -= read;\n totalRead += read;\n }\n return totalRead;\n }\n\n /// <summary>\n /// Attempts to read the specified number of bytes from the stream. If\n /// there are fewer bytes left before the end of the stream, a shorter\n /// (possibly empty) array is returned.\n /// </summary>\n /// <param name=\"stream\">Stream to read from.</param>\n /// <param name=\"length\">Number of bytes to read from the stream.</param>\n public static byte[] Read(this Stream stream, int length)\n {\n byte[] buf = new byte[length];\n int read = stream.FillBuffer(buf, 0, length);\n if (read < length)\n Array.Resize(ref buf, read);\n return buf;\n }\n" }, { "answer_id": 5088558, "author": "Shekhar_Pro", "author_id": 399722, "author_profile": "https://Stackoverflow.com/users/399722", "pm_score": 2, "selected": false, "text": "value stack reference heap" }, { "answer_id": 5800045, "author": "Boris Lipschitz", "author_id": 87475, "author_profile": "https://Stackoverflow.com/users/87475", "pm_score": 3, "selected": false, "text": "using System.Threading;\nclass Blah\n{\n static void Main() { /* Won’t run because the static constructor deadlocks. */ }\n\n static Blah()\n {\n Thread thread = new Thread(ThreadBody);\n thread.Start();\n thread.Join();\n }\n\n static void ThreadBody() { }\n}\n" }, { "answer_id": 12502678, "author": "Roboblob", "author_id": 125718, "author_profile": "https://Stackoverflow.com/users/125718", "pm_score": 3, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var originalNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };\n\n var list = new List<int>(originalNumbers);\n var collection = new Collection<int>(originalNumbers);\n\n originalNumbers.RemoveAt(0);\n\n DisplayItems(list, \"List items: \");\n DisplayItems(collection, \"Collection items: \");\n\n Console.ReadLine();\n }\n\n private static void DisplayItems(IEnumerable<int> items, string title)\n {\n Console.WriteLine(title);\n foreach (var item in items)\n Console.Write(item);\n Console.WriteLine();\n }\n}\n List items: 123456\nCollection items: 23456\n" }, { "answer_id": 13724876, "author": "Trident D'Gao", "author_id": 139667, "author_profile": "https://Stackoverflow.com/users/139667", "pm_score": 3, "selected": false, "text": "private void DumpError(Exception exception, Stack<String> context)\n{\n if (context.Any())\n {\n Trace.WriteLine(context.Pop());\n Trace.Indent();\n this.DumpError(exception, context);\n Trace.Unindent();\n }\n else\n {\n Trace.WriteLine(exception.Message);\n }\n}\n private void DumpError(Exception exception, Stack<String> context)\n{\n if (context.Any())\n {\n var popped = context.Pop();\n Trace.WriteLine(popped);\n Trace.Indent();\n this.DumpError(exception, context);\n Trace.Unindent();\n }\n else\n {\n Trace.WriteLine(exception.Message);\n }\n}\n" }, { "answer_id": 13737981, "author": "Mahdi Tahsildari", "author_id": 1471381, "author_profile": "https://Stackoverflow.com/users/1471381", "pm_score": 3, "selected": false, "text": "enum Seasons\n{\n Spring = 1, Summer = 2, Automn = 3, Winter = 4\n}\n\npublic string HowYouFeelAbout(Seasons season)\n{\n switch (season)\n {\n case Seasons.Spring:\n return \"Nice.\";\n case Seasons.Summer:\n return \"Hot.\";\n case Seasons.Automn:\n return \"Cool.\";\n case Seasons.Winter:\n return \"Chilly.\";\n }\n}\n Seasons Default" }, { "answer_id": 16546439, "author": "DevDave", "author_id": 896631, "author_profile": "https://Stackoverflow.com/users/896631", "pm_score": 4, "selected": false, "text": "int? i = null;\ni++; // I would have expected an exception but runs fine and stays as null\n" }, { "answer_id": 21197312, "author": "Chuu", "author_id": 459975, "author_profile": "https://Stackoverflow.com/users/459975", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Collections.Concurrent;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ValueFactoryBehavingBadlyExample\n{\n class Program\n {\n static ConcurrentDictionary<int, int> m_Dict = new ConcurrentDictionary<int, int>();\n static ManualResetEventSlim m_MRES = new ManualResetEventSlim(false);\n static void Main(string[] args)\n {\n for (int i = 0; i < 8; ++i)\n {\n Task.Factory.StartNew(ThreadGate, TaskCreationOptions.LongRunning);\n }\n Thread.Sleep(1000);\n m_MRES.Set();\n Thread.Sleep(1000);\n Console.WriteLine(\"Dictionary Size: \" + m_Dict.Count);\n Console.Read();\n }\n\n static void ThreadGate()\n {\n m_MRES.Wait();\n int value = m_Dict.GetOrAdd(0, ValueFactory);\n }\n\n static int ValueFactory(int key)\n {\n Thread.Sleep(1000);\n Console.WriteLine(\"Value Factory Called\");\n return key;\n }\n }\n}\n Value Factory Called\nValue Factory Called\nValue Factory Called\nValue Factory Called\nDictionary Size: 0\nValue Factory Called\nValue Factory Called\nValue Factory Called\nValue Factory Called\n" }, { "answer_id": 22555441, "author": "SkeetJon", "author_id": 831108, "author_profile": "https://Stackoverflow.com/users/831108", "pm_score": 1, "selected": false, "text": "List<int> var thisOnePasses = new List<int> {2}; // collection initializer\nvar thisOneFails = new List<int> (2); // oops, use capacity by mistake #gotcha#\n\nthisOnePasses.Count.Should().Be(1);\nthisOnePasses.First().Should().Be(2);\n\nthisOneFails.Count.Should().Be(1); // it's zero\nthisOneFails.First().Should().Be(2); // Sequence contains no elements...\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
241,141
<p>I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.</p> <p>Is there a single<code>__xxx__</code>method I can override to load the list on first usage of any list property (such as<code>len</code>,<code>getitem</code>,<code>iter</code>...etc) without having to override them all?</p>
[ { "answer_id": 241169, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "__getattribute__" }, { "answer_id": 242111, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 3, "selected": false, "text": "__getattribute__ x[y] x(y) x.__getitem__(y) x.__call__(y) >>> class x(object):\n... def __getattribute__(self, o):\n... print o\n... \n>>> x()[3]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'x' object does not support indexing\n class override(object):\n def __init__(self, methodName):\n self.methodName = methodName\n\n def __get__(self, oself, cls):\n oself._load(self.methodName)\n return getattr(super(oself.__class__, oself), self.methodName)\n\nclass LazyList(list):\n def _load(self, name):\n print 'Loading data for %s...' % (name,)\n\n for methodName in set(dir(list)) - set(dir(object)):\n locals()[methodName] = override(methodName)\n dir()" }, { "answer_id": 5104787, "author": "Lauritz V. Thaulow", "author_id": 566644, "author_profile": "https://Stackoverflow.com/users/566644", "pm_score": 3, "selected": false, "text": "from collections import MutableSequence\n\nclass Monitored(MutableSequence):\n    def __init__(self):\n        super(Monitored, self).__init__()\n        self._list = []\n\n    def __len__(self):\n        r = len(self._list)\n        print \"len: {0:d}\".format(r)\n        return r\n\n    def __getitem__(self, index):\n        r = self._list[index]\n        print \"getitem: {0!s}\".format(index)\n        return r\n\n    def __setitem__(self, index, value):\n        print \"setitem {0!s}: {1:s}\".format(index, repr(value))\n        self._list[index] = value\n\n    def __delitem__(self, index):\n        print \"delitem: {0!s}\".format(index)\n        del self._list[index]\n\n    def insert(self, index, value):\n        print \"insert at {0:d}: {1:s}\".format(index, repr(value))\n        self._list.insert(index, value)\n MutableSequence collections MutableSequence isinstance issubclass >>> isinstance([], MutableSequence)\nTrue\n>>> issubclass(list, MutableSequence)\nTrue\n Monitored" }, { "answer_id": 18638351, "author": "stub", "author_id": 2720363, "author_profile": "https://Stackoverflow.com/users/2720363", "pm_score": 1, "selected": false, "text": "class LazyList(list):\n \"\"\"List populated on first use.\"\"\"\n def __new__(cls, fill_iter):\n\n class LazyList(list):\n _fill_iter = None\n\n _props = (\n '__str__', '__repr__', '__unicode__',\n '__hash__', '__sizeof__', '__cmp__', '__nonzero__',\n '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__',\n 'append', 'count', 'index', 'extend', 'insert', 'pop', 'remove',\n 'reverse', 'sort', '__add__', '__radd__', '__iadd__', '__mul__',\n '__rmul__', '__imul__', '__contains__', '__len__', '__nonzero__',\n '__getitem__', '__setitem__', '__delitem__', '__iter__',\n '__reversed__', '__getslice__', '__setslice__', '__delslice__')\n\n def lazy(name):\n def _lazy(self, *args, **kw):\n if self._fill_iter is not None:\n _fill_lock.acquire()\n try:\n if self._fill_iter is not None:\n list.extend(self, self._fill_iter)\n self._fill_iter = None\n finally:\n _fill_lock.release()\n real = getattr(list, name)\n setattr(self.__class__, name, real)\n return real(self, *args, **kw)\n return _lazy\n\n for name in _props:\n setattr(LazyList, name, lazy(name))\n\n new_list = LazyList()\n new_list._fill_iter = fill_iter\n return new_list\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52490/" ]
241,142
<p>i want to be a good developer citizen, <a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">pay my taxes</a>, and disable things if we're running over Remote Desktop, or running on battery.</p> <p>If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and double-buffering. You can check this with:</p> <pre><code>/// &lt;summary&gt; /// Indicates if we're running in a remote desktop session. /// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes! /// /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Boolean IsRemoteSession { //This is just a friendly wrapper around the built-in way get { return System.Windows.Forms.SystemInformation.TerminalServerSession; } } </code></pre> <p>Now i need to find out if the user is running on battery power. If they are, i don't want to blow through their battery. i want to do things such as</p> <ul> <li>disable animations</li> <li>disable background spell-checking</li> <li>disable background printing</li> <li>turn off gradients </li> <li>use <code>graphics.SmoothingMode = SmoothingMode.HighSpeed;</code> </li> <li>use <code>graphics.InterpolationMode = InterpolationMode.Low;</code></li> <li>use <code>graphics.CompositingQuality = CompositingQuality.HighSpeed;</code></li> <li>minimize hard drive access - to avoid spin up</li> <li>minimize network access - to save WiFi power</li> </ul> <p>Is there a managed way to see if the machine is <strong>currently</strong> running on battery?</p> <h2>Bonus Reading</h2> <ul> <li><a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx" rel="nofollow noreferrer">How do you convince developers to pay their "taxes"?</a> <em>(<a href="https://archive.fo/iNVg5" rel="nofollow noreferrer">archive.is</a>)</em></li> <li><a href="http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx" rel="nofollow noreferrer">Taxes: Remote Desktop Connection and painting</a> <em>(<a href="https://archive.fo/lJx1u" rel="nofollow noreferrer">archive.is</a>)</em></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx" rel="nofollow noreferrer">GetSystemMetrics(SM_REMOTESESSION)</a> <em>(<a href="https://archive.fo/Ywbw7" rel="nofollow noreferrer">archive.is</a>)</em></li> </ul>
[ { "answer_id": 241159, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Runtime.InteropServices;\nnamespace PowerStateExample\n{\n [StructLayout(LayoutKind.Sequential)]\n public class PowerState\n {\n public ACLineStatus ACLineStatus;\n public BatteryFlag BatteryFlag;\n public Byte BatteryLifePercent;\n public Byte Reserved1;\n public Int32 BatteryLifeTime;\n public Int32 BatteryFullLifeTime;\n\n // direct instantation not intended, use GetPowerState.\n private PowerState() {}\n\n public static PowerState GetPowerState()\n {\n PowerState state = new PowerState();\n if (GetSystemPowerStatusRef(state))\n return state;\n\n throw new ApplicationException(\"Unable to get power state\");\n }\n\n [DllImport(\"Kernel32\", EntryPoint = \"GetSystemPowerStatus\")]\n private static extern bool GetSystemPowerStatusRef(PowerState sps);\n }\n\n // Note: Underlying type of byte to match Win32 header\n public enum ACLineStatus : byte\n {\n Offline = 0, Online = 1, Unknown = 255\n }\n\n public enum BatteryFlag : byte\n {\n High = 1, Low = 2, Critical = 4, Charging = 8,\n NoSystemBattery = 128, Unknown = 255\n }\n\n // Program class with main entry point to display an example.\n class Program\n { \n static void Main(string[] args)\n {\n PowerState state = PowerState.GetPowerState();\n Console.WriteLine(\"AC Line: {0}\", state.ACLineStatus);\n Console.WriteLine(\"Battery: {0}\", state.BatteryFlag);\n Console.WriteLine(\"Battery life %: {0}\", state.BatteryLifePercent);\n }\n }\n}\n" }, { "answer_id": 241163, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 6, "selected": true, "text": "Boolean isRunningOnBattery =\n (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus == \n PowerLineStatus.Offline);\n" }, { "answer_id": 241174, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Indicates if we're running on battery power.\n/// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc\n/// </summary>\npublic static Boolean IsRunningOnBattery\n{\n get\n {\n PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus;\n\n //Offline means running on battery\n return (pls == PowerLineStatus.Offline);\n }\n}\n" }, { "answer_id": 51645890, "author": "Byte11", "author_id": 6515420, "author_profile": "https://Stackoverflow.com/users/6515420", "pm_score": 0, "selected": false, "text": "Boolean x = (System.Windows.SystemParameters.PowerLineStatus == System.Windows.PowerLineStatus.Offline);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
241,144
<p>I know that this is a very specific C++ and Qt related question, but maybe someone can help me, anyway ...</p> <p>See the code below: I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not.</p> <pre><code>// create label for displaying an image QImage image( ":/test.png" ); QLabel *label = new QLabel( this ); label-&gt;setPixmap( image.toPixmap() ); // put label into scroll area QScollArea *area = new QScrollArea( this ); area-&gt;setWidget( label ); // set the initial size of the view port // NOTE: This is what I'd like to do, but this method does not exist :( area-&gt;setViewPortSize( QSize( 300, 300 ) ); </code></pre> <p>It shall be possible to resize the whole application so that the view port will get another size than the initial one.</p> <p>Unfortunatelly I was not able to find out, how to set the size of the view port. Qt's layout mechanism seems to set a default size for the view port, but up to now I was not able to change it. Setting a new size with </p> <pre><code>area-&gt;setMinimumSize( QSize( 300, 300 ) ); </code></pre> <p>will actually set the demanded size, but then the scroll area looses the ability to get resized to a size smaller than 300x300.</p> <p>Any ideas?</p>
[ { "answer_id": 243561, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 0, "selected": false, "text": "area->resize( 300 + fudge, 300 + fudge )" }, { "answer_id": 250257, "author": "mxcl", "author_id": 6444, "author_profile": "https://Stackoverflow.com/users/6444", "pm_score": 2, "selected": false, "text": "class MyScrollArea : public QScrollArea\n{\n virtual QSize sizeHint() const { return QSize( 300, 300 ); }\n};\n\n// create label for displaying an image\nQImage image( \":/test.png\" );\nLabel *label = new QLabel;\nlabel->setPixmap( image.toPixmap() );\n\n// put label into scroll area\nQScollArea *area = new MyScrollArea( this );\narea->setWidget( label );\n" }, { "answer_id": 263766, "author": "Bob", "author_id": 34467, "author_profile": "https://Stackoverflow.com/users/34467", "pm_score": 0, "selected": false, "text": "QGraphicsScene *scene = new QGraphicsScene(qgvImageView);\nQPixmap pixTmp(QPixmap::fromImage(image));\nQGraphicsPixmapItem * ppixItem = scene->addPixmap( pixTmp );\nppixItem->setPos(0,0);\n" }, { "answer_id": 407857, "author": "Henrik Hartz", "author_id": 50830, "author_profile": "https://Stackoverflow.com/users/50830", "pm_score": 2, "selected": false, "text": "area->resize(300,300);\n" }, { "answer_id": 409595, "author": "Alpants", "author_id": 48923, "author_profile": "https://Stackoverflow.com/users/48923", "pm_score": 0, "selected": false, "text": "area->setGeometry(int x, int y, int w, int h);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
241,145
<p>How do you create a simple, custom rule using the jQuery Validate plugin (using <a href="http://jqueryvalidation.org/jQuery.validator.addMethod" rel="noreferrer"><code>addMethod</code></a>) that doesn't use a regex?</p> <p>For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?</p>
[ { "answer_id": 241202, "author": "Mark Spangler", "author_id": 456684, "author_profile": "https://Stackoverflow.com/users/456684", "pm_score": 9, "selected": false, "text": "jQuery.validator.addMethod(\"greaterThanZero\", function(value, element) {\n return this.optional(element) || (parseFloat(value) > 0);\n}, \"* Amount must be greater than zero\");\n $('validatorElement').validate({\n rules : {\n amount : { greaterThanZero : true }\n }\n});\n" }, { "answer_id": 243647, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "$.validator.addMethod(\"greaterThanZero\", function(value, element) {\n var the_list_array = $(\"#some_form .super_item:checked\");\n return the_list_array.length > 0;\n}, \"* Please check at least one check box\");\n" }, { "answer_id": 2289990, "author": "Tracy", "author_id": 276236, "author_profile": "https://Stackoverflow.com/users/276236", "pm_score": 7, "selected": false, "text": "$(document).ready(function(){\n var response;\n $.validator.addMethod(\n \"uniqueUserName\", \n function(value, element) {\n $.ajax({\n type: \"POST\",\n url: \"http://\"+location.host+\"/checkUser.php\",\n data: \"checkUsername=\"+value,\n dataType:\"html\",\n success: function(msg)\n {\n //If username exists, set response to true\n response = ( msg == 'true' ) ? true : false;\n }\n });\n return response;\n },\n \"Username is Already Taken\"\n );\n\n $(\"#regFormPart1\").validate({\n username: {\n required: true,\n minlength: 8,\n uniqueUserName: true\n },\n messages: {\n username: {\n required: \"Username is required\",\n minlength: \"Username must be at least 8 characters\",\n uniqueUserName: \"This Username is taken already\"\n }\n }\n });\n});\n" }, { "answer_id": 4258174, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 6, "selected": false, "text": "// add a method. calls one built-in method, too.\njQuery.validator.addMethod(\"optdate\", function(value, element) {\n return jQuery.validator.methods['date'].call(\n this,value,element\n )||value==(\"0000/00/00\");\n }, \"Please enter a valid date.\"\n);\n\n// connect it to a css class\njQuery.validator.addClassRules({\n optdate : { optdate : true } \n});\n" }, { "answer_id": 33941303, "author": "BenG", "author_id": 1000934, "author_profile": "https://Stackoverflow.com/users/1000934", "pm_score": 6, "selected": false, "text": "data data-rule-rulename=\"true\"; <input type=\"checkbox\" name=\"colours[]\" value=\"red\" data-rule-oneormorechecked=\"true\" />\n $.validator.addMethod(\"oneormorechecked\", function(value, element) {\n return $('input[name=\"' + element.name + '\"]:checked').length > 0;\n}, \"Atleast 1 must be selected\");\n data-msg-rulename=\"my new message\" data-rule-rulename dataRules .toLowerCase() $.validator.addMethod(\"oneormorechecked\", function(value, element) {\n return $('input[name=\"' + element.name + '\"]:checked').length > 0;\n}, \"Atleast 1 must be selected\");\n\n$('.validate').validate(); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js\"></script>\n\n<form class=\"validate\">\n red<input type=\"checkbox\" name=\"colours[]\" value=\"red\" data-rule-oneormorechecked=\"true\" data-msg-oneormorechecked=\"Check one or more!\" /><br/>\n blue<input type=\"checkbox\" name=\"colours[]\" value=\"blue\" /><br/>\n green<input type=\"checkbox\" name=\"colours[]\" value=\"green\" /><br/>\n <input type=\"submit\" value=\"submit\"/>\n</form>" }, { "answer_id": 37562968, "author": "Bogdan Mates", "author_id": 5068697, "author_profile": "https://Stackoverflow.com/users/5068697", "pm_score": 4, "selected": false, "text": "$.validator.addMethod(\n 'booleanRequired',\n function (value, element, requiredValue) {\n return value === requiredValue;\n },\n 'Please check your input.'\n);\n PhoneToggle: {\n booleanRequired: 'on'\n} \n" }, { "answer_id": 48074571, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 2, "selected": false, "text": "<input name=\"user_name\" type=\"text\" >\n $(\"form\").validate({\n rules: {\n 'user_name': {\n // here jquery validate will start a GET request, to \n // /interface/users/is_username_valid?user_name=<input_value>\n // the response should be \"raw text\", with content \"true\" or \"false\" only\n remote: '/interface/users/is_username_valid'\n },\n },\n class Interface::UsersController < ActionController::Base\n def is_username_valid\n render :text => !User.exists?(:user_name => params[:user_name])\n end\nend\n" }, { "answer_id": 65966205, "author": "Devang Hire", "author_id": 9956618, "author_profile": "https://Stackoverflow.com/users/9956618", "pm_score": -1, "selected": false, "text": " <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n\n <script src=\"http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js\"></script>\n $(document).ready(function(){\n $(\"#submit\").click(function () {\n $('#myform').validate({ // initialize the plugin\n rules: {\n id: {\n required: true,\n email: true\n },\n password: {\n required: true,\n minlength: 1\n }\n },\n messages: {\n id: {\n required: \"Enter Email Id\"\n\n },\n password: {\n required: \"Enter Email Password\"\n\n }\n },\n submitHandler: function (form) { // for demo\n alert('valid form submitted'); // for demo\n return false; // for demo\n }\n });\n }):\n }); \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31869/" ]
241,150
<p>I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.</p> <p>I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.</p> <p>Question is: can you do both?</p>
[ { "answer_id": 241244, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 4, "selected": true, "text": "function (date) { \n var day = date.getDay(); \n return [day > 0 && day < 6, \"\"]; \n}\n" }, { "answer_id": 1427087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "onlyMondays: function(date){\n var day = date.getDay();\n return [(day == 1), \"\"]\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
241,152
<p>I'm displaying a series of images in a UIScrollView. I pretty much want to replicate the Photos application.</p> <p>My current architecture is: <li> A parent UIScrollView with content size that is wide enough for <i>x</i> number of pages + some extra space for margins in between the images.</li> <li> Each image is contained in a UIImageView.</li> <li> Each UIImageView is contained within its own UIScrollview which are then the subviews of the parent UIScrollView.</p> <p>So I basically have a row of UIScrollViews within a parent UIScrollView.</p> <p>The parent UIScrollView has paging enabled so I can scroll from page to page without any problems.</p> <p>The problem is how to seamlessly pan around a zoomed-in image. I have overridden the <code>viewForZoomingInScrollView</code> method to return the appropriate UIImageView when the user pinches in/out. I have overriden the <code>scrollViewDidEndZooming</code> method to set the parent view's <code>canCancelContentTouches</code> property to <code>NO</code> if the zoom scale is greater than 1. </p> <p>So users are able to pan around an image. However, they must hold their finger down for a moment to get past the small delay the parent scroll view has before sending touch events down to the subviews. Also, once the user is panning in one image, the next/prev images do not enter the viewable area when the user has reached the border of the current image.</p> <p>Any ideas?</p> <p>Thanks.</p>
[ { "answer_id": 831262, "author": "Andrey Tarantsov", "author_id": 58146, "author_profile": "https://Stackoverflow.com/users/58146", "pm_score": 3, "selected": false, "text": "viewForZoomingInScrollView: scrollViewDidEndZooming:withView:atScale: typedef enum {\n ScrollViewModeNotInitialized, // view has just been loaded\n ScrollViewModePaging, // fully zoomed out, swiping enabled\n ScrollViewModeZooming, // zoomed in, panning enabled\n ScrollViewModeAnimatingFullZoomOut, // fully zoomed out, animations not yet finished\n ScrollViewModeInTransition, // during the call to setPagingMode to ignore scrollViewDidScroll events\n} ScrollViewMode;\n\n@interface ScrollingMadnessViewController : UIViewController <UIScrollViewDelegate> {\n UIScrollView *scrollView;\n NSArray *pageViews;\n NSUInteger currentPage;\n ScrollViewMode scrollViewMode;\n}\n\n@end\n\n@implementation ScrollingMadnessViewController\n\n- (void)setPagingMode {\n NSLog(@\"setPagingMode\");\n if (scrollViewMode != ScrollViewModeAnimatingFullZoomOut && scrollViewMode != ScrollViewModeNotInitialized)\n return; // setPagingMode is called after a delay, so something might have changed since it was scheduled\n scrollViewMode = ScrollViewModeInTransition; // to ignore scrollViewDidScroll when setting contentOffset\n\n // reposition pages side by side, add them back to the view\n CGSize pageSize = scrollView.frame.size;\n\n NSUInteger page = 0;\n for (UIView *view in pageViews) {\n if (!view.superview)\n [scrollView addSubview:view];\n view.frame = CGRectMake(pageSize.width * page++, 0, pageSize.width, pageSize.height);\n }\n\n scrollView.pagingEnabled = YES;\n scrollView.showsVerticalScrollIndicator = scrollView.showsHorizontalScrollIndicator = NO;\n scrollView.contentSize = CGSizeMake(pageSize.width * [pageViews count], pageSize.height);\n scrollView.contentOffset = CGPointMake(pageSize.width * currentPage, 0);\n\n scrollViewMode = ScrollViewModePaging;\n}\n\n- (void)setZoomingMode {\n NSLog(@\"setZoomingMode\");\n scrollViewMode = ScrollViewModeInTransition; // to ignore scrollViewDidScroll when setting contentOffset\n\n CGSize pageSize = scrollView.frame.size;\n\n // hide all pages besides the current one\n NSUInteger page = 0;\n for (UIView *view in pageViews)\n if (currentPage != page++)\n [view removeFromSuperview];\n\n // move the current page to (0, 0), as if no other pages ever existed\n [[pageViews objectAtIndex:currentPage] setFrame:CGRectMake(0, 0, pageSize.width, pageSize.height)];\n\n scrollView.pagingEnabled = NO;\n scrollView.showsVerticalScrollIndicator = scrollView.showsHorizontalScrollIndicator = YES;\n scrollView.contentSize = pageSize;\n scrollView.contentOffset = CGPointZero;\n\n scrollViewMode = ScrollViewModeZooming;\n}\n\n- (void)loadView {\n CGRect frame = [UIScreen mainScreen].applicationFrame;\n scrollView = [[UIScrollView alloc] initWithFrame:frame];\n scrollView.delegate = self;\n scrollView.maximumZoomScale = 2.0f;\n scrollView.minimumZoomScale = 1.0f;\n\n UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"red.png\"]];\n UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"green.png\"]];\n UIImageView *imageView3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"yellow-blue.png\"]];\n\n // in a real app, you most likely want to have an array of view controllers, not views;\n // also should be instantiating those views and view controllers lazily\n pageViews = [[NSArray alloc] initWithObjects:imageView1, imageView2, imageView3, nil];\n\n self.view = scrollView;\n}\n\n- (void)setCurrentPage:(NSUInteger)page {\n if (page == currentPage)\n return;\n currentPage = page;\n // in a real app, this would be a good place to instantiate more view controllers -- see SDK examples\n}\n\n- (void)viewDidLoad {\n scrollViewMode = ScrollViewModeNotInitialized;\n [self setPagingMode];\n}\n\n- (void)viewDidUnload {\n [pageViews release]; // need to release all page views here; our array is created in loadView, so just releasing it\n pageViews = nil;\n}\n\n- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {\n [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setPagingMode) object:nil];\n CGPoint offset = scrollView.contentOffset;\n NSLog(@\"scrollViewDidScroll: (%f, %f)\", offset.x, offset.y);\n if (scrollViewMode == ScrollViewModeAnimatingFullZoomOut && ABS(offset.x) < 1e-5 && ABS(offset.y) < 1e-5)\n // bouncing is still possible (and actually happened for me), so wait a bit more to be sure\n [self performSelector:@selector(setPagingMode) withObject:nil afterDelay:0.1];\n else if (scrollViewMode == ScrollViewModePaging)\n [self setCurrentPage:roundf(scrollView.contentOffset.x / scrollView.frame.size.width)];\n}\n\n- (UIView *)viewForZoomingInScrollView:(UIScrollView *)aScrollView {\n if (scrollViewMode != ScrollViewModeZooming)\n [self setZoomingMode];\n return [pageViews objectAtIndex:currentPage];\n}\n\n- (void)scrollViewDidEndZooming:(UIScrollView *)aScrollView withView:(UIView *)view atScale:(float)scale {\n NSLog(@\"scrollViewDidEndZooming: scale = %f\", scale);\n if (fabsf(scale - 1.0) < 1e-5) {\n if (scrollView.zoomBouncing)\n NSLog(@\"scrollViewDidEndZooming, but zoomBouncing is still true!\");\n\n // cannot call setPagingMode now because scrollView will bounce after a call to this method, resetting contentOffset to (0, 0)\n scrollViewMode = ScrollViewModeAnimatingFullZoomOut;\n // however sometimes bouncing will not take place\n [self performSelector:@selector(setPagingMode) withObject:nil afterDelay:0.2];\n }\n}\n\n@end\n" }, { "answer_id": 1805226, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " public partial class Test_Details_Controller : UIViewController\n{\n private UIPageControl _pageCont;\n\n private UIScrollView _scView;\n private Object[] _pageViews;\n private int _currentPageIndex; \n private bool _rotationInProgress;\n\n\n void InitializeAfterLoad ()\n { \n\n this.Title = \"Test\";\n\n this._pageCont = CreatePageControll();\n\n }\n\n private UIPageControl CreatePageControll()\n {\n UIPageControl pageControll = new UIPageControl( new RectangleF( 146,348, 38, 20 ) );\n pageControll.BackgroundColor = UIColor.Red;\n pageControll.Alpha = 0.7f;\n\n return pageControll;\n }\n\n private void UpdatePageControll(UIPageControl cont, int current, int pages, UIView showed)\n {\n cont.CurrentPage = current;\n cont.Pages = pages;\n cont.UpdateCurrentPageDisplay();\n\n UIPageControl.AnimationsEnabled = true;\n UIPageControl.BeginAnimations(string.Empty, this.Handle);\n cont.Frame = new RectangleF(showed.Frame.Location.X \n , cont.Frame.Location.Y , pageSize().Width, cont.Frame.Height); \n UIPageControl.CommitAnimations();\n\n }\n\n private UIView loadViewForPage(int pageIndex){\n UIView _view = null;\n switch ( pageIndex ) {\n case 1:\n _view = this._page1;\n break;\n case 2:\n _view = this._page2;\n break;\n default:\n _view = this._page1;\n break;\n }\n return _view;\n }\n\n private int numberOfPages(){\n return (int)this._pageViews.Count();\n }\n\n private UIView viewForPage( int pageIndex ){\n UIView pageView;\n if(this._pageViews.ElementAt( pageIndex ) == null)\n {\n pageView = loadViewForPage( pageIndex );\n _pageViews[ pageIndex ] = pageView;\n }\n else{\n pageView = (UIView)_pageViews[ pageIndex ];\n }\n\n _scView.AddSubview( pageView );\n\n return pageView; \n }\n\n private SizeF pageSize(){\n return this._scView.Frame.Size;\n }\n\n private bool isPageLoaded( int pageIndex ){\n return this._pageViews.ElementAt( pageIndex ) != null;\n }\n\n private void layoutPage( int pageIndex ){\n\n SizeF pageSize = this.pageSize();\n ((UIView)this._pageViews[pageIndex]).Frame = new RectangleF( pageIndex * pageSize.Width,0, pageSize.Width, pageSize.Height );\n this.viewForPage( pageIndex ); \n\n }\n\n private void loadView(){\n this._scView = new UIScrollView();\n this._scView.Delegate = new ScViewDelegate( this );\n this._scView.PagingEnabled = true;\n this._scView.ShowsHorizontalScrollIndicator = false;\n this._scView.ShowsVerticalScrollIndicator = false;\n this._scView.Layer.BorderWidth = 2;\n this._scView.AddSubview( _pageCont );\n this.View = this._scView;\n\n }\n\n public override void ViewDidLoad ()\n {\n base.ViewDidLoad ();\n InitializeAfterLoad ();\n this._pageViews = new Object[]{ _page1, _page2 };\n this.loadView(); \n } \n\n private void currentPageIndexDidChange(){\n this.layoutPage( _currentPageIndex );\n\n if(_currentPageIndex+1 < this.numberOfPages()){\n this.layoutPage( _currentPageIndex + 1 );\n }\n if(_currentPageIndex >0){\n this.layoutPage( _currentPageIndex - 1 );\n }\n\n this.UpdatePageControll( _pageCont, _currentPageIndex, this.numberOfPages(), ((UIView)this._pageViews[_currentPageIndex]) );\n this._scView.BringSubviewToFront( _pageCont );\n\n\n this.NavigationController.Title = string.Format( \"{0} of {1}\", _currentPageIndex + 1, this.numberOfPages() );\n }\n\n private void layoutPages(){\n SizeF pageSize = this.pageSize();\n this._scView.ContentSize = new SizeF( this.numberOfPages() * pageSize.Width, pageSize.Height );\n // move all visible pages to their places, because otherwise they may overlap\n for (int pageIndex = 0; pageIndex < this.numberOfPages(); pageIndex++) {\n if(this.isPageLoaded( pageIndex ))\n this.layoutPage( pageIndex );\n }\n }\n\n public override void ViewWillAppear (bool animated)\n {\n this.layoutPages();\n this.currentPageIndexDidChange();\n this._scView.ContentOffset = new PointF( _currentPageIndex * this.pageSize().Width, 0 );\n }\n\n class ScViewDelegate : UIScrollViewDelegate\n {\n Test_Details_Controller id;\n public ScViewDelegate ( Test_Details_Controller id )\n {\n this.id = id;\n }\n public override void Scrolled (UIScrollView scrollView)\n {\n\n if(id._rotationInProgress)\n return;// UIScrollView layoutSubviews code adjusts contentOffset, breaking our logic\n\n SizeF pageSize = id.pageSize();\n int newPageIndex = ((int)id._scView.ContentOffset.X + (int)pageSize.Width / 2) / (int)pageSize.Width;\n if( newPageIndex == id._currentPageIndex )\n return;\n\n id._currentPageIndex = newPageIndex;\n id.currentPageIndexDidChange();\n }\n }\n\n public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)\n {\n return toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown;\n }\n\n public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration)\n { \n _rotationInProgress = true;\n // hide other page views because they may overlap the current page during animation\n for (int pageIndex = 0; pageIndex < this.numberOfPages(); pageIndex++) {\n if(this.isPageLoaded( pageIndex ))\n this.viewForPage( pageIndex ).Hidden = ( pageIndex != _currentPageIndex );\n }\n }\n public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrientation, double duration)\n {\n // resize and reposition the page view, but use the current contentOffset as page origin\n // (note that the scrollview has already been resized by the time this method is called)\n SizeF pageSize = this.pageSize();\n UIView pageView = this.viewForPage( _currentPageIndex );\n this.viewForPage( _currentPageIndex ).Frame = new RectangleF( this._scView.ContentOffset.X, 0, pageSize.Width, pageSize.Height ); \n }\n public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation)\n {\n base.DidRotate (fromInterfaceOrientation);\n\n // adjust frames according to the new page size - this does not cause any visible changes\n this.layoutPages();\n this._scView.ContentOffset = new PointF( _currentPageIndex * this.pageSize().Width, 0 );\n\n //unhide\n for (int pageIndex = 0; pageIndex < this.numberOfPages(); pageIndex++) {\n if( this.isPageLoaded( pageIndex ) )\n this.viewForPage( pageIndex ).Hidden = false;\n }\n\n _rotationInProgress = false;\n } \n\n public override void DidReceiveMemoryWarning ()\n {\n //SuperHandle = DidReceiveMemoryWarning();\n if(this._pageViews != null)\n {\n // unload non-visible pages in case the memory is scarse\n for (int pageIndex = 0; pageIndex < this.numberOfPages(); pageIndex++) {\n if( pageIndex < _currentPageIndex - 1 || pageIndex > _currentPageIndex + 1 )\n if( this.isPageLoaded(pageIndex) ){\n UIView pageview = (UIView)this._pageViews[ pageIndex ];\n this._pageViews[ pageIndex ] = null;\n pageview.RemoveFromSuperview();\n }\n }\n }\n }\n public override void ViewDidUnload ()\n {\n this._pageViews = null;\n this._scView = null;\n } \n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30896/" ]
241,166
<p>Question: Is there any reason Autocomplete=off on a ASP:Textbox would not be working in IE 7?</p> <p>In case this is the best term for it, the IE Autocomplete feature is that drop down list like thing that drops down from textboxes and shows you past things you have typed in.</p> <p>I need the IE Autocomplete feature to not work at this point for a textbox that is part of a user control that works like an Ajax Autocomplete control. Problem is, when the Ajax Autocomplete selection list shows up, so does the IE Autocomplete selection box. (In cases where I might double click the textbox) I'm using this:</p> <pre><code>someTextbox.AutoCompleteType = AutoCompleteType.Disabled; </code></pre> <p>But it stills shows up. I've tried removing the items from the IE Autocomplete, but the next time I type something in and press enter, the problem reappears. Any ideas?</p> <p>Note: The textbox is rendered with the Autocomplete=off tag when viewing the source.</p> <p>Note 2: Have tried someTextbox.Attributes.Add("autocomplete", "off"); also without success</p> <p><strong>* Update, figured it out a while ago but forgot *</strong></p> <pre><code>test.AutoCompleteType = AutoCompleteType.None; </code></pre> <p>That actually works. I'm not sure what the difference is though. Suppose Ill look that up sometime.</p>
[ { "answer_id": 241172, "author": "BoboTheCodeMonkey", "author_id": 30532, "author_profile": "https://Stackoverflow.com/users/30532", "pm_score": 1, "selected": false, "text": "someTextbox.Attributes.Add(\"autocomplete\", \"off\");\n" }, { "answer_id": 241184, "author": "Lea Cohen", "author_id": 278, "author_profile": "https://Stackoverflow.com/users/278", "pm_score": 3, "selected": false, "text": "<form name=\"form1\" id=\"form1\" method=\"post\" autocomplete=\"off\">\n" }, { "answer_id": 355341, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "txtusername.AutoCompleteType = AutoCompleteType.Disabled;\n" }, { "answer_id": 863517, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 4, "selected": true, "text": "test.AutoCompleteType = AutoCompleteType.None;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21691/" ]
241,178
<p>I would like to know who is locking a file (win32). I know about <a href="http://www.dr-hoiby.com/WhoLockMe/" rel="noreferrer">WhoLockMe</a>, but I would like a <strong>command-line tool</strong> which does more or less the same thing.</p> <p>I also looked at <a href="https://stackoverflow.com/questions/208283/is-it-possible-to-programatically-find-out-what-process-is-locking-a-file-acros">this question</a>, but it seems only applicable for files opened remotely.</p>
[ { "answer_id": 30023333, "author": "MacGyver", "author_id": 640205, "author_profile": "https://Stackoverflow.com/users/640205", "pm_score": 4, "selected": false, "text": "PATH handle \"C:\\path\\path\\file.txt\"\n" }, { "answer_id": 55616304, "author": "Augustas", "author_id": 1278129, "author_profile": "https://Stackoverflow.com/users/1278129", "pm_score": 2, "selected": false, "text": "Handle.exe Ctrl+f" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13051/" ]
241,185
<p>I'd like to write a MessageConverter class that can wrap another MessageConverter. This MessageConverter would call the child converter, which is assumed to generate a TextMessage. It would take the payload and GZIP compress it, creating a BytesMessage which is ultimately returned to the sender.</p> <p>The problem is in writing fromMessage(). I can convert the payload back into the string, but then I want to create a "dummy" TextMessage to stuff the string into to then pass to the child MessageConverter's fromMessage() method. There I'm hitting a brick wall because I can't create a TextMessage without a JMS session object, and it appears that there is no way at all to get a session in this context.</p> <p>I could create additional properties to wire up more stuff to this class, but it doesn't look like I can easily even obtain a session from a JMSTemplate object, and I can't imagine what else I'd need to have.</p> <p>I am on the verge of creating a private TextMessage implementation within this code just for the purpose of wrapping a string for the child MessageConverter. That class will require tons of dummy methods to flesh out the Interface, and all of that typing makes baby Jesus cry.</p> <p>Can anyone suggest a better way?</p>
[ { "answer_id": 241695, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 2, "selected": true, "text": " private static class FakeTextMessage implements TextMessage {\n public FakeTextMessage(Message m) { this.childMessage = m; }\n private String text;\n private Message childMessage;\n public void setText(String t) { this.text = t; }\n public String getText() { return this.text; }\n\n // All the rest of the methods are simply pass-through\n // implementations of the rest of the interface, handing off to the child message.\n public void acknowledge() throws JMSException { this.childMessage.acknowledge(); }\n public void clearBody() throws JMSException { this.childMessage.clearBody(); }\n public void clearProperties() throws JMSException { this.childMessage.clearProperties(); }\n public Enumeration getPropertyNames() throws JMSException { return this.childMessage.getPropertyNames(); }\n public boolean propertyExists(String pn) throws JMSException { return this.childMessage.propertyExists(pn); }\n\n // and so on and so on\n }\n" }, { "answer_id": 242375, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 2, "selected": false, "text": "interface MessageBodyConverter {\n /** return a converted body of the original message */\n Object convert(Object body, Message originalMessage);\n}\n class MyMessageConverter implements MessageConverter {\n private final MessageBodyConverter converter;\n\n public Object fromMessage(Message message) {\n if (message instanceof ObjectMessage) {\n return converter.convert(objectMessage.getObject(), message);\n ...\n }\n}\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757/" ]
241,193
<p>Is there a .dll version of the <a href="http://t3.dotgnu.info/blog/php/messy-programmers-beware.html" rel="nofollow noreferrer">inclued</a> extension for <a href="http://us2.php.net/manual/en/intro.inclued.php" rel="nofollow noreferrer">PHP</a>? The manual's link for <a href="http://pecl4win.php.net/ext.php/php_inclued.dll" rel="nofollow noreferrer">Inclued on PECL4WIN</a> doesn't help. I don't have a compiler to build my own DLL.</p> <p>NOTE: The spelling "inclued" is correct!</p> <p>Edit: I don't have a compiler, but do know someone with one... that's really a last resort though.</p>
[ { "answer_id": 241239, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "ERROR: The DSP inclued.dsp does not exist.\n" }, { "answer_id": 243004, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": true, "text": "[13:10] <g0pz> the inclued dumpfiles will collide, because it uses PID # + increments\n[13:11] <g0pz> but command line should work ok\n[13:12] <g0pz> is the threaded apache version which'll have the same PID and well, a \"possible\" collision \n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24181/" ]
241,211
<p>I have many instances of an application installed on an IIS 6.0, Windows Server 2003 box under the same application pool. They share many of the same assemblies and can not be joined in to a single application. </p> <p>I recently added a new instance of the application and obtained a System.OutOfMemoryException when I tried to load the ASP.NET 2.0 application. </p> <p>Will using the GAC to store common assemblies fix this error or can this only be remedied by spacing the sites between different application pools?</p>
[ { "answer_id": 259427, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 1, "selected": false, "text": "<system.web>\n <!--\n <deployment\n retail = \"false\" [true|false]\n />\n --> \n <deployment retail=\"true\" />\n</system.web>\n <processModel \n memoryLimit=\"80\"\n/>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
241,222
<p>For a particular application, I need the screen saver to be disabled while it's running. The operator COULD manually turn it off, and then back on later, but the easiest thing to do would be to just keep the screen saver at bay while the application is running.</p> <p>How do I do this? I've found code for actually turning off the screen saver with SPI_SETSCREENSAVEACTIVE, but I don't think that's what I want.</p>
[ { "answer_id": 1318629, "author": "Serafeim", "author_id": 119071, "author_profile": "https://Stackoverflow.com/users/119071", "pm_score": 5, "selected": true, "text": "SetThreadExecutionState(ES_DISPLAY_REQUIRED)" }, { "answer_id": 3739684, "author": "Ohad Schneider", "author_id": 67824, "author_profile": "https://Stackoverflow.com/users/67824", "pm_score": 5, "selected": false, "text": "SetThreadExecutionState [FlagsAttribute]\npublic enum EXECUTION_STATE : uint\n{\n ES_SYSTEM_REQUIRED = 0x00000001,\n ES_DISPLAY_REQUIRED = 0x00000002,\n // Legacy flag, should not be used.\n // ES_USER_PRESENT = 0x00000004,\n ES_AWAYMODE_REQUIRED = 0x00000040,\n ES_CONTINUOUS = 0x80000000,\n}\n\npublic static class SleepUtil\n{\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);\n}\n\npublic void PreventSleep()\n{\n if (SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS\n | EXECUTION_STATE.ES_DISPLAY_REQUIRED \n | EXECUTION_STATE.ES_SYSTEM_REQUIRED \n | EXECUTION_STATE.ES_AWAYMODE_REQUIRED) == 0) //Away mode for Windows >= Vista\n SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS\n | EXECUTION_STATE.ES_DISPLAY_REQUIRED \n | EXECUTION_STATE.ES_SYSTEM_REQUIRED); //Windows < Vista, forget away mode\n}\n" }, { "answer_id": 8973275, "author": "AVladislav", "author_id": 1165149, "author_profile": "https://Stackoverflow.com/users/1165149", "pm_score": 2, "selected": false, "text": "SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS\n | EXECUTION_STATE.ES_DISPLAY_REQUIRED \n | EXECUTION_STATE.ES_SYSTEM_REQUIRED);\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ]
241,238
<p>Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?</p> <p>Thanks!</p>
[ { "answer_id": 241291, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "using System;\nusing System.Text;\nusing System.Xml;\n\nclass Test\n{\n static void Main()\n {\n string xml = @\"\n<root>\n <foo />\n <foo>\n <bar attr='value'/>\n <bar other='va' />\n </foo>\n <foo><bar /></foo>\n</root>\";\n XmlDocument doc = new XmlDocument();\n doc.LoadXml(xml);\n XmlNode node = doc.SelectSingleNode(\"//@attr\");\n Console.WriteLine(FindXPath(node));\n Console.WriteLine(doc.SelectSingleNode(FindXPath(node)) == node);\n }\n\n static string FindXPath(XmlNode node)\n {\n StringBuilder builder = new StringBuilder();\n while (node != null)\n {\n switch (node.NodeType)\n {\n case XmlNodeType.Attribute:\n builder.Insert(0, \"/@\" + node.Name);\n node = ((XmlAttribute) node).OwnerElement;\n break;\n case XmlNodeType.Element:\n int index = FindElementIndex((XmlElement) node);\n builder.Insert(0, \"/\" + node.Name + \"[\" + index + \"]\");\n node = node.ParentNode;\n break;\n case XmlNodeType.Document:\n return builder.ToString();\n default:\n throw new ArgumentException(\"Only elements and attributes are supported\");\n }\n }\n throw new ArgumentException(\"Node was not in a document\");\n }\n\n static int FindElementIndex(XmlElement element)\n {\n XmlNode parentNode = element.ParentNode;\n if (parentNode is XmlDocument)\n {\n return 1;\n }\n XmlElement parent = (XmlElement) parentNode;\n int index = 1;\n foreach (XmlNode candidate in parent.ChildNodes)\n {\n if (candidate is XmlElement && candidate.Name == element.Name)\n {\n if (candidate == element)\n {\n return index;\n }\n index++;\n }\n }\n throw new ArgumentException(\"Couldn't find element within parent\");\n }\n}\n" }, { "answer_id": 241492, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 5, "selected": false, "text": "/node()[0]/node()[2]/node()[6]/node()[1]/node()[2]\n XmlNode static int GetNodePosition(XmlNode child)\n{\n for (int i=0; i<child.ParentNode.ChildNodes.Count; i++)\n {\n if (child.ParentNode.ChildNodes[i] == child)\n {\n // tricksy XPath, not starting its positions at 0 like a normal language\n return i + 1;\n }\n }\n throw new InvalidOperationException(\"Child node somehow not found in its parent's ChildNodes property.\");\n}\n XmlNodeList IEnumerable static string GetXPathToNode(XmlNode node)\n{\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have\n // to be matched by name, not found by position\n return String.Format(\n \"{0}/@{1}\",\n GetXPathToNode(((XmlAttribute)node).OwnerElement),\n node.Name\n ); \n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n // the path to a node is the path to its parent, plus \"/node()[n]\", where \n // n is its position among its siblings.\n return String.Format(\n \"{0}/node()[{1}]\",\n GetXPathToNode(node.ParentNode),\n GetNodePosition(node)\n );\n}\n node() GetElementsByTagName" }, { "answer_id": 1033415, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " ''' <summary>\n ''' Gets the full XPath of a single node.\n ''' </summary>\n ''' <param name=\"node\"></param>\n ''' <returns></returns>\n ''' <remarks></remarks>\n Private Function GetXPath(ByVal node As Xml.XmlNode) As String\n Dim temp As String\n Dim sibling As Xml.XmlNode\n Dim previousSiblings As Integer = 1\n\n 'I dont want to know that it was a generic document\n If node.Name = \"#document\" Then Return \"\"\n\n 'Prime it\n sibling = node.PreviousSibling\n 'Perculate up getting the count of all of this node's sibling before it.\n While sibling IsNot Nothing\n 'Only count if the sibling has the same name as this node\n If sibling.Name = node.Name Then\n previousSiblings += 1\n End If\n sibling = sibling.PreviousSibling\n End While\n\n 'Mark this node's index, if it has one\n ' Also mark the index to 1 or the default if it does have a sibling just no previous.\n temp = node.Name + IIf(previousSiblings > 0 OrElse node.NextSibling IsNot Nothing, \"[\" + previousSiblings.ToString() + \"]\", \"\").ToString()\n\n If node.ParentNode IsNot Nothing Then\n Return GetXPath(node.ParentNode) + \"/\" + temp\n End If\n\n Return temp\n End Function\n" }, { "answer_id": 1925773, "author": "James Randle", "author_id": 234265, "author_profile": "https://Stackoverflow.com/users/234265", "pm_score": 2, "selected": false, "text": " private static string GetXPathToNode(XmlNode node)\n {\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have\n // to be matched by name, not found by position\n return String.Format(\n \"{0}/@{1}\",\n GetXPathToNode(((XmlAttribute)node).OwnerElement),\n node.Name\n );\n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n //get the index\n int iIndex = 1;\n XmlNode xnIndex = node;\n while (xnIndex.PreviousSibling != null) { iIndex++; xnIndex = xnIndex.PreviousSibling; }\n // the path to a node is the path to its parent, plus \"/node()[n]\", where \n // n is its position among its siblings.\n return String.Format(\n \"{0}/node()[{1}]\",\n GetXPathToNode(node.ParentNode),\n iIndex\n );\n }\n" }, { "answer_id": 7255119, "author": "René Endress", "author_id": 921292, "author_profile": "https://Stackoverflow.com/users/921292", "pm_score": 2, "selected": false, "text": "public string GetXPathToNode(XmlNode node)\n{ \n if (node.NodeType == XmlNodeType.Attribute)\n { \n // attributes have an OwnerElement, not a ParentNode; also they have \n // to be matched by name, not found by position \n return String.Format(\"{0}/@{1}\", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);\n }\n if (node.ParentNode == null)\n { \n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n\n //get the index\n int iIndex = 1;\n XmlNode xnIndex = node;\n while (xnIndex.PreviousSibling != null && xnIndex.PreviousSibling.Name == xnIndex.Name)\n {\n iIndex++;\n xnIndex = xnIndex.PreviousSibling; \n }\n\n // the path to a node is the path to its parent, plus \"/node()[n]\", where\n // n is its position among its siblings. \n return String.Format(\"{0}/{1}[{2}]\", GetXPathToNode(node.ParentNode), node.Name, iIndex);\n}\n" }, { "answer_id": 7563545, "author": "cjbarth", "author_id": 271351, "author_profile": "https://Stackoverflow.com/users/271351", "pm_score": 1, "selected": false, "text": "XDocument XDocument /home/white/bob /home/white/mike /home/white/bob/garage Private Sub NodeItterate(XDoc As XElement, XPath As String)\n 'get the deepest path\n Dim nodes As IEnumerable(Of XElement)\n\n nodes = XDoc.XPathSelectElements(XPath)\n\n 'if it doesn't exist, try the next shallow path\n If nodes.Count = 0 Then\n NodeItterate(XDoc, XPath.Substring(0, XPath.LastIndexOf(\"/\")))\n 'by this time all the required parent elements will have been constructed\n Dim ParentPath As String = XPath.Substring(0, XPath.LastIndexOf(\"/\"))\n Dim ParentNode As XElement = XDoc.XPathSelectElement(ParentPath)\n Dim NewElementName As String = XPath.Substring(XPath.LastIndexOf(\"/\") + 1, XPath.Length - XPath.LastIndexOf(\"/\") - 1)\n ParentNode.Add(New XElement(NewElementName))\n End If\n\n 'if we find there are more than 1 elements at the deepest path we have access to, we can't proceed\n If nodes.Count > 1 Then\n Throw New ArgumentOutOfRangeException(\"There are too many paths that match your expression.\")\n End If\n\n 'if there is just one element, we can proceed\n If nodes.Count = 1 Then\n 'just proceed\n End If\n\nEnd Sub\n\nPublic Sub CreateXPath(ByVal XDoc As XElement, ByVal XPath As String)\n\n If XPath.Contains(\"//\") Or XPath.Contains(\"*\") Or XPath.Contains(\".\") Then\n Throw New ArgumentException(\"Can't create a path based on searches, wildcards, or relative paths.\")\n End If\n\n If Regex.IsMatch(XPath, \"\\[\\]()@='<>\\|\") Then\n Throw New ArgumentException(\"Can't create a path based on predicates.\")\n End If\n\n 'we will process this recursively.\n NodeItterate(XDoc, XPath)\n\nEnd Sub\n" }, { "answer_id": 11888005, "author": "rugg", "author_id": 372765, "author_profile": "https://Stackoverflow.com/users/372765", "pm_score": 2, "selected": false, "text": " static string GetXpath(XmlNode node)\n {\n if (node.Name == \"#document\")\n return String.Empty;\n return GetXpath(node.SelectSingleNode(\"..\")) + \"/\" + (node.NodeType == XmlNodeType.Attribute ? \"@\":String.Empty) + node.Name;\n }\n" }, { "answer_id": 18184670, "author": "Roemer", "author_id": 2103218, "author_profile": "https://Stackoverflow.com/users/2103218", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Gets the X-Path to a given Node\n/// </summary>\n/// <param name=\"node\">The Node to get the X-Path from</param>\n/// <returns>The X-Path of the Node</returns>\npublic string GetXPathToNode(XmlNode node)\n{\n if (node.NodeType == XmlNodeType.Attribute)\n {\n // attributes have an OwnerElement, not a ParentNode; also they have \n // to be matched by name, not found by position \n return String.Format(\"{0}/@{1}\", GetXPathToNode(((XmlAttribute)node).OwnerElement), node.Name);\n }\n if (node.ParentNode == null)\n {\n // the only node with no parent is the root node, which has no path\n return \"\";\n }\n\n // Get the Index\n int indexInParent = 1;\n XmlNode siblingNode = node.PreviousSibling;\n // Loop thru all Siblings\n while (siblingNode != null)\n {\n // Increase the Index if the Sibling has the same Name\n if (siblingNode.Name == node.Name)\n {\n indexInParent++;\n }\n siblingNode = siblingNode.PreviousSibling;\n }\n\n // the path to a node is the path to its parent, plus \"/node()[n]\", where n is its position among its siblings. \n return String.Format(\"{0}/{1}[{2}]\", GetXPathToNode(node.ParentNode), node.Name, indexInParent);\n}\n" }, { "answer_id": 24452184, "author": "Plasmabubble", "author_id": 2845705, "author_profile": "https://Stackoverflow.com/users/2845705", "pm_score": 1, "selected": false, "text": "static public int GetRank( this XmlNode node )\n{\n // return 0 if unique, else return position 1...n in siblings with same name\n try\n {\n if( node is XmlElement ) \n {\n int rank = 1;\n bool alone = true, found = false;\n\n foreach( XmlNode n in node.ParentNode.ChildNodes )\n if( n.Name == node.Name ) // sibling with same name\n {\n if( n.Equals(node) )\n {\n if( ! alone ) return rank; // no need to continue\n found = true;\n }\n else\n {\n if( found ) return rank; // no need to continue\n alone = false;\n rank++;\n }\n }\n\n }\n }\n catch{}\n return 0;\n}\n\nstatic public string GetXPath( this XmlNode node )\n{\n try\n {\n if( node is XmlAttribute )\n return String.Format( \"{0}/@{1}\", (node as XmlAttribute).OwnerElement.GetXPath(), node.Name );\n\n if( node is XmlText || node is XmlCDataSection )\n return node.ParentNode.GetXPath();\n\n if( node.ParentNode == null ) // the only node with no parent is the root node, which has no path\n return \"\";\n\n int rank = node.GetRank();\n if( rank == 0 ) return String.Format( \"{0}/{1}\", node.ParentNode.GetXPath(), node.Name );\n else return String.Format( \"{0}/{1}[{2}]\", node.ParentNode.GetXPath(), node.Name, rank );\n }\n catch{}\n return \"\";\n} \n" }, { "answer_id": 26939408, "author": "Sandy", "author_id": 4254194, "author_profile": "https://Stackoverflow.com/users/4254194", "pm_score": 1, "selected": false, "text": "Sub Parse2(oSh As Long, inode As IXMLDOMNode, Optional iXstring As String = \"\", Optional indexes)\n\n\nDim chnode As IXMLDOMNode\nDim attr As IXMLDOMAttribute\nDim oXString As String\nDim chld As Long\nDim idx As Variant\nDim addindex As Boolean\nchld = 0\nidx = 0\naddindex = False\n\n\n'determine the node type:\nSelect Case inode.NodeType\n\n Case NODE_ELEMENT\n If inode.ParentNode.NodeType = NODE_DOCUMENT Then 'This gets the root node name but ignores all the namespace attributes\n oXString = iXstring & \"//\" & fp(inode.nodename)\n Else\n\n 'Need to deal with indexing. Where an element has siblings with the same nodeName,it needs to be indexed using [index], e.g swapstreams or schedules\n\n For Each chnode In inode.ParentNode.ChildNodes\n If chnode.NodeType = NODE_ELEMENT And chnode.nodename = inode.nodename Then chld = chld + 1\n Next chnode\n\n If chld > 1 Then '//inode has siblings of the same nodeName, so needs to be indexed\n 'Lookup the index from the indexes array\n idx = getIndex(inode.nodename, indexes)\n addindex = True\n Else\n End If\n\n 'build the XString\n oXString = iXstring & \"/\" & fp(inode.nodename)\n If addindex Then oXString = oXString & \"[\" & idx & \"]\"\n\n 'If type is element then check for attributes\n For Each attr In inode.Attributes\n 'If the element has attributes then extract the data pair XString + Element.Name, @Attribute.Name=Attribute.Value\n Call oSheet(oSh, oXString & \"/@\" & attr.Name, attr.Value)\n Next attr\n\n End If\n\n Case NODE_TEXT\n 'build the XString\n oXString = iXstring\n Call oSheet(oSh, oXString, inode.NodeValue)\n\n Case NODE_ATTRIBUTE\n 'Do nothing\n Case NODE_CDATA_SECTION\n 'Do nothing\n Case NODE_COMMENT\n 'Do nothing\n Case NODE_DOCUMENT\n 'Do nothing\n Case NODE_DOCUMENT_FRAGMENT\n 'Do nothing\n Case NODE_DOCUMENT_TYPE\n 'Do nothing\n Case NODE_ENTITY\n 'Do nothing\n Case NODE_ENTITY_REFERENCE\n 'Do nothing\n Case NODE_INVALID\n 'do nothing\n Case NODE_NOTATION\n 'do nothing\n Case NODE_PROCESSING_INSTRUCTION\n 'do nothing\nEnd Select\n\n'Now call Parser2 on each of inode's children.\nIf inode.HasChildNodes Then\n For Each chnode In inode.ChildNodes\n Call Parse2(oSh, chnode, oXString, indexes)\n Next chnode\nSet chnode = Nothing\nElse\nEnd If\n\nEnd Sub\n Function getIndex(tag As Variant, indexes) As Variant\n'Function to get the latest index for an xml tag from the indexes array\n'indexes array is passed from one parser function to the next up and down the tree\n\nDim i As Integer\nDim n As Integer\n\nIf IsArrayEmpty(indexes) Then\n ReDim indexes(1, 0)\n indexes(0, 0) = \"Tag\"\n indexes(1, 0) = \"Index\"\nElse\nEnd If\nFor i = 0 To UBound(indexes, 2)\n If indexes(0, i) = tag Then\n 'tag found, increment and return the index then exit\n 'also destroy all recorded tag names BELOW that level\n indexes(1, i) = indexes(1, i) + 1\n getIndex = indexes(1, i)\n ReDim Preserve indexes(1, i) 'should keep all tags up to i but remove all below it\n Exit Function\n Else\n End If\nNext i\n\n'tag not found so add the tag with index 1 at the end of the array\nn = UBound(indexes, 2)\nReDim Preserve indexes(1, n + 1)\nindexes(0, n + 1) = tag\nindexes(1, n + 1) = 1\ngetIndex = 1\n\nEnd Function\n" }, { "answer_id": 37302453, "author": "Andrei", "author_id": 2190351, "author_profile": "https://Stackoverflow.com/users/2190351", "pm_score": 1, "selected": false, "text": "var id = _currentNode.OwnerDocument.CreateAttribute(\"some_id\");\nid.Value = Guid.NewGuid().ToString();\n_currentNode.Attributes.Append(id);\n newOrOldDocument.SelectSingleNode(string.Format(\"//*[contains(@some_id,'{0}')]\", id));\n" }, { "answer_id": 44819948, "author": "Mabrouk MAHDHI", "author_id": 5536117, "author_profile": "https://Stackoverflow.com/users/5536117", "pm_score": -1, "selected": false, "text": " public static string GetFullPath(this XmlNode node)\n {\n if (node.ParentNode == null)\n {\n return \"\";\n }\n else\n {\n return $\"{GetFullPath(node.ParentNode)}\\\\{node.ParentNode.Name}\";\n }\n }\n" }, { "answer_id": 50077811, "author": "Art", "author_id": 3328922, "author_profile": "https://Stackoverflow.com/users/3328922", "pm_score": 0, "selected": false, "text": " private string GetPath(XmlElement el)\n {\n List<string> pathList = new List<string>();\n XmlNode node = el;\n while (node is XmlElement)\n {\n pathList.Add(node.Name);\n node = node.ParentNode;\n }\n pathList.Reverse();\n string[] nodeNames = pathList.ToArray();\n return String.Join(\"/\", nodeNames);\n }\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5653/" ]
241,250
<p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p> <p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p> <p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
[ { "answer_id": 2383744, "author": "James", "author_id": 266572, "author_profile": "https://Stackoverflow.com/users/266572", "pm_score": 2, "selected": false, "text": "class Citrus(models.Model):\n how_acidic = models.PositiveIntegerField(max_value=100)\n skin_color = models.CharField()\n type = models.CharField()\n\nclass TangeloManager(models.Manager):\n def get_query_set(self):\n return super(TangeloManager, self).get_query_set().filter(type='Tangelo')\n \nclass Tangelo(models.Model):\n how_acidic = models.PositiveIntegerField(max_value=100)\n skin_color = models.CharField()\n type = models.CharField()\n objects = TangeloManager()\n\n class Meta:\n # 'appname' below is going to vary with the name of your app\n db_table = u'appname_citrus'\n" }, { "answer_id": 60894618, "author": "djvg", "author_id": 4720018, "author_profile": "https://Stackoverflow.com/users/4720018", "pm_score": 5, "selected": false, "text": "proxy models.py from django.db import models\n\n\nclass Party(models.Model):\n name = models.CharField(max_length=20)\n person_attribute = models.CharField(max_length=20)\n organization_attribute = models.CharField(max_length=20)\n\n\nclass Person(Party):\n class Meta:\n proxy = True\n\n\nclass Organization(Party):\n class Meta:\n proxy = True\n Person Organization Party Person Organization Party Person Organization Party ForeignKey Party ForeignKey Address class Address(models.Model):\n party = models.ForeignKey(to=Party, on_delete=models.CASCADE)\n Address Address(party=person_instance) Address(party=organization_instance) Person.objects.all() Party Person Organization Party Person.objects.all() Person Party Person Party Organization Person Organization proxy_name ProxyManager proxy_name from django.db import models\n\n\nclass ProxyManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(proxy_name=self.model.__name__)\n\n\nclass Party(models.Model):\n proxy_name = models.CharField(max_length=20)\n name = models.CharField(max_length=20)\n person_attribute = models.CharField(max_length=20)\n organization_attribute = models.CharField(max_length=20)\n\n def save(self, *args, **kwargs):\n self.proxy_name = type(self).__name__\n super().save(*args, **kwargs)\n\n\nclass Person(Party):\n class Meta:\n proxy = True\n\n objects = ProxyManager()\n\n\nclass Organization(Party):\n class Meta:\n proxy = True\n\n objects = ProxyManager()\n Person.objects.all() Person Organization ForeignKey Party Address.party Party proxy_name address = Address(party=person_instance) address.party Party Person Party Party.__new__ class Party(models.Model):\n PROXY_FIELD_NAME = 'proxy_name'\n \n proxy_name = models.CharField(max_length=20)\n name = models.CharField(max_length=20)\n person_attribute = models.CharField(max_length=20)\n organization_attribute = models.CharField(max_length=20)\n\n def save(self, *args, **kwargs):\n \"\"\" automatically store the proxy class name in the database \"\"\"\n self.proxy_name = type(self).__name__\n super().save(*args, **kwargs)\n\n def __new__(cls, *args, **kwargs):\n party_class = cls\n try:\n # get proxy name, either from kwargs or from args\n proxy_name = kwargs.get(cls.PROXY_FIELD_NAME)\n if proxy_name is None:\n proxy_name_field_index = cls._meta.fields.index(\n cls._meta.get_field(cls.PROXY_FIELD_NAME))\n proxy_name = args[proxy_name_field_index]\n # get proxy class, by name, from current module\n party_class = getattr(sys.modules[__name__], proxy_name)\n finally:\n return super().__new__(party_class)\n address.party Person proxy_name Person inheritance/models.py import sys\nfrom django.db import models\n\n\nclass ProxySuper(models.Model):\n class Meta:\n abstract = True\n\n proxy_name = models.CharField(max_length=20)\n\n def save(self, *args, **kwargs):\n \"\"\" automatically store the proxy class name in the database \"\"\"\n self.proxy_name = type(self).__name__\n super().save(*args, **kwargs)\n\n def __new__(cls, *args, **kwargs):\n \"\"\" create an instance corresponding to the proxy_name \"\"\"\n proxy_class = cls\n try:\n field_name = ProxySuper._meta.get_fields()[0].name\n proxy_name = kwargs.get(field_name)\n if proxy_name is None:\n proxy_name_field_index = cls._meta.fields.index(\n cls._meta.get_field(field_name))\n proxy_name = args[proxy_name_field_index]\n proxy_class = getattr(sys.modules[cls.__module__], proxy_name)\n finally:\n return super().__new__(proxy_class)\n\n\nclass ProxyManager(models.Manager):\n def get_queryset(self):\n \"\"\" only include objects in queryset matching current proxy class \"\"\"\n return super().get_queryset().filter(proxy_name=self.model.__name__)\n parties/models.py from django.db import models\nfrom inheritance.models import ProxySuper, ProxyManager\n\n\nclass Party(ProxySuper):\n name = models.CharField(max_length=20)\n person_attribute = models.CharField(max_length=20)\n organization_attribute = models.CharField(max_length=20)\n\n\nclass Person(Party):\n class Meta:\n proxy = True\n\n objects = ProxyManager()\n\n\nclass Organization(Party):\n class Meta:\n proxy = True\n\n objects = ProxyManager()\n\n\nclass Placement(models.Model):\n party = models.ForeignKey(to=Party, on_delete=models.CASCADE)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
241,269
<p>I am writing a program that will be emailing reports out many (~100) clients which I want to test before I spam everyone.</p> <p>I want to do a test run against my production data and actually send the messages to a SMTP server, but I don't want the SMTP server to actually deliver the messages. I want the server to act like a real SMTP server from the perspective of my application, but instead of delivering messages, I just want it to store the messages, and log what happened.</p> <p>Is there a SMTP server specifically designed for testing purposes?</p> <p>Does anyone know of a way to configure exim or postfix to behave like I have described above</p> <p>What do you use to test a mass-email delivery?</p>
[ { "answer_id": 241355, "author": "vmarquez", "author_id": 10740, "author_profile": "https://Stackoverflow.com/users/10740", "pm_score": 0, "selected": false, "text": "/usr/lib/sendmail -bt -Ciu-testconfiguration.cf" }, { "answer_id": 253454, "author": "George", "author_id": 8803, "author_profile": "https://Stackoverflow.com/users/8803", "pm_score": 3, "selected": false, "text": "<system.net>\n <mailSettings>\n <smtp deliveryMethod=\"SpecifiedPickupDirectory\">\n <specifiedPickupDirectory pickupDirectoryLocation=\"c:\\pickupDirectory\"/>\n </smtp>\n </mailSettings>\n</system.net>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20267/" ]
241,285
<p>I'm developing an algorithm to parse a number out of a series of short-ish strings. These strings are somewhat regular, but there's a few different general forms and several exceptions. I'm trying to build a set of regexes that will handle the various forms and exceptions; I'll apply them one after another to see if I get a match.</p> <p>One of these forms goes something like this:</p> <pre><code>X (Y) Z </code></pre> <p>Where:</p> <ul> <li><code>X</code> is a number I want to capture.</li> <li><code>Z</code> is static, pre-defined text. it's basically how I determine whether this particular form is applicable or not.</li> <li><code>Y</code> is a string of unknown length and content, surrounded by parenthesis.</li> </ul> <p>Also: <code>Y</code> is optional; it doesn't always appear in a string with <code>Z</code> and <code>X</code>. So, I want to be able to extract the numbers from all of these strings:</p> <ul> <li><code>10 Z</code></li> <li><code>20 (foo) Z</code></li> <li><code>30 (bar) Z</code></li> </ul> <p>Right now, I have a regex that will capture the first one:</p> <pre><code>([0-9]+) +Z </code></pre> <p>My problem is that I don't know how to construct a regex that will match a series of characters if and only if they're enclosed in parenthesis. Can this be done in a single regex?</p>
[ { "answer_id": 241288, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 2, "selected": false, "text": "X (\\(Y\\))? Z\n" }, { "answer_id": 241292, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "([0-9]+) (\\([^)]+\\))? Z\n" }, { "answer_id": 241308, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 7, "selected": true, "text": "(\\d+)\\s+(\\(.*?\\))?\\s?Z\n ? ?: \\s ^ $" }, { "answer_id": 241337, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 5, "selected": false, "text": "^\\d+\\s?(\\([^\\)]+\\)\\s?)?Z$\n ^ = beginning of string\n\\d+ = one or more decimal characters\n\\s? = one optional whitespace\n (\\([^\\)]+\\)\\s?)?\n (.............)?\n \\([^\\)]+\\)\\s?\n\n\\( = an opening bracket\n[^\\)]+ = a series of at least one character that is not a closing bracket\n\\) = followed by a closing bracket\n\\s? = followed by one optional whitespace\n Z$\n Z = your constant string\n$ = the end of the string\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
241,311
<p>The question is if a database connection should be passed in by reference or by value?</p> <p>For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.</p> <p>I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array).</p> <p>In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?)</p> <p>So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5?</p> <pre><code>// $connection is resource function DoSomething1(&amp;$connection) { ... } function DoSomething2($connection) { ... } </code></pre>
[ { "answer_id": 241330, "author": "TJ L", "author_id": 12605, "author_profile": "https://Stackoverflow.com/users/12605", "pm_score": 3, "selected": false, "text": "<?php\nClass Factory\n{\n private static $local_db;\n\n/**\n* Open new local database connection\n*\n* @return MySql\n*/\npublic static function localDatabase() {\n if (!is_a(self::$local_db, \"MySql\")) {\n self::$local_db = new MySql(false);\n self::$local_db->connect(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);\n self::$local_db->debugging = DEBUG;\n }\n return self::$local_db;\n}\n}\n?>\n" }, { "answer_id": 241356, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "function get_connection() {\n $test = mysql_connect('localhost', 'user', 'password');\n mysql_select_db('db');\n return $test;\n}\n\n$conn1 = get_connection();\n$conn2 = get_connection(); // \"copied\" resource under PHP4\n\n$query = \"INSERT INTO test_table (id, field) VALUES ('', 'test')\";\nmysql_query($query, $conn1);\nprint mysql_insert_id($conn1).\"<br />\"; // prints 1\n\nmysql_query($query, $conn2);\nprint mysql_insert_id($conn2).\"<br />\"; // prints 2\n\nprint mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference\n" }, { "answer_id": 241613, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "$db = & Database::Connection();" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
241,325
<p>When using <code>grep --color=always</code> I can get pretty color highlighting for regex matches.</p> <p>However, <code>grep</code> only returns lines with at least one match. Instead, I am looking for a way to simply highlight regex matches, while leaving all other input alone, without dropping lines without any matches.</p> <p>I have tried to get color working with <code>sed</code>, and read the <code>grep</code> documentation, but I can't seem to get what I want.</p> <p>In case my description isnt obvious, I want:</p> <p>INPUT:</p> <ul> <li>fred</li> <li>ted</li> <li>red</li> <li>lead</li> </ul> <p>Regex:</p> <ul> <li>".*red"</li> </ul> <p>OUTPUT:</p> <ul> <li>fred ( in red )</li> <li>ted</li> <li>red ( in red )</li> <li>lead</li> </ul> <p>So that I could do:</p> <pre><code>list_stuff | color_grep "make_this_stand_out_but_dont_hide_the_rest" </code></pre> <p>EDIT:</p> <p>I have found a solution, which isn't pretty, but it works:</p> <p>Thanks to: <a href="http://www.pixelbeat.org/docs/terminal_colours/" rel="noreferrer">http://www.pixelbeat.org/docs/terminal_colours/</a></p> <p>Particularly the script (which I modified/simplified): <a href="http://www.pixelbeat.org/talks/iitui/sedgrep" rel="noreferrer">http://www.pixelbeat.org/talks/iitui/sedgrep</a></p> <pre><code>function sedgrep () { C_PATT=`echo -e '\033[33;01m'` C_NORM=`echo -e '\033[m'` sed -s "s/$1/${C_PATT}&amp;${C_NORM}/gi" } </code></pre> <p>Still looking for an easier way to do this!</p>
[ { "answer_id": 241390, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 2, "selected": false, "text": "function color_grep {\n sed s/$1/$fg[yellow]$1$terminfo[sgr0]/g\n}\n autoload colors zsh/terminfo\n" }, { "answer_id": 241547, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 1, "selected": false, "text": "function colormatch ()\n{\n tee - | grep --color=always $1 | sort | uniq\n}\n" }, { "answer_id": 241753, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 1, "selected": false, "text": "-C<num> <num> <num>" }, { "answer_id": 428659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#!/bin/sh\nwhile read line\ndo\n if test `expr \"$line\" : \"==>.*\"` -eq 0 ;\n then\n printf '\\033[0m%s\\n' \"$line\"\n else\n printf '\\033[0;31m%s\\n' \"$line\"\n fi\ndone\n" }, { "answer_id": 2254291, "author": "TJR", "author_id": 728, "author_profile": "https://Stackoverflow.com/users/728", "pm_score": 0, "selected": false, "text": "regexp=.*red\ncolours=\"\\033[38;5;160m\"\ncount=once\n" }, { "answer_id": 8726738, "author": "crenate", "author_id": 1129848, "author_profile": "https://Stackoverflow.com/users/1129848", "pm_score": 5, "selected": false, "text": "egrep --color=always 'text|^'" }, { "answer_id": 13593327, "author": "Pawel Wiejacha", "author_id": 1857778, "author_profile": "https://Stackoverflow.com/users/1857778", "pm_score": 3, "selected": false, "text": "#!/bin/bash\n\nred=$(tput bold;tput setaf 1) \ngreen=$(tput setaf 2) \nyellow=$(tput bold;tput setaf 3) \nfawn=$(tput setaf 3)\nblue=$(tput bold;tput setaf 4) \npurple=$(tput setaf 5)\npink=$(tput bold;tput setaf 5) \ncyan=$(tput bold;tput setaf 6) \ngray=$(tput setaf 7) \nwhite=$(tput bold;tput setaf 7) \nnormal=$(tput sgr0) \n\nsep=`echo -e '\\001'` # use \\001 as a separator instead of '/'\n\nwhile [ -n \"$1\" ] ; do\n color=${!1}\n pattern=\"$2\"\n shift 2\n\n rules=\"$rules;s$sep\\($pattern\\)$sep$color\\1$normal${sep}g\"\ndone\n\n#stdbuf -o0 -i0 sed -u -e \"$rules\"\nsed -u -e \"$rules\"\n ./colorize.sh color1 pattern1 color2 pattern2 ...\n dmesg | colorize.sh red '.*Hardware Error.*' red 'CPU[0-9]*: Core temperature above threshold' \\\ngreen 'wlan.: authenticated.*' yellow 'wlan.: deauthenticated.*'\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29701/" ]
241,327
<p>I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)</p> <p>I realize that I could .match() substrings with a Regex, but that doesn't solve nesting <code>/*</code>, or having a <code>//</code> inside a <code>/* */</code>.</p> <p>Ideally, I would prefer a non-naive implementation that properly handles awkward cases.</p>
[ { "answer_id": 241329, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "//.*?\\n|/\\*.*?\\*/\n Re.S def stripcomments(text):\n return re.sub('//.*?\\n|/\\*.*?\\*/', '', text, flags=re.S)\n //.*?(\\r\\n?|\\n)|/\\*.*?\\*/\n" }, { "answer_id": 241506, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 7, "selected": false, "text": "def comment_remover(text):\n def replacer(match):\n s = match.group(0)\n if s.startswith('/'):\n return \" \" # note: a space and not an empty string\n else:\n return s\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n return re.sub(pattern, replacer, text)\n int/**/x=5; intx=5;" }, { "answer_id": 242107, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "\" */ /* SCC has been trained to know about strings /* */ */\"!\n\"\\\"Double quotes embedded in strings, \\\\\\\" too\\'!\"\n\"And \\\nnewlines in them\"\n\n\"And escaped double quotes at the end of a string\\\"\"\n\naa '\\\\\nn' OK\naa \"\\\"\"\naa \"\\\n\\n\"\n\nThis is followed by C++/C99 comment number 1.\n// C++/C99 comment with \\\ncontinuation character \\\non three source lines (this should not be seen with the -C fla\nThe C++/C99 comment number 1 has finished.\n\nThis is followed by C++/C99 comment number 2.\n/\\\n/\\\nC++/C99 comment (this should not be seen with the -C flag)\nThe C++/C99 comment number 2 has finished.\n\nThis is followed by regular C comment number 1.\n/\\\n*\\\nRegular\ncomment\n*\\\n/\nThe regular C comment number 1 has finished.\n\n/\\\n\\/ This is not a C++/C99 comment!\n\nThis is followed by C++/C99 comment number 3.\n/\\\n\\\n\\\n/ But this is a C++/C99 comment!\nThe C++/C99 comment number 3 has finished.\n\n/\\\n\\* This is not a C or C++ comment!\n\nThis is followed by regular C comment number 2.\n/\\\n*/ This is a regular C comment *\\\nbut this is just a routine continuation *\\\nand that was not the end either - but this is *\\\n\\\n/\nThe regular C comment number 2 has finished.\n\nThis is followed by regular C comment number 3.\n/\\\n\\\n\\\n\\\n* C comment */\n" }, { "answer_id": 242226, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 4, "selected": true, "text": "sed import subprocess\nfrom cStringIO import StringIO\n\ninput = StringIO(source_code) # source_code is a string with the source code.\noutput = StringIO()\n\nprocess = subprocess.Popen(['sed', '/path/to/remccoms3.sed'],\n input=input, output=output)\nreturn_code = process.wait()\n\nstripped_code = output.getvalue()\n source_code stripped_code input output input output remccoms3.sed sed" }, { "answer_id": 1078484, "author": "sigjuice", "author_id": 78720, "author_profile": "https://Stackoverflow.com/users/78720", "pm_score": 1, "selected": false, "text": "cpp -fpreprocessed foo.c\n" }, { "answer_id": 5221953, "author": "slottermoser", "author_id": 647627, "author_profile": "https://Stackoverflow.com/users/647627", "pm_score": -1, "selected": false, "text": "#!/usr/bin/python\n\"\"\"\n A simple script to remove block comments of the form /** */ from files\n Use example: ./strip_comments.py *.java\n Author: holdtotherod\n Created: 3/6/11\n\"\"\"\nimport sys\nimport fileinput\n\nfor file in sys.argv[1:]:\n inBlockComment = False\n for line in fileinput.input(file, inplace = 1):\n if \"/**\" in line:\n inBlockComment = True\n if inBlockComment and \"*/\" in line:\n inBlockComment = False\n # If the */ isn't last, remove through the */\n if line.find(\"*/\") != len(line) - 3:\n line = line[line.find(\"*/\")+2:]\n else:\n continue\n if inBlockComment:\n continue\n sys.stdout.write(line)\n" }, { "answer_id": 18234680, "author": "Menno Rubingh", "author_id": 2682892, "author_profile": "https://Stackoverflow.com/users/2682892", "pm_score": 3, "selected": false, "text": "import re\n\ndef removeCCppComment( text ) :\n\n def blotOutNonNewlines( strIn ) : # Return a string containing only the newline chars contained in strIn\n return \"\" + (\"\\n\" * strIn.count('\\n'))\n\n def replacer( match ) :\n s = match.group(0)\n if s.startswith('/'): # Matched string is //...EOL or /*...*/ ==> Blot out all non-newline chars\n return blotOutNonNewlines(s)\n else: # Matched string is '...' or \"...\" ==> Keep unchanged\n return s\n\n pattern = re.compile(\n r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n\n return re.sub(pattern, replacer, text)\n" }, { "answer_id": 18996903, "author": "Antonio Arredondo", "author_id": 2608051, "author_profile": "https://Stackoverflow.com/users/2608051", "pm_score": 1, "selected": false, "text": "from subprocess import check_output\n\nclass Util:\n def strip_comments(self,source_code):\n process = check_output(['cpp', '-fpreprocessed', source_code],shell=False)\n return process \n\nif __name__ == \"__main__\":\n util = Util()\n print util.strip_comments(\"somefile.ext\")\n" }, { "answer_id": 65104145, "author": "Thiago Mata", "author_id": 456164, "author_profile": "https://Stackoverflow.com/users/456164", "pm_score": 1, "selected": false, "text": "from pygments import lex\nfrom pygments.token import Token as ParseToken\n\ndef strip_comments(replace_query, lexer):\n generator = lex(replace_query, lexer)\n line = []\n lines = []\n for token in generator:\n token_type = token[0]\n token_text = token[1]\n if token_type in ParseToken.Comment:\n continue\n line.append(token_text)\n if token_text == '\\n':\n lines.append(''.join(line))\n line = []\n if line:\n line.append('\\n')\n lines.append(''.join(line))\n strip_query = \"\\n\".join(lines)\n return strip_query\n from pygments.lexers.c_like import CLexer\n\nstrip_comments(\"class Bla /*; complicated // stuff */ example; // out\",CLexer())\n# 'class Bla example; \\n'\n from pygments.lexers.sql import SqlLexer\n\nstrip_comments(\"select * /* this is cool */ from table -- more comments\",SqlLexer())\n# 'select * from table \\n'\n from pygments.lexers.javascript import JavascriptLexer\nstrip_comments(\"function cool /* not cool*/(x){ return x++ } /** something **/ // end\",JavascriptLexer())\n# 'function cool (x){ return x++ } \\n'\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26251/" ]
241,334
<p>I need to to iterate over the files in a directory and perform the following replacement.</p> <p><strong>Before:</strong></p> <blockquote> <p>Hello ${USER_NAME}, you live at ${HOME_ADDRESS}. It is now ${TIME}</p> </blockquote> <p><strong>After:</strong></p> <blockquote> <p>Hello ${userName}, you live at ${homeAddress}. It is now ${time}</p> </blockquote> <p>The number of different tokens that appear within ${} is large, so it's not really feasible to run:</p> <pre><code>find . -name '*' -exec sed -i 's/${USER_NAME}/${userName}/g' {} \; find . -name '*' -exec sed -i 's/${TIME}/${time}/g' {} \; </code></pre> <p>etc.</p> <p>I'm hoping it's possible to perform this replacement using a single command, that looks something like:</p> <pre><code>find . -name '*' -exec sed 's/XXX/YYY/g' {} \; </code></pre> <p>But I can't figure out what to substitute for XXX and YYY. Is it possible to do this in a single command?</p> <p>Cheers, Donal</p>
[ { "answer_id": 241350, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "-i sed -i 's/USER_NAME/userName/g'\n sub convert {\n my $r = lc $_[0];\n $r =~ s/_(.)/\\U$1\\E/g;\n return $r;\n}\nwhile (<>) {\n s/\\${([A-Z_]+)}/\\${@{[convert $1]}}/g;\n print;\n}\n perl -i convert.pl inputfile.txt\n $ cat inputfile.txt\nHello ${USER_NAME}, you live at ${HOME_ADDRESS}. It is now ${TIME}\n$ perl -i convert.pl inputfile.txt\n$ cat inputfile.txt\nHello ${userName}, you live at ${homeAddress}. It is now ${time}\n" }, { "answer_id": 241386, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "sed -i '/^Hello/ { s/\\$\\{USER_NAME\\}/\\$\\{userName\\}/g \n s/\\$\\{HOME_ADDRESS\\}/\\$\\{homeAddress\\}/g \n s/\\$\\{TIME\\}/\\$\\{time\\}/g\n }'\n /^Hello/" }, { "answer_id": 241414, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 0, "selected": false, "text": "sed '/^Hello/ { s/\\$\\{USER_NAME\\}/\\$\\{userName\\}/g' <filename> \\\n | sed 's/\\$\\{HOME_ADDRESS\\}/\\$\\{homeAddress\\}/g' \\\n | sed 's/\\$\\{TIME\\}/\\$\\{time\\}/g'\n !! | sed 'yet-enother-regexp'\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
241,339
<p>Here's what <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members" rel="noreferrer">MSDN has to say under <em>When to Use Static Classes</em></a>:</p> <blockquote> <pre><code>static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... } </code></pre> <p>Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace.</p> </blockquote> <p>To me, that example doesn't seem to cover very many possible usage scenarios for static classes. In the past I've used static classes for stateless suites of related functions, but that's about it. So, under what circumstances should (and shouldn't) a class be declared static? </p>
[ { "answer_id": 241372, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 11, "selected": true, "text": "new MyClass();" }, { "answer_id": 241411, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 4, "selected": false, "text": "public static class Log\n{\n private static readonly ILoggerFactory _loggerFactory =\n IoC.Resolve<ILoggerFactory>();\n\n public static ILogger For<T>(T instance)\n {\n return For(typeof(T));\n }\n\n public static ILogger For(Type type)\n {\n return _loggerFactory.GetLoggerFor(type);\n }\n}\n" }, { "answer_id": 241481, "author": "user25306", "author_id": 25306, "author_profile": "https://Stackoverflow.com/users/25306", "pm_score": 5, "selected": false, "text": "static" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
241,364
<p>I admit - I'm a complete novice when it comes to unit testing. I can grasp the concepts easily enough (test one thing, break-fix-test-repeat, etc.), but I'm having a bit of a problem getting my mind around this one...</p> <p>I've been tasked with rewriting a large section of our application, and I've got the class structure down pretty well. We have our test projects mixed right in with the rest of the solution, and all the references are lining up the way we want them to. Unfortunately, there are a few Friend classes that can only be accessed from inside the same namespace. As it stands, the test class is not a member of this namespace, so I cannot get direct access to any of those underlying methods, which <strong>REALLY</strong> need to be tested. </p> <p>From what I've been reading, I could create a public mockup of the classes in question and test it that way, but I'm concerned that down the road someone will make a change in the production code and not copy it out to the test code, defeating the purpose of testing entirely. Another option would be to change the access level on the classes themselves, but that would involve a lot of overhead and fiddling with the code already in place. The idea of writing an interface has also come up, but creating a whole structure of interfaces for the sake of testing hasn't flown in management.</p> <p>Am I just missing something here? What would be the best way to make sure those underlying classes are indeed functioning correctly without changing the access to them?</p>
[ { "answer_id": 241383, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 2, "selected": false, "text": "InternalsVisibleTo internal [assembly: InternalsVisibleTo(\"MyApplication.Tests\")]" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2018855/" ]
241,388
<p>I'm looking at the following code snippet:</p> <pre><code>my @ret = &lt;someMethod&gt; return (undef) if( $DB_ERROR ); return (undef) unless ($#ret &gt;= 0); </code></pre> <p>Does <code>$#</code> just give you a count of elements in a array?</p>
[ { "answer_id": 241394, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 7, "selected": true, "text": "$#arrayname @ret $#ret print scalar @ret;\n" }, { "answer_id": 241462, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "$#foo scalar @foo return (undef) unless ($#ret >= 0);\n unless foo >= bar return (undef) if ($#ret < 0);\n return (undef) if scalar @ret <= 0;\n return (undef) if scalar @ret == 0;\n return (undef) if @ret == 0;\n @ret return (undef) if !@ret;\n return (undef) unless @ret;\n return undef return unless @ret;\n" }, { "answer_id": 1991038, "author": "Rob Van Dam", "author_id": 232706, "author_profile": "https://Stackoverflow.com/users/232706", "pm_score": 2, "selected": false, "text": "my @ret = someMethod();\nreturn if $DB_ERROR;\nreturn unless @ret;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31301/" ]
241,396
<p>I produce server software and have been fine with all Linux environments so far, both for production and as deployment target. However, I want to provide a broader choice of target environments in the future and I'm also planning features that would consume and produce Office documents.</p> <p>As a first step, I am looking for a good way to get a number of MS software products (XP, Vista, Server 2003 &amp; 2008, Office 2000, 2003 &amp; 2007 ...) to put on some VMs in my testing setup, so I can start to play around.</p> <p>So far, I get quite a good impression from what I read about MS's partner program (aka Action Pack). The only thing I'm missing from what the website tells me is older software versions. As I want to mimick possible customers' setups and there's always a lot of people that run older versions, that would be quite important for the testing scenario.</p> <p>Eventually, I'm going to face similar questions with Apple OS X, so if anybody has some hints on that, I'd be glad, too.</p>
[ { "answer_id": 241394, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 7, "selected": true, "text": "$#arrayname @ret $#ret print scalar @ret;\n" }, { "answer_id": 241462, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "$#foo scalar @foo return (undef) unless ($#ret >= 0);\n unless foo >= bar return (undef) if ($#ret < 0);\n return (undef) if scalar @ret <= 0;\n return (undef) if scalar @ret == 0;\n return (undef) if @ret == 0;\n @ret return (undef) if !@ret;\n return (undef) unless @ret;\n return undef return unless @ret;\n" }, { "answer_id": 1991038, "author": "Rob Van Dam", "author_id": 232706, "author_profile": "https://Stackoverflow.com/users/232706", "pm_score": 2, "selected": false, "text": "my @ret = someMethod();\nreturn if $DB_ERROR;\nreturn unless @ret;\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
241,397
<p>How do you answer the following questions from managers, testers and other people in your team:</p> <p>In what build is bug #829 fixed? What tasks have been completed in our current test build?</p> <p>So simply put, how do you achieve traceability of your requirements, tasks and bugs right from them being reported reporting through to deployment? What processes, tools and techniques are you using to achieve this?</p>
[ { "answer_id": 241419, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 3, "selected": true, "text": "Deployed On | Environment | Changeset\n--------------+-------------------------+--------------------------\n10-01-2008 | DEV | 5100\n10-01-2008 | STAGING | 5080\n10-01-2008 | STABLE | 5050\n01-01-2008 | PRODUCTION | 5000\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30874/" ]
241,402
<p>I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.</p> <pre><code>&lt;body&gt; $("body").addClass("active"); ... &lt;/body&gt; </code></pre> <p>Thanks, Steve</p>
[ { "answer_id": 241418, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<body>\n <div id='topStories'></div>\n <script type='text/javascript'>\n $('div#topStories').addClass('active');\n </script>\n</body>\n" }, { "answer_id": 241529, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n <style type=\"text/css\">\n .foobar { background-color: #CCC; }\n </style>\n</head>\n<body>\n <script type=\"text/javascript\">\n window.document.body.className = \"foobar\";\n </script>\n <div style=\"border: solid 1px\"><br /></div>\n <script type=\"text/javascript\">\n // happens before DOM is fully loaded:\n alert(window.document.body.className);\n </script>\n <span>Appears after the alert() call.</span>\n</body>\n</html>\n alert() alert()" }, { "answer_id": 241891, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<script>\n $(document).ready(function() {\n $(\"body\").addClass(\"active\");\n });\n</script>\n<body>\n ..\n ..\n ..\n</body>\n <body class=\"active\">\n</body>\n" }, { "answer_id": 241968, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 3, "selected": true, "text": "setInterval document.getElementById() id id setInterval" }, { "answer_id": 246550, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n document.documentElement.className = 'active';\n</script>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16124/" ]
241,403
<p>How do I get a list of domain user accounts with win32 api? </p> <p>In particular, I can't get this list when the computer is not the domain controller. Instead it is a member of the domain. </p>
[ { "answer_id": 241418, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<body>\n <div id='topStories'></div>\n <script type='text/javascript'>\n $('div#topStories').addClass('active');\n </script>\n</body>\n" }, { "answer_id": 241529, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<html>\n<head>\n <style type=\"text/css\">\n .foobar { background-color: #CCC; }\n </style>\n</head>\n<body>\n <script type=\"text/javascript\">\n window.document.body.className = \"foobar\";\n </script>\n <div style=\"border: solid 1px\"><br /></div>\n <script type=\"text/javascript\">\n // happens before DOM is fully loaded:\n alert(window.document.body.className);\n </script>\n <span>Appears after the alert() call.</span>\n</body>\n</html>\n alert() alert()" }, { "answer_id": 241891, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<script>\n $(document).ready(function() {\n $(\"body\").addClass(\"active\");\n });\n</script>\n<body>\n ..\n ..\n ..\n</body>\n <body class=\"active\">\n</body>\n" }, { "answer_id": 241968, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 3, "selected": true, "text": "setInterval document.getElementById() id id setInterval" }, { "answer_id": 246550, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n document.documentElement.className = 'active';\n</script>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
241,405
<p>I have a string that I need to convert to the equivalent array of bytes in .NET. </p> <p>This ought to be easy, but I am having a brain cramp.</p>
[ { "answer_id": 241408, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "System.Text.Encoding System.Text.Encoding.Unicode var result = System.Text.Encoding.Unicode.GetBytes(text);\n" }, { "answer_id": 241409, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 3, "selected": false, "text": " string test = \"text\";\n byte[] arr = Encoding.UTF8.GetBytes(test);\n" }, { "answer_id": 241459, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "byte[] bytes = System.Text.Encoding.XXX.GetBytes(text)\n XXX ASCII\nBigEndianUnicode\nDefault\nUnicode\nUTF32\nUTF7\nUTF8\n" }, { "answer_id": 241466, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "System.Text.Encoding Encoding Encoding.GetEncoding" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23862/" ]
241,407
<p>For this xml (in a SQL 2005 XML column): </p> <pre><code>&lt;doc&gt; &lt;a&gt;1&lt;/a&gt; &lt;b ba="1" bb="2" bc="3" /&gt; &lt;c bd="3"/&gt; &lt;doc&gt; </code></pre> <p>I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values <em>inside SQL Server 2005</em>. Well, XPath certainly allows this with name() but SQL doesn't support that. This is my chief complaint with using XML in SQL; you have to figure out which parts of the XML/Xpath/XQuery spec are in there. </p> <p>The only way I can think of to do this is to build a CLR proc that loads the XML into an XML Document (iirc) and runs the XPath to extract the names of the nodes. I'm open to suggestions here. </p>
[ { "answer_id": 241687, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 4, "selected": true, "text": "DECLARE @xml as xml\nDECLARE @path as varchar(max)\nDECLARE @index int, @count int\n\nSET @xml = \n'<doc>\n <a>1</a>\n <b ba=\"1\" bb=\"2\" bc=\"3\" />\n <c bd=\"3\"/>\n</doc>'\n\n\n\nSELECT @index = 1\n\nSET @count = @xml.query('count(/doc/b/@*)').value('.','int')\n\nWHILE @index <= @count \nBEGIN\n SELECT @xml.value('local-name((/doc/b/@*[sql:variable(\"@index\")])[1])', 'varchar(max)')\n SET @index = @index + 1\nEND\n" }, { "answer_id": 1667116, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "declare @xml as xml\n\nset @xml = \n'<doc>\n <a>1</a>\n <b ba=\"1\" bb=\"2\" bc=\"3\" />\n <c bd=\"3\"/>\n</doc>'\n\nselect @xml.query('\n for $attr in /doc/b/@*\n return local-name($attr)') \n" }, { "answer_id": 4156566, "author": "Ben Davis", "author_id": 504746, "author_profile": "https://Stackoverflow.com/users/504746", "pm_score": 3, "selected": false, "text": "DECLARE @xml as xml\n\nSET @xml = \n'<doc>\n <a>1</a>\n <b ba=\"1\" bb=\"2\" bc=\"3\" />\n <c bd=\"3\"/>\n</doc>'\n\nSELECT DISTINCT\n CAST(Attribute.Name.query('local-name(.)') AS VARCHAR(100)) Attribute,\n Attribute.Name.value('.','VARCHAR(100)') Value\nFROM @xml.nodes('//@*') Attribute(Name)\n" }, { "answer_id": 52220509, "author": "Mike Thompson", "author_id": 10330179, "author_profile": "https://Stackoverflow.com/users/10330179", "pm_score": 1, "selected": false, "text": "Declare @xml Xml = '<doc><a>1</a><b ba=\"1\" bb=\"2\" bc=\"3\" /><c bd=\"3\"/></doc>'\n\nSelect n.value('local-name(.)', 'varchar(max)') from @xml.nodes('/doc/*/@*') a(n)\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/241407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30946/" ]