qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
155,544
<p>I need to create a unique ID for a given location, and the location's ID must be sequential. So its basically like a primary key, except that it is also tied to the locationID. So 3 different locations will all have ID's like 1,2,3,4,5,...,n</p> <p>What is the best way to do this? I also need a safe way of getting the nextID for a given location, I'm guessing I can just put a transaction on the stored procedure that gets the next ID?</p>
[ { "answer_id": 155557, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "transaction {\n id = getId\n}\n\n... other processing\n\ntransaction {\n createRowWithNewId\n}\n" }, { "answer_id": 155592, "author": "David Smith", "author_id": 17201, "author_profile": "https://Stackoverflow.com/users/17201", "pm_score": 2, "selected": false, "text": "CREATE TABLE LocationID {\n Location varchar(32) PRIMARY KEY,\n NextID int DEFAULT(1)\n}\n" }, { "answer_id": 44853081, "author": "S3S", "author_id": 6167855, "author_profile": "https://Stackoverflow.com/users/6167855", "pm_score": 0, "selected": false, "text": "select\n locationID\n ,row_number() over (partition by locationID order by (select null)) as LocationPK\nFrom\n YourTable\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
155,560
<p>I want a function like GetCurrentThread which returns a TThread object of the current executing thread. I know there is a Win32 API call GetCurrentThread, but it returns the thread Id. If there is a possibility to get TThread object from that ID that's also fine.</p>
[ { "answer_id": 155773, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 5, "selected": false, "text": "if Windows.GetCurrentThreadId() = System.MainThreadID then\n// ...\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
155,566
<p>Please provide tips for effectively using git with svn. What are your "best practices"?</p>
[ { "answer_id": 155577, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "git svn rebase" }, { "answer_id": 155643, "author": "andy", "author_id": 21482, "author_profile": "https://Stackoverflow.com/users/21482", "pm_score": 3, "selected": true, "text": "--prefix=svn/" }, { "answer_id": 155647, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "git svn dcommit" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
155,584
<p>I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly.</p> <p>The designer is including <a href="http://stlartworks.efficionconsulting.com/Portals/6/Skins/ArtWorks/img/ProgramsHeading.png" rel="noreferrer">a file like this</a> for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i < words.length; i++) {\n print(\"<span class=\\\"color\" + c + \"\\\">\" + words[i] + \"</span> \");\n c = c + 1; if (c > 3) c = 1;\n}\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": ":first-letter" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "var message = \"The quick brown fox.\";\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\n\nfor (var i = 0; i < message.length; i++){\n document.write(\"<span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\">\" + message[i] + \"</span>\");\n}" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4318/" ]
155,586
<p>We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult).</p> <p>However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio).</p> <p>My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks.</p> <hr> <p>UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i < words.length; i++) {\n print(\"<span class=\\\"color\" + c + \"\\\">\" + words[i] + \"</span> \");\n c = c + 1; if (c > 3) c = 1;\n}\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": ":first-letter" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "var message = \"The quick brown fox.\";\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\n\nfor (var i = 0; i < message.length; i++){\n document.write(\"<span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\">\" + message[i] + \"</span>\");\n}" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23234/" ]
155,593
<p>Is there a way to determine the number of users that have active sessions in an ASP.NET application? I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user.</p>
[ { "answer_id": 659879, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": false, "text": "void Application_Start(object sender, EventArgs e)\n{\n // Code that runs on application startup\n Application[\"OnlineUsers\"] = 0;\n}\n\nvoid Session_Start(object sender, EventArgs e)\n{\n // Code that runs when a new session is started\n Application.Lock();\n Application[\"OnlineUsers\"] = (int)Application[\"OnlineUsers\"] + 1;\n Application.UnLock();\n}\n\nvoid Session_End(object sender, EventArgs e)\n{\n // Code that runs when a session ends. \n // Note: The Session_End event is raised only when the sessionstate \n // mode is set to InProc in the Web.config file. \n // If session mode is set to StateServer or SQLServer, \n // the event is not raised.\n Application.Lock();\n Application[\"OnlineUsers\"] = (int)Application[\"OnlineUsers\"] - 1;\n Application.UnLock();\n}\n" }, { "answer_id": 659909, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "Membership.GetNumberOfUsersOnline()\n" }, { "answer_id": 18960415, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 0, "selected": false, "text": "void Main()\n{\n var pc = new PerformanceCounter(\"ASP.NET Applications\", \"Sessions Active\", \"__Total__\");\n\n Console.WriteLine(pc.NextValue());\n}\n" }, { "answer_id": 51016352, "author": "Mojtaba Madadyar", "author_id": 5353426, "author_profile": "https://Stackoverflow.com/users/5353426", "pm_score": 2, "selected": false, "text": "SELECT Count(*) As Onlines FROM ASPStateTempSessions WHERE Expires>getutcdate()\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23886/" ]
155,609
<p>Can someone provide a simple explanation of <strong>methods</strong> vs. <strong>functions</strong> in OOP context?</p>
[ { "answer_id": 155648, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 3, "selected": false, "text": "class Example\n{\n public int data = 0; // Each instance of Example holds its internal data. This is a \"field\", or \"member variable\".\n\n public void UpdateData() // .. and manipulates it (This is a method by the way)\n {\n data = data + 1;\n }\n\n public void PrintData() // This is also a method\n {\n Console.WriteLine(data);\n }\n}\n\nclass Program\n{\n public static void Main()\n {\n Example exampleObject1 = new Example();\n Example exampleObject2 = new Example();\n\n exampleObject1.UpdateData();\n exampleObject1.UpdateData();\n\n exampleObject2.UpdateData();\n\n exampleObject1.PrintData(); // Prints \"2\"\n exampleObject2.PrintData(); // Prints \"1\"\n }\n}\n" }, { "answer_id": 155700, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": false, "text": "employe whatAreYouDoing.\n" }, { "answer_id": 155722, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 7, "selected": false, "text": "class Door:\n def open(self):\n print 'hello stranger'\n\ndef knock_door():\n a_door = Door()\n Door.open(a_door)\n\nknock_door()\n" }, { "answer_id": 155767, "author": "Bradley Mazurek", "author_id": 10737, "author_profile": "https://Stackoverflow.com/users/10737", "pm_score": 4, "selected": false, "text": "f(x,y) = sin(x) + cos(y)\n" }, { "answer_id": 155827, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "# perfectly normal function\ndef hello(greetee):\n print \"Hello\", greetee\n\n# generalise a bit (still a function though)\ndef greet(greeting, greetee):\n print greeting, greetee\n\n# hide the greeting behind a layer of abstraction (still a function!)\ndef greet_with_greeter(greeter, greetee):\n print greeter.greeting, greetee\n\n# very simple class we can pass to greet_with_greeter\nclass Greeter(object):\n def __init__(self, greeting):\n self.greeting = greeting\n\n # while we're at it, here's a method that uses self.greeting...\n def greet(self, greetee):\n print self.greeting, greetee\n\n# save an object of class Greeter for later\nhello_greeter = Greeter(\"Hello\")\n\n# now all of the following print the same message\nhello(\"World\")\ngreet(\"Hello\", \"World\")\ngreet_with_greeter(hello_greeter, \"World\")\nhello_greeter.greet(\"World\")\n" }, { "answer_id": 10138680, "author": "Dirk Schumacher", "author_id": 845117, "author_profile": "https://Stackoverflow.com/users/845117", "pm_score": 3, "selected": false, "text": "new Employer().calculateSum( 8, 8 );\n" }, { "answer_id": 21594420, "author": "Abdullah Leghari", "author_id": 2091803, "author_profile": "https://Stackoverflow.com/users/2091803", "pm_score": 4, "selected": false, "text": "result = mySum(num1, num2);\n" }, { "answer_id": 34734498, "author": "Jaimin Patel", "author_id": 3396808, "author_profile": "https://Stackoverflow.com/users/3396808", "pm_score": 4, "selected": false, "text": "public void DoSomething() {} // method\npublic int DoSomethingAndReturnMeANumber(){} // function\n" }, { "answer_id": 46471318, "author": "Lahar Shah", "author_id": 5236174, "author_profile": "https://Stackoverflow.com/users/5236174", "pm_score": 2, "selected": false, "text": "test(20, 50);" }, { "answer_id": 47838166, "author": "Siraj Alam", "author_id": 5132337, "author_profile": "https://Stackoverflow.com/users/5132337", "pm_score": 2, "selected": false, "text": "constructor" }, { "answer_id": 58048948, "author": "Sapphire_Brick", "author_id": 11714860, "author_profile": "https://Stackoverflow.com/users/11714860", "pm_score": 1, "selected": false, "text": "# function\ndef putSqr(a)\n puts a ** 2\nend\n\n\nclass Math2\n # method\n def putSqr(a)\n puts a ** 2\n end\nend\n\n" }, { "answer_id": 59421186, "author": "yogendra saxena", "author_id": 6144937, "author_profile": "https://Stackoverflow.com/users/6144937", "pm_score": 2, "selected": false, "text": "\nfunction sum(){\n console.log(\"sum\")l\n}\n" }, { "answer_id": 60544808, "author": "raiks", "author_id": 412965, "author_profile": "https://Stackoverflow.com/users/412965", "pm_score": 2, "selected": false, "text": "class User {\n public string name; // I made it public intentionally\n\n // Each instance method takes a hidden reference to \"this\"\n public void printName(/*User & this*/) {\n cout << this.name << endl;\n }\n};\n" }, { "answer_id": 65513101, "author": "user1742529", "author_id": 1742529, "author_profile": "https://Stackoverflow.com/users/1742529", "pm_score": 2, "selected": false, "text": "method" }, { "answer_id": 68731476, "author": "Md. Raju Ahmed", "author_id": 14135563, "author_profile": "https://Stackoverflow.com/users/14135563", "pm_score": 1, "selected": false, "text": "method" }, { "answer_id": 70417274, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 1, "selected": false, "text": "self" }, { "answer_id": 74326977, "author": "devsam247", "author_id": 6138547, "author_profile": "https://Stackoverflow.com/users/6138547", "pm_score": 0, "selected": false, "text": "//firstName() is the function\n\nfunction firstName(){\n cosole.log('John');\n}\n\nfirstName() //Invoked without any object\n\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23973/" ]
155,610
<p>I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?</p>
[ { "answer_id": 155611, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 5, "selected": false, "text": "int code = 2;\nEnvironment.Exit( code );\n" }, { "answer_id": 155613, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 5, "selected": false, "text": "System.Environment.ExitCode \n" }, { "answer_id": 155614, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 4, "selected": false, "text": "int Main(string[] args)\n{\n return 0; // Or exit code of your choice\n}\n" }, { "answer_id": 155619, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 10, "selected": true, "text": "Main" }, { "answer_id": 156134, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 8, "selected": false, "text": "enum ExitCode : int {\n Success = 0,\n InvalidLogin = 1,\n InvalidFilename = 2,\n UnknownError = 10\n}\n\nint Main(string[] args) {\n return (int)ExitCode.Success;\n}\n" }, { "answer_id": 8220145, "author": "David", "author_id": 342994, "author_profile": "https://Stackoverflow.com/users/342994", "pm_score": 3, "selected": false, "text": "enum ExitCodes : int\n{\n Success = 0,\n SignToolNotInPath = 1,\n AssemblyDirectoryBad = 2,\n PFXFilePathBad = 4,\n PasswordMissing = 8,\n SignFailed = 16,\n UnknownError = 32\n}\n" }, { "answer_id": 8230568, "author": "Aron Tsang", "author_id": 1060255, "author_profile": "https://Stackoverflow.com/users/1060255", "pm_score": 5, "selected": false, "text": "[Flags]\nenum ExitCodes : int\n{\n Success = 0,\n SignToolNotInPath = 1,\n AssemblyDirectoryBad = 2,\n PFXFilePathBad = 4,\n PasswordMissing = 8,\n SignFailed = 16,\n UnknownError = 32\n}\n" }, { "answer_id": 12134636, "author": "Scott Munro", "author_id": 81595, "author_profile": "https://Stackoverflow.com/users/81595", "pm_score": 6, "selected": false, "text": "Main" }, { "answer_id": 38873670, "author": "Fred Mauroy", "author_id": 2988301, "author_profile": "https://Stackoverflow.com/users/2988301", "pm_score": 2, "selected": false, "text": "net helpmsg decimal_code\n" }, { "answer_id": 39986501, "author": "Vern DeHaven", "author_id": 4598767, "author_profile": "https://Stackoverflow.com/users/4598767", "pm_score": 3, "selected": false, "text": "Main" }, { "answer_id": 54960642, "author": "Swastik Bhattacharyya", "author_id": 9818599, "author_profile": "https://Stackoverflow.com/users/9818599", "pm_score": 1, "selected": false, "text": "Environment.Exit(0);\n" }, { "answer_id": 64406231, "author": "isxaker", "author_id": 364429, "author_profile": "https://Stackoverflow.com/users/364429", "pm_score": -1, "selected": false, "text": "public static class ApplicationExitCodes\n{\n public static readonly int Failure = 1;\n public static readonly int Success = 0;\n}\n" }, { "answer_id": 68150110, "author": "Victor Petrov", "author_id": 15942876, "author_profile": "https://Stackoverflow.com/users/15942876", "pm_score": 0, "selected": false, "text": "int exitCode = 0;\nEnvironment.Exit(exitCode);\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
155,615
<p>I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't?</p>
[ { "answer_id": 157042, "author": "James", "author_id": 21677, "author_profile": "https://Stackoverflow.com/users/21677", "pm_score": 2, "selected": false, "text": "<noscript>" }, { "answer_id": 4316596, "author": "Master Morality", "author_id": 304299, "author_profile": "https://Stackoverflow.com/users/304299", "pm_score": 0, "selected": false, "text": "<noscript>" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
155,649
<p>What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: <code>xValues</code> and <code>yValues</code>. (I'm trying to get the coordinates so I can animate an object along a path.)</p> <p><strong>Here's what I have so far:</strong></p> <pre><code>circle: function(radius, steps, centerX, centerY){ var xValues = [centerX]; var yValues = [centerY]; for (var i = 1; i &lt; steps; i++) { xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2)); yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2)); } } </code></pre>
[ { "answer_id": 155653, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "+ sin(...)" }, { "answer_id": 155662, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "function circle(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n var table=\"<tr><th>Step</th><th>X</th><th>Y</th></tr>\";\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.fillStyle = \"red\"\n ctx.beginPath();\n for (var i = 0; i <= steps; i++) {\n var radian = (2*Math.PI) * (i/steps);\n xValues[i+1] = centerX + radius * Math.cos(radian);\n yValues[i+1] = centerY + radius * Math.sin(radian);\n if(0==i){ctx.moveTo(xValues[i+1],yValues[i+1]);}else{ctx.lineTo(xValues[i+1],yValues[i+1]);}\n table += \"<tr><td>\" + i + \"</td><td>\" + xValues[i+1] + \"</td><td>\" + yValues[i+1] + \"</td></tr>\";\n }\n ctx.fill();\n return table;\n}\ndocument.body.innerHTML=\"<canvas id=\\\"canvas\\\" width=\\\"300\\\" height=\\\"300\\\"></canvas><table id=\\\"table\\\"/>\";\ndocument.getElementById(\"table\").innerHTML+=circle(150,15,150,150);\n" }, { "answer_id": 155678, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 0, "selected": false, "text": "circle: function(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n for (var i = 1; i < steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps*2-Math.PI/2));\n yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps*2-Math.PI/2));\n }\n}\n" }, { "answer_id": 155680, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": true, "text": "for (var i = 0; i < steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));\n yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));\n}\n" }, { "answer_id": 155688, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "Math.PI * i / steps\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
155,669
<p>I have Flex based consumer <a href="http://www.rollingrazor.com" rel="nofollow noreferrer">website</a> where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales. </p> <p>For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated.</p> <p>I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor.</p> <p>I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs.</p> <p>Any suggestions? </p>
[ { "answer_id": 627904, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 2, "selected": false, "text": "+----------------\n| User\n+----------------\n| UserId (PK)\n| ...\n+----------------\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
155,670
<p>I want to invert a 4x4 matrix. My numbers are stored in fixed-point format (1.15.16 to be exact).</p> <p>With floating-point arithmetic I usually just build the adjoint matrix and divide by the determinant (e.g. brute force the solution). That worked for me so far, but when dealing with fixed point numbers I get an unacceptable precision loss due to all of the multiplications used. </p> <p>Note: In fixed point arithmetic I always throw away some of the least significant bits of immediate results.</p> <p>So - What's the most numerical stable way to invert a matrix? I don't mind much about the performance, but simply going to floating-point would be to slow on my target architecture.</p>
[ { "answer_id": 155705, "author": "Adrian", "author_id": 23624, "author_profile": "https://Stackoverflow.com/users/23624", "pm_score": 4, "selected": false, "text": "[ux vx wx tx]\n[uy vy wy ty]\n[uz vz wz tz]\n[ 0 0 0 1]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
155,681
<p>I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to &amp;nbsp and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!</p>
[ { "answer_id": 155698, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 5, "selected": true, "text": "pre" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23976/" ]
155,685
<p>I need to replace the contents of a node in an XElement hierarchy when the element name and all the attribute names and values match an input element. (If there is no match, the new element can be added.)</p> <p>For example, if my data looks like this:</p> <pre><code>&lt;root&gt; &lt;thing1 a1="a" a2="b"&gt;one&lt;/thing1&gt; &lt;thing2 a1="a" a2="a"&gt;two&lt;/thing2&gt; &lt;thing2 a1="a" a3="b"&gt;three&lt;/thing2&gt; &lt;thing2 a1="a"&gt;four&lt;/thing2&gt; &lt;thing2 a1="a" a2="b"&gt;five&lt;/thing2&gt; &lt;root&gt; </code></pre> <p>I want to find the last element when I call a method with this input:</p> <pre><code>&lt;thing2 a1="a" a2="b"&gt;new value&lt;/thing2&gt; </code></pre> <p>The method should have no hard-coded element or attribute names - it simply matches the input to the data.</p>
[ { "answer_id": 155787, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "public static void ReplaceOrAdd(this XElement source, XElement node)\n{\n var q = from x in source.Elements()\n where x.Name == node.Name\n && x.Attributes().All(a =>node.Attributes().Any(b =>a.Name==b.Name && a.Value==b.Value))\n select x;\n\n var n = q.LastOrDefault();\n\n if (n == null) source.Add(node);\n else n.ReplaceWith(node); \n}\n\nvar root = XElement.Parse(data);\nvar newElem =XElement.Parse(\"<thing2 a1=\\\"a\\\" a2=\\\"b\\\">new value</thing2>\");\n\nroot.ReplaceOrAdd(newElem);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14842/" ]
155,706
<p>I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionality is important in easing the task of implementation and translation.</p>
[ { "answer_id": 426915, "author": "Gabriel Sosa", "author_id": 31039, "author_profile": "https://Stackoverflow.com/users/31039", "pm_score": 1, "selected": false, "text": "<?php\ninclude('lang/en.php');\ninclude('lang/en_us.php'); // this file overrides few keys from the last one.\n?>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11979/" ]
155,712
<p>Here's my problem - I have some code like this:</p> <pre><code>&lt;mx:Canvas width="300" height="300"&gt; &lt;mx:Button x="800" /&gt; &lt;/mx:Canvas&gt; </code></pre> <p>So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button.</p> <p>What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas. How do I do that?</p>
[ { "answer_id": 155817, "author": "Paul Mignard", "author_id": 3435, "author_profile": "https://Stackoverflow.com/users/3435", "pm_score": 4, "selected": true, "text": "<mx:Canvas width=\"300\" height=\"300\" clipContent=\"false\" >\n <mx:Button x=\"800\" />\n</mx:Canvas>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
155,719
<p>Internationalizing web apps always seems to be a chore. No matter how much you plan ahead for pluggable languages, there's always issues with encoding, funky phrasing that doesn't fit your templates, and other problems.</p> <p>I think it would be useful to get the SO community's input for a set of things that programmers should look out for when deciding to internationalize their web apps.</p>
[ { "answer_id": 157833, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "Click here\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14032/" ]
155,721
<p>Please post a working source code example (or link) of how to search string in another process memory and getting offset of match if found. The similar way its done in game cheating utils which search for values in game memory using ReadProcessMemory.</p>
[ { "answer_id": 157833, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "Click here\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21582/" ]
155,739
<p>I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.</p> <p>Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.</p>
[ { "answer_id": 155760, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": false, "text": "<script language=\"javascript\">\n var isDirty = false;\n\n function setDirty() {\n isDirty = true;\n }\n\n function checkSave() {\n var sSave;\n if (isDirty == true) {\n sSave = window.confirm(\"You have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.\");\n if (sSave == true) {\n document.getElementById('__EVENTTARGET').value = 'btnSubmit';\n document.getElementById('__EVENTARGUMENT').value = 'Click'; \n window.document.formName.submit();\n } else {\n return true;\n }\n }\n }\n</script>\n<body class=\"StandardBody\" onunload=\"checkSave()\">\n" }, { "answer_id": 155776, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<body onLoad=\"lookForChanges()\" onBeforeUnload=\"return warnOfUnsavedChanges()\">\n<form>\n<select name=a multiple>\n <option value=1>1\n <option value=2>2\n <option value=3>3\n</select>\n<input name=b value=123>\n<input type=submit>\n</form>\n\n<script>\nvar changed = 0;\nfunction recordChange() {\n changed = 1;\n}\nfunction recordChangeIfChangeKey(myevent) {\n if (myevent.which && !myevent.ctrlKey && !myevent.ctrlKey)\n recordChange(myevent);\n}\nfunction ignoreChange() {\n changed = 0;\n}\nfunction lookForChanges() {\n var origfunc;\n for (i = 0; i < document.forms.length; i++) {\n for (j = 0; j < document.forms[i].elements.length; j++) {\n var formField=document.forms[i].elements[j];\n var formFieldType=formField.type.toLowerCase();\n if (formFieldType == 'checkbox' || formFieldType == 'radio') {\n addHandler(formField, 'click', recordChange);\n } else if (formFieldType == 'text' || formFieldType == 'textarea') {\n if (formField.attachEvent) {\n addHandler(formField, 'keypress', recordChange);\n } else {\n addHandler(formField, 'keypress', recordChangeIfChangeKey);\n }\n } else if (formFieldType == 'select-multiple' || formFieldType == 'select-one') {\n addHandler(formField, 'change', recordChange);\n }\n }\n addHandler(document.forms[i], 'submit', ignoreChange);\n }\n}\nfunction warnOfUnsavedChanges() {\n if (changed) {\n if (\"event\" in window) //ie\n event.returnValue = 'You have unsaved changes on this page, which will be discarded if you leave now. Click \"Cancel\" in order to save them first.';\n else //netscape\n return false;\n }\n}\nfunction addHandler(target, eventName, handler) {\n if (target.attachEvent) {\n target.attachEvent('on'+eventName, handler);\n } else {\n target.addEventListener(eventName, handler, false);\n }\n}\n</script>\n" }, { "answer_id": 155812, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "/**\n * Determines if a form is dirty by comparing the current value of each element\n * with its default value.\n *\n * @param {Form} form the form to be checked.\n * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>\n * otherwise.\n */\nfunction formIsDirty(form) {\n for (var i = 0; i < form.elements.length; i++) {\n var element = form.elements[i];\n var type = element.type;\n if (type == \"checkbox\" || type == \"radio\") {\n if (element.checked != element.defaultChecked) {\n return true;\n }\n }\n else if (type == \"hidden\" || type == \"password\" ||\n type == \"text\" || type == \"textarea\") {\n if (element.value != element.defaultValue) {\n return true;\n }\n }\n else if (type == \"select-one\" || type == \"select-multiple\") {\n for (var j = 0; j < element.options.length; j++) {\n if (element.options[j].selected !=\n element.options[j].defaultSelected) {\n return true;\n }\n }\n }\n }\n return false;\n}\n" }, { "answer_id": 155841, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 8, "selected": true, "text": "var _isDirty = false;\n$(\"input[type='text']\").change(function(){\n _isDirty = true;\n});\n// replicate for other input types and selects\n" }, { "answer_id": 160493, "author": "mde", "author_id": 22440, "author_profile": "https://Stackoverflow.com/users/22440", "pm_score": 1, "selected": false, "text": "fleegix.form.diff" }, { "answer_id": 906026, "author": "reto", "author_id": 102200, "author_profile": "https://Stackoverflow.com/users/102200", "pm_score": 3, "selected": false, "text": "/* use this function to announce changes from your own scripts/event handlers.\n * Example: onClick=\"makeDirty($(this).up('form'));\"\n */\nfunction makeDirty(form) {\n form.fire(\"form:changed\");\n}\n\nfunction handleChange(form, event) {\n makeDirty(form);\n}\n\n/* generic form observer, ensure that form:changed is being fired whenever\n * a field is being changed in that particular for\n */\nfunction setupFormChangeObserver(form) {\n var handler = handleChange.curry(form);\n\n form.getElements().each(function (element) {\n element.observe(\"change\", handler);\n });\n}\n\n/* installs a form protector to a form marked with class 'protectForm' */\nfunction setupProtectForm() {\n var form = $$(\"form.protectForm\").first();\n\n /* abort if no form */\n if (!form) return;\n\n setupFormChangeObserver(form);\n\n var dirty = false;\n form.observe(\"form:changed\", function(event) {\n dirty = true;\n });\n\n /* submitting the form makes the form clean again */\n form.observe(\"submit\", function(event) {\n dirty = false;\n });\n\n /* unfortunatly a propper event handler doesn't appear to work with IE and Safari */\n window.onbeforeunload = function(event) {\n if (dirty) {\n return \"There are unsaved changes, they will be lost if you leave now.\";\n }\n };\n}\n\ndocument.observe(\"dom:loaded\", setupProtectForm);\n" }, { "answer_id": 1744350, "author": "Colin Houghton", "author_id": 212333, "author_profile": "https://Stackoverflow.com/users/212333", "pm_score": 3, "selected": false, "text": "dataChanged = 0; // global variable flags unsaved changes \n\nfunction bindForChange(){ \n $('input,checkbox,textarea,radio,select').bind('change',function(event) { dataChanged = 1})\n $(':reset,:submit').bind('click',function(event) { dataChanged = 0 })\n}\n\n\nfunction askConfirm(){ \n if (dataChanged){ \n return \"You have some unsaved changes. Press OK to continue without saving.\" \n }\n}\n\nwindow.onbeforeunload = askConfirm;\nwindow.onload = bindForChange;\n" }, { "answer_id": 9272081, "author": "PeterX", "author_id": 845584, "author_profile": "https://Stackoverflow.com/users/845584", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n var _isDirty = false;\n $(document).ready(function () { \n\n // Set exclude CSS class on radio-button list elements\n $('table.srSearch input:radio').addClass(\"srSearch\");\n\n $(\"input[type='text'],input[type='radio'],select,textarea\").not(\".srSearch\").change(function () {\n _isDirty = true;\n });\n });\n\n $(window).bind('beforeunload', function () {\n if (_isDirty) {\n return 'You have unsaved changes.';\n }\n }); \n" }, { "answer_id": 19525717, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 3, "selected": false, "text": "function formUnloadPrompt(formSelector) {\n var formA = $(formSelector).serialize(), formB, formSubmit = false;\n\n // Detect Form Submit\n $(formSelector).submit( function(){\n formSubmit = true;\n });\n\n // Handle Form Unload \n window.onbeforeunload = function(){\n if (formSubmit) return;\n formB = $(formSelector).serialize();\n if (formA != formB) return \"Your changes have not been saved.\";\n };\n}\n\n$(function(){\n formUnloadPrompt('form');\n});\n" }, { "answer_id": 24624798, "author": "Ankit", "author_id": 2353426, "author_profile": "https://Stackoverflow.com/users/2353426", "pm_score": 2, "selected": false, "text": " var unsaved = false;\n $(\":input\").change(function () { \n unsaved = true;\n });\n\n function unloadPage() { \n if (unsaved) { \n alert(\"You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?\");\n }\n } \n" }, { "answer_id": 27482349, "author": "v.babak", "author_id": 2400627, "author_profile": "https://Stackoverflow.com/users/2400627", "pm_score": 2, "selected": false, "text": "var formInitVal = $('#formId').serialize(); // detect form init value after form is displayed\n\n// check for form changes\nif ($('#formId').serialize() != formInitVal) {\n // show confirmation alert\n}\n" }, { "answer_id": 30374461, "author": "MhdSyrwan", "author_id": 923894, "author_profile": "https://Stackoverflow.com/users/923894", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n $('form :input').change(function() {\n $(this).closest('form').addClass('form-dirty');\n });\n\n $(window).bind('beforeunload', function() {\n if($('form:not(.ignore-changes).form-dirty').length > 0) {\n return 'You have unsaved changes, are you sure you want to discard them?';\n }\n });\n\n $('form').bind('submit',function() {\n $(this).closest('form').removeClass('form-dirty');\n return true;\n });\n});\n" }, { "answer_id": 31238701, "author": "Krupall", "author_id": 2003093, "author_profile": "https://Stackoverflow.com/users/2003093", "pm_score": 0, "selected": false, "text": " $(document).ready(function () {\n $(window).bind(\"load\", function () { \n $(\"input, select\").change(function () {});\n });\n});\n" }, { "answer_id": 64871468, "author": "darryn.ten", "author_id": 618172, "author_profile": "https://Stackoverflow.com/users/618172", "pm_score": 1, "selected": false, "text": "let dirty = false\ndocument.querySelectorAll('form').forEach(e => e.onchange = () => dirty = true)\n" }, { "answer_id": 73828635, "author": "dfcii", "author_id": 15461890, "author_profile": "https://Stackoverflow.com/users/15461890", "pm_score": 0, "selected": false, "text": "dataChanged = 0; // global variable flags unsaved changes\n\nfunction bindForChange() {\n $(\"input,checkbox,textarea,radio,select\").bind(\"change\", function (_event) {\n dataChanged = 1;\n });\n $(\":reset,:submit\").bind(\"click\", function (_event) {\n dataChanged = 0;\n });\n}\n\nfunction askConfirm() {\n if (dataChanged) {\n var message =\n \"You have some unsaved changes. Press OK to continue without saving.\";\n return message;\n }\n}\n\nwindow.onbeforeunload = askConfirm;\n\nwindow.onload = bindForChange;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637/" ]
155,740
<p>I am working on an application that will sport a web-based point of sale interface.</p> <p>The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN.</p> <p>I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option.</p> <p>I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server.</p> <p>Any ideas?</p>
[ { "answer_id": 155782, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;\nPrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();\naset.add(MediaSizeName.ISO_A4);\nPrintService[] pservices =\n PrintServiceLookup.lookupPrintServices(flavor, aset);\nif (pservices.length > 0) {\n DocPrintJob pj = pservices[0].createPrintJob();\n // InputStreamDoc is an implementation of the Doc interface //\n Doc doc = new InputStreamDoc(\"test.ps\", flavor);\n try {\n pj.print(doc, aset);\n } catch (PrintException e) { \n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22116/" ]
155,751
<p>In my php web app, suppose I want to go the extra mile and in addition to going gang-busters and being anal-retentive about sanitizing my inputs, I also want to ensure that no JavaScript is being output in strings I am inserting into html templates. </p> <p>Is there a standard way to make sure I don't put JavaScript in the generated html content?</p>
[ { "answer_id": 155768, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 0, "selected": false, "text": "<img src=\"${path}\">" }, { "answer_id": 158346, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "$output = strip_tags($input);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
155,780
<p>What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?</p>
[ { "answer_id": 27453342, "author": "Mike Ness", "author_id": 4286419, "author_profile": "https://Stackoverflow.com/users/4286419", "pm_score": 4, "selected": false, "text": "static class Examples\n{\n static void Example1_SafeUserToken()\n {\n const string user = \"SomeLocalUser\";\n const string domain = null;\n const string password = \"ExamplePassword\";\n NativeMethods.SafeTokenHandle userToken;\n WindowsIdentity identity;\n\n NativeMethods.LogonUser(user, domain, password, NativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out userToken);\n\n using (userToken)\n {\n // get a WindowsIdentity object for the user\n // WindowsIdentity will duplicate the token, so it is safe to free the original token after this is called\n identity = userToken.GetWindowsIdentity();\n }\n\n // impersonate the user\n using (identity)\n using (WindowsImpersonationContext impersonationContext = identity.Impersonate())\n {\n Console.WriteLine(\"I'm running as {0}!\", Thread.CurrentPrincipal.Identity.Name);\n }\n }\n\n static void Example2_SafeLocalAllocWStrArray()\n {\n const string commandLine = \"/example /command\";\n int argc;\n string[] args;\n\n using (NativeMethods.SafeLocalAllocWStrArray argv = NativeMethods.CommandLineToArgvW(commandLine, out argc))\n {\n // CommandLineToArgvW returns NULL on failure; since SafeLocalAllocWStrArray inherits from\n // SafeHandleZeroOrMinusOneIsInvalid, it will see this value as invalid\n // if that happens, throw an exception containing the last Win32 error that occurred\n if (argv.IsInvalid)\n {\n int lastError = Marshal.GetHRForLastWin32Error();\n throw new Win32Exception(lastError, \"An error occurred when calling CommandLineToArgvW.\");\n }\n\n // the one unsafe aspect of this is that the developer calling this function must be trusted to\n // pass in an array of length argc or specify the length of the copy as the value of argc\n // if the developer does not do this, the array may end up containing some garbage or an\n // AccessViolationException could be thrown\n args = new string[argc];\n argv.CopyTo(args);\n }\n\n for (int i = 0; i < args.Length; ++i)\n {\n Console.WriteLine(\"Argument {0}: {1}\", i, args[i]);\n }\n }\n}\n\n/// <summary>\n/// P/Invoke methods and helper classes used by this example.\n/// </summary>\ninternal static class NativeMethods\n{\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeTokenHandle phToken);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern bool CloseHandle(IntPtr handle);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx\n [DllImport(\"shell32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n public static extern SafeLocalAllocWStrArray CommandLineToArgvW(string lpCmdLine, out int pNumArgs);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366730(v=vs.85).aspx\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern IntPtr LocalFree(IntPtr hLocal);\n\n /// <summary>\n /// Wraps a handle to a user token.\n /// </summary>\n public class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n /// <summary>\n /// Creates a new SafeTokenHandle. This constructor should only be called by P/Invoke.\n /// </summary>\n private SafeTokenHandle()\n : base(true)\n {\n }\n\n /// <summary>\n /// Creates a new SafeTokenHandle to wrap the specified user token.\n /// </summary>\n /// <param name=\"arrayPointer\">The user token to wrap.</param>\n /// <param name=\"ownHandle\"><c>true</c> to close the token when this object is disposed or finalized,\n /// <c>false</c> otherwise.</param>\n public SafeTokenHandle(IntPtr handle, bool ownHandle)\n : base(ownHandle)\n {\n this.SetHandle(handle);\n }\n\n /// <summary>\n /// Provides a <see cref=\"WindowsIdentity\" /> object created from this user token. Depending\n /// on the type of token, this can be used to impersonate the user. The WindowsIdentity\n /// class will duplicate the token, so it is safe to use the WindowsIdentity object created by\n /// this method after disposing this object.\n /// </summary>\n /// <returns>a <see cref=\"WindowsIdentity\" /> for the user that this token represents.</returns>\n /// <exception cref=\"InvalidOperationException\">This object does not contain a valid handle.</exception>\n /// <exception cref=\"ObjectDisposedException\">This object has been disposed and its token has\n /// been released.</exception>\n public WindowsIdentity GetWindowsIdentity()\n {\n if (this.IsClosed)\n {\n throw new ObjectDisposedException(\"The user token has been released.\");\n }\n if (this.IsInvalid)\n {\n throw new InvalidOperationException(\"The user token is invalid.\");\n }\n\n return new WindowsIdentity(this.handle);\n }\n\n /// <summary>\n /// Calls <see cref=\"NativeMethods.CloseHandle\" /> to release this user token.\n /// </summary>\n /// <returns><c>true</c> if the function succeeds, <c>false otherwise</c>. To get extended\n /// error information, call <see cref=\"Marshal.GetLastWin32Error\"/>.</returns>\n protected override bool ReleaseHandle()\n {\n return NativeMethods.CloseHandle(this.handle);\n }\n }\n\n /// <summary>\n /// A wrapper around a pointer to an array of Unicode strings (LPWSTR*) using a contiguous block of\n /// memory that can be freed by a single call to LocalFree.\n /// </summary>\n public sealed class SafeLocalAllocWStrArray : SafeLocalAllocArray<string>\n {\n /// <summary>\n /// Creates a new SafeLocalAllocWStrArray. This constructor should only be called by P/Invoke.\n /// </summary>\n private SafeLocalAllocWStrArray()\n : base(true)\n {\n }\n\n /// <summary>\n /// Creates a new SafeLocalallocWStrArray to wrap the specified array.\n /// </summary>\n /// <param name=\"handle\">The pointer to the unmanaged array to wrap.</param>\n /// <param name=\"ownHandle\"><c>true</c> to release the array when this object\n /// is disposed or finalized, <c>false</c> otherwise.</param>\n public SafeLocalAllocWStrArray(IntPtr handle, bool ownHandle)\n : base(ownHandle)\n {\n this.SetHandle(handle);\n }\n\n /// <summary>\n /// Returns the Unicode string referred to by an unmanaged pointer in the wrapped array.\n /// </summary>\n /// <param name=\"index\">The index of the value to retrieve.</param>\n /// <returns>the value at the position specified by <paramref name=\"index\" /> as a string.</returns>\n protected override string GetArrayValue(int index)\n {\n return Marshal.PtrToStringUni(Marshal.ReadIntPtr(this.handle + IntPtr.Size * index));\n }\n }\n\n // This class is similar to the built-in SafeBuffer class. Major differences are:\n // 1. This class is less safe because it does not implicitly know the length of the array it wraps.\n // 2. The array is read-only.\n // 3. The type parameter is not limited to value types.\n /// <summary>\n /// Wraps a pointer to an unmanaged array of objects that can be freed by calling LocalFree.\n /// </summary>\n /// <typeparam name=\"T\">The type of the objects in the array.</typeparam>\n public abstract class SafeLocalAllocArray<T> : SafeHandleZeroOrMinusOneIsInvalid\n {\n /// <summary>\n /// Creates a new SafeLocalArray which specifies that the array should be freed when this\n /// object is disposed or finalized.\n /// <param name=\"ownsHandle\"><c>true</c> to reliably release the handle during the finalization phase;\n /// <c>false</c> to prevent reliable release (not recommended).</param>\n /// </summary>\n protected SafeLocalAllocArray(bool ownsHandle)\n : base(ownsHandle)\n {\n }\n\n /// <summary>\n /// Converts the unmanaged object referred to by <paramref name=\"valuePointer\" /> to a managed object\n /// of type T.\n /// </summary>\n /// <param name=\"index\">The index of the value to retrieve.</param>\n /// <returns>the value at the position specified by <paramref name=\"index\" /> as a managed object of\n /// type T.</returns>\n protected abstract T GetArrayValue(int index);\n\n // \n /// <summary>\n /// Frees the wrapped array by calling LocalFree.\n /// </summary>\n /// <returns><c>true</c> if the call to LocalFree succeeds, <c>false</c> if the call fails.</returns>\n protected override bool ReleaseHandle()\n {\n return (NativeMethods.LocalFree(this.handle) == IntPtr.Zero);\n }\n\n /// <summary>\n /// Copies the unmanaged array to the specified managed array.\n /// \n /// It is important that the length of <paramref name=\"array\"/> be less than or equal to the length of\n /// the unmanaged array wrapped by this object. If it is not, at best garbage will be read and at worst\n /// an exception of type <see cref=\"AccessViolationException\" /> will be thrown.\n /// </summary>\n /// <param name=\"array\">The managed array to copy the unmanaged values to.</param>\n /// <exception cref=\"ObjectDisposedException\">The unmanaged array wrapped by this object has been\n /// freed.</exception>\n /// <exception cref=\"InvalidOperationException\">The pointer to the unmanaged array wrapped by this object\n /// is invalid.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"array\"/> is null.</exception>\n public void CopyTo(T[] array)\n {\n if (array == null)\n {\n throw new ArgumentNullException(\"array\");\n }\n\n this.CopyTo(array, 0, array.Length);\n }\n\n /// <summary>\n /// Copies the unmanaged array to the specified managed array.\n /// \n /// It is important that <paramref name=\"length\" /> be less than or equal to the length of\n /// the array wrapped by this object. If it is not, at best garbage will be read and at worst\n /// an exception of type <see cref=\"AccessViolationException\" /> will be thrown.\n /// </summary>\n /// <param name=\"array\">The managed array to copy the unmanaged values to.</param>\n /// <param name=\"index\">The index to start at when copying to <paramref name=\"array\" />.</param>\n /// <param name=\"length\">The number of items to copy to <paramref name=\"array\" /></param>\n /// <exception cref=\"ObjectDisposedException\">The unmanaged array wrapped by this object has been\n /// freed.</exception>\n /// <exception cref=\"InvalidOperationException\">The pointer to the unmanaged array wrapped by this object\n /// is invalid.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"array\"/> is null.</exception>\n /// <exception cref=\"ArgumentOutOfRangeException\"><paramref name=\"index\"/> is less than zero.-or- \n /// <paramref name=\"index\" /> is greater than the length of <paramref name=\"array\"/>.-or-\n /// <paramref name=\"length\"/> is less than zero.</exception>\n /// <exception cref=\"ArgumentException\">The sum of <paramref name=\"index\" /> and <paramref name=\"length\" />\n /// is greater than the length of <paramref name=\"array\" />.</exception>\n public void CopyTo(T[] array, int index, int length)\n {\n if (this.IsClosed)\n {\n throw new ObjectDisposedException(this.ToString());\n }\n if (this.IsInvalid)\n {\n throw new InvalidOperationException(\"This object's buffer is invalid.\");\n }\n if (array == null)\n {\n throw new ArgumentNullException(\"array\");\n }\n if (index < 0 || array.Length < index)\n {\n throw new ArgumentOutOfRangeException(\"index\", \"index must be a nonnegative integer that is less than array's length.\");\n }\n if (length < 0)\n {\n throw new ArgumentOutOfRangeException(\"length\", \"length must be a nonnegative integer.\");\n }\n if (array.Length < index + length)\n {\n throw new ArgumentException(\"length\", \"length is greater than the number of elements from index to the end of array.\");\n }\n\n for (int i = 0; i < length; ++i)\n {\n array[index + i] = this.GetArrayValue(i);\n }\n }\n }\n\n /// <summary>\n /// The type of logon operation to perform.\n /// </summary>\n internal enum LogonType : uint\n {\n LOGON32_LOGON_BATCH = 1,\n LOGON32_LOGON_INTERACTIVE = 2,\n LOGON32_LOGON_NETWORK = 3,\n LOGON32_LOGON_NETWORK_CLEARTEXT = 4,\n LOGON32_LOGON_NEW_CREDENTIALS = 5,\n LOGON32_LOGON_SERVICE = 6,\n LOGON32_LOGON_UNLOCK = 7\n }\n\n /// <summary>\n /// The logon provider to use.\n /// </summary>\n internal enum LogonProvider : uint\n {\n LOGON32_PROVIDER_DEFAULT = 0,\n LOGON32_PROVIDER_WINNT50 = 1,\n LOGON32_PROVIDER_WINNT40 = 2\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7418/" ]
155,792
<p>I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.</p> <p>The basic idea is that this method will add certain things to a collection that will be used for validation.</p> <pre><code>public interface ITestInterface { //Specify stuff here. } private static void DoSomething&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; expression, params IMyInterface[] rule) { // Stuff is done here. } </code></pre> <p>The method is called as follows:</p> <pre><code>class TestClass { public int MyProperty { get; set; } } class OtherTestClass : ITestInterface { // Blah Blah Blah. } static void Main(string[] args) { DoSomething&lt;TestClass&gt;(t =&gt; t.MyProperty, new OtherTestClass()); } </code></pre> <p>I'm doing it this way because I'd like for the property names that are passed in to be strong typed.</p> <p>A couple of things I'm struggling with..</p> <ol> <li>Within DoSomething, I'd like to get a <code>PropertyInfo</code> type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from &quot;Convert.([propertyname])&quot; and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way?</li> <li>Is this a specific pattern I'm using?</li> <li>Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.</li> </ol> <p>Thanks!</p> <p>Ian</p> <h1>Edit:</h1> <p>An example of what <code>expression.Body.ToString()</code> returns within the DoSomething method is a string that contains &quot;Convert(t.MyProperty)&quot; if called from the example above.</p> <p>I do need it to be strongly typed, so it will not compile if I change a property name.</p> <p>Thanks for the suggestions!</p>
[ { "answer_id": 155845, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "DoSomething(\"MyProperty\", new OtherClass());\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10853/" ]
155,797
<p>ADO.NET has the notorious DataRow class which you cannot instantiate using new. This is a problem now that I find a need to mock it using Rhino Mocks. </p> <p>Does anyone have any ideas how I could get around this problem?</p>
[ { "answer_id": 155813, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": true, "text": "SetupResult.For(someMockClass.GetDataRow(input)).Return(GetReturnRow());\n\npublic DataRow GetReturnRow()\n{\n DataTable table = new DataTable(\"FakeTable\");\n DataRow row = table.NewRow();\n row.value1 = \"someValue\";\n row.value2 = 234;\n\n return row;\n}\n" }, { "answer_id": 69921036, "author": "Alison Rodrigues", "author_id": 14218167, "author_profile": "https://Stackoverflow.com/users/14218167", "pm_score": 0, "selected": false, "text": " private DataRow GetReturnRow()\n {\n DataTable table = new DataTable(\"FakeTable\");\n table.Columns.Add(\"column_name\");\n\n DataRow row = table.NewRow();\n row[\"column_name\"] = your_value;\n\n return row;\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
155,810
<p>When you double click on a class (in 'solution explorer')... if that class happens to be an .asmx.cs webservice... then you get this...</p> <blockquote> <p>To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create methods and events for your class, click here to switch to code view.</p> </blockquote> <p>...it's a 'visual design surface' for webservices.</p> <p>(Who actually uses that surface to write webservices?)</p> <p>So what I want to know, how do I configure visual studio to never show me that design view?</p> <p>Or at least, to show me the code view by default?</p>
[ { "answer_id": 3196200, "author": "Bob Sidie", "author_id": 385681, "author_profile": "https://Stackoverflow.com/users/385681", "pm_score": 1, "selected": false, "text": "<System.ComponentModel.DesignerCategory(\"\")>\n" }, { "answer_id": 4246213, "author": "Steinar Herland", "author_id": 111182, "author_profile": "https://Stackoverflow.com/users/111182", "pm_score": 2, "selected": false, "text": "[System.ComponentModel.DesignerCategory(\"Code\")] \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49/" ]
155,829
<p>I am getting this error but only very occasionally. 99.9% of the time it works fine:</p> <p>Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.</p> <p>Does anyone have any idea on what the cause could be? I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?</p>
[ { "answer_id": 38776066, "author": "Nick", "author_id": 1931573, "author_profile": "https://Stackoverflow.com/users/1931573", "pm_score": 0, "selected": false, "text": "varchar(100)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10102/" ]
155,848
<p>I need to create an access (mdb) database without using the ADOX interop assembly. </p> <p>How can this be done?</p>
[ { "answer_id": 155851, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 5, "selected": true, "text": "if (!File.Exists(DB_FILENAME))\n{\n var cnnStr = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + DB_FILENAME;\n\n // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. \n var catType = Type.GetTypeFromProgID(\"ADOX.Catalog\");\n object o = Activator.CreateInstance(catType);\n catType.InvokeMember(\"Create\", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});\n\n OleDbConnection cnn = new OleDbConnection(cnnStr);\n cnn.Open();\n var cmd = cnn.CreateCommand();\n cmd.CommandText = \"CREATE TABLE VideoPosition (filename TEXT , pos LONG)\";\n cmd.ExecuteNonQuery();\n\n}\n" }, { "answer_id": 155880, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 0, "selected": false, "text": "Provider=Microsoft.ACE.OLEDB.12.0;Data\nSource=C:\\myFolder\\myAccess2007file.accdb;Persist\nSecurity Info=False;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
155,852
<p>I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form.<br> The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing.<br></p> <p>In the resx file for the form it will generate binary data for storing the collection, however any time I make a change to the serialized class I get designer errors and need to delete the data manually out of the resx file and then recreate this data.</p> <p>I have tried changing the constuctor to have a try / catch block around each property in the class</p> <pre><code>try { _Name = info.GetString("Name"); } catch (SerializationException) { this._Name = string.Empty; } </code></pre> <p>but it still crashes. The last error I got was that I had to implement IConvertible.<br></p> <p>I would prefer to use xml serialization because I can at least see it, is this possible for use by the designer?<br></p> <p>Is there a way to make the serialization more stable and less resistant to changes?</p> <p>Edit:<br> More information...better description maybe<br> I have a class which inherits from Component, it has one property which is a collection of Rules. The RulesCollection seems to have to be marked as Serializable, otherwise it does not retain its members.<br> </p> <p>The Rules class is also a Component with the attribute DesignTimeVisible(false) to stop it showing in the component tray, this clas is not marked Serializable.<br></p> <p>Having the collection marked as Serializable generates binary data in the resx file (not ideal) and the IDE reports that the Rules class is not Serializable.<br></p> <p>I think this issue is getting beyond a simple question. So I will probably close it shortly.<br> If anyone has any links to something similar that would help a lot.</p>
[ { "answer_id": 199307, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": true, "text": "private List<Rule> _Rules;\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic List<Rule> Rules\n{\n get { return _Rules; }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
155,864
<p>I have a controller with an action method as follows:</p> <pre><code>public class InventoryController : Controller { public ActionResult ViewStockNext(int firstItem) { // Do some stuff } } </code></pre> <p>And when I run it I get an error stating:</p> <blockquote> <p>The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.</p> </blockquote> <p>I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.</p> <p>I'm using this url syntax to call the action:</p> <pre><code>http://localhost:2316/Inventory/ViewStockNext/11 </code></pre> <p>Any ideas why I would get this error and what I need to do to fix it? </p> <p>I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.</p>
[ { "answer_id": 155895, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 8, "selected": true, "text": "{controller}/{action}/{firstItem}" }, { "answer_id": 155902, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 4, "selected": false, "text": "routes.MapRoute(\n \"ViewStockNext\", // Route name\n \"Inventory/ViewStockNext/{firstItem}\", // URL with parameters\n new { controller = \"Inventory\", action = \"ViewStockNext\" } // Parameter defaults\n );\n" }, { "answer_id": 355023, "author": "RAL", "author_id": 44844, "author_profile": "https://Stackoverflow.com/users/44844", "pm_score": 0, "selected": false, "text": "public ActionResult ViewNextItem(string id)...\n" }, { "answer_id": 477963, "author": "Oskar Duveborn", "author_id": 49293, "author_profile": "https://Stackoverflow.com/users/49293", "pm_score": 3, "selected": false, "text": "public ActionResult ViewNextItem(int? id)" }, { "answer_id": 1551423, "author": "Felix", "author_id": 184509, "author_profile": "https://Stackoverflow.com/users/184509", "pm_score": 1, "selected": false, "text": "Html.ActionLink(\"Next page\", \"Index\", routeData)\n" }, { "answer_id": 8363659, "author": "Bart Calixto", "author_id": 826568, "author_profile": "https://Stackoverflow.com/users/826568", "pm_score": 6, "selected": false, "text": "http://localhost:2316/Inventory/ViewStockNext?firstItem=11\n" }, { "answer_id": 8923030, "author": "Aristoteles", "author_id": 247949, "author_profile": "https://Stackoverflow.com/users/247949", "pm_score": 0, "selected": false, "text": "routes.MapRoute (\"Default\", \"{controller}/{action}/{id}\", \n new { controller = \"Home\", action = \"Index\", id = \"\" });\n" }, { "answer_id": 12394449, "author": "Matthew Nichols", "author_id": 165031, "author_profile": "https://Stackoverflow.com/users/165031", "pm_score": 3, "selected": false, "text": "[ParameterAlias(\"firstItem\", \"id\", Order = 3)]\npublic ActionResult ViewStockNext(int firstItem)\n{\n // Do some stuff\n}\n" }, { "answer_id": 32272225, "author": "Yar", "author_id": 2517730, "author_profile": "https://Stackoverflow.com/users/2517730", "pm_score": 4, "selected": false, "text": "public class InventoryController : Controller\n{\n [Route(\"whatever/{firstItem}\")]\n public ActionResult ViewStockNext(int firstItem)\n {\n int yourNewVariable = firstItem;\n // ...\n }\n}\n" }, { "answer_id": 43215223, "author": "Sasha Yakobchuk", "author_id": 4691615, "author_profile": "https://Stackoverflow.com/users/4691615", "pm_score": 3, "selected": false, "text": "<a asp-controller=\"Home\" asp-action=\"SetLanguage\" asp-route-yourparam1=\"@item.Value\">@item.Text</a>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11908/" ]
155,869
<p>The Interwebs are no help on this one. We're encoding data in ColdFusion using <code>serializeJSON</code> and trying to decode it in PHP using <code>json_decode</code>. Most of the time, this is working fine, but in some cases, <code>json_decode</code> returns <code>NULL</code>. We've looked for the obvious culprits, but <code>serializeJSON</code> seems to be formatting things as expected. What else could be the problem?</p> <p>UPDATE: A couple of people (wisely) asked me to post the output that is causing the problem. I would, except we just discovered that the result set is all of our data (listing information for 2300+ rental properties for a total of 565,135 ASCII characters)! That could be a problem, though I didn't see anything in the PHP docs about a max size for the string. What would be the limiting factor there? RAM?</p> <p>UPDATE II: It looks like the problem was that a couple of our users had copied and pasted Microsoft Word text with "smart" quotes. Those pesky users...</p>
[ { "answer_id": 171521, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "json_decode" }, { "answer_id": 1184143, "author": "Stewart Robinson", "author_id": 47424, "author_profile": "https://Stackoverflow.com/users/47424", "pm_score": 1, "selected": false, "text": "$string = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $string);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
155,884
<p>What is a realistic use for VB.Net's MyClass keyword?</p> <p>I understand the <a href="http://msdn.microsoft.com/en-us/library/b3b35kyk.aspx" rel="noreferrer">technical usage of MyClass</a>; I don't understand the practical usage of it in the real world.</p> <p>Using MyClass only makes sense if you have any virtual (overridable) members. But it also means that you want to ignore the overridden implementations in sub classes. It appears to be self-contradicting.</p> <p>I can think of some contrived examples, but they are simply bad design rather than practical usage.</p>
[ { "answer_id": 169787, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": -1, "selected": false, "text": "Public Sub New(ByVal accountKey As Integer)\n MyClass.New(accountKey, Nothing)\nEnd Sub\n\nPublic Sub New(ByVal accountKey As Integer, ByVal accountName As String)\n MyClass.New(accountKey, accountName, Nothing)\nEnd Sub\n\nPublic Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String)\n m_AccountKey = accountKey\n m_AccountName = accountName\n m_AccountNumber = accountNumber\nEnd Sub\n" }, { "answer_id": 19080080, "author": "Allen Clark Copeland Jr", "author_id": 557100, "author_profile": "https://Stackoverflow.com/users/557100", "pm_score": 3, "selected": true, "text": "MyClass" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6375/" ]
155,891
<p>Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection. Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch. Any one have a handy trick for this conundrum?</p>
[ { "answer_id": 158948, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 2, "selected": false, "text": "<cfcollection action=\"map\" ...>\n" }, { "answer_id": 571061, "author": "crb", "author_id": 51691, "author_profile": "https://Stackoverflow.com/users/51691", "pm_score": 2, "selected": true, "text": "rcadmin> indexdetach\nServer Alias:YourDocserver\nIndex Alias:CollectionName\nIndex Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n\nrcadmin> collpurge\nCollection alias:CollectionName\nAdmin Alias:AdminServer\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n\nrcadmin> adminsignal\nAdmin Alias:AdminServer\nType of signal (Shutdown=2,WSRefresh=3,RestartAllServers=4):4\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ]
155,908
<p>I have defined tomcat:catalina:5.5.23 as a dependency to the cargo plugin, however I still get the following exception:</p> <pre><code>java.lang.ClassNotFoundException: org.apache.catalina.Connector at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274) at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.codehaus.cargo.container.tomcat.internal.Tomcat5xEmbedded.preloadEmbedded(Tomcat5xEmbedded.java:232) </code></pre> <p>It looks like the RealmClassLoader is not finding the class, possibly due to java.security.AccessController.doPrivileged denying access. </p> <p>Has anyone got tomcat to run in embedded mode from within maven?</p>
[ { "answer_id": 169029, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 1, "selected": false, "text": "mvn jetty6:run\n" }, { "answer_id": 640436, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 0, "selected": false, "text": "<plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>tomcat-maven-plugin</artifactId>\n </plugin>\n</plugins>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
155,911
<p>During software development, there may be bugs in the codebase which are known issues. These bugs will cause the regression/unit tests to fail, if the tests have been written well.</p> <p>There is constant debate in our teams about how failing tests should be managed:</p> <ol> <li><p>Comment out failing test cases with a REVISIT or TODO comment.</p> <ul> <li><strong>Advantage</strong>: We will always know when a <em>new</em> defect has been introduced, and not one we are already aware of.</li> <li><strong>Disadvantage</strong>: May forget to REVISIT the commented-out test case, meaning that the defect could slip through the cracks.</li> </ul></li> <li><p>Leave the test cases failing.</p> <ul> <li><strong>Advantage</strong>: Will not forget to fix the defects, as the script failures will constantly reminding you that a defect is present.</li> <li><strong>Disadvantage</strong>: Difficult to detect when a <em>new</em> defect is introduced, due to failure noise.</li> </ul></li> </ol> <p>I'd like to explore what the best practices are in this regard. Personally, I think a tri-state solution is the best for determining whether a script is passing. For example when you run a script, you could see the following:</p> <ul> <li>Percentage passed: 75%</li> <li>Percentage failed (expected): 20%</li> <li>Percentage failed (unexpected): 5%</li> </ul> <p>You would basically mark any test cases which you <em>expect</em> to fail (due to some defect) with some metadata. This ensures you still see the failure result at the end of the test, but immediately know if there is a <em>new</em> failure which you weren't expecting. This appears to take the best parts of the 2 proposals above.</p> <p>Does anyone have any best practices for managing this?</p>
[ { "answer_id": 155942, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": true, "text": "// TODO: fix test case\n" }, { "answer_id": 155971, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 1, "selected": false, "text": "3. Connect to a web service\n ...\n3.1. Get the version number\n ...\n3.2. Data:\n 3.2.1. Get the version number\n 3.2.2. Retrieve simple data\n 3.2.3. Retrieve detailed data\n 3.2.4. Change data\n" }, { "answer_id": 156047, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "TODO: {\n local $TODO = \"This has not been implemented yet.\"\n\n # Tests expected to fail go here\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
155,912
<p>Calling <code>Validate()</code> on an <strong>XmlDocument</strong> requires passing in a <code>ValidationEventHandler</code> delegate. That event function gets a <code>ValidationEventArgs</code> parameter which in turn has an <code>Exception</code> property of the type <code>XmlSchemaException</code>. Whew!</p> <p>My current code looks like this:</p> <pre><code>ValidationEventHandler onValidationError = delegate(object sender, ValidationEventArgs args) { throw(args.Exception); } doc.Validate(onValidationError); </code></pre> <p>Is there some other method I'm overlooking which simply <em>throws</em> the <code>XmlSchemaException</code> if validation fails (warnings ignored entirely)?</p>
[ { "answer_id": 57436064, "author": "Adam Porad", "author_id": 21353, "author_profile": "https://Stackoverflow.com/users/21353", "pm_score": 0, "selected": false, "text": "null" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
155,913
<p>The project I'm working is using n-tier architecture. Our layers are as follows:</p> <ul> <li>Data Access</li> <li>Business Logic</li> <li>Business Entities</li> <li>Presentation</li> </ul> <p>The Business Logic calls down into the data access layer, and the Presentation layer calls down into the Business Logic layer, and the Business entities are referenced by all of them. </p> <p>Our business entities essentially match our data model 1-1. For every table, we have a class. Initially when the framework was designed, there was no consideration for managing master-detail or child-parent relationships. So all of the Business logic, data access, and business entities, only referenced a single table in the database. Once we started developing the application it quickly became apparent that not having these relationships in our object model was severely hurting us.</p> <p>All of your layers (including the database) are all generated from an in-house metadata-database which we use to drive our home-grown code generator.</p> <p>The question is what is the best way to load or lazy load the relationships in our entities. For instance Let's say we have a person class that has a master-child relationship to an address table. This shows up in the business entity as a collection property of Addresses on the Person object. If we have a one-to-one relationship then this would show up as a single entity property. What is the best approach for filling and saving the relationship objects? Our Business entities have no knowledge of the Business Logic layer, so it can't be done internally when the property get's called.</p> <p>I'm sure there is some sort of standard patter out there for doing this. Any suggestions?</p> <p>Also, one caveat is that the DataAcess layer uses reflection to build our entities. The stored procedures return one result selt based on one table, and using reflection we populate our business object by matching the names of the properties with the names of the columns. So doing joins would be difficult.</p>
[ { "answer_id": 155965, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "public class Relation<T>\n{\n private T _value;\n\n private void FetchData()\n {\n if( LoadData != null ) {\n LoadDataEventArgs args = new LoadDataEventArgs(typeof(T), /* magic to get correct object */);\n LoadData(this, args);\n _value = (T)args.Value;\n }\n }\n\n public event EventHandler<LoadDataEventArgs> LoadData;\n\n public T Value {\n get {\n if( _value == default(T) )\n FetchData();\n return _value; \n }\n set { /* Do magic here. */ }\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
155,920
<p>I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?</p> <p>Here is an example script that does not work on my hosts' server as of right now:</p> <pre><code>&lt;?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; echo '&lt;p&gt;&lt;a href="page1.php"&gt;Refresh&lt;/a&gt;&lt;/p&gt;'; ?&gt; </code></pre> <p>The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.</p> <p>Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): <img src="https://i.stack.imgur.com/3bv0K.png" alt="alt text"></p>
[ { "answer_id": 155941, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 3, "selected": false, "text": "phpinfo()" }, { "answer_id": 155945, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "if (isset($_SESSION['views'])) {\n if (!is_numeric($_SESSION['views'])) {\n echo \"CRAP!\";\n }\n ++$_SESSION['views'];\n} else {\n $_SESSION['views'] = 1;\n}\n" }, { "answer_id": 159948, "author": "Crackerjack", "author_id": 13556, "author_profile": "https://Stackoverflow.com/users/13556", "pm_score": 6, "selected": true, "text": "ini_set(' session.save_path','SOME WRITABLE PATH');" }, { "answer_id": 6428807, "author": "Aleks G", "author_id": 717214, "author_profile": "https://Stackoverflow.com/users/717214", "pm_score": 2, "selected": false, "text": "$_SESSION['full_list'] = $full_list" }, { "answer_id": 6777970, "author": "harry", "author_id": 856186, "author_profile": "https://Stackoverflow.com/users/856186", "pm_score": 3, "selected": false, "text": "<?\n session_start();\n $_SESSION['a'] = 123;\n header('location:index2.php');\n?>\n" }, { "answer_id": 12554786, "author": "emaniacs", "author_id": 1286248, "author_profile": "https://Stackoverflow.com/users/1286248", "pm_score": 1, "selected": false, "text": "session.gc_probability=0\n" }, { "answer_id": 26180998, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "www.mysite.com" }, { "answer_id": 26191908, "author": "Pete855217", "author_id": 855217, "author_profile": "https://Stackoverflow.com/users/855217", "pm_score": 0, "selected": false, "text": "session.use_trans_sid=0 ; Do not add session id to URI (osc does this)\nsession.use_cookies=0; ; ensure cookies are not used\nsession.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT\nsession.save_path=~/tmp/osc; ; Set to same as admin setting\nsession.auto_start = off; Tell PHP not to start sessions, osc code will do this\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556/" ]
155,930
<p>I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.</p> <p>Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. </p> <p>For windows I use:</p> <pre><code>ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); </code></pre> <p>For Linux I currently use:</p> <pre><code>pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); } </code></pre>
[ { "answer_id": 155946, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "xdg-open" }, { "answer_id": 159102, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 0, "selected": false, "text": "firefox -remote 'openurl(http://stackoverflow.com)'\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
155,932
<p>I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.</p>
[ { "answer_id": 155937, "author": "Michael Ratanapintha", "author_id": 1879, "author_profile": "https://Stackoverflow.com/users/1879", "pm_score": 3, "selected": false, "text": "cmd.exe" }, { "answer_id": 155950, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 6, "selected": false, "text": "for /F \"eol=; tokens=2,3* delims=,\" %i in (myfile.txt) do @echo %i %j %k\n" }, { "answer_id": 155954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "REM ******************************************************************\nREM Runs all *.sql scripts sorted by filename in the current folder.\nREM To use integrated auth change -U <user> -P <password> to -E\nREM ******************************************************************\n\ndir /B /O:n *.sql > RunSqlScripts.tmp\nfor /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A\ndel RunSqlScripts.tmp\n" }, { "answer_id": 163873, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 9, "selected": true, "text": "for /F \"tokens=*\" %%A in (myfile.txt) do [process] %%A\n" }, { "answer_id": 1266109, "author": "Paul", "author_id": 121257, "author_profile": "https://Stackoverflow.com/users/121257", "pm_score": 4, "selected": false, "text": "FOR /F %%i IN (myfile.txt) DO ECHO %%i\n" }, { "answer_id": 2766240, "author": "user332474", "author_id": 332474, "author_profile": "https://Stackoverflow.com/users/332474", "pm_score": 5, "selected": false, "text": "%%" }, { "answer_id": 8976789, "author": "Yogesh Mahajan", "author_id": 1852508, "author_profile": "https://Stackoverflow.com/users/1852508", "pm_score": 5, "selected": false, "text": "for /F \"tokens=*\" %A in (MyList.txt) do CALL %A ARG1\n" }, { "answer_id": 14285280, "author": "DotDotJames", "author_id": 625754, "author_profile": "https://Stackoverflow.com/users/625754", "pm_score": 1, "selected": false, "text": "cmd /C \"heroku list > heroku_apps.txt\"\nfind /v \"=\" heroku_apps.txt | find /v \".TXT\" | findstr /r /v /c:\"^$\" > heroku_apps_list.txt\nfor /F \"tokens=1\" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i\n" }, { "answer_id": 16792536, "author": "Marvin Thobejane", "author_id": 1358924, "author_profile": "https://Stackoverflow.com/users/1358924", "pm_score": 5, "selected": false, "text": "cd /d %~dp0\nfor /F \"tokens=*\" %%A in (myfile.txt) do [process] %%A\n" }, { "answer_id": 17723989, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 4, "selected": false, "text": ";" }, { "answer_id": 52806421, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "cmd.exe" }, { "answer_id": 60025292, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": 1, "selected": false, "text": "set input=\"path/to/file.txt\"\n\nfor /f \"tokens=* delims=[\" %i in ('type \"%input%\" ^| find /v /n \"\"') do (\nset a=%i\nset a=!a:*]=]!\necho:!a:~1!)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5132/" ]
155,934
<p>What GNU/Linux command-line tool would I use for performing a search and replace on a file? </p> <p>Can the search text, and replacement, be specified in a regex format?</p>
[ { "answer_id": 155939, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 5, "selected": false, "text": "perl -pi -e 's/foo/bar/g;' *.txt\n" }, { "answer_id": 155956, "author": "Cristian Ciupitu", "author_id": 12892, "author_profile": "https://Stackoverflow.com/users/12892", "pm_score": 7, "selected": true, "text": "sed 's/a.*b/xyz/g;' old_file > new_file\n" }, { "answer_id": 159354, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 3, "selected": false, "text": "-i" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
155,959
<p>The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources?</p> <pre><code>using (OleDbConnection conn = new OleDbConnection(connectionString)) using (OleDbCommand cmd = new OleDbCommand(commandText, conn)) { conn.Open(); cmd.ExecuteNonQuery(); } </code></pre>
[ { "answer_id": 155961, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "using (OleDBConnection conn = new OleDBConnection(connstr))\n{\n while (IHaveData)\n {\n using (OldDBCommand cmd = new OldDBCommand())\n {\n cmd.Connection = conn;\n cmd.ExecuteScalar();\n }\n }\n}\n" }, { "answer_id": 21227708, "author": "jaymeht", "author_id": 1703129, "author_profile": "https://Stackoverflow.com/users/1703129", "pm_score": -1, "selected": false, "text": "OledbCommand.Dispose();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669/" ]
155,964
<p>I know about the <a href="http://developer.apple.com/library/mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines/Intro/Intro.html" rel="noreferrer">HIG</a> (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).</p>
[ { "answer_id": 155966, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 6, "selected": false, "text": "alloc" }, { "answer_id": 156098, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 10, "selected": true, "text": "#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n" }, { "answer_id": 156186, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 6, "selected": false, "text": "@interface MyClass (private)\n- (void) someMethod\n- (void) someOtherMethod\n@end\n" }, { "answer_id": 156288, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 4, "selected": false, "text": "- (void)dealloc\n{\n self.someAttribute = NULL;\n [super dealloc];\n}\n" }, { "answer_id": 156295, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 7, "selected": false, "text": "dealloc" }, { "answer_id": 156665, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "*Listener" }, { "answer_id": 158304, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 7, "selected": false, "text": "id m_something;" }, { "answer_id": 167495, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "@interface MyClass :NSObject {\n NSTextField *textField;\n}\n@property (nonatomic, retain) IBOutlet NSTextField *textField;\n@end\n" }, { "answer_id": 169783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "cd" }, { "answer_id": 175118, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "NSLog" }, { "answer_id": 175134, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "compare:" }, { "answer_id": 175874, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": false, "text": "aVariable = [AClass convenienceMethod];\n" }, { "answer_id": 195969, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "nil" }, { "answer_id": 297307, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 6, "selected": false, "text": "#pragma mark [section]" }, { "answer_id": 3583204, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 5, "selected": false, "text": "@interface FooInt:NSObject{}\n-(int) print;\n@end\n\n@implementation FooInt\n-(int) print{\n return 5;\n}\n@end\n\n@interface FooFloat:NSObject{}\n-(float) print;\n@end\n\n@implementation FooFloat\n-(float) print{\n return 3.3;\n}\n@end\n\nint main (int argc, const char * argv[]) {\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; \n id f1=[[FooFloat alloc]init];\n //prints 0, runtime considers [f1 print] to return int, as f1's type is \"id\" and FooInt precedes FooBar\n NSLog(@\"%f\",[f1 print]);\n\n FooFloat* f2=[[FooFloat alloc]init];\n //prints 3.3 expectedly as the static type is FooFloat\n NSLog(@\"%f\",[f2 print]);\n\n [f1 release];\n [f2 release]\n [pool drain];\n\n return 0;\n} \n" }, { "answer_id": 5476751, "author": "eonil", "author_id": 246776, "author_profile": "https://Stackoverflow.com/users/246776", "pm_score": 3, "selected": false, "text": "CGRectMake()" }, { "answer_id": 6977572, "author": "Tuan Nguyen", "author_id": 504257, "author_profile": "https://Stackoverflow.com/users/504257", "pm_score": 2, "selected": false, "text": "self.<property> = nil;\n" }, { "answer_id": 7816085, "author": "Sulthan", "author_id": 669586, "author_profile": "https://Stackoverflow.com/users/669586", "pm_score": 3, "selected": false, "text": "\n@synthesize property = property_;\n" }, { "answer_id": 10314854, "author": "Nirmit Pathak", "author_id": 1302622, "author_profile": "https://Stackoverflow.com/users/1302622", "pm_score": 0, "selected": false, "text": "#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21804/" ]
155,977
<p>I have the following markup, and I want to make the <code>All</code> radio button checked.</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;input type="radio" value="All" name="Foo"/&gt;All&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="New" name="Foo"/&gt;New&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Removed" name="Foo"/&gt;Removed&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Updated" name="Foo"/&gt;Updated&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'd like to match via attribute, but I need to match on 2 attributes, <code>@name='Foo'</code> and <code>@value='All'</code>.</p> <p>Something like this:</p> <pre><code>$("input[@name='Foo' @value='all']").attr('checked','checked'); </code></pre> <p>Can someone show how this can be done?</p>
[ { "answer_id": 156027, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 7, "selected": true, "text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"input[name='Foo'][value='All']\").attr('checked','checked');\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <ul>\n <li><input type=\"radio\" value=\"All\" name=\"Foo\" />All</li>\n <li><input type=\"radio\" value=\"New\" name=\"Foo\" />New</li>\n <li><input type=\"radio\" value=\"Removed\" name=\"Foo\" />Removed</li>\n <li><input type=\"radio\" value=\"Updated\" name=\"Foo\" />Updated</li>\n </ul>\n <a href=\"\" >Click here</a>\n </body>\n</html>\n" }, { "answer_id": 771618, "author": "easel", "author_id": 16706, "author_profile": "https://Stackoverflow.com/users/16706", "pm_score": 4, "selected": false, "text": "jQuery('input[name=field1][val=checked]') \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ]
155,996
<p>I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.</p> <p>The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:</p> <pre><code>MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) </code></pre> <p>Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.</p> <p>Any ideas?</p>
[ { "answer_id": 156039, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 2, "selected": false, "text": "MessageBoxOptions.DefaultDesktopOnly" }, { "answer_id": 156040, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "MessageBoxOptions.DefaultDesktopOnly" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10224/" ]
155,998
<p>Given this:</p> <pre><code>Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) If DateTime.Now() &gt; g_RemindTime Then Reminders.ShowDialog() timReminder.Enabled = False End If End Sub </code></pre> <p>I want to be able to say this (as I would in Delphi):</p> <pre><code>timReminder.Tick = timReminder_Tick </code></pre> <p>But I get errors when I try it.</p> <p>Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?</p>
[ { "answer_id": 354784, "author": "Jon Winstanley", "author_id": 42106, "author_profile": "https://Stackoverflow.com/users/42106", "pm_score": 0, "selected": false, "text": "addHandler" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
156,002
<p>I have a very basic question about MVC web applications in Java.</p> <p>Since the olden days of raw JSP up until current technologies like Seam, a very basic pattern has always been the internal dispatch from the controller that initially accepted the request to the view layer that creates the output to be sent to the client.</p> <p>This internal dispatch is generally done (although the mechanism may be hidden through an extra layer of configuration) by asking the servlet container for a new resource using a URL. The mapping of these URL are done by the same web.xml that also defines the "real" URL to the outside.</p> <p>Unless special measures are taken, it is often possible to directly access the view layer directly. Witness the Seam "registration" demo, where you can bypass "register.seam" and directly go to "registered.xhtml". This is a potential security problem. At the very least, it leaks view template source code. </p> <p>I am aware that this is only a basic sample application, but it is also strange that any extra measures should need to be taken to declare these internal resources invisible to the outside.</p> <p>What is the easiest way to restrict URL entry points?</p> <p>Is there maybe something like the "WEB-INF" directory, a magic URL path component that can only be accessed by internal requests?</p>
[ { "answer_id": 453374, "author": "Simon Lieschke", "author_id": 2766, "author_profile": "https://Stackoverflow.com/users/2766", "pm_score": 2, "selected": false, "text": "security-constraint" }, { "answer_id": 2046033, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 1, "selected": true, "text": "WEB-INF/jsp" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
156,009
<p>Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java. </p> <p>The file I read from looks like this:</p> <pre><code>xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about </code></pre> <p>All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.</p>
[ { "answer_id": 156020, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "perl -nae 'print \"$F[0] $F[1]\\n\";'\n" }, { "answer_id": 156025, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "perl -ane 'print \"@F[0,1]\\n\";'\n" }, { "answer_id": 156034, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 2, "selected": false, "text": "perl -nae 'print \"$F[0] $F[1}\\n\";\n" }, { "answer_id": 156037, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl -n\nchop; # strip newline (in case next line doesn't strip it)\ns/#.*//; # strip comments\nnext unless /\\S/; # don't process line if it has nothing (left)\n@fields = (split)[0,1]; # split line, and get wanted fields\nprint join(' ', @fields), \"\\n\";\n" }, { "answer_id": 156063, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 4, "selected": true, "text": "if($line =~ m/(\\S+)\\s+(\\S+)/) {\n $ip = $1;\n $hostname = $2;\n}\n" }, { "answer_id": 160230, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<ARGV>" }, { "answer_id": 20851920, "author": "Amit", "author_id": 2857960, "author_profile": "https://Stackoverflow.com/users/2857960", "pm_score": 0, "selected": false, "text": "@echo off\n\nREM Next line = Set command value to a file OR Just Choose Your File By Skipping The Line\nvol E: > %temp%\\justtmp.txt\nREM Vol E: = Find Volume Lable Of Drive E\n\nREM Next Line to choose line line no. +0 = line no. 1 \nfor /f \"usebackq delims=\" %%a in (`more +0 %temp%\\justtmp.txt`) DO (set findstringline=%%a& goto :nextstep)\n\n:nextstep\n\nREM Next line to read nth to mth Character here 22th Character to 40th Character\nset result=%findstringline:~22,40%\n\necho %result%\npause\nexit /b\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3879/" ]
156,013
<p>I can't quite figure out this syntax problem with a <code>case</code> expression in a <code>do</code> block.</p> <p>What is the correct syntax? </p> <p>If you could correct my example and explain it that would be the best.</p> <pre><code>module Main where main = do putStrLn "This is a test" s &lt;- foo putStrLn s foo = do args &lt;- getArgs return case args of [] -&gt; "No Args" [s]-&gt; "Some Args" </code></pre> <p>A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems. Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.</p>
[ { "answer_id": 156050, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 6, "selected": true, "text": "module Main where \nimport System(getArgs)\n\nmain = do \n putStrLn \"This is a test\"\n s <- foo\n putStrLn s \n\nfoo = do\n args <- getArgs \n return (case args of\n [] -> \"No Args\"\n [s]-> \"Some Args\")\n" }, { "answer_id": 156459, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 4, "selected": false, "text": "foo = do\n args <- getArgs \n case args of\n [] -> return \"No Args\"\n [s]-> return \"Some Args\"\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8965/" ]
156,032
<p>Java &amp; Oracle both have a <em>timestamp</em> type called Date. Developers tend to manipulate these as if they were <em>calendar</em> dates, which I've seen cause nasty one-off bugs.</p> <ol> <li><p>For a basic date quantity you can simply chop off the time portion upon input, i.e., reduce the precision. But if you do that with a date range, (e.g.: <strong>9/29-9/30</strong>), the difference between these two values is 1 day, rather than 2. Also, range comparisons require either 1) a truncate operation: <code>start &lt; trunc(now) &lt;= end</code>, or 2) arithmetic: <code>start &lt; now &lt; (end + 24hrs)</code>. Not horrible, but not <a href="http://www.artima.com/intv/dry.html" rel="nofollow noreferrer">DRY</a>.</p></li> <li><p>An alternative is to use true timestamps: <strong>9/29</strong> 00:00:00 - <strong>10/1</strong> 00:00:00. (midnight-to-midnight, so does not include any part of Oct). Now durations are intrinsically correct, and range comparisons are simpler: <code>start &lt;= now &lt; end</code>. Certainly cleaner for internal processing, however end dates do need to be converted upon initial input (+1), and for output (-1), presuming a calendar date metaphor at the user level.</p></li> </ol> <p>How do you handle date ranges on your project? Are there other alternatives? I am particularly interested in how you handle this on both the Java and the Oracle sides of the equation.</p>
[ { "answer_id": 156038, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "java.util.Date" }, { "answer_id": 156041, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "MY_DATE = TO_DATE('2008-09-12 15:00:00') AND\nTO_DATE('2008-09-12 15:00:00') = TRUNC(TO_DATE('2008-09-12 15:00:00'))\n" }, { "answer_id": 156639, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "start <= now < end" }, { "answer_id": 22595862, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "DateTimeZone timeZone_NewYork = DateTimeZone.forID( \"America/New_York\" );\nDateTime start = new DateTime( 2014, 9, 29, 15, 16, 17, timeZone_NewYork );\nDateTime stop = new DateTime( 2014, 9, 30, 1, 2, 3, timeZone_NewYork );\n\nint daysBetween = Days.daysBetween( start, stop ).getDays();\n\nPeriod period = new Period( start, stop );\n\nInterval interval = new Interval( start, stop );\nInterval intervalWholeDays = new Interval( start.withTimeAtStartOfDay(), stop.plusDays( 1 ).withTimeAtStartOfDay() );\n\nDateTime lateNight29th = new DateTime( 2014, 9, 29, 23, 0, 0, timeZone_NewYork );\nboolean containsLateNight29th = interval.contains( lateNight29th );\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
156,046
<p>I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?</p>
[ { "answer_id": 156067, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "this.TopMost = true; // as a result the form gets thrown to the front\nthis.TopMost = false; // but we don't actually want our form to always be on top\n" }, { "answer_id": 156082, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": -1, "selected": false, "text": "Form f = new Form();\nf.ShowDialog();\n" }, { "answer_id": 156117, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "Form.Shown" }, { "answer_id": 156159, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": false, "text": "private const int SW_SHOWNOACTIVATE = 4;\nprivate const int HWND_TOPMOST = -1;\nprivate const uint SWP_NOACTIVATE = 0x0010;\n\n[DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\nstatic extern bool SetWindowPos(\n int hWnd, // Window handle\n int hWndInsertAfter, // Placement-order handle\n int X, // Horizontal position\n int Y, // Vertical position\n int cx, // Width\n int cy, // Height\n uint uFlags); // Window positioning flags\n\n[DllImport(\"user32.dll\")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nstatic void ShowInactiveTopmost(Form frm)\n{\n ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);\n SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,\n frm.Left, frm.Top, frm.Width, frm.Height,\n SWP_NOACTIVATE);\n}\n" }, { "answer_id": 157843, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 8, "selected": true, "text": "protected override bool ShowWithoutActivation\n{\n get { return true; }\n}\n" }, { "answer_id": 884706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern bool OpenIcon(IntPtr hWnd);\n\n[DllImport(\"user32.dll\")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\npublic static void ActivateInstance()\n{\n IntPtr hWnd = IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;\n\n // Restore the program.\n bool result = OpenIcon(hWnd); \n // Activate the application.\n result = SetForegroundWindow(hWnd);\n\n // End the current instance of the application.\n //System.Environment.Exit(0); \n}\n" }, { "answer_id": 1472053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "this.TopMost = true;\nthis.TopMost = false;\nthis.TopMost = true;\nthis.SendToBack();\n" }, { "answer_id": 8144035, "author": "pkr", "author_id": 774828, "author_profile": "https://Stackoverflow.com/users/774828", "pm_score": 2, "selected": false, "text": "this.Focus();\n" }, { "answer_id": 9370064, "author": "Ziketo", "author_id": 1222233, "author_profile": "https://Stackoverflow.com/users/1222233", "pm_score": 3, "selected": false, "text": "<Window\n x:Class=\"myApplication.winNotification\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Notification Popup\" Width=\"300\" SizeToContent=\"Height\"\n WindowStyle=\"None\" AllowsTransparency=\"True\" Background=\"Transparent\" ShowInTaskbar=\"False\" Topmost=\"True\" Focusable=\"False\" ShowActivated=\"False\" >\n</Window>\n" }, { "answer_id": 13790153, "author": "Pawel Pawlowski", "author_id": 1886141, "author_profile": "https://Stackoverflow.com/users/1886141", "pm_score": -1, "selected": false, "text": "window.WindowState = WindowState.Minimized;" }, { "answer_id": 15271415, "author": "Meta", "author_id": 2144113, "author_profile": "https://Stackoverflow.com/users/2144113", "pm_score": 1, "selected": false, "text": "internal static DateTime LastBringToFrontTime { get; set; }\n\nprivate void Form1_Activated(object sender, EventArgs e)\n{\n var eventTime = DateTime.Now;\n if ((eventTime - LastBringToFrontTime).TotalMilliseconds > 500)\n Core.BringAllToFront(this);\n LastBringToFrontTime = eventTime;\n}\n" }, { "answer_id": 25219399, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": 4, "selected": false, "text": " protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n\n private const int WS_EX_TOPMOST = 0x00000008;\n protected override CreateParams CreateParams\n {\n get\n {\n CreateParams createParams = base.CreateParams;\n createParams.ExStyle |= WS_EX_TOPMOST;\n return createParams;\n }\n }\n" }, { "answer_id": 30612891, "author": "Domi", "author_id": 4733663, "author_profile": "https://Stackoverflow.com/users/4733663", "pm_score": 1, "selected": false, "text": " [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SetForegroundWindow(IntPtr hWnd);\n\n public static void ShowTopmostNoFocus(Form f)\n {\n IntPtr activeWin = GetForegroundWindow();\n\n f.Show();\n f.BringToFront();\n f.TopMost = true;\n\n if (activeWin.ToInt32() > 0)\n {\n SetForegroundWindow(activeWin);\n }\n }\n" }, { "answer_id": 35929506, "author": "Steven Cvetko", "author_id": 6047481, "author_profile": "https://Stackoverflow.com/users/6047481", "pm_score": 0, "selected": false, "text": " form.Visible = false;\n form.TopMost = false;\n ShowWindow(form.Handle, ShowNoActivate);\n SetWindowPos(form.Handle, HWND_TOPMOST,\n form.Left, form.Top, form.Width, form.Height,\n NoActivate);\n form.Visible = true; //So that Load event happens\n" }, { "answer_id": 69726485, "author": "Antony Cartwright", "author_id": 16692341, "author_profile": "https://Stackoverflow.com/users/16692341", "pm_score": 0, "selected": false, "text": "a = new Assign_Stock(); \na.MdiParent = this.ParentForm;\na.Visible = false; //hide for a bit. \na.Show(); //show the form. Invisible form now at the top.\nthis.Focus(); //focus on this form. make old form come to the top.\na.Visible = true; //make other form visible now. Behind the main form.\n" }, { "answer_id": 70596793, "author": "lava", "author_id": 7706354, "author_profile": "https://Stackoverflow.com/users/7706354", "pm_score": 0, "selected": false, "text": " protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
156,051
<p>I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop:</p> <pre><code>function populateDropDown(dropdownId, list, enable, showCount) { var dropdown = $get(dropdownId); dropdown.options.length = 1; for (var i = 0; i &lt; list.length; i++) { var opt = document.createElement("option"); if (showCount) { opt.text = list[i].Name + ' (' + list[i].ChildCount + ')'; } else { opt.text = list[i].Name; } opt.value = list[i].Name; dropdown.options.add(opt); } dropdown.disabled = !enable; } </code></pre> <p>However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback?</p> <p><strong>Edit:</strong> Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?</p>
[ { "answer_id": 156065, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
156,083
<p>I hear people writing these programs all the time and I know what they do, but how do they actually do it? I'm looking for general concepts.</p>
[ { "answer_id": 156312, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "//Show My SO Reputation Score\nvar repval = $('span.reputation-score:first'); alert('StackOverflow User \"' + repval.prev().attr('href').split('/').pop() + '\" has (' + repval.html() + ') Reputation Points.');\n" }, { "answer_id": 1170435, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "string pageContents = new WebClient(\"www.stackoverflow.com\").DownloadString();\nint numberOfPosts = // regex match\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
156,084
<p>Using VBA i have a set of functions that return an <code>ADODB.Recordset</code> where all the columns as <code>adVarChar</code>. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7</p> <p>Is there any methods that can sort numerics as text columns without resorting to changing the type of the column?</p> <pre><code>Sub TestSortVarChar() Dim strBefore, strAfter As String Dim r As ADODB.RecordSet Set r = New ADODB.RecordSet r.Fields.Append "ID", adVarChar, 100 r.Fields.Append "Field1", adVarChar, 100 r.Open r.AddNew r.Fields("ID") = "1" r.Fields("Field1") = "A" r.AddNew r.Fields("ID") = "7" r.Fields("Field1") = "B" r.AddNew r.Fields("ID") = "16" r.Fields("Field1") = "C" r.AddNew r.Fields("ID") = "22" r.Fields("Field1") = "D" r.MoveFirst Do Until r.EOF strBefore = strBefore &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop r.Sort = "[ID] ASC" r.MoveFirst Do Until r.EOF strAfter = strAfter &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop MsgBox strBefore &amp; vbCrLf &amp; vbCrLf &amp; strAfter End Sub </code></pre> <p>NB: I am using Project 2003 and Excel 2003 and referencing <strong>Microsoft ActiveX DataObject 2.8 Library</strong></p>
[ { "answer_id": 157741, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 2, "selected": false, "text": "SELECT ID, Field1\nFROM tablename\nORDER BY Val(Field1);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ]
156,089
<p>I am just starting with SL and WPF. I am using the DataGrid control and I need to remove the mouseover effect (I actually will need to do more customizations than that). How do I do this. I think I need to do it with a control template but not sure how. I'm researching and reading right now. Any help would be appreciated.</p>
[ { "answer_id": 183936, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 2, "selected": false, "text": "<vsm:VisualState x:Name=\"MouseOver\">" }, { "answer_id": 1681462, "author": "Scott", "author_id": 38832, "author_profile": "https://Stackoverflow.com/users/38832", "pm_score": 2, "selected": false, "text": " <Style x:Key=\"CellStyle\" TargetType=\"local:DataGridCell\">\n <Setter Property=\"Background\" Value=\"Transparent\" />\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"Cursor\" Value=\"Arrow\" />\n <Setter Property=\"IsTabStop\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"local:DataGridCell\">\n <Grid Name=\"Root\" Background=\"Transparent\">\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"CurrentStates\" >\n <vsm:VisualStateGroup.Transitions>\n <vsm:VisualTransition GeneratedDuration=\"0\" />\n </vsm:VisualStateGroup.Transitions>\n\n <vsm:VisualState x:Name=\"Regular\" />\n <vsm:VisualState x:Name=\"Current\" />\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"FocusVisual\" Storyboard.TargetProperty=\"Opacity\" To=\"1\" Duration=\"0\" />\n </Storyboard>\n </vsm:VisualState>-->\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <Rectangle Name=\"FocusVisual\" Stroke=\"#FF6DBDD1\" StrokeThickness=\"1\" Fill=\"#66FFFFFF\" HorizontalAlignment=\"Stretch\" VerticalAlignment=\"Stretch\" IsHitTestVisible=\"false\" Opacity=\"0\" />\n <ContentPresenter Content=\"{TemplateBinding Content}\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" Cursor=\"{TemplateBinding Cursor}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" Margin=\"{TemplateBinding Padding}\" />\n <Rectangle Name=\"RightGridLine\" Grid.Column=\"1\" VerticalAlignment=\"Stretch\" Width=\"1\" />\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23663/" ]
156,113
<p>I have some linq entities that inherit something like this:</p> <pre><code>public abstract class EntityBase { public int Identifier { get; } } public interface IDeviceEntity { int DeviceId { get; set; } } public abstract class DeviceEntityBase : EntityBase, IDeviceEntity { public abstract int DeviceId { get; set; } } public partial class ActualLinqGeneratedEntity : DeviceEntityBase { } </code></pre> <p>In a generic method I am querying DeviceEnityBase derived entities with:</p> <pre><code>return unitOfWork.GetRepository&lt;TEntity&gt;().FindOne(x =&gt; x.DeviceId == evt.DeviceId); </code></pre> <p>where TEntity has a contraint that is it a DeviceEntityBase. This query is always failing with an InvalidOperationException with the message "Class member DeviceEntityBase.DeviceId is unmapped". Even if I add some mapping info in the abstract base class with</p> <pre><code>[Column(Storage = "_DeviceId", DbType = "Int", Name = "DeviceId", IsDbGenerated = false, UpdateCheck = UpdateCheck.Never)] </code></pre>
[ { "answer_id": 156365, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "static Expression<Func<T, bool>> BuildWhere<T>(int deviceId) {\n var id = Expression.Constant(deviceId, typeof(int));\n var arg = Expression.Parameter(typeof(T), \"x\");\n var prop = Expression.Property(arg, \"DeviceId\");\n return Expression.Lambda<Func<T, bool>>(\n Expression.Equal(prop, id), arg);\n}\n" }, { "answer_id": 5070997, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "return unitOfWork.GetRepository<TEntity>().Select(x => x).FindOne(x => x.DeviceId == evt.DeviceId);\n" }, { "answer_id": 41870896, "author": "ViRuSTriNiTy", "author_id": 3936440, "author_profile": "https://Stackoverflow.com/users/3936440", "pm_score": 0, "selected": false, "text": ".OfType<>()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
156,114
<p>When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls.</p> <p>Currently I do that by running the query twice, once wrapped in a <code>count()</code> to determine the total results, and a second time with a limit applied to get back just the results I need for the current page.</p> <p>This seems inefficient. Is there a better way to determine how many results would have been returned before <code>LIMIT</code> was applied?</p> <p>I am using PHP and Postgres.</p>
[ { "answer_id": 8242764, "author": "Erwin Brandstetter", "author_id": 939860, "author_profile": "https://Stackoverflow.com/users/939860", "pm_score": 8, "selected": true, "text": "SELECT foo\n , count(*) OVER() AS full_count\nFROM bar\nWHERE <some condition>\nORDER BY <some col>\nLIMIT <pagesize>\nOFFSET <offset>;" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
156,116
<p>I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox.</p> <p>Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred.</p> <pre><code>&lt;style type="text/css"&gt; .CSSClassName {filter:Invert;} .CSSClassName {filter:Xray;} .CSSClassName {filter:Gray;} .CSSClassName {filter:FlipV;} &lt;/style&gt; </code></pre> <p>Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?</p>
[ { "answer_id": 156142, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "filter" }, { "answer_id": 156238, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 0, "selected": false, "text": "filter" }, { "answer_id": 26088245, "author": "aWebDeveloper", "author_id": 406659, "author_profile": "https://Stackoverflow.com/users/406659", "pm_score": 0, "selected": false, "text": "filter: <filter-function> [<filter-function>]* | none\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice" rel="noreferrer">http://code.google.com/p/google-guice</a>) for Python?</p>
[ { "answer_id": 34346267, "author": "Aigrefin", "author_id": 1014321, "author_profile": "https://Stackoverflow.com/users/1014321", "pm_score": 0, "selected": false, "text": "from py3njection import inject\nfrom some_package import ClassToInject\n\nclass Demo:\n @inject\n def __init__(self, object_to_use: ClassToInject):\n self.dependency = object_to_use\n\ndemo = Demo()\n" }, { "answer_id": 35831886, "author": "Roman Mogylatov", "author_id": 4224605, "author_profile": "https://Stackoverflow.com/users/4224605", "pm_score": 2, "selected": false, "text": "\"\"\"Pythonic way for Dependency Injection.\"\"\"\n\nfrom dependency_injector import providers\nfrom dependency_injector import injections\n\n\n@providers.DelegatedCallable\ndef get_user_info(user_id):\n \"\"\"Return user info.\"\"\"\n raise NotImplementedError()\n\n\n@providers.Factory\n@injections.inject(get_user_info=get_user_info)\nclass AuthComponent(object):\n \"\"\"Some authentication component.\"\"\"\n\n def __init__(self, get_user_info):\n \"\"\"Initializer.\"\"\"\n self.get_user_info = get_user_info\n\n def authenticate_user(self, token):\n \"\"\"Authenticate user by token.\"\"\"\n user_info = self.get_user_info(user_id=token + '1')\n return user_info\n\n\nprint AuthComponent\nprint get_user_info\n\n\n@providers.override(get_user_info)\n@providers.DelegatedCallable\ndef get_user_info(user_id):\n \"\"\"Return user info.\"\"\"\n return {'user_id': user_id}\n\n\nprint AuthComponent().authenticate_user(token='abc')\n# {'user_id': 'abc1'}\n" }, { "answer_id": 47136116, "author": "Éttore Leandro Tognoli", "author_id": 8484999, "author_profile": "https://Stackoverflow.com/users/8484999", "pm_score": 1, "selected": false, "text": "import logging\nfrom logging import Logger\n\nfrom pycdi import Inject, Singleton, Producer\nfrom pycdi.shortcuts import call\n\n\n@Producer(str, _context='app_name')\ndef get_app_name():\n return 'PyCDI'\n\n\n@Singleton(produce_type=Logger)\n@Inject(app_name=str, _context='app_name')\ndef get_logger(app_name):\n return logging.getLogger(app_name)\n\n\n@Inject(name=(str, 'app_name'), logger=Logger)\ndef main(name, logger):\n logger.info('I\\'m starting...')\n print('Hello World!!!\\nI\\'m a example of %s' % name)\n logger.debug('I\\'m finishing...')\n\n\ncall(main)\n" }, { "answer_id": 48965677, "author": "Rodrigo Oliveira", "author_id": 2468458, "author_profile": "https://Stackoverflow.com/users/2468458", "pm_score": 2, "selected": false, "text": "def foo(dep = None): # great for unit testing!\n ...\n" }, { "answer_id": 61826579, "author": "David", "author_id": 428640, "author_profile": "https://Stackoverflow.com/users/428640", "pm_score": 0, "selected": false, "text": "3.6" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
156,243
<p>What is the difference between the following 2 ways to allocate and init an object?</p> <pre><code>AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; </code></pre> <p>and</p> <pre><code>self.aController= [[AController alloc] init]; </code></pre> <p>Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?</p>
[ { "answer_id": 156289, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 7, "selected": true, "text": "@property (retain)" }, { "answer_id": 156516, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "self.aController = [[[AController alloc] init] autorelease];\n" }, { "answer_id": 159069, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 2, "selected": false, "text": "@property (readwrite, retain) id aController;" }, { "answer_id": 167783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "self.aController= [[[AController alloc] init] autorelease];\n" }, { "answer_id": 1225254, "author": "mk12", "author_id": 148195, "author_profile": "https://Stackoverflow.com/users/148195", "pm_score": 2, "selected": false, "text": "@property (nonatomic, retain)AController *aController;\n...\nself.aController= [[AController alloc] init];\n[aController release];\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
156,256
<p>The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing?</p> <p>Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call.</p> <pre><code>using System.Windows; namespace TextBoxClear { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Test_LostFocus(object sender, RoutedEventArgs e) { Test.Clear(); } } } &lt;Window x:Class="TextBoxClear.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;StackPanel&gt; &lt;TextBox /&gt; &lt;TextBox LostFocus="Test_LostFocus" Name="Test" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>Assembly references:</p> <ul> <li>mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> </ul>
[ { "answer_id": 156277, "author": "Jason Anderson", "author_id": 5142, "author_profile": "https://Stackoverflow.com/users/5142", "pm_score": 2, "selected": false, "text": " private void Test_LostFocus(object sender, RoutedEventArgs e)\n {\n if (Test != null)\n Test.Clear();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,257
<p>In an AI application I am writing in C++, </p> <ol> <li>there is not much numerical computation </li> <li>there are lot of structures for which run-time polymorphism is needed </li> <li>very often, several polymorphic structures interact during computation</li> </ol> <p>In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). </p> <p>In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? </p> <p>Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. </p> <p><em>Update</em>: Also see the following related forums: <a href="https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#171549">Performance Penalty for Interface</a>, <a href="https://stackoverflow.com/questions/99510/does-several-levels-of-base-classes-slow-down-a-classstruct-in-c">Several Levels of Base Classes</a> </p>
[ { "answer_id": 156420, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 6, "selected": true, "text": "classptr -> [vtable:4][classdata:x]\nvtable -> [first:4][second:4][third:4][fourth:4][...]\nfirst -> [code:x]\nsecond -> [code:x]\n...\n" }, { "answer_id": 157025, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 2, "selected": false, "text": "Class A {\n inline virtual int foo() {...}\n};\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19501/" ]
156,275
<p>Is there a good reason why there is no <code>Pair&lt;L,R&gt;</code> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.</p> <p>It seems that <strong>1.6</strong> is providing something similar (<code>AbstractMap.SimpleEntry&lt;K,V&gt;</code>), but this looks quite convoluted.</p>
[ { "answer_id": 156286, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 4, "selected": false, "text": "Map<String, Object> map = ... ; // just an example\nfor (Map.Entry<String, Object> entry : map.entrySet()) {\n System.out.printf(\"%s -> %s\\n\", entry.getKey(), entry.getValue());\n}\n" }, { "answer_id": 156685, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 10, "selected": true, "text": "comp.lang.java.help" }, { "answer_id": 677248, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 7, "selected": false, "text": "public class Pair<A, B> {\n private A first;\n private B second;\n\n public Pair(A first, B second) {\n super();\n this.first = first;\n this.second = second;\n }\n\n public int hashCode() {\n int hashFirst = first != null ? first.hashCode() : 0;\n int hashSecond = second != null ? second.hashCode() : 0;\n\n return (hashFirst + hashSecond) * hashSecond + hashFirst;\n }\n\n public boolean equals(Object other) {\n if (other instanceof Pair) {\n Pair otherPair = (Pair) other;\n return \n (( this.first == otherPair.first ||\n ( this.first != null && otherPair.first != null &&\n this.first.equals(otherPair.first))) &&\n ( this.second == otherPair.second ||\n ( this.second != null && otherPair.second != null &&\n this.second.equals(otherPair.second))) );\n }\n\n return false;\n }\n\n public String toString()\n { \n return \"(\" + first + \", \" + second + \")\"; \n }\n\n public A getFirst() {\n return first;\n }\n\n public void setFirst(A first) {\n this.first = first;\n }\n\n public B getSecond() {\n return second;\n }\n\n public void setSecond(B second) {\n this.second = second;\n }\n}\n" }, { "answer_id": 2192715, "author": "Illarion Kovalchuk", "author_id": 255667, "author_profile": "https://Stackoverflow.com/users/255667", "pm_score": 2, "selected": false, "text": "WeakHashMap<Pair<String, String>, String> map = ...\n" }, { "answer_id": 3646398, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 5, "selected": false, "text": "public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> {\n\n public final FIRST first;\n public final SECOND second;\n\n private Pair(FIRST first, SECOND second) {\n this.first = first;\n this.second = second;\n }\n\n public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first,\n SECOND second) {\n return new Pair<FIRST, SECOND>(first, second);\n }\n\n @Override\n public int compareTo(Pair<FIRST, SECOND> o) {\n int cmp = compare(first, o.first);\n return cmp == 0 ? compare(second, o.second) : cmp;\n }\n\n // todo move this to a helper class.\n private static int compare(Object o1, Object o2) {\n return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1\n : ((Comparable) o1).compareTo(o2);\n }\n\n @Override\n public int hashCode() {\n return 31 * hashcode(first) + hashcode(second);\n }\n\n // todo move this to a helper class.\n private static int hashcode(Object o) {\n return o == null ? 0 : o.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Pair))\n return false;\n if (this == obj)\n return true;\n return equal(first, ((Pair) obj).first)\n && equal(second, ((Pair) obj).second);\n }\n\n // todo move this to a helper class.\n private boolean equal(Object o1, Object o2) {\n return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2));\n }\n\n @Override\n public String toString() {\n return \"(\" + first + \", \" + second + ')';\n }\n}\n" }, { "answer_id": 4453599, "author": "MaxBuzz", "author_id": 543762, "author_profile": "https://Stackoverflow.com/users/543762", "pm_score": 3, "selected": false, "text": "operator <" }, { "answer_id": 4471509, "author": "Michael Piefel", "author_id": 2621917, "author_profile": "https://Stackoverflow.com/users/2621917", "pm_score": 6, "selected": false, "text": "@Data\n@AllArgsConstructor(staticName = \"of\")\npublic class Pair<F, S> {\n private F first;\n private S second;\n}\n" }, { "answer_id": 5734522, "author": "G_H", "author_id": 630136, "author_profile": "https://Stackoverflow.com/users/630136", "pm_score": 1, "selected": false, "text": "hashCode" }, { "answer_id": 8444461, "author": "Bastiflew", "author_id": 1083225, "author_profile": "https://Stackoverflow.com/users/1083225", "pm_score": 0, "selected": false, "text": "public class Pair<K, V> {\n\n private final K element0;\n private final V element1;\n\n public static <K, V> Pair<K, V> createPair(K key, V value) {\n return new Pair<K, V>(key, value);\n }\n\n public Pair(K element0, V element1) {\n this.element0 = element0;\n this.element1 = element1;\n }\n\n public K getElement0() {\n return element0;\n }\n\n public V getElement1() {\n return element1;\n }\n\n}\n" }, { "answer_id": 9522297, "author": "cyberoblivion", "author_id": 1062131, "author_profile": "https://Stackoverflow.com/users/1062131", "pm_score": 5, "selected": false, "text": "Unit<A> (1 element)\nPair<A,B> (2 elements)\nTriplet<A,B,C> (3 elements)\nQuartet<A,B,C,D> (4 elements)\nQuintet<A,B,C,D,E> (5 elements)\nSextet<A,B,C,D,E,F> (6 elements)\nSeptet<A,B,C,D,E,F,G> (7 elements)\nOctet<A,B,C,D,E,F,G,H> (8 elements)\nEnnead<A,B,C,D,E,F,G,H,I> (9 elements)\nDecade<A,B,C,D,E,F,G,H,I,J> (10 elements)\n" }, { "answer_id": 13299709, "author": "Earth Engine", "author_id": 812034, "author_profile": "https://Stackoverflow.com/users/812034", "pm_score": 3, "selected": false, "text": "Pair" }, { "answer_id": 13660918, "author": "Mr_and_Mrs_D", "author_id": 281545, "author_profile": "https://Stackoverflow.com/users/281545", "pm_score": 3, "selected": false, "text": "hashCode()" }, { "answer_id": 14064648, "author": "Andrew Mao", "author_id": 586086, "author_profile": "https://Stackoverflow.com/users/586086", "pm_score": 0, "selected": false, "text": "Pair" }, { "answer_id": 15468967, "author": "Swapneel Patil", "author_id": 251769, "author_profile": "https://Stackoverflow.com/users/251769", "pm_score": 2, "selected": false, "text": "public class Pair<First,Second>{.. }\n" }, { "answer_id": 23468362, "author": "sherpya", "author_id": 764426, "author_profile": "https://Stackoverflow.com/users/764426", "pm_score": 4, "selected": false, "text": "Pair" }, { "answer_id": 33282633, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 2, "selected": false, "text": "Pair" }, { "answer_id": 34976779, "author": "RAJAN_PARMAR", "author_id": 3812854, "author_profile": "https://Stackoverflow.com/users/3812854", "pm_score": 3, "selected": false, "text": "javafx.util.Pair" }, { "answer_id": 35036111, "author": "Dominik", "author_id": 4465567, "author_profile": "https://Stackoverflow.com/users/4465567", "pm_score": 0, "selected": false, "text": "@Value(staticConstructor = \"of\") public class Pair <E> {\n E first, second;\n}\n" }, { "answer_id": 35358753, "author": "Denis Arkharov", "author_id": 5917590, "author_profile": "https://Stackoverflow.com/users/5917590", "pm_score": 2, "selected": false, "text": "Collections.singletonMap(left, rigth);\n" }, { "answer_id": 36493674, "author": "Sathyanarayanan Ganesan", "author_id": 4700500, "author_profile": "https://Stackoverflow.com/users/4700500", "pm_score": 3, "selected": false, "text": "Pair" }, { "answer_id": 45154057, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "class SumHolder{MyObject trackedObject, double sum};\n" }, { "answer_id": 53380628, "author": "Matt Broekhuis", "author_id": 412366, "author_profile": "https://Stackoverflow.com/users/412366", "pm_score": 2, "selected": false, "text": "import lombok.Value;\n\n@Value(staticConstructor = \"of\")\npublic class Pair<F, S> {\n private final F first;\n private final S second;\n}\n" }, { "answer_id": 66396046, "author": "Arefe", "author_id": 2746110, "author_profile": "https://Stackoverflow.com/users/2746110", "pm_score": 0, "selected": false, "text": "Pair<S, T> pair = Pair.of(S type data, T type data)\n" }, { "answer_id": 69213294, "author": "HomeworkHopper", "author_id": 10334839, "author_profile": "https://Stackoverflow.com/users/10334839", "pm_score": 0, "selected": false, "text": "record Pair<K, V>(K key, V value) { }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13673/" ]
156,278
<p>Yet again, my teacher was unable to answer my question. I knew who may be able to...</p> <p>So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put </p> <pre><code>setbuf( stdout , NULL ); </code></pre> <p>at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.</p> <p>My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? </p> <p>Thanks in advance!</p>
[ { "answer_id": 156321, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "std::endl" }, { "answer_id": 156413, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "// make cout unbuffered\nstd::cout.rdbuf()->pubsetbuf(0, 0);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73/" ]
156,279
<p>The title is self explanatory. Is there a way of directly doing such kind of importing?</p>
[ { "answer_id": 156479, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 7, "selected": true, "text": "sqlcmd -S <COMPUTERNAME>\\SQLExpress" }, { "answer_id": 7179605, "author": "Andrew", "author_id": 561698, "author_profile": "https://Stackoverflow.com/users/561698", "pm_score": 1, "selected": false, "text": "MOVE 'mydbName_log' TO 'c:\\temp\\mydbName_data.ldf',\nMOVE 'sysft_...' TO 'c:\\temp\\other';\n" }, { "answer_id": 59558734, "author": "INDRAJITH EKANAYAKE", "author_id": 8134164, "author_profile": "https://Stackoverflow.com/users/8134164", "pm_score": 3, "selected": false, "text": "MsSQL" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
156,280
<p>When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this?</p> <p>I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out).</p> <p>The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy.</p> <p>I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools.</p>
[ { "answer_id": 157642, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "-R" }, { "answer_id": 164566, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 4, "selected": true, "text": "hg clone http://hg.kublai.com/mercurial/extensions/rdiff \n" }, { "answer_id": 3367041, "author": "Ton Plomp", "author_id": 47860, "author_profile": "https://Stackoverflow.com/users/47860", "pm_score": 0, "selected": false, "text": "hg incoming --template {files}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
156,292
<p>I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question.</p> <p>Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies. </p> <p>So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit.</p> <p>Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg:</p> <pre><code>public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc) </code></pre> <p>... or should the dependencies come first and the Order object last, eg:</p> <pre><code>public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order) </code></pre> <p>Does it matter? Does it depend on which IoC container I use? Or is there a "better" way?</p>
[ { "answer_id": 63869152, "author": "Efran Cobisi", "author_id": 904178, "author_profile": "https://Stackoverflow.com/users/904178", "pm_score": 0, "selected": false, "text": "*Service" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
156,322
<p>fossil <a href="http://www.fossil-scm.org" rel="noreferrer">http://www.fossil-scm.org</a><br> I found this recently and have started using it for my home projects. I want to hear what other people think of this VCS. </p> <p>What is missing in my mind, is IDE support. Hopefully it will come, but I use the command line just fine.</p> <p>My favorite things about fossil: single executable with built in web server wiki and bug tracking. The repository is just one SQLite (<a href="http://www.sqlite.org" rel="noreferrer">http://www.sqlite.org</a>) database file, easy to do backups on. I also like that I can run fossil from and keep the repository on my thumb drive. This means my software development has become completely portable. </p> <p>Tell me what you think....</p>
[ { "answer_id": 265829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "for /r %i in (*.*) do fossil add \"%i\"\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576/" ]
156,329
<p>I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle.</p> <pre><code>select to_char(1011,'00000000') OPE_NO from dual; select length(to_char(1011,'00000000')) OPE_NO from dual; </code></pre> <p>Instead of '00001011' I get ' 00001011'. Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this?</p> <p>P.S. I realise I can just use <code>trim()</code>, but I want to understand number formatting better.</p> <p>@Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. </p> <p>@David: So does that mean there's no way but to use <code>trim()</code>?</p>
[ { "answer_id": 156670, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 6, "selected": true, "text": "select to_char(1011,'FM00000000') OPE_NO from dual;" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
[ { "answer_id": 156335, "author": "blackwing", "author_id": 9107, "author_profile": "https://Stackoverflow.com/users/9107", "pm_score": 5, "selected": false, "text": "time()" }, { "answer_id": 156339, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "import datetime\n\nstart = datetime.datetime.now()\ndo_long_code()\nfinish = datetime.datetime.now()\ndelta = finish - start\nprint delta.seconds\n" }, { "answer_id": 157423, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "time" }, { "answer_id": 13300640, "author": "leetNightshade", "author_id": 353094, "author_profile": "https://Stackoverflow.com/users/353094", "pm_score": 3, "selected": false, "text": "class Timer:\n def __enter__(self):\n self.begin = now()\n\n def __exit__(self, type, value, traceback):\n print(format_delta(self.begin, now()))\n" }, { "answer_id": 35675299, "author": "Mark", "author_id": 723090, "author_profile": "https://Stackoverflow.com/users/723090", "pm_score": 0, "selected": false, "text": "class Ticker:\n def __init__(self):\n self.t = clock()\n\n def __call__(self):\n dt = clock() - self.t\n self.t = clock()\n return 1000 * dt\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
156,331
<p>I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks</p>
[ { "answer_id": 156346, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 5, "selected": false, "text": "msaccess.exe \"target database.accdb\" /compact \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24020/" ]
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
[ { "answer_id": 156564, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "from __future__ import with_statement\nimport threading\n\nclass ItemStore(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.items = []\n\n def add(self, item):\n with self.lock:\n self.items.append(item)\n\n def getAll(self):\n with self.lock:\n items, self.items = self.items, []\n return items\n" }, { "answer_id": 156736, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 4, "selected": true, "text": "get_nowait()" }, { "answer_id": 25768255, "author": "Gab", "author_id": 768335, "author_profile": "https://Stackoverflow.com/users/768335", "pm_score": 4, "selected": false, "text": "def get_all_queue_result(queue):\n\n result_list = []\n while not queue.empty():\n result_list.append(queue.get())\n\n return result_list\n" }, { "answer_id": 28571101, "author": "Wraith404", "author_id": 809268, "author_profile": "https://Stackoverflow.com/users/809268", "pm_score": 2, "selected": false, "text": "responseList = []\nfor items in range(0, q.qsize()):\n responseList.append(q.get_nowait())\n" }, { "answer_id": 55519286, "author": "EvertW", "author_id": 1767653, "author_profile": "https://Stackoverflow.com/users/1767653", "pm_score": 3, "selected": false, "text": "items = [q.get() for _ in range(q.qsize())]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
156,362
<p>Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. </p> <ul> <li><strong>include</strong>: mixes in specified module methods as <strong>instance methods</strong> in the target class</li> <li><strong>extend</strong>: mixes in specified module methods as <strong>class methods</strong> in the target class</li> </ul> <p><em>So is the major difference just this or is a bigger dragon lurking?</em> e.g.</p> <pre><code>module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" </code></pre>
[ { "answer_id": 156927, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 9, "selected": true, "text": "Klazz" }, { "answer_id": 5008349, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 9, "selected": false, "text": "Klazz.extend(Mod)" }, { "answer_id": 36247164, "author": "user1136228", "author_id": 1136228, "author_profile": "https://Stackoverflow.com/users/1136228", "pm_score": 2, "selected": false, "text": "include" }, { "answer_id": 58022371, "author": "Chintan", "author_id": 6543250, "author_profile": "https://Stackoverflow.com/users/6543250", "pm_score": 4, "selected": false, "text": "include" }, { "answer_id": 70124407, "author": "Abdullah Numan", "author_id": 4515413, "author_profile": "https://Stackoverflow.com/users/4515413", "pm_score": 1, "selected": false, "text": "include" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
156,369
<p>It seems quite a few mainstream languages support <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">function literals</a> these days. They are also called <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous functions</a>, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, <code>&amp;printf</code> doesn't count.</p> <p>EDIT to add: if you have a genuine function literal expression <code>&lt;exp&gt;</code>, you should be able to pass it to a function <code>f(&lt;exp&gt;)</code> or immediately apply it to an argument, ie. <code>&lt;exp&gt;(5)</code>. </p> <p>I'm curious which languages let you write function literals which are <em>recursive</em>. Wikipedia's "<a href="http://en.wikipedia.org/wiki/Anonymous_recursion" rel="noreferrer">anonymous recursion</a>" article doesn't give any programming examples.</p> <p>Let's use the recursive factorial function as the example.</p> <p>Here are the ones I know:</p> <ul> <li><p>JavaScript / ECMAScript can do it with <code>callee</code>:</p> <pre><code>function(n){if (n&lt;2) {return 1;} else {return n * arguments.callee(n-1);}} </code></pre></li> <li><p>it's easy in languages with <code>letrec</code>, eg Haskell (which calls it <code>let</code>):</p> <blockquote> <p><code>let fac x = if x&lt;2 then 1 else fac (x-1) * x in fac</code></p> </blockquote> <p>and there are equivalents in Lisp and Scheme. Note that the binding of <code>fac</code> is local to the expression, so the whole expression is in fact an anonymous function.</p></li> </ul> <p>Are there any others?</p>
[ { "answer_id": 156374, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "labels" }, { "answer_id": 156393, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "# Define Y combinator...come on Gudio, put it in functools!\nY = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))\n\n# Define anonymous recursive factorial function\nfac = Y(lambda f: lambda n: (1 if n<2 else n*f(n-1)))\nassert fac(7) == 5040\n" }, { "answer_id": 156409, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "my $factorial = do {\n my $fac;\n $fac = sub {\n my $n = shift;\n if ($n < 2) { 1 } else { $n * $fac->($n-1) }\n };\n};\n\nprint $factorial->(4);\n" }, { "answer_id": 156426, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "Func<int, int> fac = null;\nfac = n => n < 2 ? 1 : n * fac(n-1);\nConsole.WriteLine(fac(7));\n" }, { "answer_id": 156444, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "(labels ((factorial (x) ;define name and params\n ; body of function addrec\n (if (= x 1)\n (return 1)\n (+ (factorial (- x 1))))) ;should not close out labels\n ;call factorial inside labels function\n (factorial 5)) ;this would return 15 from labels\n" }, { "answer_id": 156468, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 3, "selected": false, "text": "delegate Func<A, R> Recursive<A, R>(Recursive<A, R> r);\n\nstatic Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)\n{\n Recursive<A, R> rec = r => a => f(r(r))(a);\n return rec(rec);\n}\n\nstatic void Main(string[] args)\n{\n Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);\n Func<int, int> fact = Y<int, int>(f => n => n > 1 ? n * f(n - 1) : 1);\n Console.WriteLine(fib(6)); // displays 8\n Console.WriteLine(fact(6));\n Console.ReadLine();\n} \n" }, { "answer_id": 156555, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "type\n // method reference\n TProc = reference to procedure(x: Integer); \n\nprocedure Call(const proc: TProc);\nbegin\n proc(42);\nend;\n" }, { "answer_id": 156655, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "foo(function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}});\n" }, { "answer_id": 171023, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "my $f = -> $n { if ($n <= 1) {1} else {$n * &?BLOCK($n - 1)} }\n$f(42); # ==> 1405006117752879898543142606244511569936384000000000\n" }, { "answer_id": 642890, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 0, "selected": false, "text": ">> fact = @(val,branchFcns) val*branchFcns{(val <= 1)+1}(val-1,branchFcns);\n>> returnOne = @(val,branchFcns) 1;\n>> branchFcns = {fact returnOne};\n>> fact(4,branchFcns)\n\nans =\n\n 24\n\n>> fact(5,branchFcns)\n\nans =\n\n 120\n" }, { "answer_id": 1675978, "author": "Andrew Janke", "author_id": 105904, "author_profile": "https://Stackoverflow.com/users/105904", "pm_score": 1, "selected": false, "text": "f = @(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1)\n" }, { "answer_id": 2858779, "author": "Puppy", "author_id": 298661, "author_profile": "https://Stackoverflow.com/users/298661", "pm_score": 0, "selected": false, "text": "auto kek = [](){kek();}\n" }, { "answer_id": 2870453, "author": "Zorf", "author_id": 2281094, "author_profile": "https://Stackoverflow.com/users/2281094", "pm_score": 0, "selected": false, "text": "(define-syntax lambdarec\n (syntax-rules ()\n ((lambdarec (tag . params) . body)\n ((lambda ()\n (define (tag . params) . body)\n tag)))))\n" }, { "answer_id": 6949191, "author": "Mechanical snail", "author_id": 319931, "author_profile": "https://Stackoverflow.com/users/319931", "pm_score": 1, "selected": false, "text": "#0" }, { "answer_id": 41702432, "author": "Ssswift", "author_id": 7419656, "author_profile": "https://Stackoverflow.com/users/7419656", "pm_score": 0, "selected": false, "text": "fn" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15069/" ]
156,373
<p>I'm storing an object (<code>TTF_Font</code>) in a <code>shared_ptr</code> that is provided to me from a third-party API. I cannot use new or delete on the object, so the <code>shared_ptr</code> is also provided a "freeing" functor.</p> <pre><code>// Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr&lt;TTF_Font&gt; screenFont; screenFont = boost::shared_ptr&lt;TTF_Font&gt;( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); </code></pre> <p>If, later, I need to explicitly free this object is it correct to do this:</p> <pre><code>screenFont.reset(); </code></pre> <p>And then let <code>screenFont</code> (the actual <code>shared_ptr</code> object) be destroyed naturally?</p>
[ { "answer_id": 156386, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "TTF_OpenFont" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
156,394
<p>How is it that Ruby allows a class access methods outside of the class implicitly?</p> <p>Example:</p> <pre><code>class Candy def land homer end end def homer puts "Hello" end Candy.new.land #Outputs Hello </code></pre>
[ { "answer_id": 161113, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "homer" }, { "answer_id": 8286738, "author": "Linuxios", "author_id": 1008938, "author_profile": "https://Stackoverflow.com/users/1008938", "pm_score": 0, "selected": false, "text": "def" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,395
<p>As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what "<em>sending a message to nil</em>" means - let alone how it is actually useful. Taking an excerpt from the documentation:</p> <blockquote> <p>There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:</p> <ul> <li>If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.</li> <li>If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.</li> <li>If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.</li> </ul> </blockquote> <p>Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass?</p> <p>I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be <code>nil</code>.</p>
[ { "answer_id": 156415, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 4, "selected": false, "text": "[someNullNSArrayReference count] => 0\n" }, { "answer_id": 156463, "author": "Michael Buckley", "author_id": 22540, "author_profile": "https://Stackoverflow.com/users/22540", "pm_score": 8, "selected": true, "text": "void foo(ArrayList list)\n{\n for(int i = 0; i < list.size(); ++i){\n System.out.println(list.get(i).toString());\n }\n}\n" }, { "answer_id": 156498, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "[someVariable release];\n" }, { "answer_id": 195944, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": false, "text": "nil" }, { "answer_id": 276943, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 6, "selected": false, "text": "nil" }, { "answer_id": 310215, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 5, "selected": false, "text": "nil" }, { "answer_id": 5530582, "author": "Rinzwind", "author_id": 276925, "author_profile": "https://Stackoverflow.com/users/276925", "pm_score": 3, "selected": false, "text": "nil" }, { "answer_id": 27105329, "author": "Zee", "author_id": 1210962, "author_profile": "https://Stackoverflow.com/users/1210962", "pm_score": 2, "selected": false, "text": "// For example, this expression...\nif (name != nil && [name isEqualToString:@\"Steve\"]) { ... }\n\n// ...can be simplified to:\nif ([name isEqualToString:@\"Steve\"]) { ... }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931/" ]
156,412
<p><code>GWT</code> gets locale from either the locale property or the locale query string. If neither is specified, it uses the "default" (ie <code>en_US</code>) locale.</p> <p>Why doesn't it get it from the browser settings?</p> <p>It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?</p>
[ { "answer_id": 161313, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 2, "selected": false, "text": "<!-- Slovenian in Slovenia -->\n<extend-property name=\"locale\" values=\"sl\"/>\n\n<!-- English language, independent of country -->\n<extend-property name=\"locale\" values=\"en\"/>\n" }, { "answer_id": 7992504, "author": "ljader", "author_id": 498096, "author_profile": "https://Stackoverflow.com/users/498096", "pm_score": 3, "selected": false, "text": "<set-configuration-property name=\"locale.useragent\" value=\"Y\"/>\n" }, { "answer_id": 8259725, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 0, "selected": false, "text": "Accept-Language" }, { "answer_id": 16627609, "author": "Jorge P.", "author_id": 1815133, "author_profile": "https://Stackoverflow.com/users/1815133", "pm_score": 1, "selected": false, "text": "<set-configuration-property name=\"locale.cookie\" value=\"yourCookieName\"/>\n<set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\"/>\n" }, { "answer_id": 17296508, "author": "Manish Prajapati", "author_id": 1651893, "author_profile": "https://Stackoverflow.com/users/1651893", "pm_score": 0, "selected": false, "text": "<set-configuration-property name=\"locale.useragent\" value=\"Y\"/>" }, { "answer_id": 28435325, "author": "JuanFran Adame", "author_id": 1530949, "author_profile": "https://Stackoverflow.com/users/1530949", "pm_score": 0, "selected": false, "text": "<!-- Locales -->\n<extend-property name=\"locale\" values=\"en_US\"/>\n<extend-property name=\"locale\" values=\"es\"/> \n<set-property-fallback name=\"locale\" value=\"en_US\"/>\n<set-configuration-property name=\"locale.useragent\" value=\"Y\" />\n<set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\" />\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
156,430
<p>I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume.</p> <p>Why is that?</p> <p>Are there any known and proven regexps that actually do this fully?</p> <p>What are some good alternatives to using regexps for matching email addresses?</p>
[ { "answer_id": 156449, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 3, "selected": false, "text": "\" @ \"@example.com\n" }, { "answer_id": 156455, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 1, "selected": false, "text": "\"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\"\n" }, { "answer_id": 156469, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 5, "selected": false, "text": "Mail::VRFY" }, { "answer_id": 156812, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));\n" }, { "answer_id": 167511, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 2, "selected": false, "text": "^[a-zA-Z]([.]?([a-zA-Z0-9_-]+)*)?@([a-zA-Z0-9\\-_]+\\.)+[a-zA-Z]{2,4}$ \n" }, { "answer_id": 1985762, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 2, "selected": false, "text": "MailAddress" }, { "answer_id": 59903872, "author": "Service Objects Engineering", "author_id": 12327828, "author_profile": "https://Stackoverflow.com/users/12327828", "pm_score": 0, "selected": false, "text": "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
156,436
<p>It's quite a simple question - how do I sort a collection?</p> <p>I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary?</p> <p>I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b.</p>
[ { "answer_id": 156496, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<%\n\nDim strConnection, conn, rs, strSQL\n\nstrConnection = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\inetpub\\wwwroot\\;Extended Properties='text;HDR=Yes;FMT=Delimited';\"\n\nSet conn = Server.CreateObject(\"ADODB.Connection\")\nconn.Open strConnection\n\nSet rs = Server.CreateObject(\"ADODB.recordset\")\nstrSQL = \"SELECT * FROM test.csv order by date desc\"\nrs.open strSQL, conn, 3,3\n\nWHILE NOT rs.EOF\n Response.Write(rs(\"date\") & \"<br/>\") \n rs.MoveNext\nWEND\n\nrs.Close\nSet rs = Nothing\n\nconn.Close\nSet conn = Nothing\n\n%>\n" }, { "answer_id": 156611, "author": "Michal", "author_id": 21672, "author_profile": "https://Stackoverflow.com/users/21672", "pm_score": 5, "selected": true, "text": "set list = server.createObject(\"System.Collections.Sortedlist\")\nwith list\n .add \"something\", \"YY\"\n .add \"something else\", \"XX\"\nend with\n\nfor i = 0 to list.count - 1\n response.write(list.getKey(i) & \" = \" & list.getByIndex(i))\nnext\n" }, { "answer_id": 10835474, "author": "James Wiseman", "author_id": 144491, "author_profile": "https://Stackoverflow.com/users/144491", "pm_score": 0, "selected": false, "text": "'Simple collection manager class.\n'Performs the opration of adding/setting a collection item.\n'Encapulated off here in order to delegate responsibility away from the collection class.\nClass clsCollectionManager\n Public Sub PopulateCollectionItem(collection, strKey, Value)\n If collection.Exists(strKey) Then\n If (VarType(Value) = vbObject) Then\n Set collection.Item(strKey) = Value\n Else\n collection.Item(strKey) = Value\n End If\n Else\n Call collection.Add(strKey, Value)\n End If\n End Sub\n\n 'take a collection and a new element as input parameters, an spit out a brand new collection \n 'with the new item iserted into the correct location by order\n 'This works on the assumption that the collection it is receiving is already ordered \n '(which it should be if we always use this method to populate the item)\n\n 'This mutates the passed collection, so we highlight this by marking it as byref \n '(this is not strictly necessary as objects are passed by reference anyway)\n Public Sub AddCollectionItemInOrder(byref existingCollection, strNewKey, Value)\n Dim orderedCollection: Set orderedCollection = Server.CreateObject(\"Scripting.Dictionary\")\n Dim strExistingKey\n\n 'If there is something already in our recordset then we need to add it in order.\n\n 'There is no sorting available for a collection (or an array) in VBScript. Therefore we have to do it ourself.\n 'First, iterate over eveything in our current collection. We have to assume that it is itself sorted.\n For Each strExistingKey In existingCollection\n\n 'if the new item doesn't exist AND it occurs after the current item, then add the new item in now \n '(before adding in the current item.)\n If (Not orderedCollection.Exists(strNewKey)) And (strExistingKey > strNewKey) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n Call PopulateCollectionItem(orderedCollection, strExistingKey, existingCollection.item(strExistingKey))\n Next\n\n 'Finally check to see if it still doesn't exist. \n 'It won't if the last place for it is at the very end, or the original collection was empty\n If (Not orderedCollection.Exists(strNewKey)) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n\n Set existingCollection = orderedCollection\n End Sub\nEnd Class\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5744/" ]
156,438
<p>See title: what does it mean for a C++ function to be inline?</p>
[ { "answer_id": 156453, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "if" }, { "answer_id": 156511, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 5, "selected": false, "text": "inline" }, { "answer_id": 157859, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 0, "selected": false, "text": "int foo();\ninline int bar();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
156,457
<p>Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls?</p>
[ { "answer_id": 2297261, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 2, "selected": false, "text": "foreach (Control ctrl in errProv.ContainerControl.Controls)\n{\n Console.WriteLine(errProv.GetError(ctrl));\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
156,467
<p>I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier.</p> <p>In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows:</p> <ul> <li>match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc]</li> <li>match by predicate</li> <li>combinations of the above (and possibly some other scenarios I'm not aware of)</li> </ul> <p>While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow:</p> <pre><code>var getRentPrice = new Switch&lt;Vehicle, int&gt;() .Case&lt;Motorcycle&gt;(bike =&gt; 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case&lt;Bicycle&gt;(30) // returns a constant .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Diesel, car =&gt; 220 + car.Doors * 20) .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Gasoline, car =&gt; 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator </code></pre> <p>where getRentPrice is a Func&lt;Vehicle,int&gt;.</p> <p>[note - maybe Switch/Case here is the wrong terms... but it shows the idea]</p> <p>To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a <em>lot</em> of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage.</p> <p><strong>I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?</strong></p> <p>Note additionally that I've been playing with 3 variants of the above:</p> <ul> <li>a Func&lt;TSource,TValue&gt; version for evaluation - comparable to composite ternary conditional statements</li> <li>an Action&lt;TSource&gt; version - comparable to if/else if/else if/else if/else</li> <li>an Expression&lt;Func&lt;TSource,TValue&gt;&gt; version - as the first, but usable by arbitrary LINQ providers</li> </ul> <p>Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func&lt;...&gt; based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases.</p> <p>I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).</p>
[ { "answer_id": 156566, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": false, "text": "let getRentPrice (v : Vehicle) = \n match v with\n | :? Motorcycle as bike -> 100 + bike.Cylinders * 10\n | :? Bicycle -> 30\n | :? Car as car when car.EngineType = Diesel -> 220 + car.Doors * 20\n | :? Car as car when car.EngineType = Gasoline -> 200 + car.Doors * 20\n | _ -> failwith \"blah\"\n" }, { "answer_id": 156837, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "typeof(Motorcycle)" }, { "answer_id": 7301884, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 4, "selected": false, "text": "public class PatternMatcher<Output>\n{\n List<Tuple<Predicate<Object>, Func<Object, Output>>> cases = new List<Tuple<Predicate<object>,Func<object,Output>>>();\n\n public PatternMatcher() { } \n\n public PatternMatcher<Output> Case(Predicate<Object> condition, Func<Object, Output> function)\n {\n cases.Add(new Tuple<Predicate<Object>, Func<Object, Output>>(condition, function));\n return this;\n }\n\n public PatternMatcher<Output> Case<T>(Predicate<T> condition, Func<T, Output> function)\n {\n return Case(\n o => o is T && condition((T)o), \n o => function((T)o));\n }\n\n public PatternMatcher<Output> Case<T>(Func<T, Output> function)\n {\n return Case(\n o => o is T, \n o => function((T)o));\n }\n\n public PatternMatcher<Output> Case<T>(Predicate<T> condition, Output o)\n {\n return Case(condition, x => o);\n }\n\n public PatternMatcher<Output> Case<T>(Output o)\n {\n return Case<T>(x => o);\n }\n\n public PatternMatcher<Output> Default(Func<Object, Output> function)\n {\n return Case(o => true, function);\n }\n\n public PatternMatcher<Output> Default(Output o)\n {\n return Default(x => o);\n }\n\n public Output Match(Object o)\n {\n foreach (var tuple in cases)\n if (tuple.Item1(o))\n return tuple.Item2(o);\n throw new Exception(\"Failed to match\");\n }\n}\n" }, { "answer_id": 46201472, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 1, "selected": false, "text": "switch" }, { "answer_id": 47795205, "author": "Marcus Pierce", "author_id": 5506486, "author_profile": "https://Stackoverflow.com/users/5506486", "pm_score": 6, "selected": true, "text": "switch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"<unknown shape>\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23354/" ]
156,478
<p>I'm implementing a cache in a class library that i'm using in an asp.net application. </p> <p>I created my cache object as a singleton pattern with a static method to update the cache which is really just loading a member variable/property with a collection of data i need cached (got some locking logic ofcourse). I figured it was a nice way to go since i can just access my data by calling </p> <pre><code>MyCacheObject.Instance.MyDataCollection </code></pre> <p>I'm creating a new cache object to store a pretty big amount of data partitioned by some key. What i'm saying is i'm creating a new cache but this one will not load all of the data at once, but rather store a collection for each key accessed.</p> <pre><code>MyOtherCacheObject.Instance.MyOtherDataCollection(indexkey) </code></pre> <p>This time the question about garbage collection was brought up. Since i'm storing a huge amount of data, wouldn't it be a waste if it got gc'ed all of a sudden? Since it's just a singleton pattern there is nothing ensuring data will stay in cache.</p> <p>So my question is - what is best practice for implemeting a cache to handle this situation? I really don't like a huge complex solution to this, and i know there is caching in System.Web but that seems a bit 'off' since this is just a class library, or what do you think?</p>
[ { "answer_id": 156506, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 4, "selected": true, "text": "public interface ICacheService \n{\n AddItem(...);\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
156,492
<p>I have built a CFC designed to serve as a dynamic, aging cache intended for almost everything worth caching. LDAP queries, function results, arrays, ojects, you name it. Whatever takes time or resources to calculate and is needed more than once. I'd like to be able to do a few things:</p> <ul> <li><strong>share the CFC between applications</strong></li> <li><strong>define the scope of the cache (server / application / session / current request only)</strong></li> <li>use different cache instances at the same time, in the same request</li> <li>be independent from CFCs using the cache component</li> <li>generally adhere to common sense (decoupling, encapsulation, orthogonality, locking)</li> </ul> <p>I would of course be using a different cache instance for every distinct task, but I'd like to be able to use the same CFC across applications. The cache itself is (what else) a Struct, private to the cache instance. How would I properly implement caching and locking when the scope itself is subject to change?</p> <p>For locking, I use named locks (<code>'CacheRead'</code>, <code>'CacheWrite'</code>) currently, this is safe but strikes me as odd. Why would I want a server-wide lock for, say, a session-only operation? (Yes, maybe this <em>is</em> academic, but anyway.)</p> <p>Passing in the APPLICATION scope as a reference when I want application level caching also seems the wrong thing to do. Is there a better way?</p>
[ { "answer_id": 240702, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 2, "selected": true, "text": "<cfcomponent>\n <cfset variables.cacheScope = \"session\" /><!--- default to session --->\n <cfset variables.cache = \"\"/>\n\n <cfscript>\n function init(scope){\n variables.cacheScope = arguments.scope;\n return this;\n }\n\n function cacheWrite(key, value){\n structInsert(evaluate(variables.cacheScope),arguments.key,arguments.value,true);\n return this;\n }\n\n function cacheRead(key){\n if (not structKeyExists(evaluate(variables.cacheScope), arguments.key)){\n return \"\";\n }else{\n variables.cache = evaluate(variables.cacheScope);\n return variables.cache[arguments.key];\n }\n } \n </cfscript>\n</cfcomponent>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
156,503
<p>How can I use JUnit idiomatically to test that some code throws an exception?</p> <p>While I can certainly do something like this:</p> <pre><code>@Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } </code></pre> <p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p>
[ { "answer_id": 156515, "author": "Johan", "author_id": 11347, "author_profile": "https://Stackoverflow.com/users/11347", "pm_score": 5, "selected": false, "text": "public void testFooThrowsIndexOutOfBoundsException() {\n Throwable e = null;\n\n try {\n foo.doStuff();\n } catch (Throwable ex) {\n e = ex;\n }\n\n assertTrue(e instanceof IndexOutOfBoundsException);\n}\n" }, { "answer_id": 156528, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 12, "selected": true, "text": "JUnit <= 4.12" }, { "answer_id": 156868, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 9, "selected": false, "text": "try {\n methodThatShouldThrow();\n fail( \"My method didn't throw when I expected it to\" );\n} catch (MyException expectedException) {\n}\n" }, { "answer_id": 2935935, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 10, "selected": false, "text": "Assertions.assertThrows()" }, { "answer_id": 7927418, "author": "rwitzel", "author_id": 998938, "author_profile": "https://Stackoverflow.com/users/998938", "pm_score": 5, "selected": false, "text": "verifyException(foo, IndexOutOfBoundsException.class).doStuff();\n" }, { "answer_id": 12822499, "author": "Hugh Perkins", "author_id": 212731, "author_profile": "https://Stackoverflow.com/users/212731", "pm_score": 4, "selected": false, "text": "public class ExceptionAssertions {\n public static void assertException(BlastContainer blastContainer ) {\n boolean caughtException = false;\n try {\n blastContainer.test();\n } catch( Exception e ) {\n caughtException = true;\n }\n if( !caughtException ) {\n throw new AssertionFailedError(\"exception expected to be thrown, but was not\");\n }\n }\n public static interface BlastContainer {\n public void test() throws Exception;\n }\n}\n" }, { "answer_id": 16424903, "author": "John Mikic", "author_id": 1636207, "author_profile": "https://Stackoverflow.com/users/1636207", "pm_score": 5, "selected": false, "text": "@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n try {\n foo.doStuff();\n assert false;\n } catch (IndexOutOfBoundsException e) {\n assert true;\n }\n}\n" }, { "answer_id": 16948961, "author": "Tor P", "author_id": 1218054, "author_profile": "https://Stackoverflow.com/users/1218054", "pm_score": 3, "selected": false, "text": "public class ExceptionMatcher extends BaseMatcher<Throwable> {\n private boolean active = true;\n private Class<? extends Throwable> throwable;\n\n public ExceptionMatcher(Class<? extends Throwable> throwable) {\n this.throwable = throwable;\n }\n\n public void on() {\n this.active = true;\n }\n\n public void off() {\n this.active = false;\n }\n\n @Override\n public boolean matches(Object object) {\n return active && throwable.isAssignableFrom(object.getClass());\n }\n\n @Override\n public void describeTo(Description description) {\n description.appendText(\"not the covered exception type\");\n }\n}\n" }, { "answer_id": 17421500, "author": "Macchiatow", "author_id": 1161494, "author_profile": "https://Stackoverflow.com/users/1161494", "pm_score": 3, "selected": false, "text": "@Test\npublic void testThrowsExceptionWhenWrongSku() {\n\n // Given\n String articleSimpleSku = \"999-999\";\n int amountOfTransactions = 1;\n Exception exception = null;\n\n // When\n try {\n createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);\n } catch (RuntimeException e) {\n exception = e;\n }\n\n // Then\n shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);\n}\n\nprivate void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {\n assertNotNull(e);\n assertTrue(e.getMessage().contains(message));\n}\n" }, { "answer_id": 20008854, "author": "MariuszS", "author_id": 516167, "author_profile": "https://Stackoverflow.com/users/516167", "pm_score": 5, "selected": false, "text": "import static com.googlecode.catchexception.apis.BDDCatchException.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n\n when(() -> foo.doStuff());\n\n then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);\n\n}\n" }, { "answer_id": 24621006, "author": "Rafal Borowiec", "author_id": 718515, "author_profile": "https://Stackoverflow.com/users/718515", "pm_score": 8, "selected": false, "text": "@Test\npublic void verifiesTypeAndMessage() {\n assertThrown(new DummyService()::someMethod)\n .isInstanceOf(RuntimeException.class)\n .hasMessage(\"Runtime exception occurred\")\n .hasMessageStartingWith(\"Runtime\")\n .hasMessageEndingWith(\"occurred\")\n .hasMessageContaining(\"exception\")\n .hasNoCause();\n}\n" }, { "answer_id": 28940773, "author": "Shessuky", "author_id": 1387275, "author_profile": "https://Stackoverflow.com/users/1387275", "pm_score": 3, "selected": false, "text": "try{\n methodThatThrowMyException();\n Assert.fail(\"MyException is not thrown !\");\n} catch (final Exception exception) {\n // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure\n assertTrue(exception instanceof MyException, \"An exception other than MyException is thrown !\");\n // In case of verifying the error message\n MyException myException = (MyException) exception;\n assertEquals(\"EXPECTED ERROR MESSAGE\", myException.getMessage());\n}\n" }, { "answer_id": 28974751, "author": "Alex Collins", "author_id": 1055223, "author_profile": "https://Stackoverflow.com/users/1055223", "pm_score": 4, "selected": false, "text": "// this try block should be as small as possible,\n// as you want to make sure you only catch exceptions from your code\ntry {\n sut.doThing();\n fail(); // fail if this does not throw any exception\n} catch(MyException e) { // only catch the exception you expect,\n // otherwise you may catch an exception for a dependency unexpectedly\n // a strong assertion on the message, \n // in case the exception comes from anywhere an unexpected line of code,\n // especially important if your checking IllegalArgumentExceptions\n assertEquals(\"the message I get\", e.getMessage()); \n}\n" }, { "answer_id": 30404203, "author": "Srini", "author_id": 3281476, "author_profile": "https://Stackoverflow.com/users/3281476", "pm_score": 3, "selected": false, "text": "@Rule \npublic ExpectedException expectedException;\n\n@Before\npublic void setup()\n{\n expectedException = ExpectedException.none();\n}\n" }, { "answer_id": 31826781, "author": "walsh", "author_id": 4101415, "author_profile": "https://Stackoverflow.com/users/4101415", "pm_score": 8, "selected": false, "text": "assertThrows" }, { "answer_id": 34362168, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 3, "selected": false, "text": "public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )\n{\n try\n {\n runnable.run();\n }\n catch( Throwable throwable )\n {\n if( throwable instanceof AssertionError && throwable.getCause() != null )\n throwable = throwable.getCause(); //allows testing for \"assert x != null : new IllegalArgumentException();\"\n assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.\n assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.\n @SuppressWarnings( \"unchecked\" )\n T result = (T)throwable;\n return result;\n }\n assert false; //expected exception was not thrown.\n return null; //to keep the compiler happy.\n}\n" }, { "answer_id": 35813323, "author": "weston", "author_id": 360211, "author_profile": "https://Stackoverflow.com/users/360211", "pm_score": 5, "selected": false, "text": "import static org.assertj.core.api.Assertions.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n assertThatThrownBy(() -> foo.doStuff())\n .isInstanceOf(IndexOutOfBoundsException.class);\n}\n" }, { "answer_id": 35908056, "author": "Matt Welke", "author_id": 5051165, "author_profile": "https://Stackoverflow.com/users/5051165", "pm_score": -1, "selected": false, "text": "public void testConstructor() {\n boolean expectedExceptionThrown;\n try {\n // Call constructor with bad arguments\n double a = 1;\n double b = 2;\n double c = a + b; // In my example, this is an invalid option for c\n new Triangle(a, b, c);\n expectedExceptionThrown = false; // because it successfully constructed the object\n }\n catch(IllegalArgumentException e) {\n expectedExceptionThrown = true; // because I'm in this catch block\n }\n catch(Exception e) {\n expectedExceptionThrown = false; // because it threw an exception but not the one expected\n }\n assertTrue(expectedExceptionThrown);\n}\n" }, { "answer_id": 38553412, "author": "Daniel Käfer", "author_id": 1079174, "author_profile": "https://Stackoverflow.com/users/1079174", "pm_score": 4, "selected": false, "text": "import static org.junit.jupiter.api.Assertions.assertThrows;\n\n@Test\nvoid testFooThrowsIndexOutOfBoundsException() { \n IndexOutOfBoundsException exception = expectThrows(IndexOutOfBoundsException.class, foo::doStuff);\n \n assertEquals(\"some message\", exception.getMessage());\n}\n" }, { "answer_id": 40317041, "author": "Shirsh Sinha", "author_id": 4840515, "author_profile": "https://Stackoverflow.com/users/4840515", "pm_score": 1, "selected": false, "text": "public int divideByZeroDemo(int a,int b){\n\n return a/b;\n}\n\npublic void exceptionWithMessage(String [] arr){\n\n throw new ArrayIndexOutOfBoundsException(\"Array is out of bound\");\n}\n" }, { "answer_id": 41019785, "author": "Brice", "author_id": 48136, "author_profile": "https://Stackoverflow.com/users/48136", "pm_score": 7, "selected": false, "text": "try" }, { "answer_id": 41032596, "author": "Jobin", "author_id": 2893693, "author_profile": "https://Stackoverflow.com/users/2893693", "pm_score": 3, "selected": false, "text": "@Rule\npublic ExpectedException exceptions = ExpectedException.none();\n" }, { "answer_id": 41559786, "author": "Dilini Rajapaksha", "author_id": 679822, "author_profile": "https://Stackoverflow.com/users/679822", "pm_score": 6, "selected": false, "text": "assertThrows" }, { "answer_id": 46512202, "author": "fahrenx", "author_id": 1482358, "author_profile": "https://Stackoverflow.com/users/1482358", "pm_score": 1, "selected": false, "text": "private void expectException(Runnable r, Class<?> clazz) { \n try {\n r.run();\n fail(\"Expected: \" + clazz.getSimpleName() + \" but not thrown\");\n } catch (Exception e) {\n if (!clazz.isInstance(e)) fail(\"Expected: \" + clazz.getSimpleName() + \" but \" + e.getClass().getSimpleName() + \" found\", e);\n }\n }\n" }, { "answer_id": 46514550, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 6, "selected": false, "text": "Assertions.assertThrows()" }, { "answer_id": 46563308, "author": "heio", "author_id": 4031101, "author_profile": "https://Stackoverflow.com/users/4031101", "pm_score": 0, "selected": false, "text": "public static <T extends Throwable> T assertThrows(Class<T> expected, ThrowingRunnable action) throws Throwable {\n try {\n action.run();\n Assert.fail(\"Did not throw expected \" + expected.getSimpleName());\n return null; // never actually\n } catch (Throwable actual) {\n if (!expected.isAssignableFrom(actual.getClass())) { // runtime '!(actual instanceof expected)'\n System.err.println(\"Threw \" + actual.getClass().getSimpleName() \n + \", which is not a subtype of expected \" \n + expected.getSimpleName());\n throw actual; // throw the unexpected Throwable for maximum transparency\n } else {\n return (T) actual; // return the expected Throwable for further examination\n }\n }\n}\n" }, { "answer_id": 47195186, "author": "Mohit ladia", "author_id": 7750672, "author_profile": "https://Stackoverflow.com/users/7750672", "pm_score": 0, "selected": false, "text": "@Test(expected = IndexOutOfBoundsException.class)" }, { "answer_id": 48441467, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 4, "selected": false, "text": "try/catch" }, { "answer_id": 49696649, "author": "Donatello", "author_id": 1034782, "author_profile": "https://Stackoverflow.com/users/1034782", "pm_score": 2, "selected": false, "text": "public Throwable assertThrows(Class<? extends Throwable> expectedException, java.util.concurrent.Callable<?> funky) {\n try {\n funky.call();\n } catch (Throwable e) {\n if (expectedException.isInstance(e)) {\n return e;\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but was [%s]\", expectedException, e));\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but nothing was thrown.\", expectedException));\n}\n" }, { "answer_id": 51400976, "author": "Piotr Rogowski", "author_id": 3782729, "author_profile": "https://Stackoverflow.com/users/3782729", "pm_score": 2, "selected": false, "text": "assertj-core" }, { "answer_id": 51744696, "author": "Hossam Badri", "author_id": 1807373, "author_profile": "https://Stackoverflow.com/users/1807373", "pm_score": -1, "selected": false, "text": "try {\n my method();\n fail( \"This method must thrwo\" );\n} catch (Exception ex) {\n assertThat(ex.getMessage()).isEqual(myErrormsg);\n}\n" }, { "answer_id": 55708672, "author": "MangduYogii", "author_id": 9491394, "author_profile": "https://Stackoverflow.com/users/9491394", "pm_score": 1, "selected": false, "text": " @Test(expectedException=IndexOutOfBoundsException.class) \n public void testFooThrowsIndexOutOfBoundsException() throws Exception {\n doThrow(IndexOutOfBoundsException.class).when(foo).doStuff(); \n try {\n foo.doStuff(); \n } catch (IndexOutOfBoundsException e) {\n assertEquals(IndexOutOfBoundsException .class, ex.getCause().getClass());\n throw e;\n\n }\n\n }\n" }, { "answer_id": 61762605, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 2, "selected": false, "text": "assertThrows()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
156,504
<p>I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:</p> <pre><code>lines = open('filename.py').readlines() </code></pre> <p>How to find the line number, where the docstring ends?</p>
[ { "answer_id": 156513, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "count = 0\nfor line in lines:\n if line.startswith ('\"\"\"'):\n count += 1\n if count < 3:\n # Before or during end of the docstring\n continue\n # Line is after docstring\n" }, { "answer_id": 156973, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "import tokenize\nf=open(filename)\ninsert_index = None\nfor tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n" }, { "answer_id": 40376257, "author": "The Unfun Cat", "author_id": 992687, "author_profile": "https://Stackoverflow.com/users/992687", "pm_score": 0, "selected": false, "text": "def split_docstring_and_code(infile):\n\n import tokenize\n insert_index = None\n f = open(infile)\n for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n\n lines = open(infile).readlines()\n if insert_index is not None:\n erow = insert_index[0]\n return \"\".join(lines[:erow]), \"\".join(lines[erow:])\n else:\n return \"\", \"\".join(lines)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
156,508
<p>Alright, I have been doing the following (variable names have been changed):</p> <pre><code> FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } </code> </pre> <p>Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.</p>
[ { "answer_id": 156520, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": false, "text": "FileInputStream fis = null;\ntry\n{\n fis = new FileInputStream(file);\n\n ... process ...\n\n\n}\ncatch (IOException e)\n{\n ... blah blah blah ...\n}\nfinally\n{\n try\n {\n if (fis != null)\n fis.close();\n }\n catch (IOException e)\n {\n }\n}\n" }, { "answer_id": 156526, "author": "squiddle", "author_id": 6554, "author_profile": "https://Stackoverflow.com/users/6554", "pm_score": 2, "selected": false, "text": "public static void closeQuietly(InputStream s) {\n if (null == s) {\n return;\n }\n try {\n s.close();\n } catch (IOException ioe) {\n //ignore exception\n }\n}\n" }, { "answer_id": 156546, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": " Inputstream s = ....;\n withClosable(s) {\n //your code here\n }\n" }, { "answer_id": 156674, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 2, "selected": false, "text": "IOException" }, { "answer_id": 156721, "author": "Dave Griffiths", "author_id": 15379, "author_profile": "https://Stackoverflow.com/users/15379", "pm_score": -1, "selected": false, "text": "if (fis != null)" }, { "answer_id": 156889, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 7, "selected": true, "text": "try (InputStream in = new FileInputStream(file)) {\n // TODO: work\n} catch (IOException e) {\n // TODO: handle error\n}\n" }, { "answer_id": 157084, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "final InputStream is = ... // (assuming some construction that can't return null)\ntry {\n // process is\n ...\n} finally {\n is.close();\n}\n" }, { "answer_id": 6802774, "author": "Olivier Cailloux", "author_id": 859604, "author_profile": "https://Stackoverflow.com/users/859604", "pm_score": 1, "selected": false, "text": "try {\n InputStream in = new FileInputStream(file);\n try {\n // work\n in.close();\n } finally {\n Closeables.closeQuietly(in);\n }\n} catch(IOException exc) {\n // kernel panic\n}\n" }, { "answer_id": 10644404, "author": "Edwin Dalorzo", "author_id": 697630, "author_profile": "https://Stackoverflow.com/users/697630", "pm_score": 3, "selected": false, "text": "static String readFirstLineFromFile(String path) throws IOException {\n try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n return br.readLine();\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ]
156,510
<p>Is there a way to increase the stack size of a Windows application at compile/link time with GCC?</p>
[ { "answer_id": 156730, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 5, "selected": false, "text": "gcc -Wl,--stack,16777216 -o file.exe file.c\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
156,532
<p>I need to import largish (24MB) text files into a MySQL table. Each line looks like this:</p> <pre><code>1 1 0.008 0 0 0 0 0 </code></pre> <p>There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.</p> <p>How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried</p> <pre><code>LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' '; </code></pre> <p>but MySQL will interpret a sequence of more than one space as delimiting an empty field.</p> <p>Any ideas?</p>
[ { "answer_id": 156550, "author": "Jauco", "author_id": 6874, "author_profile": "https://Stackoverflow.com/users/6874", "pm_score": 4, "selected": true, "text": "sed 's/ \\+/ /g' thefile > thefile.new\n" }, { "answer_id": 156578, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 0, "selected": false, "text": "<?php\n\n$db = mysql_connect('host', 'user', 'password')\nor die('Failed to connect');\nmysql_select_db('database', $db);\n\n$fileHandle= @fopen(\"import.file\", \"r\");\nif ($fileHandle) {\n while (!feof($fileHandle)) {\n $rawLine = fgets($fileHandle, 4096);\n\n $columns = preg_split(\"/\\s+/\", $rawLine);\n\n //Construct and run an INSERT statement here ... \n\n }\n fclose($fileHandle);\n}\n\n?>\n" }, { "answer_id": 5462898, "author": "Felix", "author_id": 680691, "author_profile": "https://Stackoverflow.com/users/680691", "pm_score": 2, "selected": false, "text": "LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ','; \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
156,552
<p>I want to implement a two-pass cache system:</p> <ul> <li><p>The first pass generates a PHP file, with all of the common stuff (e.g. news items), hardcoded. The database then has a cache table to link these with the pages (eg "index.php page=1 style=default"), the database also stores an uptodate field, which if false causes the first pass to rerun the next time the page is viewed.</p></li> <li><p>The second pass fills in the minor details, such as how long ago something(?) was, and mutable items like "You are logged in as...".</p></li> </ul> <p>However I'm not sure on a efficient implementation, that supports both cached and non-cached (e.g., search) pages, without a lot of code and several queries.</p> <p>Right now each time the page is loaded the PHP script is run regenerating the page. For pages like search this is fine, because most searches are different, but for other pages such as the index this is virtually the same for each hit, yet generates a large number of queries and is quite a long script.</p> <p>The problem is some parts of the page do change on a per-user basis, such as the "You are logged in as..." section, so simply saving the generated pages would still result in 10,000's of nearly identical pages.</p> <p>The main concern is with reducing the load on the server, since I'm on shared hosting and at this point can't afford to upgrade, but the site is using a sizeable portion of the servers CPU + putting a fair load on the MySQL server.</p> <p>So basically minimising how much has to be done for each page request, and not regenerating stuff like the news items on the index all the time seems a good start, compared to say search which is a far less static page.</p> <p>I actually considered hard coding the news items as plain HTML, but then that means maintaining them in several places (since they may be used for searches and the comments are on a page dedicated to that news item (i.e. news.php), etc).</p>
[ { "answer_id": 156561, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "if filename exists\n include filename\nelse\n generate results\n render to html (as string)\n write to file\n output string or include file\nendif\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
156,563
<p>How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box?</p> <p>The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though.</p> <p>EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema.</p> <p>EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.</p>
[ { "answer_id": 158238, "author": "ThatBloke", "author_id": 7050, "author_profile": "https://Stackoverflow.com/users/7050", "pm_score": 4, "selected": true, "text": "\n void Application_Start(object sender, EventArgs e) \n {\n // Code that runs on application startup\n\n // check that the minimal security settings are created\n Security.SetupSecurity();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17176/" ]
156,575
<p>I'm looking for a good TraceListener for .Net that supports rolling over the log file based on size limits. </p> <p><strong>Constraints</strong></p> <ul> <li>Uses .Net built in Trace logging</li> <li>Independent class or binary that's not part of some gigantic library</li> <li>Allows rolling over a log file based on size</li> </ul>
[ { "answer_id": 36406938, "author": "Ostati", "author_id": 2654100, "author_profile": "https://Stackoverflow.com/users/2654100", "pm_score": 4, "selected": false, "text": "<system.diagnostics>\n <sources>\n <source name=\"System.Net\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n <source name=\"System.Net.Http\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n <source name=\"System.Net.Sockets\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n </sources>\n <switches>\n <add name=\"System.Net\" value=\"Verbose\"/>\n <add name=\"System.Net.Http\" value=\"Verbose\"/>\n <add name=\"System.Net.Sockets\" value=\"Verbose\"/>\n </switches>\n <sharedListeners>\n <add name=\"System.Net\"\n type=\"Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n traceOutputOptions=\"DateTime,ProcessId,ThreadId\"\n customLocation=\"c:\\temp\"\n location=\"Custom\"\n logFileCreationSchedule=\"Daily\"\n baseFileName=\"NetworkTrace\"/>\n </sharedListeners>\n <trace autoflush=\"true\"/>\n</system.diagnostics>\n" }, { "answer_id": 41772876, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 2, "selected": false, "text": "try/catch (InvalidOperationException)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17222/" ]
156,582
<p>I started using <a href="http://www.codeplex.com/SHFB" rel="noreferrer">Sandcastle</a> some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it.</p> <p>Just adding comments to the namespace declaration doesn't seem to work (C#):</p> <pre><code>/// &lt;summary&gt; /// My short namespace description /// &lt;/summary&gt; namespace MyNamespace { ... } </code></pre> <p>Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)</p>
[ { "answer_id": 156726, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 3, "selected": false, "text": "<namespaceSummaryItem name=\"System\" isDocumented=\"True\">\n Generic interfaces and helper classes.\n</namespaceSummaryItem>\n" }, { "answer_id": 857062, "author": "Tuinstoelen", "author_id": 106145, "author_profile": "https://Stackoverflow.com/users/106145", "pm_score": 7, "selected": true, "text": "namespace Some.Test\n{\n /// <summary>\n /// The <see cref=\"Some.Test\"/> namespace contains classes for ....\n /// </summary>\n\n [System.Runtime.CompilerServices.CompilerGenerated]\n class NamespaceDoc\n {\n }\n}\n" }, { "answer_id": 23339077, "author": "user1587804", "author_id": 1587804, "author_profile": "https://Stackoverflow.com/users/1587804", "pm_score": 1, "selected": false, "text": "/// <summary>\n /// Concrete implementation of see cref=\"IInterface\" using see cref=\"Concrete\"\n /// </summary>\n class NamespaceDoc\n {\n }" }, { "answer_id": 48572464, "author": "JohnKoz", "author_id": 3368670, "author_profile": "https://Stackoverflow.com/users/3368670", "pm_score": 0, "selected": false, "text": "<doc>\n <assembly/>\n <members>\n <member/>\n </members>\n</doc>\n" }, { "answer_id": 61606330, "author": "B Pete", "author_id": 83781, "author_profile": "https://Stackoverflow.com/users/83781", "pm_score": 0, "selected": false, "text": "Namespace Global.TestNamespace\n ''' <summary>\n ''' The <see cref=\"TestNamespace\"/> namespace contains classes for ....\n ''' </summary>\n <System.Runtime.CompilerServices.CompilerGeneratedAttribute()>\n Class NamespaceDoc\n End Class\nEnd Namespace\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
156,584
<p>I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do:</p> <ol> <li>Deploy the build to a folder that has the build number (eg. Project\Builds\8423)</li> <li>Alter the version number in the .NET AssmblyInfo.cs to match the build number</li> </ol> <p>Has anyone done this before with .NET projects using NAnt + CruiseControl.net?</p>
[ { "answer_id": 163518, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 0, "selected": false, "text": "<AssemblyInfo CodeLanguage=\"C#\"\n OutputFile=\"%(YourProjects.RootDir)%(Directory)Properties\\AssemblyInfo.cs\"\n AssemblyVersion=\"$(CCNetLabel)\"\n/>\n" }, { "answer_id": 170239, "author": "scott.caligan", "author_id": 14814, "author_profile": "https://Stackoverflow.com/users/14814", "pm_score": 4, "selected": false, "text": "<target name=\"publish\">\n <if test=\"${not property::exists('CCNetLabel')}\">\n <fail message=\"CCNetLabel property not set, so can't create labelled distribution files\" />\n </if>\n\n <property name=\"publishDirectory\" value=\"D:\\Public\\Project\\Builds\\${CCNetLabel}\" />\n\n <mkdir dir=\"${publishDirectory}\" />\n <copy todir=\"${publishDirectory}\">\n <fileset basedir=\"${buildDirectory}\\bin\">\n <include name=\"*.dll\" />\n </fileset>\n </copy> \n</target>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17222/" ]
156,585
<p>I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.</p> <p>Currently I'm doing something like this:</p> <pre><code>IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() &lt; 1) { // can that ever happen? throw new ArgumentException("hostName has no assigned IP-Address"); } TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234); </code></pre> <p>My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.</p>
[ { "answer_id": 156638, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 2, "selected": true, "text": "InternalGetHostByName(string hostName, bool includeIPv6)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21038/" ]
156,586
<p>We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that). When we modify a value in database, we have to reload the web server to display the new value on the web app.</p> <p>Is there any simple way to use the new value without restarting the web server ?</p> <p>(We do <strong>not</strong> want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL)</p> <p>EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :)</p>
[ { "answer_id": 156675, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 3, "selected": false, "text": "getTimeToLive()" }, { "answer_id": 55914608, "author": "y.hussain", "author_id": 5874302, "author_profile": "https://Stackoverflow.com/users/5874302", "pm_score": 1, "selected": false, "text": "ReloadableResourceBundleMessageSource" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
156,610
<p>I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. </p> <p>Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?</p>
[ { "answer_id": 156631, "author": "Nadav", "author_id": 23094, "author_profile": "https://Stackoverflow.com/users/23094", "pm_score": 0, "selected": false, "text": "ResourceBundle" }, { "answer_id": 156718, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": ".properties" }, { "answer_id": 157927, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 0, "selected": false, "text": "copylocale.exe en_US sv_SE\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24039/" ]
156,641
<p>I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this?</p>
[ { "answer_id": 156656, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 6, "selected": true, "text": "UPDATE Tablename SET Username = Concat('0', Username);\n" }, { "answer_id": 156657, "author": "f13o", "author_id": 20288, "author_profile": "https://Stackoverflow.com/users/20288", "pm_score": 3, "selected": false, "text": "UPDATE your_table SET column_name=concat('0',column_name);\n" }, { "answer_id": 156664, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "select LPAD(CONVERT(username, CHAR), 7, '0')\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13658/" ]
156,650
<p>When reviewing, I sometimes encounter this kind of loop:</p> <pre><code>i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } </code></pre> <p>Then I ask the question: would you write this?</p> <pre><code>i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i &gt; mid ) { ... do other stuff } increment i } </code></pre> <p>In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:</p> <pre><code>i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } </code></pre> <p>Now I even saw a <a href="https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator">question</a> on SO on how to write the <code>if</code>-clause in a nice way... And I got sad: something isn't right here.</p> <p>Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?</p>
[ { "answer_id": 156669, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": false, "text": "for(i=0;i<elements.size;i++) {\n if (i>0) {\n string += ','\n }\n string += elements[i]\n}\n" }, { "answer_id": 156678, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "for (i=0; i<5; i++)\n{\n switch(i)\n {\n case 0:\n // something\n break;\n case 1:\n // something else\n break;\n // etc...\n }\n}\n" }, { "answer_id": 156790, "author": "Swanand", "author_id": 18768, "author_profile": "https://Stackoverflow.com/users/18768", "pm_score": 3, "selected": false, "text": "i = begin\nmid = ( end - begin ) / 2 //(the middle element)\nwhile ( i != mid ) { \n // ... do stuff\n increment i\n}\n\nwhile ( i != end ) {\n // ... do other stuff\n increment i\n}\n" }, { "answer_id": 156932, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 3, "selected": false, "text": "if(items == null)\n return null;\n\nStringBuilder result = new StringBuilder();\nif(items.Length != 0)\n{\n result.Append(items[0]); // Special case outside loop.\n for(int i = 1; i < items.Length; i++) // Note: we start at element one.\n {\n result.Append(\";\");\n result.Append(items[i]);\n }\n}\nreturn result.ToString();\n" }, { "answer_id": 15847571, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 2, "selected": false, "text": "i = begin\nwhile ( i != end -1 ) { \n // ... do stuff for element from begn to second last element\n increment i\n}\n\nif(given_array(end -1) != ''){\n // do stuff for the EOF element in the array\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6610/" ]
156,683
<p>I would like to know what of the many XSLT engines out there works well with Perl.</p> <p>I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs.</p> <p>I'm new to this kind of projects so any comment or suggestion will be welcome.</p> <p>Thanks.</p> <hr> <p>Doing a simple search on Google I found a lot and I suppose that there are to many more.</p> <ul> <li><a href="http://www.mod-xslt2.com/" rel="noreferrer">http://www.mod-xslt2.com/</a></li> <li><a href="http://xml.apache.org/xalan-j/" rel="noreferrer">http://xml.apache.org/xalan-j/</a></li> <li><a href="http://saxon.sourceforge.net/" rel="noreferrer">http://saxon.sourceforge.net/</a></li> <li><a href="http://www.dopscripts.com/xslt_parser.html" rel="noreferrer">http://www.dopscripts.com/xslt_parser.html</a></li> </ul> <p>Any comment on your experiences will be welcome.</p>
[ { "answer_id": 156870, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 6, "selected": true, "text": " use XML::LibXSLT;\n use XML::LibXML;\n\n my $parser = XML::LibXML->new();\n my $xslt = XML::LibXSLT->new();\n\n my $source = $parser->parse_file('foo.xml');\n my $style_doc = $parser->parse_file('bar.xsl');\n\n my $stylesheet = $xslt->parse_stylesheet($style_doc);\n\n my $results = $stylesheet->transform($source);\n\n print $stylesheet->output_string($results);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ]