qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
292,167
<p>I have the following regex expression to match html links:</p> <pre><code>&lt;a\s*href=['|"](http:\/\/(.*?)\S['|"]&gt; </code></pre> <p>it kind of works. Except not really. Because it grabs everything after the &lt; a href... and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p> <p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the &lt; a href btw</p>
[ { "answer_id": 292193, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": ">>> import re\n>>> regex = '<a\\s+href=[\"\\'](http://(.*?))[\"\\']>'\n>>> string = '<a href=\"http://google.com/test/this\">'\n>>> match = re.search(regex, string)\n>>> match.group(1)\n'http://google.com/test/this'\n>>> match.group(2)\n'google.com/test/this'\n \\s+ = match at least one white space (<ahref) is a bad link\n [\"\\'] = character class, | has no meaning within square brackets\n (it will match a literal pipe \"|\")\n" }, { "answer_id": 292213, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 3, "selected": true, "text": "<a\\s*href=['|\"](http:\\/\\/(.*?)\\S['|\"]>\n <a .*?+href=['\"](http:\\/\\/.*?)['\"].*?>\n" }, { "answer_id": 292749, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<a\\s*href=['|\"](http:\\/\\/(.*?)\\S['|\"]>\n <a\\s+href=['|\"]http://([^'\"><]+)\\1>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
292,169
<p>I'm already familiar with the standard Java package naming convention of using a domain name to create a unique package name (i.e. package <code>com.stackoverflow.widgets</code>). However, I've never seen any recommendations for how to choose package names for personal projects. I assume because this is because this is really a matter of personal taste.</p> <p>So, how do you choose package names for personal projects that will never make it into production (you might be experimenting with a new framework in your spare time). Assuming you don't have a personal website whose domain you can use to create your package structure, what do (or would) you do? Do you have a logical system in place for generating new package names for hobby projects, or do you just use simple throw-away package names like <code>mypackage</code>?</p> <p>Since I'm just curious to see what different people's thoughts are on this, I've made this a community wiki.</p> <p>For me personally, I've never given it much thought, but I wanted to play around with <a href="http://wicket.apache.org/" rel="noreferrer">Wicket</a> tonight and it occurred to me that I don't have a clear idea of how I want to organize my hobby projects. A separate, distinct package naming convention for hobby projects (in my mind, at least) would serve as a good way to keep personal and work-related code clearly separate from each other.</p> <p>I was thinking of a simple hierarchal naming convention, to keep the source for my personal projects in a single root folder:</p> <ul> <li>Use <code>myprojects</code> as the root folder </li> <li>Append the project name </li> <li>Add any additional subpackage names</li> </ul> <p>So, my Wicket project would be in the package <code>myprojects.learningwicket</code> and unit tests would be in the package <code>myprojects.learningwicket.tests</code> (for example).</p>
[ { "answer_id": 292175, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": true, "text": "com. net. com.john" }, { "answer_id": 292234, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 4, "selected": false, "text": "com.googlecode.donkirkby.someproject" }, { "answer_id": 296472, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 4, "selected": false, "text": "<sarcasm> </sarcasm>" }, { "answer_id": 564444, "author": "paulmurray", "author_id": 63189, "author_profile": "https://Stackoverflow.com/users/63189", "pm_score": 4, "selected": false, "text": "pmurray_at_bigpond_dot_com.project.package\n" }, { "answer_id": 932565, "author": "cd1", "author_id": 38333, "author_profile": "https://Stackoverflow.com/users/38333", "pm_score": 2, "selected": false, "text": "com.myopenid.cd1.twitter" }, { "answer_id": 9241741, "author": "Amir Saniyan", "author_id": 309798, "author_profile": "https://Stackoverflow.com/users/309798", "pm_score": 2, "selected": false, "text": "prj.project_name" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17862/" ]
292,204
<p>I need to find whether the user clicking the browser back button or Refresh button.</p> <p>I need to redirect the page to Error page when he clicks the back or refresh button. How to do this.</p> <p>I need to do this in javascript for my ASP.net page</p>
[ { "answer_id": 292251, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 1, "selected": false, "text": "<html><body onload=\"location.replace('someURL.asp')\"></body></html>\n" }, { "answer_id": 10455109, "author": "Charles Byrne", "author_id": 514120, "author_profile": "https://Stackoverflow.com/users/514120", "pm_score": 3, "selected": false, "text": "public void GeneratePageToken()\n{\n SessionVariables currSession = new SessionVariables();\n hfMasterPageToken.Value = System.DateTime.Now.ToString();\n currSession.PageToken = hfMasterPageToken.Value;\n}\n\npublic string GetLastPageToken\n{\n get\n {\n SessionVariables currSession = new SessionVariables();\n return currSession.PageToken;\n }\n}\n\npublic bool TokensMatch\n{\n get\n {\n SessionVariables currSession = new SessionVariables();\n return (currSession.PageToken != null\n && currSession.PageToken == hfMasterPageToken.Value);\n }\n}\n if (this.TokensMatch == false)\n{\n //Reload the data.\n //Generates a NewPageToken (this.GeneratePageToken();)\n ReloadDataMethod();\n this.MessageToUser =\n \"Data reloaded. Click Edit or Insert button to change.\";\n this.MessageType = MessageToUserType.Success;\n this.DisplayMessageToUser = true;\n return;\n}\n" }, { "answer_id": 22788799, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 2, "selected": false, "text": "Site.Master Site.Master <body> <asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" EnablePageMethods=\"true\" />\n<dx:ASPxLoadingPanel ID=\"MainLoadingPanel\" runat=\"server\" ClientInstanceName=\"MainLoadingPanel\" Modal=\"True\" />\n<input type=\"hidden\" id=\"refreshed\" value=\"no\" />\n<script type=\"text/javascript\" language=\"javascript\">\n MainLoadingPanel.Show();\n window.onload = function () {\n var e = document.getElementById(\"refreshed\");\n if (e.value == \"no\") {\n MainLoadingPanel.Hide();\n e.value = \"yes\";\n } else {\n e.value = \"no\";\n location.reload(true); // Reload the page or redirect...\n }\n };\n</script>\n Site.Master <body> <input type=\"hidden\" id=\"refreshed\" value=\"no\" />\n<script type=\"text/javascript\" language=\"javascript\">\n window.onload = function () {\n var e = document.getElementById(\"refreshed\");\n if (e.value == \"no\") {\n e.value = \"yes\";\n } else {\n e.value = \"no\";\n location.reload(true); // Reload the page or redirect...\n }\n };\n</script>\n" }, { "answer_id": 55653946, "author": "Max Alexander Hanna", "author_id": 6327086, "author_profile": "https://Stackoverflow.com/users/6327086", "pm_score": 1, "selected": false, "text": "if(performance.navigation.type == 2)\n{\n //Do your code here\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
292,230
<p>I have the following table structure</p> <pre><code>CREATE TABLE `table` ( `id` int(11) NOT NULL auto_increment, `date_expired` datetime NOT NULL, `user_id` int(11) NOT NULL, `foreign_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `date_expired` (`date_expired`,`user_id`,`foreign_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>As you'll notice, I have duplicate indexes on user_id: <code>date_expired</code> &amp; <code>user_id</code>. I of course want the unique index because I want to ensure the data is unique.</p> <p>The reason for the duplicate indexes is because without the <code>user_id</code> index, my main search query takes 4 seconds. With the extra index it takes 1 second. The query is joining the table on <code>user_id</code> and checking <code>date_expired</code>.</p> <p>The table only has 275 records.</p> <ul> <li>How bad is it to have a unique and normal index on the same field?</li> <li>How bad is it to have larger indexes than data when the table is purely ids?</li> </ul>
[ { "answer_id": 292249, "author": "Kendrick Erickson", "author_id": 37882, "author_profile": "https://Stackoverflow.com/users/37882", "pm_score": 4, "selected": true, "text": "user_id date_expired foreign_id user_id user_id id" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
292,233
<p>I'm pretty green with web services and WCF, and I'm using Windows integrated authentication - how do I get the username on the server-side interface? I believe that I'm supposed to implement a custom Behavior, or perhaps something with WCF Sessions? Any clues would be super-handy.</p>
[ { "answer_id": 292266, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": -1, "selected": false, "text": "WindowsIdentity.GetCurrent();" }, { "answer_id": 292329, "author": "Mitch Baker", "author_id": 37896, "author_profile": "https://Stackoverflow.com/users/37896", "pm_score": 4, "selected": true, "text": "private static void DemandManagerPermission()\n{\n // Verify the use has authority to proceed\n string permissionGroup = ConfigurationManager.AppSettings[\"ManagerPermissionGroup\"];\n if (string.IsNullOrEmpty(permissionGroup))\n throw new FaultException(\"Group permissions not set for access control.\");\n\n AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n var p = new PrincipalPermission(ServiceSecurityContext.Current.WindowsIdentity.Name, permissionGroup, true);\n p.Demand();\n\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5728/" ]
292,254
<p>Trying to create a random string, x characters in length using 0-9 and a-z/A-Z and can't seem to find a good example, any ideas?</p>
[ { "answer_id": 292283, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 5, "selected": false, "text": "Function RandomString(cb As Integer) As String\n\n Randomize\n Dim rgch As String\n rgch = \"abcdefghijklmnopqrstuvwxyz\"\n rgch = rgch & UCase(rgch) & \"0123456789\"\n\n Dim i As Long\n For i = 1 To cb\n RandomString = RandomString & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)\n Next\n\nEnd Function\n" }, { "answer_id": 910027, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "all_chars = array(\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\")\nRandomize\nfor i = 1 to 4\n random_index = int(Rnd()*25)\nclave = clave & all_chars(random_index) \nnext\n" }, { "answer_id": 915572, "author": "Oorang", "author_id": 102270, "author_profile": "https://Stackoverflow.com/users/102270", "pm_score": 0, "selected": false, "text": "Public Function RandomString( _\n ByVal length As Long, _\n Optional charset As String = \"abcdefghijklmnopqrstuvwxyz0123456789\" _\n ) As String\n Dim chars() As Byte, value() As Byte, chrUprBnd As Long, i As Long\n If length > 0& Then\n Randomize\n chars = charset\n chrUprBnd = Len(charset) - 1&\n length = (length * 2&) - 1&\n ReDim value(length) As Byte\n For i = 0& To length Step 2&\n value(i) = chars(CLng(chrUprBnd * Rnd) * 2&)\n Next\n End If\n RandomString = value\nEnd Function\n" }, { "answer_id": 38156584, "author": "adam", "author_id": 5795746, "author_profile": "https://Stackoverflow.com/users/5795746", "pm_score": 0, "selected": false, "text": "SELECT NEWID() as KeyValue" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,256
<p>I'm a simple soul with simple needs, and I'm trying to configure a form. I detest forms.</p> <p>It needs to have JavaScript to transfer the data, it needs to send an e-mail with the data to an e-mail address, and it needs to redirect visitors to a pdf. CGI has always been confusing to me, and I don't know much JavaScript.</p> <p>I've already done the html, but the post action and the JavaScript is killing me. It's been 4 hours of searching. Stick a fork in me. I'm done.</p>
[ { "answer_id": 292443, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\" src=\"script.js\"></script>\n<form id=\"emailForm\" method=\"post\" action=\"mail.php\">\n <input type='text' name='firstName' id=\"firstName\"><br>\n <input type='text' name='lastName' id='lastname'><br>\n <input type='submit' value='submit' name='submit'>\n</form>\n var formIsOkay = true;\n$(document).ready( function() {\n$('#emailForm').submit( function() {\n $('#emailForm input').each( function() {\n if ( this.val() == '' ) { formIsOkay = false; }\n }\n return formIsOkay;\n}\n}\n <?php\n $to = 'email@domain.com';\n $from = 'email@domain.com';\n $subject = 'Form';\n $message = 'Hello, the following variables were supplied:<br>';\n foreach($_POST as $key => $val){\n $message .= \"$key = $val<br>\";\n }\n $message = wordwrap($message, 70);\n $headers = 'MIME-Version: 1.0' . \"\\r\\n\";\n $headers .= 'Content-type: text/html; charset=iso-8859-1' . \"\\r\\n\";\n $headers .= \"To: $to\" . \"\\r\\n\";\n $headers .= \"From: $from\" . \"\\r\\n\";\n mail($to, $subject, $message, $headers);\n ?>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,257
<p>My page has two components that depend on JavaScript. On the left-hand side, there is attribute-based navigation (abn). And the right-hand side is the Result of the abn.</p> <p>There is an event handler for abn and an event handler for the result (both are on clicks) Whenever the user clicks on the abn, I do an Ajax call which returns a JSON object where the HTML result is a value of one of the key/value pair. The HTML is being inserted into the result component.</p> <p>The event handler for the result of the page works fine on a page refresh. It stops working when I insert the HTML content into the result slot after the Ajax call. I have verified that the result has all the divs and class that my JavaScript depends on.</p> <p>I think when I replaced the HTML content, the JavaScript handler just stop working. Can someone explain why this is happening and how I can solve this?</p>
[ { "answer_id": 292951, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 0, "selected": false, "text": "function iAmCalledWhenSomeoneClicksOnAbn(){\n alert(\"I was called, w00t!\");\n //...rest of function\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,265
<p>What are the coolest new features that you guys are looking for, or that you've heard are releasing in c# 4.0.</p>
[ { "answer_id": 292273, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "Person p = new Person (name: \"Jon\", age: 32);\n" }, { "answer_id": 292289, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": false, "text": "public void MyMethod1(string value1 = \"test\", int num1 = 10, double num2 = 12.2)\n{\n //...\n}\n public var MyMethod2()\n{\n // ..\n}\n" }, { "answer_id": 292302, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 3, "selected": false, "text": "IDynamicObject dynamic DataSet dynamic dynamic obj = GetScriptObject();\n\nHtmlPage.Window.Alert(obj.someProperty);\n HtmlPage.Window.Alert(obj.someMethod() + obj.items[0]);\n public void WriteSomePropertyValue(object target)\n{\n Console.WriteLine((target as dynamic).SomeProperty);\n}\n\npublic void WriteSomeMethodValue(object target, int arg1, string arg2)\n{\n Console.WriteLine((target as dynamic).SomeMethod(arg1, arg2));\n}\n dynamic" }, { "answer_id": 2196931, "author": "si618", "author_id": 44540, "author_profile": "https://Stackoverflow.com/users/44540", "pm_score": 2, "selected": false, "text": "Stopwatch.Restart()" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37881/" ]
292,274
<p>I read through the Wikipedia article <em><a href="https://en.wikipedia.org/wiki/Type_system#Existential_types" rel="noreferrer">Existential types</a></em>. I gathered that they're called existential types because of the existential operator (∃). I'm not sure what the point of it is, though. What's the difference between </p> <pre><code>T = ∃X { X a; int f(X); } </code></pre> <p>and</p> <pre><code>T = ∀x { X a; int f(X); } </code></pre> <p>?</p>
[ { "answer_id": 292293, "author": "user35910", "author_id": 35910, "author_profile": "https://Stackoverflow.com/users/35910", "pm_score": -1, "selected": false, "text": "abstract class MyType<T>{\n private T a;\n\n public abstract int f(T x);\n}\n" }, { "answer_id": 742763, "author": "Bartosz Milewski", "author_id": 90088, "author_profile": "https://Stackoverflow.com/users/90088", "pm_score": 4, "selected": false, "text": "fopen let exfile = fopen(\"foo.txt\"); // No type for exfile!\nread(exfile, buf, size);\n size_t read(T exfile, char* buf, size_t size);\n char*" }, { "answer_id": 5520212, "author": "Kannan Goundan", "author_id": 163832, "author_profile": "https://Stackoverflow.com/users/163832", "pm_score": 9, "selected": true, "text": "∀X X ∃X X void copy<T>(List<T> source, List<T> dest) {\n ...\n}\n copy T interface VirtualMachine<B> {\n B compile(String source);\n void run(B bytecode);\n}\n\n// Now, if you had a list of VMs you wanted to run on the same input:\nvoid runAllCompilers(List<∃B:VirtualMachine<B>> vms, String source) {\n for (∃B:VirtualMachine<B> vm : vms) {\n B bytecode = vm.compile(source);\n vm.run(bytecode);\n }\n}\n runAllCompilers VirtualMachine.compile VirtualMachine.run List<?> // A wrapper that hides the type parameter 'B'\ninterface VMWrapper {\n void unwrap(VMHandler handler);\n}\n\n// A callback (control inversion)\ninterface VMHandler {\n <B> void handle(VirtualMachine<B> vm);\n}\n VMWrapper VMHandler handle B void runWithAll(List<VMWrapper> vms, final String input)\n{\n for (VMWrapper vm : vms) {\n vm.unwrap(new VMHandler() {\n public <B> void handle(VirtualMachine<B> vm) {\n B bytecode = vm.compile(input);\n vm.run(bytecode);\n }\n });\n }\n}\n class MyVM implements VirtualMachine<byte[]>, VMWrapper {\n public byte[] compile(String input) {\n return null; // TODO: somehow compile the input\n }\n public void run(byte[] bytecode) {\n // TODO: Somehow evaluate 'bytecode'\n }\n public void unwrap(VMHandler handler) {\n handler.handle(this);\n }\n}\n" }, { "answer_id": 8686154, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 5, "selected": false, "text": "class Tree<α>\n{\n α value;\n Tree<α> left;\n Tree<α> right;\n}\n\nint height(Tree<α> t)\n{\n return (t != null) ? 1 + max( height(t.left), height(t.right) )\n : 0;\n}\n Tree<α> value left right height t height height <α> int height(Tree<α> t)\n{\n return (t != null) ? 1 + max( height(t.left), height(t.right) )\n : 0;\n}\n height int height(Tree<?> t)\n{\n return (t != null) ? 1 + max( height(t.left), height(t.right) )\n : 0;\n}\n height t.value ? t.value Object ===========================================================\n | universally existentially\n | quantified type quantified type\n---------------------+-------------------------------------\n calling method | \n needs to know | yes no\n the type argument | \n---------------------+-------------------------------------\n called method | \n can use / refer to | yes no \n the type argument | \n=====================+=====================================\n" }, { "answer_id": 9473088, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 7, "selected": false, "text": "∃x. F(x) x F(x) ∀x. F(x) x F(x) F T = ∃X { X a; int f(X); }\n T X a:X f:X->int T X X a int f T int X T = int\n T = ∀X { X a; int f(X); }\n T X a:X f:X->int X T X T X a X int null (∃b. F(b)) -> Int\n ∀b. (F(b) -> Int)\n n+1 n" }, { "answer_id": 12327276, "author": "Rogon", "author_id": 1656021, "author_profile": "https://Stackoverflow.com/users/1656021", "pm_score": 4, "selected": false, "text": "P<X> = Pair<X, X> = (X, X) P<X> = Option<X> = X | Nil List<X> = (X, List<X>) | Nil List<X> List<X> ∃X.P<X> P<X> P<X>" }, { "answer_id": 13651842, "author": "Dobes Vandermeer", "author_id": 399738, "author_profile": "https://Stackoverflow.com/users/399738", "pm_score": 4, "selected": false, "text": "T X T<String> T<Integer> T T T<?> public class MyClass<T> {\n // T is existential in here\n T whatever; \n public MyClass(T w) { this.whatever = w; }\n\n public static MyClass<?> secretMessage() { return new MyClass(\"bazzlebleeb\"); }\n}\n\n// T is universal from out here\nMyClass<String> mc1 = new MyClass(\"foo\");\nMyClass<Integer> mc2 = new MyClass(123);\nMyClass<?> mc3 = MyClass.secretMessage();\n MyClass T T MyClass MyClass T T ? T ? MyClass T MyClass<?> secretMessage() public class ToDraw<T> {\n T obj;\n Function<Pair<T,Graphics>, Void> draw;\n ToDraw(T obj, Function<Pair<T,Graphics>, Void>\n static void draw(ToDraw<?> d, Graphics g) { d.draw.apply(new Pair(d.obj, g)); }\n}\n\n// Now you can put these in a list and draw them like so:\nList<ToDraw<?>> drawList = ... ;\nfor(td in drawList) ToDraw.draw(td);\n Object Object T<Int> T<Long> T<?> T" }, { "answer_id": 30837163, "author": "Shelby Moore III", "author_id": 615784, "author_profile": "https://Stackoverflow.com/users/615784", "pm_score": 3, "selected": false, "text": "trait Existential {\n type Parameter <: Interface\n}\n trait Existential[Parameter <: Interface]\n Interface Existential type Parameter Interface List[_] List<?>" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
292,279
<p>I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.</p>
[ { "answer_id": 292287, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": true, "text": "new AbstractTableModel() {\n public String getColumnName(int col) {\n return columnNames[col].toString();\n }\n public int getRowCount() { return rowData.length; }\n public int getColumnCount() { return columnNames.length; }\n public Object getValueAt(int row, int col) {\n return rowData[row][col];\n }\n public boolean isCellEditable(int row, int col)\n { return true; }\n public void setValueAt(Object value, int row, int col) {\n rowData[row][col] = value;\n fireTableCellUpdated(row, col);\n }\n}\n package eed3si9n.hashtabletable;\n\nimport java.awt.BorderLayout;\nimport java.util.Enumeration;\nimport java.util.Hashtable;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.AbstractTableModel;\nimport javax.swing.JButton;\nimport java.awt.Dimension;\n\npublic class MainForm extends JFrame {\n\n private static final long serialVersionUID = 1L;\n private JPanel jContentPane = null; // @jve:decl-index=0:visual-constraint=\"23,38\"\n private JScrollPane m_scrollPane = null;\n private JTable m_table = null;\n private Hashtable<String, String> m_hash = null;\n private JButton m_btnAdd = null; \n\n /**\n * This is the default constructor\n */\n public MainForm() {\n super();\n initialize();\n m_hash = new Hashtable<String, String>();\n m_hash.put(\"Dog\", \"Bow\");\n }\n\n private void onButtonPressed() {\n m_hash.put(\"Cow\", \"Moo\");\n m_table.revalidate();\n }\n\n /**\n * This method initializes this\n * \n * @return void\n */\n private void initialize() {\n this.setSize(409, 290);\n this.setTitle(\"JFrame\");\n this.setContentPane(getJContentPane());\n }\n\n /**\n * This method initializes jContentPane\n * \n * @return javax.swing.JPanel\n */\n private JPanel getJContentPane() {\n if (jContentPane == null) {\n jContentPane = new JPanel();\n jContentPane.setLayout(new BorderLayout());\n jContentPane.setSize(new Dimension(500, 500));\n jContentPane.setPreferredSize(new Dimension(500, 500));\n jContentPane.add(getM_scrollPane(), BorderLayout.NORTH);\n jContentPane.add(getM_btnAdd(), BorderLayout.SOUTH);\n }\n return jContentPane;\n }\n\n /**\n * This method initializes m_scrollPane \n * \n * @return javax.swing.JScrollPane \n */\n private JScrollPane getM_scrollPane() {\n if (m_scrollPane == null) {\n m_scrollPane = new JScrollPane();\n m_scrollPane.setViewportView(getM_table());\n }\n return m_scrollPane;\n }\n\n /**\n * This method initializes m_table \n * \n * @return javax.swing.JTable \n */\n private JTable getM_table() {\n if (m_table == null) {\n m_table = new JTable();\n m_table.setModel(new AbstractTableModel(){\n private static final long serialVersionUID = 1L;\n\n public int getColumnCount() {\n return 2;\n }\n\n public int getRowCount() {\n return m_hash.size();\n }\n\n public String getColumnName(int column) {\n if (column == 0) {\n return \"Animal\";\n } else {\n return \"Sound\";\n }\n }\n\n public Object getValueAt(int rowIndex, int columnIndex) {\n if (columnIndex == 0) {\n return getKey(rowIndex);\n } else {\n return m_hash.get(getKey(rowIndex));\n } // if-else\n\n }\n\n private String getKey(int a_index) {\n String retval = \"\";\n Enumeration<String> e = m_hash.keys();\n for (int i = 0; i < a_index + 1; i++) {\n retval = e.nextElement();\n } // for\n\n return retval;\n }\n\n });\n }\n return m_table;\n }\n\n /**\n * This method initializes m_btnAdd \n * \n * @return javax.swing.JButton \n */\n private JButton getM_btnAdd() {\n if (m_btnAdd == null) {\n m_btnAdd = new JButton();\n m_btnAdd.setPreferredSize(new Dimension(34, 30));\n m_btnAdd.addActionListener(new java.awt.event.ActionListener() {\n public void actionPerformed(java.awt.event.ActionEvent e) {\n onButtonPressed();\n }\n });\n }\n return m_btnAdd;\n }\n\n public static void main(String[] args) {\n //Schedule a job for the event-dispatching thread:\n //creating and showing this application's GUI.\n javax.swing.SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n MainForm frame = new MainForm();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(500, 500);\n frame.setVisible(true);\n }\n });\n }\n} // @jve:decl-index=0:visual-constraint=\"10,10\"\n" }, { "answer_id": 292421, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 1, "selected": false, "text": "Hashtable Map LinkedHashMap TreeMap SortedMap NavigableMap Comparator Map TableModel Map public static TableModel toTableModel(Map<?,?> map) {\n DefaultTableModel model = new DefaultTableModel(\n new Object[] { \"Key\", \"Value\" }, 0\n );\n for (Map.Entry<?,?> entry : map) {\n model.addRow(new Object[] { entry.getKey(), entry.getValue() });\n }\n return model;\n}\n JTable Map TableModel Map TableModel Map TableModel Map Map DefaultTableModel Map" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
292,295
<p>We are supposed to instantiate our entities through a factory since they are set up differently on the client and server. I want to make sure this is the case but cant quite get it to work.</p> <pre><code>public interface IEntityFactory { TEntity Create&lt;TEntity&gt;() where TEntity : new(); } public abstract class Entity { protected Entity() { VerifyEntityIsCreatedThroughFactory(); } [Conditional("DEBUG")] private void VerifyEntityIsCreatedThroughFactory() { foreach (var methodBase in new StackTrace().GetFrames().Select(x =&gt; x.GetMethod())) { if (!typeof(IEntityFactory).IsAssignableFrom(methodBase.DeclaringType) || methodBase.Name != "Create") continue; // The generic type is TEnitiy but I want the provided type! if (methodBase.GetGenericArguments()[0] != GetType()) Debug.Fail(string.Format("Use factory when creating {0}.", GetType().Name)); } } } </code></pre>
[ { "answer_id": 292541, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "internal" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37889/" ]
292,307
<p>How do I select the unique elements from the list <code>{0, 1, 2, 2, 2, 3, 4, 4, 5}</code> so that I get <code>{0, 1, 3, 5}</code>, effectively removing <em>all instances of</em> the repeated elements <code>{2, 4}</code>?</p>
[ { "answer_id": 292310, "author": "CVertex", "author_id": 209, "author_profile": "https://Stackoverflow.com/users/209", "pm_score": 4, "selected": false, "text": "var nums = new int{ 0...4,4,5};\nvar distinct = nums.Distinct();\n" }, { "answer_id": 292317, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 6, "selected": true, "text": "var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };\n\nvar uniqueNumbers =\n from n in numbers\n group n by n into nGroup\n where nGroup.Count() == 1\n select nGroup.Key;\n\n// { 0, 1, 3, 5 }\n" }, { "answer_id": 292632, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 3, "selected": false, "text": "static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)\n{\n Dictionary<T, int> counts = new Dictionary<T, int>();\n\n foreach (T item in things)\n {\n int count;\n if (counts.TryGetValue(item, out count))\n counts[item] = ++count;\n else\n counts.Add(item, 1);\n }\n\n foreach (KeyValuePair<T, int> kvp in counts)\n {\n if (kvp.Value == 1)\n yield return kvp.Key;\n }\n}\n" }, { "answer_id": 292834, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": " static IEnumerable<T> GetUniques<T>(IEnumerable<T> things)\n {\n Dictionary<T, bool> uniques = new Dictionary<T, bool>();\n foreach (T item in things)\n {\n if (!(uniques.ContainsKey(item)))\n {\n uniques.Add(item, true);\n }\n }\n return uniques.Keys;\n }\n" }, { "answer_id": 450332, "author": "Barbaros Alp", "author_id": 51734, "author_profile": "https://Stackoverflow.com/users/51734", "pm_score": 4, "selected": false, "text": "var all = new[] {0,1,1,2,3,4,4,4,5,6,7,8,8}.ToList();\nvar unique = all.GroupBy(i => i).Where(i => i.Count() == 1).Select(i=>i.Key);\n" }, { "answer_id": 4416966, "author": "Murilo Beltrame", "author_id": 538896, "author_profile": "https://Stackoverflow.com/users/538896", "pm_score": -1, "selected": false, "text": "public IEnumerable<T> Distinct<T>(IEnumerable<T> source)\n{\n List<T> uniques = new List<T>();\n foreach (T item in source)\n {\n if (!uniques.Contains(item)) uniques.Add(item);\n }\n return uniques;\n}\n" }, { "answer_id": 9325348, "author": "Ewald Stieger", "author_id": 443315, "author_profile": "https://Stackoverflow.com/users/443315", "pm_score": 3, "selected": false, "text": "var uniqueValues= myItems.Select(k => k.MyProperty)\n .GroupBy(g => g)\n .Where(c => c.Count() == 1)\n .Select(k => k.Key)\n .ToList();\n var distinctValues = myItems.Select(p => p.MyProperty)\n .Distinct()\n .ToList();\n public class OrderComparer : IEqualityComparer<Order>\n{\n public bool Equals(Order o1, Order o2)\n {\n return o1.OrderID == o2.OrderID;\n }\n\n public int GetHashCode(Order obj)\n {\n return obj.OrderID.GetHashCode();\n }\n}\n" }, { "answer_id": 9355790, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 2, "selected": false, "text": "var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };\n\nHashSet<int> r = new HashSet<int>(numbers);\n\nforeach( int i in r ) {\n Console.Write( \"{0} \", i );\n}\n" }, { "answer_id": 72779582, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 0, "selected": false, "text": "var numbers = new[] { 0, 1, 2, 2, 2, 3, 4, 4, 5 };\n\n// This assumes the numbers are sorted\nvar noRepeats = new List<int>();\nint temp = numbers[0]; // Or .First() if using IEnumerable\nvar count = 1;\nfor(int i = 1; i < numbers.Length; i++) // Or foreach (var n in numbers.Skip(1)) if using IEnumerable\n{\n if (numbers[i] == temp) count++;\n else\n {\n if(count == 1) noRepeats.Add(temp);\n temp = numbers[i];\n count = 1;\n }\n}\nif(count == 1) noRepeats.Add(temp);\n\nConsole.WriteLine($\"[{string.Join(separator: \",\", values: numbers)}] -> [{string.Join(separator: \",\", values: noRepeats)}]\");\n [0,1,2,2,2,3,4,4,5] -> [0,1,3,5]\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/976/" ]
292,308
<p>I always see the code like this in the blogs: </p> <pre><code>$.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "WebService.asmx/HelloWorld", data: "{}", dataType: "json", success: function(msg) { alert(msg.d); } }); </code></pre> <p>But I think this is run only with asp.net 3.5. I couldn't run it with 2.0. How can I use such these codes in my Applications? </p>
[ { "answer_id": 292321, "author": "mavera", "author_id": 439507, "author_profile": "https://Stackoverflow.com/users/439507", "pm_score": 0, "selected": false, "text": " $(document).ready(function() { \n $('#clKaydet').click(function() {\n $.ajax({\n type: \"POST\",\n contentType: \"application/json; charset=utf-8\",\n url: \"WebService.asmx/HelloWorld\",\n data: \"{}\",\n dataType: \"json\",\n success: function(msg) {\n alert(msg);\n }\n });\n\n });\n\n });\n <form id=\"form1\" runat=\"server\">\n <asp:ScriptManager ID=\"ScriptManager1\" EnablePageMethods=\"true\" runat=\"server\" />\n <div>\n\n <input type=\"button\" id=\"clKaydet\" runat=\"server\" value=\"Kayıt\" onclick=\"Kayit()\" />\n </div>\n\n </div>\n </form>\n <WebMethod()> _\nPublic Function HelloWorld() As String\n Dim sText As String = \"Hello\"\n Return sText\nEnd Function\n" }, { "answer_id": 293922, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 3, "selected": true, "text": "[System.Web.Script.Services.ScriptService]\npublic class Service : System.Web.Services.WebService\n [ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n" }, { "answer_id": 2006707, "author": "hrabizadeh", "author_id": 243993, "author_profile": "https://Stackoverflow.com/users/243993", "pm_score": 1, "selected": false, "text": "ScriptManager ScriptManager" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439507/" ]
292,357
<p>What are the differences between <a href="https://git-scm.com/docs/git-pull" rel="noreferrer"><code>git pull</code></a> and <a href="https://git-scm.com/docs/git-fetch" rel="noreferrer"><code>git fetch</code></a>?</p>
[ { "answer_id": 292359, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 14, "selected": true, "text": "git pull git fetch git merge git fetch refs/remotes/<remote>/ refs/heads git pull git pull git pull git fetch git merge FETCH_HEAD" }, { "answer_id": 2791156, "author": "mepster", "author_id": 335755, "author_profile": "https://Stackoverflow.com/users/335755", "pm_score": 9, "selected": false, "text": "git fetch git fetch\ngit diff ...origin\n git diff .. ..." }, { "answer_id": 5376768, "author": "Antonio Bardazzi", "author_id": 614407, "author_profile": "https://Stackoverflow.com/users/614407", "pm_score": 7, "selected": false, "text": "origin master origin/master git checkout master \ngit fetch \ngit diff origin/master\ngit rebase origin master\n" }, { "answer_id": 6011169, "author": "jfmercer", "author_id": 754842, "author_profile": "https://Stackoverflow.com/users/754842", "pm_score": 8, "selected": false, "text": "git pull git fetch git merge git pull origin master git diff origin/master git rebase git pull origin master\ngit checkout foo-branch\ngit rebase master\ngit push origin foo-branch\n git pull --rebase man git-pull 2.3.5" }, { "answer_id": 7104747, "author": "Mouna Cheikhna", "author_id": 271999, "author_profile": "https://Stackoverflow.com/users/271999", "pm_score": 11, "selected": false, "text": "git pull git pull git fetch git merge" }, { "answer_id": 10556826, "author": "Gerardo", "author_id": 604020, "author_profile": "https://Stackoverflow.com/users/604020", "pm_score": 9, "selected": false, "text": "master HEAD HEAD HEAD git fetch HEAD git pull HEAD" }, { "answer_id": 11527075, "author": "pn1 dude", "author_id": 34475, "author_profile": "https://Stackoverflow.com/users/34475", "pm_score": 7, "selected": false, "text": "--------------------- ----------------------- -----------------------\n- Remote Repo - - Remote Repo - - Remote Repo -\n- - - gets pushed - - -\n- @ R01 - - @ R02 - - @ R02 -\n--------------------- ----------------------- -----------------------\n\n--------------------- ----------------------- -----------------------\n- Local Repo - - Local Repo - - Local Repo -\n- pull - - - - fetch -\n- @ R01 - - @ R01 - - @ R02 -\n--------------------- ----------------------- -----------------------\n\n--------------------- ----------------------- -----------------------\n- Local Sandbox - - Local Sandbox - - Local Sandbox -\n- Checkout - - new work done - - -\n- @ R01 - - @ R01+ - - @R01+ -\n--------------------- ----------------------- -----------------------\n --------------------- ----------------------- -----------------------\n- Remote Repo - - Remote Repo - - Remote Repo -\n- - - gets pushed - - -\n- @ R01 - - @ R02 - - @ R02 -\n--------------------- ----------------------- -----------------------\n\n--------------------- ----------------------- -----------------------\n- Local Repo - - Local Repo - - Local Repo -\n- pull - - - - pull -\n- @ R01 - - @ R01 - - @ R02 -\n--------------------- ----------------------- -----------------------\n\n--------------------- ----------------------- -----------------------\n- Local Sandbox - - Local Sandbox - - Local Sandbox -\n- Checkout - - new work done - - merged with R02 -\n- @ R01 - - @ R01+ - - @R02+ -\n--------------------- ----------------------- -----------------------\n" }, { "answer_id": 13573856, "author": "ntanase", "author_id": 1854415, "author_profile": "https://Stackoverflow.com/users/1854415", "pm_score": 6, "selected": false, "text": "git fetch git diff git merge git pull git fetch" }, { "answer_id": 15003413, "author": "Selvamani", "author_id": 1514776, "author_profile": "https://Stackoverflow.com/users/1514776", "pm_score": 7, "selected": false, "text": "git pull == git fetch + git merge\n git pull git fetch git merge" }, { "answer_id": 15733096, "author": "Mike DeAngelo", "author_id": 7031, "author_profile": "https://Stackoverflow.com/users/7031", "pm_score": 10, "selected": false, "text": "git fetch git pull git pull git fetch" }, { "answer_id": 15990759, "author": "Snowcrash", "author_id": 343204, "author_profile": "https://Stackoverflow.com/users/343204", "pm_score": 8, "selected": false, "text": "git fetch git pull git fetch merge git fetch pull refs objects origin/master master git pull git clone git rebase git pull -rebase git branch -a git pull git fetch git clone git rebase git fetch \n git diff master origin/master \n git pull\n git rebase origin merge pull pull rebase" }, { "answer_id": 16920037, "author": "Rohitashv Singhal", "author_id": 1492648, "author_profile": "https://Stackoverflow.com/users/1492648", "pm_score": 6, "selected": false, "text": "git pull git fetch git pull git fetch" }, { "answer_id": 18903881, "author": "Michael Durrant", "author_id": 631619, "author_profile": "https://Stackoverflow.com/users/631619", "pm_score": 6, "selected": false, "text": "git fetch origin origin/ origin/master origin/mybranch-123 git pull git fetch git fetch" }, { "answer_id": 20271460, "author": "Pawel Furmaniak", "author_id": 221315, "author_profile": "https://Stackoverflow.com/users/221315", "pm_score": 6, "selected": false, "text": "master@remote >> remote/origin/master@local remote/origin/master@local >> master@local git git fetch git merge git rebase git pull git fetch git merge" }, { "answer_id": 21892643, "author": "Justus Romijn", "author_id": 334243, "author_profile": "https://Stackoverflow.com/users/334243", "pm_score": 7, "selected": false, "text": " LOCAL SYSTEM\n . ===================================================== \n================= . ================= =================== =============\nREMOTE REPOSITORY . REMOTE REPOSITORY LOCAL REPOSITORY WORKING COPY\n(ORIGIN) . (CACHED) \nfor example, . mirror of the \na github repo. . remote repo\nCan also be .\nmultiple repo's .\n .\n .\nFETCH *------------------>*\nYour local cache of the remote is updated with the origin (or multiple\nexternal sources, that is git's distributed nature)\n .\nPULL *-------------------------------------------------------->*\nchanges are merged directly into your local copy. when conflicts occur, \nyou are asked for decisions.\n .\nCOMMIT . *<---------------*\nWhen coming from, for example, subversion, you might think that a commit\nwill update the origin. In git, a commit is only done to your local repo.\n .\nPUSH *<---------------------------------------*\nSynchronizes your changes back into the origin.\n" }, { "answer_id": 25255924, "author": "Marcus Thornton", "author_id": 2288882, "author_profile": "https://Stackoverflow.com/users/2288882", "pm_score": 5, "selected": false, "text": "git fetch origin master git log -p master..origin/master git merge origin/master git pull origin master git fetch git merge git fetch" }, { "answer_id": 28365125, "author": "th3sly", "author_id": 492937, "author_profile": "https://Stackoverflow.com/users/492937", "pm_score": 7, "selected": false, "text": "git fetch git pull git pull git fetch git merge FETCH_HEAD" }, { "answer_id": 30324983, "author": "Donal", "author_id": 379855, "author_profile": "https://Stackoverflow.com/users/379855", "pm_score": 5, "selected": false, "text": "git pull git fetch git fetch git pull git pull git fetch" }, { "answer_id": 31364215, "author": "Saqib R.", "author_id": 932733, "author_profile": "https://Stackoverflow.com/users/932733", "pm_score": 5, "selected": false, "text": "git pull = git fetch + git merge \n" }, { "answer_id": 31364749, "author": "Animesh Sharma", "author_id": 3894956, "author_profile": "https://Stackoverflow.com/users/3894956", "pm_score": 5, "selected": false, "text": "git fetch\ngit rebase origin/master\n" }, { "answer_id": 31708577, "author": "Montells", "author_id": 818094, "author_profile": "https://Stackoverflow.com/users/818094", "pm_score": 6, "selected": false, "text": "shortcut" }, { "answer_id": 32553304, "author": "Pokemon", "author_id": 5233045, "author_profile": "https://Stackoverflow.com/users/5233045", "pm_score": 5, "selected": false, "text": "git fetch git pull git pull" }, { "answer_id": 34438903, "author": "Sazzad Hissain Khan", "author_id": 1084174, "author_profile": "https://Stackoverflow.com/users/1084174", "pm_score": 7, "selected": false, "text": "git pull --rebase" }, { "answer_id": 42092094, "author": "Aman Tiwari", "author_id": 7416375, "author_profile": "https://Stackoverflow.com/users/7416375", "pm_score": 7, "selected": false, "text": "A B C D D E F C D D C" }, { "answer_id": 44672602, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 8, "selected": false, "text": "git pull git fetch git fetch git pull" }, { "answer_id": 45049899, "author": "Mohideen bin Mohammed", "author_id": 4453737, "author_profile": "https://Stackoverflow.com/users/4453737", "pm_score": 5, "selected": false, "text": "git pull \n git rebase git pull origin master\n git fetch origin master\n git rebase origin/master\n" }, { "answer_id": 47947099, "author": "Andrei Todorut", "author_id": 6318702, "author_profile": "https://Stackoverflow.com/users/6318702", "pm_score": 3, "selected": false, "text": "git repository GitFlow branches git fetch --all command branches repository git fetch git reset git fetch --all // get known about latest updates\ngit reset --hard origin/[branch] // revert to current branch state\n branch repository branch GitFlow branches merged develop branch git pull develop branch" }, { "answer_id": 54657340, "author": "mfaani", "author_id": 5175709, "author_profile": "https://Stackoverflow.com/users/5175709", "pm_score": 7, "selected": false, "text": "git fetch origin <branch> git push origin <branch> git fetch git checkout git pull git fetch git fetch git pull git merge git pull git merge git fetch .git/refs/remotes .git/refs/remotes .git/refs/heads/ git fetch heads remotes git fetch remotes heads merge pull git ls ls -a . .git cd .git ls refs cd refs heads remotes cd git fetch /.git/refs/remotes /.git/refs/heads git pull git fetch /.git/refs/remotes /.git/refs/heads git fetch origin master\ngit checkout master\n Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded.\n (use \"git pull\" to update your local branch)\n fetch git checkout master Already on 'master'\nYour branch is up to date with 'origin/master'.\n git fetch git pull git fetch origin feature/123\n git checkout feature/123\n git checkout -b feature/123 origin/feature/123\n" }, { "answer_id": 58743394, "author": "8bitIcon", "author_id": 9266709, "author_profile": "https://Stackoverflow.com/users/9266709", "pm_score": 4, "selected": false, "text": ".git/refs .git/refs/heads .git/refs/remotes git fetch git fetch .git/refs/remotes git pull dev/jd/feature/auth git fetch origin dev/jd/feature/auth git checkout dev/jd/feature/auth git pull origin dev/jd/feature/auth git fetch origin branch_name git pull origin branch_name" }, { "answer_id": 61779963, "author": "Akash Yellappa", "author_id": 1908827, "author_profile": "https://Stackoverflow.com/users/1908827", "pm_score": 3, "selected": false, "text": "git fetch\n git pull\n" }, { "answer_id": 64908685, "author": "Piaget Hadzizi", "author_id": 8336869, "author_profile": "https://Stackoverflow.com/users/8336869", "pm_score": 3, "selected": false, "text": "git pull git fetch git merge" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
292,363
<p>I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable <code>private ArrayList&lt;String&gt; names</code>. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the <code>run()</code> method instead.</p> <p>I thought about this for a bit and I kind of feel it might be a matter of taste, but in general how does one choose in situations like this? Does one take up less memory or something?</p> <p>PS I like the instance variables in Ruby that start with an @ symbol: they are lovelier.</p> <p>(meta-question: What would be a better title for this question?)</p>
[ { "answer_id": 292906, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "final final /* DON'T DO THIS! */\nColor color = null;\nswitch(colorCode) {\n case RED: color = new Color(\"crimson\"); break;\n case GREEN: color = new Color(\"lime\"); break;\n case BLUE: color = new Color(\"azure\"); break;\n}\ncolor.fill(widget);\n NullPointerException null color.fill() color run() Thread run run Runnable Exception class Oops extends Thread { /* Note that thread implements \"Runnable\" */\n\n private int counter = 0;\n\n private Collection<Integer> state = ...;\n\n public void run() {\n state.add(counter);\n counter++;\n }\n\n public static void main(String... argv) throws Exception {\n Oops oops = new Oops();\n oops.start();\n Thread t2 = new Thread(oops); /* Now pass the same Runnable to a new Thread. */\n t2.start(); /* Execute the \"run\" method of the same instance again. */\n ...\n }\n}\n main Collection state" }, { "answer_id": 292956, "author": "mtruesdell", "author_id": 6479, "author_profile": "https://Stackoverflow.com/users/6479", "pm_score": 0, "selected": false, "text": "private ArrayList<String> myStrings = new ArrayList<String>(); new Foo()" }, { "answer_id": 308948, "author": "user2427", "author_id": 1356709, "author_profile": "https://Stackoverflow.com/users/1356709", "pm_score": -1, "selected": false, "text": "// Lazy initialization holder class idiom for static fields\nprivate static class FieldHolder {\n static final FieldType field = computeFieldValue();\n}\nstatic FieldType getField() { return FieldHolder.field; }\n // Double-check idiom for lazy initialization of instance fields\nprivate volatile FieldType field;\nFieldType getField() {\n FieldType result = field;\n if (result == null) { // First check (no locking)\n synchronized(this) {\n result = field;\n if (result == null) // Second check (with locking)\n field = result = computeFieldValue();\n }\n }\n return result;\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29182/" ]
292,378
<p>I have a number of user permissions that are tested throughout my ASP.NET application. These permission values are referenced in an Enum so that I can conveniently test permissions like so:</p> <ul> <li>btnCreate.Enabled = PermissionManager.TestPermission(Permission.AllowCreate);</li> </ul> <p>However, I also have these permissions stored in the database because I need hold more info about them than just their Id. But this creates a horrible dependency between the enum values and those in the database, an ill considered change to either and I have problems throughout my application. Is there a better way around this issue? Has anyone dealt with this before?</p>
[ { "answer_id": 292386, "author": "Ruben", "author_id": 21733, "author_profile": "https://Stackoverflow.com/users/21733", "pm_score": 1, "selected": false, "text": "public enum MyEnum : int \n{\n None =0,\n Value = 1,\n AnotherValue =2 \n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
292,380
<p>I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.</p> <p>As soon as a blacklisted character is encountered, the string before that point should be returned.</p> <p>For instance, if I have an array:</p> <pre><code>$chars = array(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;); </code></pre> <p>How would I go through the following string...</p> <pre><code>log dog hat bat </code></pre> <p>...and end up with:</p> <pre><code>log dog h </code></pre>
[ { "answer_id": 292391, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<?php\n\n$mask = \"abc\";\n\n$string = \"log dog hat bat\";\n\n$result = substr($string,0,strcspn($string,$mask));\n\nvar_dump($result);\n\n?>\n" }, { "answer_id": 66565472, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 0, "selected": false, "text": "['a', 'b', 'c'] abc implode($array) echo preg_split('~[abc]~', $string, 2)[0];\n echo preg_match('~^[^abc]+~', $string, $match) ? $match[0] : '';\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
292,395
<p>I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment:</p> <p>Firstly I use <code>fetch_template</code> to load the template contents from the database - this works (and I collect all the templates at startup if you're interested).</p> <p>I use PHP variables in my template code and in the logic - e.g.:</p> <pre><code>// PHP: $name = 'Ross'; // Tpl: &lt;p&gt;Hello, my name is $name.&lt;/p&gt; </code></pre> <p>I then use <code>output_template</code> (below) to parse through the variables in the template and replace them. Previously I was using template tags with a glorified <code>str_replace</code> template class but it was too inefficient.</p> <pre><code>/** * Returns a template after evaluating it * @param string $template Template contents * @return string Template output */ function output_template($template) { eval('return "' . $template . '";'); } </code></pre> <p>My problem, if you haven't already guessed, is that the variables are not declared inside the function - therefore the function can't parse them in <code>$template</code> unless I put them in the global scope - which I'm not sure I want to do. That or have an array of variables as a parameter in the function (which sounds even more tedious but possible).</p> <p>Does anyone have any solutions other than using the code from the function (it is only a one-liner) in my code, rather than using the function?</p> <p>Thanks, Ross</p> <p><em>P.s. I know about Smarty and the vast range of templating engines out there - I'm not looking to use them so please don't suggest them. Thanks!</em></p>
[ { "answer_id": 292400, "author": "Dave Vogt", "author_id": 35189, "author_profile": "https://Stackoverflow.com/users/35189", "pm_score": 3, "selected": false, "text": "function output_template($template, $vars) {\n extract($vars);\n eval('return \"' . $template . '\";');\n}\n" }, { "answer_id": 292404, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "function inc_scope( $file , $vars )\n{\n extract($vars); \n ob_start(); \n require($file); \n return ob_get_clean(); \n}\n" }, { "answer_id": 292409, "author": "Howard Sandford", "author_id": 37904, "author_profile": "https://Stackoverflow.com/users/37904", "pm_score": 4, "selected": true, "text": "include($template_name) $template_name = 'template.php';\n\n// import the contents into this template\nob_start();\ninclude($template_name);\n$content = ob_get_clean();\n\n// do something with $content now ...\n <?php if ($a == 5): ?>\nA is equal to 5\n<?php endif; ?>\n" }, { "answer_id": 36580240, "author": "Semu", "author_id": 6194547, "author_profile": "https://Stackoverflow.com/users/6194547", "pm_score": -1, "selected": false, "text": "/* semu design */\n// HTTP URL\ndefine('HTTP_SERVER', 'http://localhost/1/');\n\n// HTTPS URL DISABLE\n// define('HTTPS_SERVER', 'http://localhost/1/');\n\n// DİZİNLER\ndefine('DIR_INC', 'C:\\wamp\\www\\1/inc/');\ndefine('DIR_TEMLATE', 'C:\\wamp\\www\\1/template/default/');\ndefine('DIR_MODULES', 'C:\\wamp\\www\\1/template/default/module/');\ndefine('DIR_IMAGE', 'C:\\wamp\\www\\1/image/');\ndefine('DIR_CACHE', 'cache'); // [php cache system turkish coder][1]\n\n// DB\ndefine('DB_HOSTNAME', 'localhost');\ndefine('DB_USERNAME', 'root');\ndefine('DB_PASSWORD', '123');\ndefine('DB_DATABASE', 'default');\ndefine('DB_PREFIX', '');\n <?php \n// Version\ndefine('VERSION', '1.0');\n\n// Config file\nif (file_exists('config.php')) {\n require_once('config.php');\n}\n\n// Moduller\nrequire_once(DIR_INC . 'startup.php'); // mysql.php db engine, cache.php, functions.php, mail.php ... vs require_once code\n\n// Cache System\n//$sCache = new sCache();\n\n/*$options = array(\n 'time' => 120,\n 'buffer' => true,\n 'load' => false,\n //'external'=>array('nocache.php','nocache2.php'), // no cache file\n);\n\n$sCache = new sCache($options);*/\n\n// page\n$page = isset($_GET['page']) ? trim(strtolower($_GET['page'])) : \"home\";\n\n$allowedPages = array(\n 'home' => DIR_TEMPLATE.'controller/home.php',\n 'login' => DIR_TEMPLATE.'controller/login.php',\n 'register' => DIR_TEMPLATE.'controller/register.php',\n 'contact' => DIR_TEMPLATE.'controller/contact.php'\n);\n\ninclude( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages[\"home\"] );\n?>\n <ul>\n<li <?php if ( $page == 'home' ) echo 'class=\"active\"'; ?> Home </li>\n<li <?php if ( $page == 'login' ) echo 'class=\"active\"'; ?> Login </li>\n</ul>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
292,403
<p>Say that I have two models- Users and Accounts. Each account can have at most n users associated with it, and a user can only be associated with one account. </p> <p>It would seem natural to say that User </p> <pre><code>belongs_to :account </code></pre> <p>and Account </p> <pre><code>has_many :users </code></pre> <p>However, I'm not clear on the best practice when it comes to limiting the number of associations through that has_many declaration. I know that there is a :limit argument, but that that only limits the number of associations returned, not the number that are able to exist.</p> <p>I suspect that the answer is to use something like :before_add. However, that approach seems only to apply to associations created via &lt;&lt; . So it would get called when you used</p> <pre><code>@account.users &lt;&lt; someuser </code></pre> <p>but not if you used </p> <pre><code>@account.users.create </code></pre> <p>I had also considered that it might be more practical to implement the limit using before_save within the User model, but it seems like it would be a bit off to implement Account business rules within the User model.</p> <p>What is the best practice for limiting the number of associations?</p> <p>Edit: the n users per account would be some business data that is stored within the individual accounts, rather than being a straight up magic number that would be floating around willy nilly in the code.</p>
[ { "answer_id": 292473, "author": "Raimonds Simanovskis", "author_id": 16829, "author_profile": "https://Stackoverflow.com/users/16829", "pm_score": 4, "selected": true, "text": "class User\n belongs_to :account\nend\n class User\n validates_each :account do |user, attr, value|\n user.errors.add attr, \"too much users for account\" if user.account.users.size >= 3\n end\nend\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35345/" ]
292,437
<p>In .net (C#), If you have two types discovered through reflection is it possible to determine if one can be cast to the other? (implicit and/or explicit).</p> <p>What I'm trying to do is create a library that allows users to specify that a property on one type is mapped to a property on another type. Everything is fine if the two properties have matching types, but I'd like to be able to allow them to map properties where an implicit/explicit cast is available. So if they have </p> <pre><code>class from { public int IntProp{get;set;} } class to { public long LongProp{get;set;} public DateTime DateTimeProp{get;set;} } </code></pre> <p>they would be able to say that from.IntProp will be assigned to to.LongProp (as an implicity cast exists). But if they said that it mapped to DateTimeProp I'd be able to determine that there's no available cast and throw an exception.</p>
[ { "answer_id": 1809539, "author": "Alex Marshall", "author_id": 32232, "author_profile": "https://Stackoverflow.com/users/32232", "pm_score": 2, "selected": false, "text": "to.GetType().IsAssignableFrom(from.GetType());\n" }, { "answer_id": 4640305, "author": "ephere", "author_id": 417615, "author_profile": "https://Stackoverflow.com/users/417615", "pm_score": 3, "selected": false, "text": "public static bool HasConversionOperator( Type from, Type to )\n {\n Func<Expression, UnaryExpression> bodyFunction = body => Expression.Convert( body, to );\n ParameterExpression inp = Expression.Parameter( from, \"inp\" );\n try\n {\n // If this succeeds then we can cast 'from' type to 'to' type using implicit coercion\n Expression.Lambda( bodyFunction( inp ), inp ).Compile();\n return true;\n }\n catch( InvalidOperationException )\n {\n return false;\n }\n }\n" }, { "answer_id": 23675901, "author": "ChaseMedallion", "author_id": 1142970, "author_profile": "https://Stackoverflow.com/users/1142970", "pm_score": 3, "selected": false, "text": "public static bool IsCastableTo(this Type from, Type to)\n{\n // from https://web.archive.org/web/20141017005721/http://www.codeducky.org/10-utilities-c-developers-should-know-part-one/ \n Throw.IfNull(from, \"from\");\n Throw.IfNull(to, \"to\");\n\n // explicit conversion always works if to : from OR if \n // there's an implicit conversion\n if (from.IsAssignableFrom(to) || from.IsImplicitlyCastableTo(to))\n {\n return true;\n }\n\n // for nullable types, we can simply strip off the nullability and evaluate the underyling types\n var underlyingFrom = Nullable.GetUnderlyingType(from);\n var underlyingTo = Nullable.GetUnderlyingType(to);\n if (underlyingFrom != null || underlyingTo != null)\n {\n return (underlyingFrom ?? from).IsCastableTo(underlyingTo ?? to);\n }\n\n if (from.IsValueType)\n {\n try\n {\n ReflectionHelpers.GetMethod(() => AttemptExplicitCast<object, object>())\n .GetGenericMethodDefinition()\n .MakeGenericMethod(from, to)\n .Invoke(null, new object[0]);\n return true;\n }\n catch (TargetInvocationException ex)\n {\n return !(\n ex.InnerException is RuntimeBinderException\n // if the code runs in an environment where this message is localized, we could attempt a known failure first and base the regex on it's message\n && Regex.IsMatch(ex.InnerException.Message, @\"^Cannot convert type '.*' to '.*'$\")\n );\n }\n }\n else\n {\n // if the from type is null, the dynamic logic above won't be of any help because \n // either both types are nullable and thus a runtime cast of null => null will \n // succeed OR we get a runtime failure related to the inability to cast null to \n // the desired type, which may or may not indicate an actual issue. thus, we do \n // the work manually\n return from.IsNonValueTypeExplicitlyCastableTo(to);\n }\n}\n\nprivate static bool IsNonValueTypeExplicitlyCastableTo(this Type from, Type to)\n{\n if ((to.IsInterface && !from.IsSealed)\n || (from.IsInterface && !to.IsSealed))\n {\n // any non-sealed type can be cast to any interface since the runtime type MIGHT implement\n // that interface. The reverse is also true; we can cast to any non-sealed type from any interface\n // since the runtime type that implements the interface might be a derived type of to.\n return true;\n }\n\n // arrays are complex because of array covariance \n // (see http://msmvps.com/blogs/jon_skeet/archive/2013/06/22/array-covariance-not-just-ugly-but-slow-too.aspx).\n // Thus, we have to allow for things like var x = (IEnumerable<string>)new object[0];\n // and var x = (object[])default(IEnumerable<string>);\n var arrayType = from.IsArray && !from.GetElementType().IsValueType ? from\n : to.IsArray && !to.GetElementType().IsValueType ? to\n : null;\n if (arrayType != null)\n {\n var genericInterfaceType = from.IsInterface && from.IsGenericType ? from\n : to.IsInterface && to.IsGenericType ? to\n : null;\n if (genericInterfaceType != null)\n {\n return arrayType.GetInterfaces()\n .Any(i => i.IsGenericType\n && i.GetGenericTypeDefinition() == genericInterfaceType.GetGenericTypeDefinition()\n && i.GetGenericArguments().Zip(to.GetGenericArguments(), (ia, ta) => ta.IsAssignableFrom(ia) || ia.IsAssignableFrom(ta)).All(b => b));\n }\n }\n\n // look for conversion operators. Even though we already checked for implicit conversions, we have to look\n // for operators of both types because, for example, if a class defines an implicit conversion to int then it can be explicitly\n // cast to uint\n const BindingFlags conversionFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;\n var conversionMethods = from.GetMethods(conversionFlags)\n .Concat(to.GetMethods(conversionFlags))\n .Where(m => (m.Name == \"op_Explicit\" || m.Name == \"op_Implicit\")\n && m.Attributes.HasFlag(MethodAttributes.SpecialName)\n && m.GetParameters().Length == 1 \n && (\n // the from argument of the conversion function can be an indirect match to from in\n // either direction. For example, if we have A : B and Foo defines a conversion from B => Foo,\n // then C# allows A to be cast to Foo\n m.GetParameters()[0].ParameterType.IsAssignableFrom(from)\n || from.IsAssignableFrom(m.GetParameters()[0].ParameterType)\n )\n );\n\n if (to.IsPrimitive && typeof(IConvertible).IsAssignableFrom(to))\n {\n // as mentioned above, primitive convertible types (i. e. not IntPtr) get special \n // treatment in the sense that if you can convert from Foo => int, you can convert\n // from Foo => double as well\n return conversionMethods.Any(m => m.ReturnType.IsCastableTo(to));\n }\n\n return conversionMethods.Any(m => m.ReturnType == to);\n}\n\nprivate static void AttemptExplicitCast<TFrom, TTo>()\n{\n // based on the IL generated from\n // var x = (TTo)(dynamic)default(TFrom);\n\n var binder = Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(TTo), typeof(TypeHelpers));\n var callSite = CallSite<Func<CallSite, TFrom, TTo>>.Create(binder);\n callSite.Target(callSite, default(TFrom));\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11921/" ]
292,450
<p>I need to do some process injection using C++ but I would prefer to use C# for everything other than the low level stuff. I have heard about "function wrapping" and "marshaling" and have done quite a bit of google searching and have found bits of information here and there but I am still really lacking. </p> <p>Things I have read in order of usefulness;<br> <a href="http://msdn.microsoft.com/en-us/library/ms235281(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms235281(VS.80).aspx</a><br> <a href="http://www.drdobbs.com/cpp/184401742" rel="nofollow noreferrer">http://www.drdobbs.com/cpp/184401742</a><br> <a href="http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html" rel="nofollow noreferrer">http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html</a> </p> <p>How can I wrap all the lower level stuff (native C++) in C# so I can easily command those functions in a language I am more comfortable with, C#? </p> <p>Any information on the topic is much appreciated.</p>
[ { "answer_id": 292582, "author": "Arnout", "author_id": 3496, "author_profile": "https://Stackoverflow.com/users/3496", "pm_score": 4, "selected": true, "text": "static extern DllImport" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67445/" ]
292,453
<p>I'm looking into the feasibility of adding a function to my Rails-based intranet site that allows users to upload files.</p> <p>Two purposes: My users are widely distributed geographically and linking to documents on the shared network storage doesn't always work (different addresses, DNS entries and stuff outside my control or interest) so I'm thinking about providing a database-oriented alternative. We have a number of files from which we parse data at the client end. I'd rather like to be able to push that up to the server.</p> <p>I've looked at attachment_fu, Paperclip and another one (forgotten the name!) all of which seem very image-oriented, although attachment_fu at least can work without a image processing library present, thank goodness.</p> <p>The big problem is that my server does not permit my application to write files locally, and these plugins all seem to want to create a Tempfile.</p> <p>The questions (finally!)</p> <p>Is there a reasonable way to upload binary data and process it in memory and/or store it as a BLOB without any server-side file saves?</p> <p>Or should I give up on the file distribution idea and give the users a second-best option of copy-and-paste text boxes where possible?</p> <p>(Closest I could find on SO was <a href="https://stackoverflow.com/questions/116353/uploading-files-in-ruby-on-rails">this</a> which doesn't really help)</p>
[ { "answer_id": 294102, "author": "blindgaenger", "author_id": 38045, "author_profile": "https://Stackoverflow.com/users/38045", "pm_score": 3, "selected": false, "text": "<% form_for :upload, :url => {:action=>:upload}, :html=>{:multipart=>true} do |f| %>\n <%= f.file_field :file %>\n <%= f.submit 'Upload' %>\n<% end %>\n class TestController < ApplicationController\n\n def upload \n file_param = params[:upload][:file]\n filename = file_param.original_filename\n filedata = file_param.read\n\n @data = UploadedFile.create(:name => filename, :data => filedata)\n\n render :text => \"created #{@data.id}\"\n end\n\nend\n class CreateUploadedFiles < ActiveRecord::Migration\n def self.up\n create_table :uploaded_files do |t|\n t.string :name\n t.binary :data\n t.timestamps\n end\n end\n\n def self.down\n drop_table :uploaded_files\n end\nend\n" }, { "answer_id": 296845, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": true, "text": "<%= f.file_field :file %>\n....\nfile_param = params[:upload][:file]\n params[:upload][:file] ActionController::UploadedTempFile Technoweenie::AttachmentFu.tempfile_path = Dir::tmpdir\n" }, { "answer_id": 305428, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 0, "selected": false, "text": " def upload\n file_content = params[:upload][:file]\n render :text => [\n [:original_path, :content_type, :local_path, :path, :original_filename].collect {|m| file_content.send(m)},\n file_content.class, \n file_content.size.to_s].flatten.join(\"<br/>\")\n end\n b_wib.xls\napplication/vnd.ms-excel\n\n\nb_wib.xls\nActionController::UploadedStringIO\n13824\n a_wib.xls\napplication/vnd.ms-excel\n/tmp/CGI.10029.1\n/tmp/CGI.10029.1\na_wib.xls\nActionController::UploadedTempfile\n27648\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060/" ]
292,458
<p>If you have a lot of Stored Procedures and you change the name of a column of a table, is there a way to check which Stored Procedures won't work any longer?</p> <hr> <p><strong>Update</strong>: I've read some of the answers and it's clear to me that there's is no easy way to do this. Would it be easier to move away from Stored Procedures?</p>
[ { "answer_id": 292487, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT Object_Name(ID) \nFROM SysComments \nWHERE text LIKE '%Table%'\nAND text LIKE '%Column%'\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26521/" ]
292,464
<p>Since I've started using NetBeans, I've learned of some <a href="http://www.netbeans.org/kb/60/java/gui-db.html" rel="nofollow noreferrer">powerful ways</a> to abstract away the process of creating Java database applications with automatically generated UI, beans bindings, and a bunch of other stuff I only vaguely understand the workings of at the moment (I hate being a newb). Problem is, <em>how do I do the basic stuff I actually want to do</em>? The tutorials I've read make a big deal about being able to connect to and mess around with a database from within the IDE, or how to create and bind some UI sliders and checkboxes to table columns, etc. But where can I learn about how to make my own code do that stuff? Abstraction is nice and all, but it's quite useless to me at the moment for what I need done.</p> <p>Can anyone refer me to some good resources or tutorials to learn this? The few I've found aren't proving as useful as I'd hoped to get my project underway...</p>
[ { "answer_id": 292470, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": " Connection con = DriverManager.getConnection\n ( \"jdbc:myDriver:wombat\", \"myLogin\",\"myPassword\");\n\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"SELECT a, b, c FROM Table1\");\n while (rs.next()) {\n int x = rs.getInt(\"a\");\n String s = rs.getString(\"b\");\n float f = rs.getFloat(\"c\");\n }\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
292,516
<p>I would like such empty span tags (filled with <code>&amp;nbsp;</code> and space) to be removed:</p> <p><code>&lt;span&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/span&gt;</code></p> <p>I've tried with this regex, but it needs adjusting: </p> <p><code>(&lt;span&gt;(&amp;nbsp;|\s)*&lt;/span&gt;)</code></p> <p><code>preg_replace('#&lt;span&gt;(&amp;nbsp;|\s)*&lt;/span&gt;#si','&lt;\\1&gt;',$encoded);</code></p>
[ { "answer_id": 292520, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "qr{<span[^>]*(/>|>\\s*?</span>)}\n" }, { "answer_id": 292538, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "preg_replace('#<span>(&nbsp;|\\s)*?</span>#si', '<$1>', $encoded);" }, { "answer_id": 292628, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 3, "selected": false, "text": "preg_match_all('#<span[^>]*(?:/>|>(?:\\s|&nbsp;)*</span>)#im', $html, $result);\n <br />" }, { "answer_id": 292816, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "<span><span> &nbsp; </span></span> <span>" }, { "answer_id": 301325, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$test=\"<span> <span>& nbsp; </span> test <span>& nbsp; <span>& nbsp; </span> </span> & nbsp;& nbsp; </span>\";\n\n$pattern = '#<(\\w+)[^>]*>(& nbsp;|\\s)*</\\1>#im'; \nwhile(preg_match($pattern, $test, $matches, PREG_OFFSET_CAPTURE)!= 0)\n{$test= preg_replace($pattern,'', $test);}\n" }, { "answer_id": 5753786, "author": "jsruok", "author_id": 584505, "author_profile": "https://Stackoverflow.com/users/584505", "pm_score": 0, "selected": false, "text": "function remove_empty_spans($html_replace)\n{\n$pattern = '/<span[^>]*(?:\\/>|>(?:\\s|&nbsp;)*<\\/span>)/im';\nreturn preg_replace($pattern, '', $html_replace);\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,535
<p>Every time that I change a value in the designer after saving it, the .designer.cs file will be deleted. </p> <p>Can anyone tell me how can I fix this problem?</p>
[ { "answer_id": 292605, "author": "gius", "author_id": 19712, "author_profile": "https://Stackoverflow.com/users/19712", "pm_score": 5, "selected": true, "text": "using DataContext.cs DataContext.designer.cs namespace" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34623/" ]
292,544
<p>Just that... I get a string which contains a path to a file plus some arguments. How can I recognize the path? I thought about the index of the '.' in the file... but I don't like it.<br> What about using regular expressions? Can anyone point me in the right direction?</p> <p>Regards</p> <p>Edit: Theses are valid entries...<br> somefile.msi /a<br> C:\MyFolder\SomeFile.exe -i -d</p> <p>I don't care much about the arguments cause once I have the path I'll assume the rest are arguments</p>
[ { "answer_id": 292579, "author": "Frode Lillerud", "author_id": 33431, "author_profile": "https://Stackoverflow.com/users/33431", "pm_score": 3, "selected": false, "text": "bool isPath = System.IO.Path.GetDirectoryName(@\"C:\\MyFolder\\SomeFile.exe -i -d\") != String.Empty;\nif (isPath)\n{\n Console.WriteLine(\"The string contains a path\");\n}\n" }, { "answer_id": 292699, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "private ProcessStartInfo GetProcessInfo(string uninstallString)" }, { "answer_id": 292996, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "C:\\My Folder\\Some File.exe -i -d\n=>\nC:\\My Folder\\Some File.exe -i -d (no, although it might exist!)\nC:\\My Folder\\Some File.exe -i (no)\nC:\\My Folder\\Some File.exe (yes => That's this one)\n notepad/p C:/windows/notepad.exe" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ]
292,548
<p>I trying to learn swt, and I use maven for all my builds and eclipse for my IDE. When getting the swt jars out of the maven repository, I get:</p> <pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: no swt-pi-gtk-3034 in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1709) at java.lang.Runtime.loadLibrary0(Runtime.java:823) at java.lang.System.loadLibrary(System.java:1030) at org.eclipse.swt.internal.Library.loadLibrary(Library.java:100) at org.eclipse.swt.internal.gtk.OS.&lt;clinit&gt;(OS.java:19) at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:63) at org.eclipse.swt.internal.Converter.wcsToMbcs(Converter.java:54) at org.eclipse.swt.widgets.Display.&lt;clinit&gt;(Display.java:112) at wenzlick.test.swt.main.Main.main(Main.java:30) </code></pre> <p>Has anyone successfully got a swt app to build and run using maven? </p> <p><strong>Edit</strong>: I did a little research and found the problem. look at my post below</p>
[ { "answer_id": 292799, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 4, "selected": true, "text": ".so .jnilib .dll .so java.library.path -D UnsatisifedLinkError" }, { "answer_id": 9985251, "author": "urish", "author_id": 830623, "author_profile": "https://Stackoverflow.com/users/830623", "pm_score": 4, "selected": false, "text": "<repositories>\n <repository>\n <id>swt-repo</id>\n <url>https://swt-repo.googlecode.com/svn/repo/</url>\n </repository>\n</repositories>\n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.win32.win32.x86</artifactId>\n <version>4.2.2</version>\n </dependency>\n" }, { "answer_id": 15487277, "author": "Stephan", "author_id": 363573, "author_profile": "https://Stackoverflow.com/users/363573", "pm_score": 3, "selected": false, "text": "<dependency>\n <groupId>org.eclipse.platform</groupId>\n <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>\n <version>${swt.version}</version>\n</dependency>\n" }, { "answer_id": 43235769, "author": "Witold Kaczurba", "author_id": 6931119, "author_profile": "https://Stackoverflow.com/users/6931119", "pm_score": 2, "selected": false, "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.whatever</groupId>\n <artifactId>whatever</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>swt</name>\n <url>http://maven.apache.org</url>\n\n <repositories>\n <repository>\n <id>maven-eclipse-repo</id>\n <url>http://maven-eclipse.github.io/maven</url>\n </repository>\n </repositories>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n <swt.version>4.6</swt.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.12</version>\n <scope>test</scope>\n </dependency>\n <!-- select prefered one, or move the preferred on to the top: -->\n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId>\n <version>${swt.version}</version>\n </dependency>\n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.win32.win32.x86</artifactId>\n <version>${swt.version}</version>\n <!-- To use the debug jar, add this -->\n <classifier>debug</classifier>\n </dependency> \n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.gtk.linux.x86</artifactId>\n <version>${swt.version}</version>\n </dependency>\n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.gtk.linux.x86_64</artifactId>\n <version>${swt.version}</version>\n </dependency>\n <dependency>\n <groupId>org.eclipse.swt</groupId>\n <artifactId>org.eclipse.swt.cocoa.macosx.x86_64</artifactId>\n <version>${swt.version}</version>\n </dependency>\n\n </dependencies>\n</project>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28068/" ]
292,551
<p>Here's the problem: </p> <p>I have to modify an existing Excel spreadsheet using .NET. The spreadsheet is hugely complex, and I just have to add data in some predefined areas.</p> <p>I'm investigating my options, and Excel Automation/InterOp is out of the question, as I'm implementing an ASP.NET website, and Excel probably isn't installed on the server. From what I find online, InterOp is also a very expensive solution performancewise.</p> <p>Creating a CSV file is also ruled out because of the complex nature of the original spreadsheet.</p> <p>Currently I'm leaning towards an ADO.NET OleDb solution, but I find that mentioned very rarely (Google and Stackoverflow.com) so I'm kinda worried: What's the catch with OldDb for Excel? The only drawback I can find on MSDN so far, is that I can't create cells with formulas, but that's really not an issue in my case.</p> <p>I've also considered SSIS, but that's only based on my assumption that you can use existing Excel files when you generate spreadsheets. I don't know if that possible or not.</p> <p>Then there's OpenXml. It seems overly complicated compared to OldDb, plus it's still undetermined which of the older Excel versions I have to support.</p> <p>Am I missing something? Are there more alternatives?</p>
[ { "answer_id": 292561, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<html><body>\n<table>\n<tr><td><b>Column A</b></td><td><b>Column B</b></td></tr>\n<tr><td><font color=\"red\">-154</b></td><td><font size=\"5\">hello world</font></td></tr>\n</table>\n</body></html>\n" }, { "answer_id": 292585, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "Excel Web Access" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10932/" ]
292,552
<p>I'm wondering to using extension method to avoid checking for null in hierarchy. The example:</p> <pre><code>// GetItems(), GetFirstOrDefault(), GetProduct(), GetIDProduct() are extension methods like: public static SomeType GetSomeProperty( this XYZ obj ) { if ( object.ReferenceEquals( obj, null ) ) { return default( SomeType ); } return obj.SomeProperty; } // the code with extension methods Guid? idProduct = this.Invoice.GetItems().GetFirstOrDefault().GetProduct().GetIDProduct(); // instead of Guid? idProduct = null; Invoice invoice = this.Invoce; if ( null != invoice ) { InvoiceItems items = invoice.Items; if ( null != items &amp;&amp; items.Count &gt; 0 ) { InvoiceItem item = items[0]; if ( null != item ) { idProduct = item.IDProduct(); } } } </code></pre> <p>I know, there is available Null Object pattern, but the solution with this type of extension methods looks better.</p> <p>Do you think, this solution is good or bad (because bad/good design, lucidity, whatever else)?</p> <p>Please vote "Good" or "Bad" and why do you think so. Posts are flaged as community.</p>
[ { "answer_id": 292565, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "Guid? idProduct = null;\nInvoice invoice = this.Invoce;\n\nif (invoice != null && \n invoice.Items != null &&\n invoice.Items.Count > 0 &&\n invoice.Items[0] != null) \n{\n idProduct = invoice.Items[0].IDProduct();\n}\n" }, { "answer_id": 7884242, "author": "Kit", "author_id": 64348, "author_profile": "https://Stackoverflow.com/users/64348", "pm_score": 0, "selected": false, "text": "GetFirstOrDefault().GetProduct()\n Get OrDefault null GetFirst().GetProduct()\n" }, { "answer_id": 12714267, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "String StringBuilder struct Nullable<T> this default(string).Length" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20382/" ]
292,558
<p>How can I draw a concave corner rectangle in WPF?</p>
[ { "answer_id": 292569, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "do you mean a rectangle with concave corners?, ie: \n ____________________\n | |\n __| |__\n | |\n | |\n | |\n |__ __|\n | |\n |____________________|\n w x h r A : 0,0\nB : w,0\nC : w,h\nD : 0,h\n w = 2r\nh = 2r\n A,B,C,D (0,0)--(0+r,0)---(w-r,0)---(w,0)\n| |\n(0,0+r) (w,0+r)\n| |\n| |\n(0,h-r) (w,h-r)\n| |\n(0,h)--(0+r,h)---(w-r,h)---(w,h)\n" }, { "answer_id": 293282, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 2, "selected": false, "text": "M17.200002,0L120.4,0 120.4,2.3066998E-06C120.4,6.7378696,128.10079,12.200001,137.60001,12.200001L137.60001,85.400003C128.10077,85.400003,120.4,90.862138,120.4,97.6L17.200002,97.6C17.200002,90.862151,9.4993697,85.400003,0,85.400003L0,12.199999C9.4993663,12.200015,17.200002,6.7378725,17.200002,0z\n public class ConcaveRectangle:System.Windows.Shapes.Shape\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37918/" ]
292,564
<p>I have looked at the SQL Server 2008 feature comparison matrix and it lists the express/web and workgroup editions as having the SSIS runtime. Does this mean it is possible to develop SSIS packages using the developer edition, and then deploy and run them on a server running one of the lowly SQL Server editions such as SQL Server 2008 Express edition?</p>
[ { "answer_id": 2645213, "author": "Jon Webb", "author_id": 317483, "author_profile": "https://Stackoverflow.com/users/317483", "pm_score": 3, "selected": false, "text": "Description: The product level is insufficient for component \"<component>\" (1828)." } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982/" ]
292,587
<p>I'm writing a J2ME application. One of the pieces is something that polls the contents of a directory periodically, and, if there are any new things, paints them on the screen. I've done this by having the UI form launch a polling thread with a pointer back to itself, and when the polling thread finds something it calls back to the form and calls a syncrhonized method to update it's display. This seems to work fine.</p> <p>The question I have is this. In C#/.NET I know it is not nice to have non-UI threads updating the UI, and the correct way to handle this is to delegate it up to the UI thread. </p> <p>E.g. the following:</p> <pre><code>public void DoSomeUIThing() { if (this.uiComponent.InvokeRequired) { this.uiComponent.Invoke(someDelegateThatCallsBackToThis); } else { this.uiComponent.Text = "This is the update I want to happen"; } } </code></pre> <p>Is there a J2ME equivalent for how to manage this process? How about Java? Or does Java/J2ME just play nicer in regard to this? If not, how is this done?</p> <p>[EDIT] It appears that Swing supports what I'm asking about via the SwingUtilities.invokeLater() and invokeAndWait() methods. Is there an equivalent framework for J2ME?</p>
[ { "answer_id": 292658, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 1, "selected": false, "text": "public void itemRemoved(final ModelEvent me)\n{\n final TableViewer tableViewer = this.viewer;\n\n if (tableViewer != null)\n {\n display.asyncExec(new Runnable()\n {\n public void run()\n {\n tableViewer.remove(me.getItem());\n }\n }\n }\n}\n" }, { "answer_id": 292829, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "Display.runSerially EventQueue.invokeLater SwingUtilities.invokeLater EventQueue DOMService.invokeLater" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8207/" ]
292,615
<p>As the question says, how do I set the value of a DropDownList control using jQuery?</p>
[ { "answer_id": 292620, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 10, "selected": true, "text": "$(\"#mydropdownlist\").val(\"thevalue\");\n" }, { "answer_id": 8165399, "author": "mattsson", "author_id": 511801, "author_profile": "https://Stackoverflow.com/users/511801", "pm_score": 6, "selected": false, "text": "$(\"#mydropdownlist\").attr('selectedIndex', 0);\n $(\"#mydropdownlist\").get(0).selectedIndex = index_here;\n" }, { "answer_id": 16032119, "author": "Clyde", "author_id": 1084987, "author_profile": "https://Stackoverflow.com/users/1084987", "pm_score": 5, "selected": false, "text": "/*make sure that value is included in the options value of the dropdownlist \ne.g. \n(<select><option value='CA'>California</option><option value='AK'>Alaska</option> </select>)\n*/\n\n$('#mycontrolId').val(myvalue).attr(\"selected\", \"selected\");\n" }, { "answer_id": 16746700, "author": "salah9", "author_id": 1935898, "author_profile": "https://Stackoverflow.com/users/1935898", "pm_score": 3, "selected": false, "text": " $(\"#<%=DropDownName.ClientID%>\")[0].selectedIndex=0;\n $(\"#DropDownName\")[0].selectedIndex=0;\n" }, { "answer_id": 18872510, "author": "JapineJ", "author_id": 2160684, "author_profile": "https://Stackoverflow.com/users/2160684", "pm_score": 1, "selected": false, "text": " $.getJSON('<%= Url.Action(\"GetDepartment\") %>', \n { coDepartment: paramDepartment },\n function(data) {\n $(\".autoCompleteDepartment\").empty();\n $(\".autoCompleteDepartment\").append($(\"<option />\").val(-1));\n $.each(data, function() {\n $(\".autoCompleteDepartment\").append($(\"<option />\").val(this.CodDepartment).text(this.DepartmentName));\n });\n $(\".autoCompleteDepartment\").val(-1); \n } \n );\n" }, { "answer_id": 30306000, "author": "GrvTyagi", "author_id": 3405842, "author_profile": "https://Stackoverflow.com/users/3405842", "pm_score": 0, "selected": false, "text": "<options ....></options> function set_ip_base_country(countryCode)\n $('#country').val(countryCode)\n} \n success: function (doc) {\n .....\n .....\n $(\"#country\").append('<option style=\"color:black;\" value=\"' + key + '\">' + value + '</option>')\n set_ip_base_country(ip_base_country)\n}\n" }, { "answer_id": 33864457, "author": "vishwakarma09", "author_id": 3205407, "author_profile": "https://Stackoverflow.com/users/3205407", "pm_score": 0, "selected": false, "text": "function SetSelected(elem, val){\n $('#'+elem+' option').each(function(i,d){\n // console.log('searching match for '+ elem + ' ' + d.value + ' equal to '+ val);\n if($.trim(d.value).toLowerCase() == $.trim(val).toLowerCase()){\n // console.log('found match for '+ elem + ' ' + d.value);\n $('#'+elem).prop('selectedIndex', i);\n }\n });\n }\n SetSelected('selectID','some option');\n" }, { "answer_id": 34394485, "author": "IRSHAD", "author_id": 4164167, "author_profile": "https://Stackoverflow.com/users/4164167", "pm_score": 6, "selected": false, "text": "$(\"#mydropdownlist\").val(\"thevalue\").change();\n" }, { "answer_id": 37611352, "author": "Dilip Kumar Yadav", "author_id": 2398547, "author_profile": "https://Stackoverflow.com/users/2398547", "pm_score": 2, "selected": false, "text": "$(\"._statusDDL\").val('2');\n $('select').prop('selectedIndex', 3);\n" }, { "answer_id": 47976852, "author": "Deepak Tambe", "author_id": 8794913, "author_profile": "https://Stackoverflow.com/users/8794913", "pm_score": 0, "selected": false, "text": "drop-down selected $(\"#PR2DistrictId option[value='@Model.PR2DistrictId']\").attr(\"selected\", true).trigger(\"chosen:updated\")\n Model" }, { "answer_id": 48820809, "author": "Sikha", "author_id": 7683210, "author_profile": "https://Stackoverflow.com/users/7683210", "pm_score": 0, "selected": false, "text": "<select id=\"MyDropDownList\">\n<option value=test1 selected>test1</option>\n<option value=test2>test2</option>\n<option value=test3>test3</option>\n<option value=test4>test4</option>\n var NewOprionValue = \"Test2\"\n\n var RemoveSelected = $(\"#MyDropDownList\")[0].innerHTML.replace('selected', '');\n var ChangeSelected = RemoveSelected.replace(NewOption, NewOption + 'selected>');\n $('#MyDropDownList').html(ChangeSelected);\n" }, { "answer_id": 49207982, "author": "Asif Ramzan", "author_id": 9471527, "author_profile": "https://Stackoverflow.com/users/9471527", "pm_score": 3, "selected": false, "text": "$(\"#comboboxid\").val(yourvalue).trigger(\"chosen:updated\");\n $(\"#CityID\").val(20).trigger(\"chosen:updated\");\n $(\"#CityID\").val(\"chicago\").trigger(\"chosen:updated\");\n" }, { "answer_id": 51085053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<select id=\"select\" onChange=\"window.location.href=this.value\">\n <option value=\"\">Select a task </option>\n <option value=\"http://127.0.0.1:5000/choose_form/1\">Task 1</option>\n <option value=\"http://127.0.0.1:5000/choose_form/2\">Task 2</option>\n <option value=\"http://127.0.0.1:5000/choose_form/3\">Task 3</option>\n <option value=\"http://127.0.0.1:5000/choose_form/4\">Task 4</option>\n <option value=\"http://127.0.0.1:5000/choose_form/5\">Task 5</option>\n <option value=\"http://127.0.0.1:5000/choose_form/6\">Task 6</option>\n <option value=\"http://127.0.0.1:5000/choose_form/7\">Task 7</option>\n <option value=\"http://127.0.0.1:5000/choose_form/8\">Task 8</option>\n</select>\n<script>\n var pathArray = window.location.pathname.split( '/' );\n var selectedItem = \"http://127.0.0.1:5000/\" + pathArray[1] + \"/\" + pathArray[2];\n var trimmedItem = selectedItem.trim();\n $(\"#select\").val(trimmedItem);\n</script>\n" }, { "answer_id": 56377473, "author": "Jignesh Joisar", "author_id": 4101154, "author_profile": "https://Stackoverflow.com/users/4101154", "pm_score": 2, "selected": false, "text": "$(\"#id\").val(\"1234\").change();\n" }, { "answer_id": 58801093, "author": "Mannu saraswat", "author_id": 11454721, "author_profile": "https://Stackoverflow.com/users/11454721", "pm_score": 2, "selected": false, "text": "$(\"#ID\").val(\"2\");\n $(\"#ID\").val(\"2\").change();\n" }, { "answer_id": 61318056, "author": "Tejas Joshi", "author_id": 13359825, "author_profile": "https://Stackoverflow.com/users/13359825", "pm_score": 0, "selected": false, "text": "$(#elementId').selectpicker('val','elementValue') $('#elementId').val('elementValue') .change() $('#elementId').change(function(){ //do something })" }, { "answer_id": 68029758, "author": "Manoj Nio", "author_id": 16205221, "author_profile": "https://Stackoverflow.com/users/16205221", "pm_score": 2, "selected": false, "text": "$(\"#mydropdownlist\").val(\"thevalue\");\n $(\"#mydropdownlist\").val(\"thevalue\").change();\n" }, { "answer_id": 71433589, "author": "Abeetha Heshan", "author_id": 14951983, "author_profile": "https://Stackoverflow.com/users/14951983", "pm_score": 0, "selected": false, "text": "//customerDB is an Array \nfor(i of customerDB){ \n\n //create option and add to drop down list \n var set = `<option value=${i.id}>${i.id}</option>`;\n $('#dropDown').append(set);\n\n} \n\n\n// print dropdown values on console\n$('#dropDown').click(function(){\n console.log($(this).val())\n})\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
292,618
<p>I need to store of 100-200 data in mysql, the data which would be separated by pipes..</p> <p>any idea how to store it on mysql? should I use a single column or should I make many multiple columns? I don't know exactly how many data users will input. </p> <p>I made a form, it halted at the part where multiple data needs to be stored.</p> <p>Anyone know how to store multiple data in single column or is there any alternative way?</p> <p>please help me..</p> <p>thank you very much</p>
[ { "answer_id": 292640, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": true, "text": "sourceID data\n-------- ----\n 1 100\n 1 200\n 1 300\n 2 100\n 3 100\n 3 200\n SELECT data\nFROM dataTable\nWHERE sourceID = 3\n JOIN userID userName otherData\n------ -------- ---------\n 1 Bob xyz\n 2 Jim abc\n 3 Sue lmnop\n SELECT userID, userName, data, otherData\nFROM userTable\nLEFT JOIN dataTable\nON userTable.userID = dataTable.sourceID\nWHERE userTable.userID = 1\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37922/" ]
292,642
<p>I have a page that spits out db data in long horizontal tables. </p> <p>I need to print it nicely so it does not cut off. Any tips ?</p>
[ { "answer_id": 293347, "author": "Morten Bergfall", "author_id": 447694, "author_profile": "https://Stackoverflow.com/users/447694", "pm_score": 3, "selected": false, "text": "<style type=\"text/css\" media=\"print\"> em display:none" }, { "answer_id": 293366, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "@page {size:landscape} table {display: inline-table}" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35513/" ]
292,646
<p>I need to pick up list items from an list, and then perform operations like adding event handlers on them. I can think of two ways of doing this.</p> <p>HTML:</p> <pre><code> &lt;ul id="list"&gt; &lt;li id="listItem-0"&gt; first item &lt;/li&gt; &lt;li id="listItem-1"&gt; second item &lt;/li&gt; &lt;li id="listItem-2"&gt; third item &lt;/li&gt; &lt;/ul&gt; </code></pre> <ol> <li><p>Using the IDs-</p> <pre><code>for(i=0;i&lt;3;i++) { document.getElementById("listItem-"+i).addEventListener("click",foo,false); } </code></pre></li> <li><p>Using childNodes property-</p> <pre><code>for(i=0;i&lt;3;i++) { document.getElementById("list").childNodes[i] .addEventListener("click",foo,false); } </code></pre></li> </ol> <p>The reason i'm using the first approach is that in the function foo, if I want the index at which the item is located in the list, i can do it by splitting the id -</p> <pre><code> function foo() { tempArr = this.id.split('-'); index = tempArr[tempArr.length-1]; // the last element in the array } </code></pre> <p>I can't think of a way of doing it by using the second method, that is, without using the id naming scheme.</p> <p>The questions:</p> <ol> <li>How do I get the index using the second method or any better method</li> <li>Are there some very bad affects of following the first method ? </li> </ol>
[ { "answer_id": 292675, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 3, "selected": true, "text": "<li key=\"myKey\">\n\n//oData is a object (eg. var oData = {};) that has been populated with properties\n//whose value is the desired data (eg. oData[\"myKey\"] = 123;)\n\nalert(oData[event.srcElement.key]); // alerts 123\n" }, { "answer_id": 292680, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 1, "selected": false, "text": "$('ul#list li').click(function () {\n var i = this.id.split('-').pop();\n alert( i );\n});\n" }, { "answer_id": 292702, "author": "cic", "author_id": 4771, "author_profile": "https://Stackoverflow.com/users/4771", "pm_score": 1, "selected": false, "text": "var lis = document.getElementById(\"list\").getElementsByTagName(\"li\");\n\nfor (var i = 0, li; li = lis[i]; ++i) {\n li.addEventListener(\"click\", (function(pos) {\n return function() {\n alert(pos);\n };\n })(i), false);\n}\n var lis = document.getElementById(\"list\").getElementsByTagName(\"li\");\n\nfor (var i = 0, li; li = lis[i]; ++i) {\n li.setAttribute(\"data-index\", i); // Or whatever value you want...\n li.addEventListener(\"click\", function() {\n alert(this.getAttribute(\"data-index\"));\n }, false);\n}\n" }, { "answer_id": 293316, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 0, "selected": false, "text": "var lis = document.getElementById(\"list\").getElementsByTagName(\"li\");\n\nfor( var i = 0, l = lis.length; i < l; ++i )\n{\n (function(){\n\n // As a new variable will be created for each loop, \n // you can use it in your event handler \n var li = lis[i]; \n\n li.addEventListener(\"click\", function() \n {\n li.className = \"clicked\";\n\n }, false);\n\n })();\n}\n document.getElementById(\"list\").addEventListener(\"click\", function(event)\n{\n var li = event.target;\n if( li.nodeName.toLowerCase() == \"li\" )\n {\n ...\n }\n}, false);\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30252/" ]
292,660
<p>Using <strong>only MySQL</strong>, I'm seeing if it's possible run an insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you can't use "WHERE" along with an insert statement. Any ideas on how to get this working?</p> <pre><code>// See if the "country" table exists -- saving the result to a variable SELECT @table_exists := COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country'; // Create the table if it doesn't exist CREATE TABLE IF NOT EXISTS country ( id INT unsigned auto_increment primary key, name VARCHAR(64) ); // Insert data into the table if @table_exists &gt; 0 INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 &lt; @table_exists; </code></pre>
[ { "answer_id": 292662, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "IF @TableExists > 0 THEN\n BEGIN\n INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');\n END\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32881/" ]
292,667
<p>Let's start with the following snippet:</p> <pre><code>Foreach(Record item in RecordList){ .. item = UpdateRecord(item, 5); .. } </code></pre> <p>The UpdateRecode function changes some field of item and returns the altered object. In this case the compiler throws an exception saying that the item can not be updated in a foreach iteration. </p> <p>Now the UpdateRecord method is changed so that it returns void and the snippet would look like this:</p> <pre><code>Foreach(Record item in RecordList){ .. UpdateRecord(item, 5); .. } </code></pre> <p>In this case the item would be updated because Record is a reference type. But it makes the code unreadable.</p> <p>The project I'm working on has lots of foreach-loops with the almost the same code over and over, so I would like to create methods that update parts of the records. Is there a nice way to do this? One that make the code more readable instead of trashing it further more?</p>
[ { "answer_id": 292678, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 0, "selected": false, "text": "foreach(Record item in RecordList){\n ..\n yield return GetUpdatedRecord(item, 5);\n ..\n}\n" }, { "answer_id": 292716, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "static void Update(this Record item, int value) {\n // do logic\n}\n\nforeach (Record item in RecordList) {\n item.Update(5);\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31722/" ]
292,676
<p>Unlike C++, in C# you can't overload the assignment operator. </p> <p>I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...</p> <p>Here's an example:</p> <pre><code>Number a = new Number(55); Number b = a; //I want to copy the value, not the reference </code></pre> <p>Is there a workaround for that issue?</p>
[ { "answer_id": 292685, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "MyType * a = new MyType();\nMyType * b = new MyType(); \na = b; /* only exchange pointers. will not change any content */\n MyType a = new MyType();\nMyType b = new MyType();\n\n// instead of a = b\na.Assign(b);\n public MyType Self {\n set {\n /* copy content of value to this */\n this.Assign(value);\n }\n}\n" }, { "answer_id": 516466, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "public static implicit operator Foo(string normalString)\n{\n //write your code here to go from string to Foo and return the new Foo.\n}\n Foo x = \"whatever\";\n" }, { "answer_id": 39962010, "author": "ttrixas", "author_id": 6950068, "author_profile": "https://Stackoverflow.com/users/6950068", "pm_score": 0, "selected": false, "text": "public class MyTestClass\n{\n private int a;\n private string str;\n\n public MyTestClass()\n {\n a = 0;\n str = null;\n }\n\n public MyTestClass(int a, string str)\n {\n this.a = a;\n this.str = str;\n }\n\n public MyTestClass Clone\n {\n get\n {\n return new MyTestClass(this.a, this.str);\n }\n }\n}\n MyTestClass test1 = new MyTestClass(5, \"Cat\");\nMyTestClass test2 = test1.Clone;\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,706
<p>I have a table like the following:</p> <pre><code>transaction_id user_id other_user_id trans_type amount </code></pre> <p>This table is used to maintain the account transactions for a finance type app.</p> <p>Its double entry accounting so a transfer from User A to B would insert two rows into the table looking like.</p> <pre><code>1, A, B, Sent, -100 1, B, A, Received, 100 </code></pre> <p>The balance on any account is calculated by summing up the transactions for that account.</p> <p>For example:</p> <pre><code>select sum(amount) from transactions where user_id=A </code></pre> <p>What is the best way to lock down transferring of funds? My current code looks like:</p> <pre><code>Start Transaction Debit the sender's account check the balance of the sender's account if new balance is negative then the sender didn't have enough money and rollback if the balance is positive then credit the receiver and commit </code></pre> <p>This seems not to be working exactly as expected. I see a lot of examples online about transactions that say basically: start, debit sender, credit receiver, commit. But what is the best way to check the sender's balance in between?</p> <p>I have transactions getting through that shouldn't. Say a user has a balance of 3K and two transactions come in at exactly the same time for 3K, both of these are getting through when only one should.</p> <p>Thank you</p>
[ { "answer_id": 293015, "author": "rgmarcha", "author_id": 20642, "author_profile": "https://Stackoverflow.com/users/20642", "pm_score": 1, "selected": false, "text": "begin transaction;\nupdate db.accounts set lock=1 where account_id='Bob' and lock=0;\nif (update is NOT successful) # lock wasn't on zero\n {\n rollback;\n return;\n }\nif (Bob hasn't enough funds)\n {\n rollback;\n return;\n }\n\ninsert into db.transactions value (?, 'Bob', 'Alice', 'Sent', -3000);\ninsert into db.transactions value (?, 'Alice', 'Bob', 'Received', 3000);\nupdate db.accounts set lock=0 where account_id='Bob' and lock=1;\n\ncommit;\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,710
<p>I'm working on something that needs a webpage to go full screen. The screen must become completely white. </p> <p>Is there anyway that I can do this without flash or silverlight? Thanks in advance</p> <p>edit: Im not trying to force anybody into fullscreen, this will be mainly used by a couple of people. Even so I'll give proper feedback on how to get in and out of fullscreen .</p>
[ { "answer_id": 292727, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "window.open (\"http://stackoverflow.com\", \"\",\"fullscreen=yes\");\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
292,711
<p>How are you managing your usage of <a href="http://dojotoolkit.org/projects/dojox" rel="nofollow noreferrer">DojoX</a> code or widgets in a production application?</p> <p>The <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">Dojo Toolkit</a> is comprised of Core, Dijit, and DojoX. As an incubator for new ideas to extend the toolkit, DojoX code and widgets are functional with varying degrees of instability. </p> <p>DojoX Code like <em><a href="http://dojotoolkit.org/book/book-dojo/part-3-javascript-programming-dojo-and-dijit/using-dojo-data/available-stores/dojox-d" rel="nofollow noreferrer">QueryReadStore</a></em> (for fetching batches of data from the server) or widgets like <em><a href="http://dojotoolkit.org/book/dojo-book-0-9/docx-documentation-under-development/grid" rel="nofollow noreferrer">Grid</a></em> (for utilizing a user interface grid component) are not included in Core or Dijit. But they are functional enough to utilize in some cases, with the caveat "developer beware", because in future Toolkit versions the API or the component location in the source tree might change. Another catch is that you may have to tweak the DojoX component you are using for it to function properly in your environment, as there's not yet a high degree of robustness in the code. </p> <p>So, how are you ensuring that as the DojoX components you use evolve, your application stays on a smooth track?</p>
[ { "answer_id": 300892, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 3, "selected": true, "text": "dojo.provide(\"dojox.charting.abc\");\n// the rest of the file\n...\n dojo.provide(\"my.patched_abc\");\n// now I include the rest of the file with my modifications\n\ndojo.provide(\"dojox.charting.abc\");\n// the rest of the file\n...\n dojo.require(\"my.patched_abc\");\n// now I can include dojox.charting,\n// which will use my patched dojox.charting.abc module\n\ndojo.require(\"dojox.charting.Chart2D\");\n// the rest of the file\n...\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,715
<p>I am having some problems with events being raised from the non-UI thread, in that i dont wish to have to handle the If me.invokerequired on every event handler added to the thread in Form1.</p> <p>I am sure i have read somewhere how to use a delegate event (on SO) but i am unable to find it.</p> <pre><code>Public Class Form1 Private WithEvents _to As New ThreadedOperation Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button.Click _to.start() End Sub Private Sub _to_SomthingHappend(ByVal result As Integer) Handles _to.SomthingHappend TextBox.Text = result.ToString //cross thread exception here End Sub End Class Public Class ThreadedOperation Public Event SomthingHappend(ByVal result As Integer) Private _thread As Threading.Thread Public Sub start() If _thread Is Nothing Then _thread = New Threading.Thread(AddressOf Work) End If _thread.Start() End Sub Private Sub Work() For i As Integer = 0 To 10 RaiseEvent SomthingHappend(i) Threading.Thread.Sleep(500) Next End Sub End Class </code></pre>
[ { "answer_id": 292758, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": true, "text": " Private Delegate Sub SomethingHappenedDelegate(ByVal result As Integer)\n\n Private Sub Work()\n For i As Integer = 0 To 10\n Me.Invoke(New SomethingHappenedDelegate(AddressOf SomethingHappenedThreadSafe), i)\n Threading.Thread.Sleep(500)\n Next\n End Sub\n\n Private Sub SomethingHappenedThreadSafe(ByVal result As Integer)\n RaiseEvent SomthingHappend(result)\n End Sub\n Private mHost As Form\n\n Public Sub New(ByVal host As Form)\n mHost = host\n End Sub\n Dim main As Form = Application.OpenForms(0)\n main.Invoke(New SomethingHappenedDelegate(AddressOf SomethingHappenedThreadSafe), i)\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500/" ]
292,740
<p>I am implementing a very simple file database. I have 2 basic operations: </p> <pre><code>void Insert(const std::string &amp; i_record) { //create or append to the file m_fileStream.open(m_fileName.c_str(), std::ios::out | std::ios::app); if (m_fileStream.is_open()) { m_fileStream &lt;&lt; i_record &lt;&lt; "\n"; } m_fileStream.flush(); m_fileStream.close(); } /* * Returns a list with all the items in the file. */ std::vector&lt;std::string&gt; SelectAll() { std::vector&lt;std::string&gt; results; m_fileStream.open(m_fileName.c_str(), std::ios::in); std::string line; if (m_fileStream.is_open()) { while (!m_fileStream.eof()) { getline (m_fileStream, line); results.push_back(line); } } m_fileStream.close(); return results; } </code></pre> <p>the class has m_fileStream and m_fileName as private members. </p> <p>OK - here's the problem: </p> <p>If I do something like: </p> <pre><code>db-&gt;Insert("a"); db-&gt;SelectAll(); db-&gt;Insert("b"); </code></pre> <p>The end result is that the file will contain <em>only</em> "a"; WHY? </p> <p>NOTE: it seems that getline() will set the fail bit. but why?</p>
[ { "answer_id": 292764, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": " while (!m_fileStream.eof())\n {\n getline (m_fileStream, line);\n results.push_back(line);\n\n }\n while (getline (m_fileStream, line))\n {\n results.push_back(line);\n }\n eof() failbit getline '\\n' stream.get(c) failbit getline eofbit .eof() failbit !stream.eof() stream.peek() != EOF .close() .clear() failbit stream.clear()" }, { "answer_id": 292882, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 1, "selected": false, "text": "while ( stream && (stream.peek() != EOF) ) {...}\n ifstream stream ( m_fileName.c_str() );\nASSERT( stream, !=, NULL ); // Uses my own ASSERT macro && stream.operator().\nwhile ( stream && (stream.peek() != EOF) ) {...}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21634/" ]
292,756
<p>In my master pages I have <code>&lt;form ... action="" ...&gt;</code>, in pre SP1, if I viewed the source the action attribute would be an empty string. In SP1 the action attribute is overridden "MyPage.aspx?MyParams", unfortunately, this causes my postbacks to fail as I have additional pathinfo in the URL (ie. MyPage.aspx\CustomerData?MyParams). I have checked the action attribute in the OnLoad event and it is still blank at this time, so somewhere SP1 is overriding this :(.</p> <p>Sorry, I just realized that part of my post was missing since I did not use the markdown correctly.</p>
[ { "answer_id": 292943, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<form /> <form /> <form name=\"form1\" method=\"post\" runat=\"server\" action=\"test.aspx\"></form>\n <form name=\"form1\" method=\"post\" runat=\"server\"></form> \n" }, { "answer_id": 314829, "author": "MrJavaGuy", "author_id": 7138, "author_profile": "https://Stackoverflow.com/users/7138", "pm_score": 0, "selected": false, "text": "public class HtmlFormAdapter : ControlAdapter\n {\n protected override void Render(HtmlTextWriter writer)\n {\n HtmlForm form = this.Control as HtmlForm;\n if (form == null)\n {\n throw new InvalidOperationException(\"Can only use HtmlFormAdapter as an adapter for an HtmlForm control\");\n }\n\n base.Render(new CustomActionTextWriter(writer));\n }\n\n public class CustomActionTextWriter : HtmlTextWriter\n {\n public CustomActionTextWriter(HtmlTextWriter writer) : base(writer)\n {\n this.InnerWriter = writer.InnerWriter;\n }\n\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n if (name == \"action\")\n {\n value = \"\";\n } \n base.WriteAttribute(name, value, fEncode); //// override action\n }\n }\n" }, { "answer_id": 748354, "author": "AndyM", "author_id": 77295, "author_profile": "https://Stackoverflow.com/users/77295", "pm_score": 2, "selected": true, "text": "public class HtmlFormAdapter : ControlAdapter \n{\n protected override void Render(HtmlTextWriter writer)\n {\n HtmlForm form = this.Control as HtmlForm;\n\n if (form == null)\n {\n throw new InvalidOperationException(\"Can only use HtmlFormAdapter as an adapter for an HtmlForm control\");\n }\n base.Render(new CustomActionTextWriter(writer));\n }\n\n\n public class CustomActionTextWriter : HtmlTextWriter\n {\n public CustomActionTextWriter(HtmlTextWriter writer) : base(writer)\n {\n this.InnerWriter = writer.InnerWriter;\n }\n\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n if (name == \"action\")\n {\n value = \"\";\n }\n base.WriteAttribute(name, value, fEncode); \n }\n }\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7138/" ]
292,767
<p>So, I'm reasonably new to both unit testing and mocking in C# and .NET; I'm using xUnit.net and Rhino Mocks respectively. I'm a convert, and I'm focussing on writing behaviour specifications, I guess, instead of being purely TDD. Bah, semantics; I want an automated safety net to work above, essentially.</p> <p>A thought struck me though. I get programming against interfaces, and the benefits as far as breaking apart dependencies goes there. Sold. However, in my behaviour verification suite (aka unit tests ;-) ), I'm asserting behaviour one interface at a time. As in, one implementation of an interface at a time, with all of its dependencies mocked out and expectations set up.</p> <p>The approach seems to be that if we verify that a class behaves as it should against its collaborating dependencies, and in turn relies on each of those collaborating dependencies to have signed that same quality contract, we're golden. Seems reasonable enough.</p> <p>Back to the thought, though. Is there any value in semi-integration tests, where a test-fixture is asserting against a unit of concrete implementations that are wired together, and we're testing its internal behaviour against mocked dependencies? I just re-read that and I think I could probably have worded it better. Obviously, there's going to be a certain amount of "well, if it adds value for you, keep doing it", I suppose - but has anyone else thought about doing that, and reaped benefits from it outweighing the costs?</p>
[ { "answer_id": 292943, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<form /> <form /> <form name=\"form1\" method=\"post\" runat=\"server\" action=\"test.aspx\"></form>\n <form name=\"form1\" method=\"post\" runat=\"server\"></form> \n" }, { "answer_id": 314829, "author": "MrJavaGuy", "author_id": 7138, "author_profile": "https://Stackoverflow.com/users/7138", "pm_score": 0, "selected": false, "text": "public class HtmlFormAdapter : ControlAdapter\n {\n protected override void Render(HtmlTextWriter writer)\n {\n HtmlForm form = this.Control as HtmlForm;\n if (form == null)\n {\n throw new InvalidOperationException(\"Can only use HtmlFormAdapter as an adapter for an HtmlForm control\");\n }\n\n base.Render(new CustomActionTextWriter(writer));\n }\n\n public class CustomActionTextWriter : HtmlTextWriter\n {\n public CustomActionTextWriter(HtmlTextWriter writer) : base(writer)\n {\n this.InnerWriter = writer.InnerWriter;\n }\n\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n if (name == \"action\")\n {\n value = \"\";\n } \n base.WriteAttribute(name, value, fEncode); //// override action\n }\n }\n" }, { "answer_id": 748354, "author": "AndyM", "author_id": 77295, "author_profile": "https://Stackoverflow.com/users/77295", "pm_score": 2, "selected": true, "text": "public class HtmlFormAdapter : ControlAdapter \n{\n protected override void Render(HtmlTextWriter writer)\n {\n HtmlForm form = this.Control as HtmlForm;\n\n if (form == null)\n {\n throw new InvalidOperationException(\"Can only use HtmlFormAdapter as an adapter for an HtmlForm control\");\n }\n base.Render(new CustomActionTextWriter(writer));\n }\n\n\n public class CustomActionTextWriter : HtmlTextWriter\n {\n public CustomActionTextWriter(HtmlTextWriter writer) : base(writer)\n {\n this.InnerWriter = writer.InnerWriter;\n }\n\n public override void WriteAttribute(string name, string value, bool fEncode)\n {\n if (name == \"action\")\n {\n value = \"\";\n }\n base.WriteAttribute(name, value, fEncode); \n }\n }\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20971/" ]
292,774
<p>I am trying to animate an object, let's say its a car. I want it go from point</p> <p><em>x1,y1,z1</em></p> <p>to point <em>x2,y2,z2</em> . It moves to those points, but it appears to be <em>drifting</em> rather than pointing in the direction of motion. So my question is: how can I solve this issue in my updateframe() event? Could you point me in the direction of some good resources?</p> <p>Thanks.</p>
[ { "answer_id": 302766, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "x = r.sin(2πt/n)\n vx = dx/dt = r.(2π/n)cos(2πt/n) \n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748529/" ]
292,779
<p>When I create a graph after using range.copy and range.paste it leaves the paste range selected, and then when I create a graph a few lines later, it uses the selection as the first series in the plot. I can delete the series, but is there a more elegant way to do this? I tried </p> <pre><code>Set selection = nothing </code></pre> <p>but it won't let me set selection. I also tried selection.clear, but that just cleared the last cells that were selected, and still added an extra series to the plot.</p>
[ { "answer_id": 292836, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 2, "selected": false, "text": "Sub UnSelectActiveCell()\n Dim R As Range\n Dim RR As Range\n For Each R In Selection.Cells\n If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then\n If RR Is Nothing Then\n Set RR = R\n Else\n Set RR = Application.Union(RR, R)\n End If\n End If\n Next R\n If Not RR Is Nothing Then\n RR.Select\n End If\nEnd Sub\n Sub UnSelectCurrentArea()\n Dim Area As Range\n Dim RR As Range\n\n For Each Area In Selection.Areas\n If Application.Intersect(Area, ActiveCell) Is Nothing Then\n If RR Is Nothing Then\n Set RR = Area\n Else\n Set RR = Application.Union(RR, Area)\n End If\n End If\n Next Area\n If Not RR Is Nothing Then\n RR.Select\n End If\nEnd Sub\n" }, { "answer_id": 293091, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 6, "selected": true, "text": "Cells(1,1).Select\n" }, { "answer_id": 2453130, "author": "Jaaahn", "author_id": 294590, "author_profile": "https://Stackoverflow.com/users/294590", "pm_score": 0, "selected": false, "text": "Application.ScreenUpdating = False .ScreenUpdating" }, { "answer_id": 3794312, "author": "David", "author_id": 458206, "author_profile": "https://Stackoverflow.com/users/458206", "pm_score": 6, "selected": false, "text": "Application.CutCopyMode = False\n" }, { "answer_id": 3848961, "author": "Madhur Kashyap", "author_id": 465036, "author_profile": "https://Stackoverflow.com/users/465036", "pm_score": 1, "selected": false, "text": "Application.CutCopyMode = xlCopy\nActiveSheet.Range(\"A\" & lngRow).Select\n" }, { "answer_id": 9023120, "author": "Miguel", "author_id": 1171921, "author_profile": "https://Stackoverflow.com/users/1171921", "pm_score": 3, "selected": false, "text": "MYDOC.Shapes(\"Ready\").visible=True\nMYDOC.Shapes(\"Ready\").Select\nMYDOC.Shapes(\"Ready\").visible=False\n" }, { "answer_id": 20194366, "author": "user3032537", "author_id": 3032537, "author_profile": "https://Stackoverflow.com/users/3032537", "pm_score": 3, "selected": false, "text": "Range(\"A1\").Select\nApplication.CutCopyMode = False\n" }, { "answer_id": 20194915, "author": "iDevlop", "author_id": 78522, "author_profile": "https://Stackoverflow.com/users/78522", "pm_score": 0, "selected": false, "text": "Selection(1, 1).Select" }, { "answer_id": 25405553, "author": "Garreth Tinsley", "author_id": 3960349, "author_profile": "https://Stackoverflow.com/users/3960349", "pm_score": 0, "selected": false, "text": "Sub BtnCopypasta_Worksheet_Click()\n range.copy\n range.paste\nBtnCopypasta.Activate\nEnd sub\n" }, { "answer_id": 42916601, "author": "RHH1095", "author_id": 7358141, "author_profile": "https://Stackoverflow.com/users/7358141", "pm_score": 3, "selected": false, "text": "Application.CutCopyMode = True\n" }, { "answer_id": 50559304, "author": "dko", "author_id": 4739826, "author_profile": "https://Stackoverflow.com/users/4739826", "pm_score": 0, "selected": false, "text": "Application.CutCopyMode .Select Sub NoSelect()\n With ActiveSheet\n .EnableSelection = xlNoSelection\n .Protect\n End With\nEnd Sub\n" }, { "answer_id": 55150628, "author": "BOBY", "author_id": 11199540, "author_profile": "https://Stackoverflow.com/users/11199540", "pm_score": 1, "selected": false, "text": "Sub MyFunc()\n\n Range(\"B6\").Select\n\n Selection.Locked = True\n\nEnd Sub\n" }, { "answer_id": 63239717, "author": "Michael Yeh", "author_id": 10627740, "author_profile": "https://Stackoverflow.com/users/10627740", "pm_score": 0, "selected": false, "text": "ActiveSheet.Cells(ActiveWindow.SplitRow+1,ActiveWindow.SplitColumn+1).Select\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30441/" ]
292,787
<p>I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)</p>
[ { "answer_id": 292833, "author": "gius", "author_id": 19712, "author_profile": "https://Stackoverflow.com/users/19712", "pm_score": 4, "selected": false, "text": "<script type=\"text/javascript\" src=\"jquery.js\" />" }, { "answer_id": 292839, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": " $('[id$=myButton]').click(function(){ alert('button clicked'); }); \n function asp$( id, tagName ) {\n var idRegexp = new RegExp( id + '$', 'i' );\n var tags = new Array();\n if (tagName) {\n tags = document.getElementsByTagName( tagName );\n }\n else {\n tags = document.getElementsByName( id );\n }\n var control = null;\n for (var i = 0; i < tags.length; ++i) {\n var ctl = tags[i];\n if (idRegexp.test(ctl.id)) {\n control = ctl;\n break;\n }\n }\n\n if (control) {\n return $(control.id);\n }\n else {\n return null;\n }\n}\n jQuery(asp$('myButton','input')).click ( function() { alert('button clicked'); } );\n <asp:Button ID=\"myButton\" runat=\"server\" Text=\"Click Me\" />\n" }, { "answer_id": 292868, "author": "Patrick de Kleijn", "author_id": 33221, "author_profile": "https://Stackoverflow.com/users/33221", "pm_score": 1, "selected": false, "text": "<head>\n <script type=\"text/javascript\" src=\"/Scripts/jquery-1.2.6.min.js\"></script> \n <% if (false) { %>\n <script type=\"text/javascript\" src=\"/Scripts/jquery-1.2.6-vsdoc.js\"></script>\n <% } %>\n</head>\n <head>\n<script type=\"text/javascript\">\n $(document).ready(\n function()\n {\n alert('Hello!');\n }\n );\n</script>\n</head>\n this.textBox.Attributes.Add(\"onChange\",\n String.Format(\"passElementReferenceToJavascript({0})\", this.textBox.ClientID));\n" }, { "answer_id": 292990, "author": "Jared", "author_id": 3442, "author_profile": "https://Stackoverflow.com/users/3442", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\" src=\"/Scripts/jquery-1.2.6.min.js\"></script> \n $('#<%= myBtn.ClientID%>').show() \n" }, { "answer_id": 300801, "author": "djuth", "author_id": 38787, "author_profile": "https://Stackoverflow.com/users/38787", "pm_score": 5, "selected": false, "text": "ResolveUrl <script type=\"text/javascript\" src='<%= ResolveUrl(\"~/Scripts/jquery-1.2.6.min.js\") %>' ></script>\n" }, { "answer_id": 659947, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 4, "selected": false, "text": "<asp:Button ID=\"myButton\" runat=\"server\" Text=\"Submit\" />\n $(document).ready(function() {\n $('[id$=myButton]').click(function() { alert('button clicked'); });\n});\n $(document).ready() $(function() {});\n $('[id$=myButton]') '[id^=myButton]'" }, { "answer_id": 1177887, "author": "Scott Marlowe", "author_id": 1683, "author_profile": "https://Stackoverflow.com/users/1683", "pm_score": 0, "selected": false, "text": "<head>" }, { "answer_id": 2343397, "author": "Andrei Drynov", "author_id": 208881, "author_profile": "https://Stackoverflow.com/users/208881", "pm_score": 3, "selected": false, "text": "<head runat=\"server\"> \n <title></title>\n <link href=\"~/Styles/Site.css\" rel=\"stylesheet\" type=\"text/css\" />\n <script src=\"Scripts/jquery-1.3.2.js\" type=\"text/javascript\"></script>\n <asp:ContentPlaceHolder ID=\"HeadContent\" runat=\"server\">\n </asp:ContentPlaceHolder> \n</head>\n <asp:Content ID=\"HeaderContent\" runat=\"server\" ContentPlaceHolderID=\"HeadContent\"> \n<script type=\"text/javascript\">\n $(document).ready(function () {\n $(\"[id$=AlertButton]\").click(function () {\n alert(\"Welcome jQuery !\");\n });\n }); \n</script> \n</asp:Content>\n <asp:Button ID=\"AlertButton\" runat=\"server\" Text=\"Button\" />\n" }, { "answer_id": 8898588, "author": "hoodwink", "author_id": 1154452, "author_profile": "https://Stackoverflow.com/users/1154452", "pm_score": 1, "selected": false, "text": "$('[id$=lbl]').text('Hello');\n lbl" }, { "answer_id": 9897559, "author": "n00b", "author_id": 534062, "author_profile": "https://Stackoverflow.com/users/534062", "pm_score": 0, "selected": false, "text": "$(\"#myButton\").click(function() { alert('button clicked'); }); $(\".myButtonCssClass\").click(function() { alert('button clicked'); }); <asp:Button ID=\"myButton\" runat=\"server\" Text=\"Submit\" CssClass=\"myButtonCssClass\" />\n" }, { "answer_id": 12445977, "author": "Nitin Nayyar", "author_id": 1675462, "author_profile": "https://Stackoverflow.com/users/1675462", "pm_score": 1, "selected": false, "text": "#controlid input[id$=controlid] a[id$=controlid]" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37939/" ]
292,806
<p>I'm not sure how to search for this answer, so I'll go ahead and ask it.</p> <p>In my rails project I have a User model and a foo model. A user can have one or more foo models assigned to it. I have accomplished this by adding </p> <pre><code>has_many :foo, :through =&gt; :user_foo </code></pre> <p>in my user model. </p> <p>Now, over in my view, I want to display a list of all foos. Not just the ones that are selected (i will be making these radio buttons, but that's another question). When I try to do this (yes, i'm using haml):</p> <pre><code> - for foo in @foos </code></pre> <p>I get this error:</p> <pre><code>You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each </code></pre> <p>My assumption is that this is caused because the @foos collection is empty. What is the proper way to get access to this collection within my user view?</p> <p>** edit **</p> <p>I think my initial question was a bit confusing. the first issue i'm trying to figure out is how to access a collection of foos from within my user view. the relationship doesn't matter. I just want a list of all foos in the system. not just the ones assigned to the user.</p>
[ { "answer_id": 292819, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 3, "selected": true, "text": "belongs_to :user def index\n @foos = Foo.all\nend\n" }, { "answer_id": 294479, "author": "wzzrd", "author_id": 36610, "author_profile": "https://Stackoverflow.com/users/36610", "pm_score": 0, "selected": false, "text": "my_user = User.find(1) # finds user with id no. 1\nlist_of_foos = my_user.foos # finds all foos associated with my_user\n list_of_foos = Foo.find(:all)\n" }, { "answer_id": 298028, "author": "Chris Lloyd", "author_id": 42413, "author_profile": "https://Stackoverflow.com/users/42413", "pm_score": 2, "selected": false, "text": "@foos = Foo.all\n - if @foos.empty?\n %p There are no Foos\n- else\n ...\n #each for - @foos.each do |foo|\n %p= foo.name\n - if @foos.empty?\n %p There are no Foos\n- else\n - @foos.each do |foo|\n %p= foo.name\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23458/" ]
292,820
<p>In a code review, I stumbled over this (simplified) code fragment to unregister an event handler:</p> <pre><code> Fire -= new MyDelegate(OnFire); </code></pre> <p>I thought that this does not unregister the event handler because it creates a new delegate which had never been registered before. But searching MSDN I found several code samples which use this idiom.</p> <p>So I started an experiment:</p> <pre><code>internal class Program { public delegate void MyDelegate(string msg); public static event MyDelegate Fire; private static void Main(string[] args) { Fire += new MyDelegate(OnFire); Fire += new MyDelegate(OnFire); Fire("Hello 1"); Fire -= new MyDelegate(OnFire); Fire("Hello 2"); Fire -= new MyDelegate(OnFire); Fire("Hello 3"); } private static void OnFire(string msg) { Console.WriteLine("OnFire: {0}", msg); } } </code></pre> <p>To my surprise, the following happened:</p> <ol> <li><code>Fire("Hello 1");</code> produced two messages, as expected.</li> <li><code>Fire("Hello 2");</code> produced one message!<br> This convinced me that unregistering <code>new</code> delegates works!</li> <li><code>Fire("Hello 3");</code> threw a <code>NullReferenceException</code>.<br> Debugging the code showed that <code>Fire</code> is <code>null</code> after unregistering the event.</li> </ol> <p>I know that for event handlers and delegate, the compiler generates a lot of code behind the scene. But I still don't understand why my reasoning is wrong.</p> <p>What am I missing?</p> <p>Additional question: from the fact that <code>Fire</code> is <code>null</code> when there are no events registered, I conclude that everywhere an event is fired, a check against <code>null</code> is required.</p>
[ { "answer_id": 292840, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 7, "selected": true, "text": "Delegate.Combine Delegate.Remove Fire = (MyDelegate) Delegate.Remove(Fire, new MyDelegate(Program.OnFire));\n Delegate.Remove MyDelegate Program.OnFire MyDelegate new MyDelegate Fire += OnFire;\nFire -= OnFire;\n Delegate.Remove MyDelegate handler = Fire;\nif (handler != null)\n handler(\"Hello 3\");\n public static event MyDelegate Fire = delegate { };\n" }, { "answer_id": 293030, "author": "user37325", "author_id": 37325, "author_profile": "https://Stackoverflow.com/users/37325", "pm_score": 4, "selected": false, "text": "public event MyDelegate Fire = delegate {};\n public event MyDelegate Fire;\npublic void FireEvent(string msg)\n{\n MyDelegate temp = Fire;\n if (temp != null)\n temp(msg);\n}\n [MethodImpl(MethodImplOptions.NoInlining)]\npublic void FireEvent(MyDelegate fire, string msg)\n{\n if (fire != null)\n fire(msg);\n}\n FireEvent(Fire,\"Hello 3\");\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23772/" ]
292,826
<p>I have a canvas in Flex that shall be able only to be scrolled in vertical direction, so I set the attributes of the canvas as follows:</p> <pre><code>verticalScrollPolicy="auto" horizontalScrollPolicy="off" </code></pre> <p>The problem here is that the vertical scrollbar covers the content when it appears - altough there is enough horizontal room left. I would have expected that the content size would have been automatically adjusted.</p> <p>When setting the vertical scroll policy to "on", no content is covered also.</p> <p>In case I set both scroll policies to 'auto' I also get a horizontal scroll bar just for scrolling to the area that is covered by the vertical scroll bar.</p> <p>Is there a workaround how I can relayout the content of the canvas when the vertical scroll bar is shown so that it does not cover any content?</p>
[ { "answer_id": 294093, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "ScrollPolicy.ON height" }, { "answer_id": 2455633, "author": "LE GALL Benoît", "author_id": 244911, "author_profile": "https://Stackoverflow.com/users/244911", "pm_score": 0, "selected": false, "text": "ExternalInterface.call(\"setInitialFlashHeight\", this.height);\n function setInitialFlashHeight(newHeight) {\n document.getElementById('my_flash').style.height = newHeight + 'px';\n}\n function addFlashHeight(height) {\n var divHeight;\n var obj = document.getElementById('my_flash');\n\n if (obj.offsetHeight) {\n divHeight = obj.offsetHeight;\n } else if (obj.style.pixelHeight){\n divHeight = obj.style.pixelHeight;\n }\n\n var newHeight = divHeight + height;\n document.getElementById('my_flash').style.height = newHeight + 'px';\n}\n" }, { "answer_id": 7103934, "author": "Dogus ATASOY", "author_id": 900108, "author_profile": "https://Stackoverflow.com/users/900108", "pm_score": 2, "selected": false, "text": "<mx:VBox width=\"100%\" height=\"100%\"\n verticalScrollPolicy=\"auto\" horizontalScrollPolicy=\"off\">\n <mx:Repeater dataProvider=\"{hede}\">\n <custom:RenderItem ........../>\n </mx:Repeater>\n</mx:VBox>\n <mx:VBox width=\"100%\" height=\"100%\"\n **minHeight=\"1\"** horizontalScrollPolicy=\"off\">\n <mx:Repeater dataProvider=\"{hede}\">\n <custom:RenderItem ........../>\n </mx:Repeater>\n</mx:VBox>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7524/" ]
292,841
<p>I would like to know how to get the name of the property that a method parameter value came from. The code snippet below shows what I want to do:</p> <pre><code>Person peep = new Person(); Dictionary&lt;object, string&gt; mapping = new Dictionary&lt;object, string&gt;(); mapping[peep.FirstName] = "Name"; Dictionary&lt;string, string&gt; propertyToStringMapping = Convert(mapping); if (mapping[peep.FirstName] == propertyToStringMapping["FirstName"]) Console.WriteLine("This is my desired result"); private Dictionary&lt;string, string&gt; Convert(Dictionary&lt;object, string&gt; mapping) { Dictionary&lt;string, string&gt; stringMapping = new Dictionary&lt;string, string&gt;(); foreach (KeyValuePair&lt;object, string&gt; kvp in mapping) { //propertyName should eqal "FirstName" string propertyName = kvp.Key?????? stringMapping[propertyName] = kvp.Value; } return stringMapping; } </code></pre>
[ { "answer_id": 292875, "author": "ckramer", "author_id": 20504, "author_profile": "https://Stackoverflow.com/users/20504", "pm_score": 1, "selected": true, "text": "mapping[peep.FirstName] = \"Name\";\n mapping[\"FirstName\"] = \"Name\";\n var mapping = new Dictionary<Expression<Action<T>>,string>();\nmapping[ p => p.FirstName ] = \"Name\";\n private Dictionary<string,string> Convert(Dictionary<Expression<Action<T>>,string> mapping)\n{\n var result = new Dictionary<string,string>();\n foreach(var item in mapping)\n {\n LambdaExpression ex = item.Key as LambdaExpression;\n string propertyName = ((MemberExpression)ex.Body).Member.Name;\n string propertyValue = item.Value;\n result.Add(propertyName,proeprtyValue);\n }\n return result;\n}\n" }, { "answer_id": 292891, "author": "balu", "author_id": 36253, "author_profile": "https://Stackoverflow.com/users/36253", "pm_score": 0, "selected": false, "text": "String propertyName = kvp.key.toString()\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215086/" ]
292,844
<p>I try to keep it brief and concise. I have to write a program that takes queries in SQL form and searches an XML. Right now I am trying to disassemble a string into logical pieces so I can work with them. I have a string as input and want to get a MatchCollection as output.</p> <p>Please not that the test string below is of a special format that I impose on the user to keep things simple. Only one statement per line is permitted and nested queries are excluded-</p> <p>string testString = "select apples \n from dblp \r where we ate \n group by all of them \r HAVING NO SHAME \n";</p> <p>I use Regex with the following pattern:</p> <pre><code>Regex reg = new Regex(@"(?&lt;select&gt; \A\bselect\b .)" + @"(?&lt;from&gt; ^\bfrom\b .)" + @"(?&lt;where&gt; ^\bwhere\b .)" + @"(?&lt;groupBy&gt; ^\bgroup by\b .)" + @"(?&lt;having&gt; ^\bhaving\b .)" , RegexOptions.IgnoreCase | RegexOptions.Multiline ); </code></pre> <p>As far as I know this should give me matches for every group with the test string. I would be looking for an exact match of "select" at the start of each line followed by any characters except newlines.</p> <p>Now I create the collection:</p> <pre><code>MatchCollection matches = reg.Matches(testString); </code></pre> <p>To makes sure it worked I used a foreach and printed the matches like:</p> <pre><code>foreach(Match match in matches) { Console.WriteLine("Select: {0}", match.Groups["select"]); //and so on } </code></pre> <p>The problem is that the collection is always empty. There must be a flaw in the Regex somewhere but I am too inexperienced to find it. Could you please assist me? Thank you very much!</p> <hr> <p>I tried using .* instead of just . until I was told that . would even mathc multiple character. I have no doubt that this could be a problem but even when replacing it I get no result.</p> <p>I fail to see why it is so difficult to match a line starting with a defined word and having any characters appended to it until the regex finds a newline. Seems to me that this should be a relatively easy task.</p>
[ { "answer_id": 293103, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 2, "selected": false, "text": "@\"(?<select>\\Aselect .+)[\\n\\r]\" +\n@\"(?<from>\\s*from .+)[\\n\\r]\" +\n@\"(?<where>\\s*where .+)[\\n\\r]\" +\n@\"(?<groupBy>\\s*group by .+)[\\n\\r]\" +\n@\"(?<having>\\s*having .+)[\\n\\r]\"\n @\"\\Aselect (?<select>.+)[\\n\\r]\" +\n@\"\\s*from (?<from>.+)[\\n\\r]\" +\n@\"\\s*where (?<where>.+)[\\n\\r]\" +\n@\"\\s*group by (?<groupBy>.+)[\\n\\r]\" +\n@\"\\s*having (?<having>.+)[\\n\\r]\"\n" }, { "answer_id": 293262, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "[\\n\\r]+ (?<from>^\\s*from\\b.*[\\n\\r]+$)\n" }, { "answer_id": 293396, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "@\"select\\s+(?<select>.+)\\s+\" +\n@\"from\\s+(?<from>.+)\\s+\" +\n@\"where\\s+(?<where>.+)\\s+\" +\n@\"group by\\s+(?<groupBy>.+)\\s+\" +\n@\"having\\s+(?<having>.+)\";\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,851
<p>I am trying to insert a new row into my table which holds the same data as the one I am trying to select from the same table but with a different <code>user_id</code> and without a fixed value for <code>auto_id</code> since that is an auto_increment field, and setting <code>ti</code> to NOW(). Below is my mockup query where '1' is the new <code>user_id</code>. I have been trying many variations but am still stuck, anyone who can help me with turning this into a working query. </p> <pre><code>INSERT INTO `lins` ( `user_id` , `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , `ti` ) ( SELECT '1', `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , NOW( ) FROM `lins` WHERE autoid = '4' AND user_id = '2' ) </code></pre> <p>Thank you for taking the time to help me out!</p>
[ { "answer_id": 293103, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 2, "selected": false, "text": "@\"(?<select>\\Aselect .+)[\\n\\r]\" +\n@\"(?<from>\\s*from .+)[\\n\\r]\" +\n@\"(?<where>\\s*where .+)[\\n\\r]\" +\n@\"(?<groupBy>\\s*group by .+)[\\n\\r]\" +\n@\"(?<having>\\s*having .+)[\\n\\r]\"\n @\"\\Aselect (?<select>.+)[\\n\\r]\" +\n@\"\\s*from (?<from>.+)[\\n\\r]\" +\n@\"\\s*where (?<where>.+)[\\n\\r]\" +\n@\"\\s*group by (?<groupBy>.+)[\\n\\r]\" +\n@\"\\s*having (?<having>.+)[\\n\\r]\"\n" }, { "answer_id": 293262, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "[\\n\\r]+ (?<from>^\\s*from\\b.*[\\n\\r]+$)\n" }, { "answer_id": 293396, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "@\"select\\s+(?<select>.+)\\s+\" +\n@\"from\\s+(?<from>.+)\\s+\" +\n@\"where\\s+(?<where>.+)\\s+\" +\n@\"group by\\s+(?<groupBy>.+)\\s+\" +\n@\"having\\s+(?<having>.+)\";\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,861
<p>I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:</p> <pre><code>function clear_input(element) { element.value = ""; element.onfocus = null; } </code></pre> <p>The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):</p> <pre><code>function restore_default(element) { if(element.value == '') { element.value = element.name.substring(0, 1).toUpperCase() + element.name.substring(1, element.name.length); } } </code></pre> <p>It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.</p> <p>I added</p> <pre><code>element.onfocus = "javascript:clear_input(this);"; </code></pre> <p>In restore_default function but that doesn't work. How do I do this?</p>
[ { "answer_id": 292869, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 3, "selected": false, "text": "element.onfocus = clear_input;\n element.onfocus = function () { \n clear_input( param, param2 ); \n};\n function clear_input () {\n this.value = \"\";\n this.onfocus = null;\n}\n" }, { "answer_id": 292879, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "function hightlight_input(element) {\n element.select();\n}\n\nfunction restore_default(element) // optional, do we restore if the user deletes?\n{\n if(element.value == '')\n {\n element.value = element.name.substring(0, 1).toUpperCase()\n + element.name.substring(1, element.name.length);\n }\n}\n" }, { "answer_id": 292978, "author": "some", "author_id": 36866, "author_profile": "https://Stackoverflow.com/users/36866", "pm_score": 1, "selected": false, "text": "function trim(str) {\n return str.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');\n}\n function capitalize(str) {\n return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();\n}\n function clear_default(element) {\n if (trim(element.value) == element.defaultValue ) { element.value = \"\"; }\n}\n\nfunction restore_default(element) {\n if (!trim(element.value).length) { element.value = element.defaultValue;}\n}\n" }, { "answer_id": 1763674, "author": "Andrey", "author_id": 214637, "author_profile": "https://Stackoverflow.com/users/214637", "pm_score": 0, "selected": false, "text": "<!-- JavaScript\nfunction checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=\"\"} else if(A.value==\"\"){A.value=\"Search\"}}\n//-->\n\n<form method=\"post\" action=\"search.php\">\n<input type=\"submit\" name=\"1\">\n<input type=\"text\" name=\"srh\" Value=\"Search\" onfocus=\"checkClear(this,'Search')\" onblur=\"checkClear(this,' ')\">\n</form>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
292,883
<p>I have an app that writes messages to the event log. The source I'm passing in to EventLog.WriteEntry does not exist, so the Framework tries to create the source by adding it to the registry. It works fine if the user is an Admin by I get the following whe the user is not an admin:</p> <p>"System.Security.SecurityException : Requested registry access is not allowed." message. </p> <p>How can I fix that?</p> <p><strong>Update</strong></p> <p>I have create the registry with the Admin account manually in the registry. Now, I have the error : System.Security.SecurityException: Requested registry access is not allowed.</p> <p>I do not understand because I have create a user in the Group Administrator... what do I have to do more?</p>
[ { "answer_id": 295582, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": true, "text": "Run regedt32\nNavigate to the following key:\nHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Eventlog\\Security\nRight click on this entry and select Permissions\nAdd the ASPNET user\nGive it Read permission\n\n2. Change settings in machine.config file\n\nRun Explorer\nNavigate to WINDOWS or WINNT folder\nOpen Microsoft.NET folder\nOpen Framework folder\nOpen v1.1.4322 folder (folder name may be different, depending on what dotnet version is installed)\nOpen CONFIG folder\nOpen machine.config file using notepad (make a backup of this file first)\nLocate processmodel tag (approx. at line 441)\nLocate userName=\"machine\" (approx. at line 452)\nChange it to userName=\"SYSTEM\"\nSave and close the file\nClose Explorer\n\n3. Restart IIS\n\nRun IISReset\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
292,887
<p>What is the best way to store DateTime in SQL for different timezones and different locales<br> There a few questions/answers about timezones, but none is addressing the locale problems. DateTime.ToUniversalTime is locale specific, and I need it locale independent.</p> <p>For example:</p> <pre><code> DateTime.Now.ToUniversalTime.ToString() In US locale returns something like: 11/23/2008 8:20:00 In France locale returns 23/11/2008 8:20:00 Notice that day/month are inverted </code></pre> <p>If you save the DateTime while in France Locale on a US SQL DB - you get an error, because it is a wrong date format. </p> <p>Best would be a C# code snippet for</p> <ol> <li>Get a DateTime in a specific locale and store it in SQL datetime field</li> <li>Retrieved a SQL datetime field and convert it to a locale DateTime</li> </ol> <p>Thanks</p>
[ { "answer_id": 295582, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": true, "text": "Run regedt32\nNavigate to the following key:\nHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Eventlog\\Security\nRight click on this entry and select Permissions\nAdd the ASPNET user\nGive it Read permission\n\n2. Change settings in machine.config file\n\nRun Explorer\nNavigate to WINDOWS or WINNT folder\nOpen Microsoft.NET folder\nOpen Framework folder\nOpen v1.1.4322 folder (folder name may be different, depending on what dotnet version is installed)\nOpen CONFIG folder\nOpen machine.config file using notepad (make a backup of this file first)\nLocate processmodel tag (approx. at line 441)\nLocate userName=\"machine\" (approx. at line 452)\nChange it to userName=\"SYSTEM\"\nSave and close the file\nClose Explorer\n\n3. Restart IIS\n\nRun IISReset\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37955/" ]
292,893
<p>This code is causing a memory leak for me, and I'm not sure why.</p> <p>[EDIT] Included code from <a href="http://paste.pocoo.org/show/91254/" rel="nofollow noreferrer">here</a> into question:</p> <pre><code>#include "src/base.cpp" typedef std::map&lt;std::string, AlObj*, std::less&lt;std::string&gt;, gc_allocator&lt;std::pair&lt;const std::string, AlObj*&gt; &gt; &gt; KWARG_TYPE; AlInt::AlInt(int val) { this-&gt;value = val; this-&gt;setup(); } // attrs is of type KWARG_TYPE void AlInt::setup() { this-&gt;attrs["__add__"] = new AddInts(); this-&gt;attrs["__sub__"] = new SubtractInts(); this-&gt;attrs["__mul__"] = new MultiplyInts(); this-&gt;attrs["__div__"] = new DivideInts(); this-&gt;attrs["__pow__"] = new PowerInts(); this-&gt;attrs["__str__"] = new PrintInt(); } int main() { while (true) { AlObj* a = new AlInt(3); } } </code></pre> <p>AlInt inherits from AlObj, which in turn inherits from gc. When I comment out the contents of setup() then I don't have a memory leak, this leads me to believe the issue is with the map not cleaning up, however I'm using the gc allocator, so I'm not sure where to look next. Thoughts?</p>
[ { "answer_id": 292931, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "std::pair<const std::string, AlObj*>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37181/" ]
292,914
<p>Does anyone know because all the places I've tried seem to timeout!</p>
[ { "answer_id": 12755564, "author": "Deepak Lamichhane", "author_id": 551087, "author_profile": "https://Stackoverflow.com/users/551087", "pm_score": 2, "selected": false, "text": "http://findjar.com/jar/javax/servlet/jstl/1.2/jstl-1.2.jar.html\n" }, { "answer_id": 20868920, "author": "Dashovsky", "author_id": 3151191, "author_profile": "https://Stackoverflow.com/users/3151191", "pm_score": 2, "selected": false, "text": "<dependency>\n<groupId>javax.servlet</groupId>\n<artifactId>jstl</artifactId>\n<version>1.2</version>\n</dependency>\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16684/" ]
292,935
<p>which one of the two is more spread? I want to read out the version number from <a href="http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519" rel="nofollow noreferrer">http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519</a> but I want to use the one which more people have.</p> <p>If you know another way to get the latest stable version number from mysql please tell me ;)</p>
[ { "answer_id": 292975, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "DomDocument DomXPath DomDocument DomXPath" }, { "answer_id": 293128, "author": "Ciaran McNulty", "author_id": 34024, "author_profile": "https://Stackoverflow.com/users/34024", "pm_score": 0, "selected": false, "text": "$struct = simplexml_load_string($xml);\n$version = (string)$struct->project->latest_release->latest_release_version;\n if(preg_match('/<latest_release_version>(.*?)<\\\\/latest_release_version>/', $xml, $matches)){\n$version = $matches[1];\n}\n" }, { "answer_id": 293200, "author": "Phillip B Oldham", "author_id": 30478, "author_profile": "https://Stackoverflow.com/users/30478", "pm_score": 2, "selected": false, "text": "$xml = simplexml_load_file(\n 'http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519'\n );\n$result = $xml->xpath('//latest_release/latest_release_version'); \n// or '//latest_release/*' if you'd rather loop through all release information.\n\nwhile(list( , $node) = each($result))\n echo $node, \"\\n\";\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
292,941
<p>I've rewritten my family web site using JavaScript (JQuery) making Ajax calls to PHP on the back end. It's your standard &quot;bunch of image thumbnails and one main image, and when you click on a thumbnail image the main image changes&quot; kind of thing. Everything is working as expected when using Firefox, but on IE, when I click on a thumbnail, the main image changes to the one I clicked and then immediately changes back to the first one. I have tried MS Script Debugger to no avail; I set a breakpoint in the JavaScript code that starts the Ajax call, and when I click the thumbnail the breakpoint fires. Then I hit F5 and it continues but does not fire again. If I use Wireshark to watch the actual TCP packets over the network, I can see that we are definitely sending more than one request to the server. I cannot figure out where the second query (the one to revert back to the original image) comes from.</p> <p>Any suggestions? One example of what I'm talking about is <a href="http://perrow.ca/gallery.php?tag=nicholas-1" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 292969, "author": "Glenn", "author_id": 25191, "author_profile": "https://Stackoverflow.com/users/25191", "pm_score": 0, "selected": false, "text": "var inProcess = 0;\n\nfunction eventHandler() {\n\n if (inProcess == 0) {\n\n inProcess = 1;\n\n // do stuff\n\n setTimeout('inProcess = 0', 5000);\n\n }\n\n}\n" }, { "answer_id": 293140, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 3, "selected": true, "text": "$(window).bind(\"resize\", function(){ \n ResizeWindow( 'nicholas-1' )\n});\n // Send the data\ntry {\n xhr.send(s.data);\n} catch(e) {\n jQuery.handleError(s, xhr, null, e);\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ]
292,966
<p>I found this web site (photoblog) <a href="http://www.OneReaction.net/" rel="nofollow noreferrer">http://www.OneReaction.net/</a></p> <p>and I am very curious how this is done: 1) From source code you don't see the image URL 2) How to overlay the copyright information on the image without changing the underlying photo?</p> <p>Ideas? Thanks!</p>
[ { "answer_id": 293120, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "HttpHandler web.config /photos/*.jpg" }, { "answer_id": 304563, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 0, "selected": false, "text": "<img id=\"image\" title=\"Condemned to Contrast II\" src=\"Resources/ImageHandler.ashx\" \n alt=\"Condemned to Contrast II\" style=\"border-width:0px;\" />\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20067/" ]
292,967
<p>Is there any way to restrict users with administrative privileges from managing specific Windows service based applications? I would like to restrict administrators from stopping or re-starting my service very similar to the Windows event log service. What are some of the more popular approaches or recommended approaches to securing services followed by product vendors (like antivirus applications, firewalls etc where the service has to be running continuously)?</p>
[ { "answer_id": 293144, "author": "Igal Serban", "author_id": 25737, "author_profile": "https://Stackoverflow.com/users/25737", "pm_score": 1, "selected": false, "text": "ServicesToRun = new ServiceBase[] { new Service1() };\nServicesToRun[0].CanStop = false;\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37450/" ]
292,991
<p>I need to allow the vertical scrollbar in a multiselect listbox (VB6) however, when the control is disabled, I can't scroll.</p> <p>I would think there is an API to allow this, but my favorite <a href="http://vbnet.mvps.org" rel="nofollow noreferrer">VB6 site (MVPS VB.NET)</a> does not have a way.</p> <p>I toyed with pretending it was disabled, and ignore the clicks... but to do that with VB6 code is really ugly... so if this is a solution, I need an API to ignore the clicks.</p> <p>Thanks for your help.</p>
[ { "answer_id": 293069, "author": "Chetan S", "author_id": 31284, "author_profile": "https://Stackoverflow.com/users/31284", "pm_score": 1, "selected": false, "text": "SelectionMode SelectionIndexChanged SelectionIndex" }, { "answer_id": 294608, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 3, "selected": true, "text": "GetSystemMetrics Form_Load CustomScrollingSupport.cls ListBoxExtras.bas Form_Load AddCustomListBoxScrolling Me AddCustomScrollingSupport ZOrder .ZOrder 0 VB.ListBox Add* ListBoxExtras.bas Option Explicit\n\nPrivate Declare Function GetSystemMetrics Lib \"user32\" (ByVal nIndex As Long) As Long\nPrivate Const SM_CXVSCROLL = 2\nPrivate Const SM_CXFRAME = 32\n\nPrivate m_runningScrollers As Collection\nPrivate WithEvents m_list As VB.listbox\nPrivate WithEvents m_listScroller As VB.listbox\n\n'--------------------------------------------------------------'\n' Bind '\n' '\n' Adds custom scrolling support to a ListBox control. '\n' Specifically, it allows the ListBox to be '\n' scrolled even when it is disabled. '\n' '\n' Parameters: '\n' '\n' + list '\n' the ListBox control to add custom scrolling support to '\n' '\n' + runningScrollers '\n' a Collection of CustomScrollingSupport objects. Passed '\n' in so that this object can remove itself from the list '\n' when it is terminated. '\n' '\n'--------------------------------------------------------------'\n\nPublic Sub Bind(ByVal list As VB.listbox, runningScrollers As Collection)\n\n Set m_list = list\n Set m_runningScrollers = runningScrollers\n\n 'Create another ListBox loaded with the same number of entries as the real listbox'\n Set m_listScroller = m_list.Container.Controls.Add(\"VB.ListBox\", list.Name & \"_scroller\")\n LoadScrollerList\n\n Dim nScrollbarWidth As Long\n nScrollbarWidth = GetSystemMetricScaled(SM_CXVSCROLL, m_list) + _\n GetSystemMetricScaled(SM_CXFRAME, m_list)\n\n 'Display the other listbox (the \"scroller\"), just wide enough so that only its scrollbar is visible'\n 'and place it over the real listboxs scroll bar'\n With m_listScroller\n .Left = m_list.Left + m_list.Width - nScrollbarWidth\n .Top = m_list.Top\n .Height = m_list.Height\n .Width = nScrollbarWidth\n .Enabled = True\n .Visible = True\n .ZOrder 0\n End With\n\nEnd Sub\n\nPrivate Sub m_listScroller_Scroll()\n 'If the master list has changed, need to reload scrollers list'\n '(not ideal, but there is no ItemAdded event that we could use to keep the lists in sync)'\n If m_list.ListCount <> m_listScroller.ListCount Then\n LoadScrollerList\n End If\n\n 'Make any scrolling done on the scroller listbox occur in the real listbox'\n m_list.TopIndex = m_listScroller.TopIndex\n\nEnd Sub\n\nPrivate Sub Class_Terminate()\n\n Dim scroller As CustomScrollingSupport\n Dim nCurrIndex As Long\n\n If m_runningScrollers Is Nothing Then\n Exit Sub\n End If\n\n 'Remove ourselves from the list of running scrollers'\n\n For Each scroller In m_runningScrollers\n nCurrIndex = nCurrIndex + 1\n If scroller Is Me Then\n m_runningScrollers.Remove nCurrIndex\n Debug.Print m_runningScrollers.Count & \" scrollers are running\"\n Exit Sub\n End If\n Next\n\nEnd Sub\n\nPrivate Sub LoadScrollerList()\n\n Dim i As Long\n\n m_listScroller.Clear\n For i = 1 To m_list.ListCount\n m_listScroller.AddItem \"\"\n Next\n\nEnd Sub\n\nPrivate Function GetSystemMetricScaled(ByVal nIndex As Long, ByVal ctrl As Control)\n GetSystemMetricScaled = ctrl.Container.ScaleX(GetSystemMetrics(nIndex), vbPixels, ctrl.Container.ScaleMode)\nEnd Function\n AddCustomScrollingSupport VB.ListBox AddCustomListBoxScrolling VB.ListBox Form Option Explicit\n\nPublic Sub AddCustomScrollingSupport(ByVal list As VB.listbox)\n\n Static runningScrollers As New Collection\n\n Dim newScroller As CustomScrollingSupport\n Set newScroller = New CustomScrollingSupport\n\n runningScrollers.Add newScroller\n newScroller.Bind list, runningScrollers\n\nEnd Sub\n\nPublic Sub AddCustomListBoxScrolling(ByVal frm As Form)\n\n Dim ctrl As Control\n For Each ctrl In frm.Controls\n\n If TypeOf ctrl Is VB.listbox Then\n AddCustomScrollingSupport ctrl\n End If\n\n Next\n\nEnd Sub\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
292,993
<p>What's the secret to getting ClaimsResponse working with <a href="http://code.google.com/p/dotnetopenid/" rel="noreferrer">DotNetOpenId</a>?</p> <p>For example, in this bit of code (from <a href="http://www.hanselman.com/blog/CategoryView.aspx?category=DasBlog" rel="noreferrer">Scott Hanselman's blog</a>) the ClaimsResponse object should have lots of nice little things like 'nickname' and 'email address', but the ClaimsResponse object itself is 'null':</p> <pre><code> OpenIdRelyingParty openid = new OpenIdRelyingParty(); if (openid.Response != null) { // Stage 3: OpenID Provider sending assertion response switch (openid.Response.Status) { case AuthenticationStatus.Authenticated: ClaimsResponse fetch = openid.Response.GetExtension(typeof(ClaimsResponse)) as ClaimsResponse; string nick = fetch.Nickname; string homepage = openid.Response.ClaimedIdentifier; string email = fetch.Email; string comment = Session["pendingComment"] as string; string entryId = Session["pendingEntryId"] as string; if (String.IsNullOrEmpty(comment) == false &amp;&amp; String.IsNullOrEmpty(entryId) == false) { AddNewComment(nick, email, homepage, comment, entryId, true); } break; } } </code></pre> <p>At first, I thought it was because I wasn't redirecting to the provider with a 'ClaimsRequest' ... but using this code to redirect to the OpenId provider still doesn't help:</p> <pre><code>OpenIdRelyingParty openid = new OpenIdRelyingParty(); IAuthenticationRequest req = openid.CreateRequest(openid_identifier.Text); ClaimsRequest fetch = new ClaimsRequest(); fetch.Email = DemandLevel.Require; fetch.Nickname = DemandLevel.Require; req.AddExtension(fetch); req.RedirectToProvider(); </code></pre> <p>What am I doing wrong? Or have other devs experienced the same pain?</p>
[ { "answer_id": 293185, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 2, "selected": false, "text": "var request = openid.CreateRequest(openid_identifier);\nvar fields = new ClaimsRequest();\nfields.Email = DemandLevel.Require;\nfields.Nickname = DemandLevel.Require;\nrequest.AddExtension(fields);\nrequest.RedirectToProvider();\n var claimResponse = openid.Response.GetExtension<ClaimsResponse>();\n" }, { "answer_id": 4354967, "author": "Parminder", "author_id": 96346, "author_profile": "https://Stackoverflow.com/users/96346", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- \n Note: As an alternative to hand editing this file you can use the \n web admin tool to configure settings for your application. Use\n the Website->Asp.Net Configuration option in Visual Studio.\n A full list of settings and comments can be found in \n machine.config.comments usually located in \n \\Windows\\Microsoft.Net\\Framework\\v2.x\\Config \n-->\n<configuration>\n <configSections>\n <sectionGroup name=\"elmah\">\n </sectionGroup>\n <section name=\"dotNetOpenAuth\" type=\"DotNetOpenAuth.Configuration.DotNetOpenAuthSection\" requirePermission=\"false\" allowLocation=\"true\" />\n </configSections>\n <connectionStrings configSource=\"connectionStrings.config\">\n </connectionStrings>\n <dotNetOpenAuth>\n <openid>\n <relyingParty>\n <behaviors>\n <add type=\"DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth\" />\n </behaviors>\n </relyingParty>\n </openid>\n </dotNetOpenAuth>\n <system.web>\n <!-- \n Set compilation debug=\"true\" to insert debugging \n symbols into the compiled page. Because this \n affects performance, set this value to true only \n during development.\n -->\n <compilation debug=\"true\" targetFramework=\"4.0\">\n <assemblies>\n <add assembly=\"System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n <add assembly=\"System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n <add assembly=\"System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n <add assembly=\"System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\" />\n <add assembly=\"System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\n </assemblies>\n </compilation>\n <!--\n The <authentication> section enables configuration \n of the security authentication mode used by \n ASP.NET to identify an incoming user. \n -->\n <authentication mode=\"Forms\">\n <forms loginUrl=\"~/Account/Logon\" />\n </authentication>\n <membership>\n <providers>\n <clear />\n <add name=\"AspNetSqlMembershipProvider\" type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" connectionStringName=\"ApplicationServices\" enablePasswordRetrieval=\"false\" enablePasswordReset=\"true\" requiresQuestionAndAnswer=\"false\" requiresUniqueEmail=\"false\" passwordFormat=\"Hashed\" maxInvalidPasswordAttempts=\"5\" minRequiredPasswordLength=\"6\" minRequiredNonalphanumericCharacters=\"0\" passwordAttemptWindow=\"10\" passwordStrengthRegularExpression=\"\" applicationName=\"/\" />\n </providers>\n </membership>\n <profile>\n <providers>\n <clear />\n <add name=\"AspNetSqlProfileProvider\" type=\"System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" connectionStringName=\"ApplicationServices\" applicationName=\"/\" />\n </providers>\n </profile>\n <roleManager enabled=\"false\">\n <providers>\n <clear />\n <add connectionStringName=\"ApplicationServices\" applicationName=\"/\" name=\"AspNetSqlRoleProvider\" type=\"System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n <add applicationName=\"/\" name=\"AspNetWindowsTokenRoleProvider\" type=\"System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n </providers>\n </roleManager>\n <customErrors mode=\"RemoteOnly\" defaultRedirect=\"/Dinners/Trouble\">\n <error statusCode=\"404\" redirect=\"/Dinners/Confused\" />\n </customErrors>\n\n <pages controlRenderingCompatibilityVersion=\"3.5\" clientIDMode=\"AutoID\">\n <namespaces>\n <add namespace=\"System.Web.Mvc\" />\n <add namespace=\"System.Web.Mvc.Ajax\" />\n <add namespace=\"System.Web.Mvc.Html\" />\n <add namespace=\"System.Web.Routing\" />\n <add namespace=\"System.Globalization\" />\n <add namespace=\"System.Linq\" />\n <add namespace=\"System.Collections.Generic\" />\n </namespaces>\n </pages>\n <httpHandlers>\n <add verb=\"*\" path=\"*.mvc\" validate=\"false\" type=\"System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n </httpHandlers>\n <httpModules>\n </httpModules>\n <trace enabled=\"true\" requestLimit=\"10\" pageOutput=\"false\" traceMode=\"SortByTime\" localOnly=\"true\" />\n </system.web>\n <!-- \n The system.webServer section is required for running ASP.NET AJAX under Internet\n Information Services 7.0. It is not necessary for previous version of IIS.\n -->\n <system.webServer>\n <validation validateIntegratedModeConfiguration=\"false\" />\n <modules runAllManagedModulesForAllRequests=\"true\">\n </modules>\n <handlers>\n <remove name=\"MvcHttpHandler\" />\n <remove name=\"UrlRoutingHandler\" />\n <add name=\"MvcHttpHandler\" preCondition=\"integratedMode\" verb=\"*\" path=\"*.mvc\" type=\"System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\" />\n </handlers>\n </system.webServer>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"System.Web.Mvc\" publicKeyToken=\"31bf3856ad364e35\" />\n <bindingRedirect oldVersion=\"1.0.0.0\" newVersion=\"2.0.0.0\" />\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n <appSettings>\n <add key=\"microsoft.visualstudio.teamsystems.backupinfo\" value=\"8;web.config.backup\" />\n <!-- Fill in your various consumer keys and secrets here to make the sample work. -->\n <!-- You must get these values by signing up with each individual service provider. -->\n <!-- Twitter sign-up: https://twitter.com/oauth_clients -->\n <add key=\"twitterConsumerKey\" value=\"\" />\n <add key=\"twitterConsumerSecret\" value=\"\" />\n </appSettings>\n <system.serviceModel>\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\" />\n </system.serviceModel>\n</configuration> \n" }, { "answer_id": 5286351, "author": "M.Hefny", "author_id": 637718, "author_profile": "https://Stackoverflow.com/users/637718", "pm_score": 2, "selected": false, "text": " /* worked */var fetch = new FetchRequest();\n fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);\n request.AddExtension(fetch);\n /* didnt work*/\n var fields = new ClaimsRequest();\n fields.Email = DemandLevel.Require;\n fields.FullName = DemandLevel.Require;\n request.AddExtension(fields); \n this.Request.Params[\"openid.ext1.value.alias1\"];\n" }, { "answer_id": 5338169, "author": "M.Hefny", "author_id": 637718, "author_profile": "https://Stackoverflow.com/users/637718", "pm_score": 0, "selected": false, "text": "<section name=\"dotNetOpenAuth\"\n type=\"DotNetOpenAuth.Configuration.DotNetOpenAuthSection\"\n requirePermission=\"false\" \n allowLocation=\"true\"/>\n <configsections> <dotNetOpenAuth>\n <openid>\n <relyingParty>\n <behaviors>\n <add type=\"DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth\"/>\n </behaviors>\n </relyingParty>\n </openid>\n</dotNetOpenAuth>\n" }, { "answer_id": 8391072, "author": "Ian Cullen", "author_id": 1082236, "author_profile": "https://Stackoverflow.com/users/1082236", "pm_score": 1, "selected": false, "text": "OpenIdRelyingParty openid = new OpenIdRelyingParty();\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n var response = openid.GetResponse();\n\n if (response != null)\n {\n switch (response.Status)\n {\n case AuthenticationStatus.Authenticated:\n\n if (this.Request.Params[\"openid.ext1.value.alias1\"] != null)\n {\n Response.Write(this.Request.Params[\"openid.ext1.value.alias1\"]);\n Response.Write(this.Request.Params[\"openid.ext1.value.alias2\"]);\n }\n else {\n Response.Write(\"Alias wrong\");\n }\n break;\n }\n }\n}\n protected void loginButton_Click(object sender, EventArgs e)\n{\n\n var openidRequest = openid.CreateRequest(openIdBox.Text);\n var fetch = new FetchRequest();\n\n fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);\n fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);\n openidRequest.AddExtension(fetch);\n\n openidRequest.RedirectToProvider();\n\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19020/" ]
292,997
<p>can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?</p> <p>If so how?</p> <p>Note I know you can use timers instead, but I'd like to know about these socket options in particular. </p>
[ { "answer_id": 293012, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "boost::asio::detail::socket_option boost/asio/socket_base.hpp typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>\n send_timeout;\ntypedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>\n receive_timeout;\n timeval boost::asio::detail::socket_option socket_option::timeval socket_option::integer // Helper template for implementing timeval options.\ntemplate <int Level, int Name>\nclass timeval\n{\npublic:\n // Default constructor.\n timeval()\n : value_(zero_timeval())\n {\n }\n\n // Construct with a specific option value.\n explicit timeval(::timeval v)\n : value_(v)\n {\n }\n\n // Set the value of the timeval option.\n timeval& operator=(::timeval v)\n {\n value_ = v;\n return *this;\n }\n\n // Get the current value of the timeval option.\n ::timeval value() const\n {\n return value_;\n }\n\n // Get the level of the socket option.\n template <typename Protocol>\n int level(const Protocol&) const\n {\n return Level;\n }\n\n // Get the name of the socket option.\n template <typename Protocol>\n int name(const Protocol&) const\n {\n return Name;\n }\n\n // Get the address of the timeval data.\n template <typename Protocol>\n ::timeval* data(const Protocol&)\n {\n return &value_;\n }\n\n // Get the address of the timeval data.\n template <typename Protocol>\n const ::timeval* data(const Protocol&) const\n {\n return &value_;\n }\n\n // Get the size of the timeval data.\n template <typename Protocol>\n std::size_t size(const Protocol&) const\n {\n return sizeof(value_);\n }\n\n // Set the size of the timeval data.\n template <typename Protocol>\n void resize(const Protocol&, std::size_t s)\n {\n if (s != sizeof(value_))\n throw std::length_error(\"timeval socket option resize\");\n }\n\nprivate:\n static ::timeval zero_timeval()\n {\n ::timeval result = {};\n return result;\n }\n\n ::timeval value_;\n};\n" }, { "answer_id": 390279, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 3, "selected": true, "text": "boost::asio::ip::tcp::socket my_socket;\n open bind my_socket SOCKET native_sock = my_socket.native();\nint result = SOCKET_ERROR;\n\nif (INVALID_SOCKET != native_sock)\n{\n result = setsockopt(native_sock, SOL_SOCKET, <the pertinent params you want to use>);\n}\n" }, { "answer_id": 46366008, "author": "Andrea Bondavalli", "author_id": 7069627, "author_profile": "https://Stackoverflow.com/users/7069627", "pm_score": 1, "selected": false, "text": "struct timeval tv = { 1, 0 };\nsetsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));\nssize_t nsent = ::write(socket->native_handle(), buff, size);\nif (nsent > 0) {\n BOOST_LOG_TRIVIAL(debug) << \"Sent \" << nsent << \" bytes to remote client \" << ep;\n} else if (nsent == 0) {\n BOOST_LOG_TRIVIAL(info) << \"Client \" << ep << \" closed connection\";\n} else if (errno != EAGAIN) {\n BOOST_LOG_TRIVIAL(info) << \"Client \" << ep << \" error: \" << strerror(errno);\n}\n struct timeval tv = { 1, 0 };\nsetsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\nssize_t nread = ::read(socket.native_handle(), buff, audio_buff_size);\nif (nread > 0) {\n} else if (nread == 0) {\n BOOST_LOG_TRIVIAL(info) << \"Source \" << source << \" server \" << host << \" closed connection\";\n break;\n} else if (errno != EAGAIN) {\n BOOST_LOG_TRIVIAL(info) << \"Source \" << source << \" server \" << host << \" error: \" << strerror(errno);\n break;\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
292,998
<p>Do I need a UUID to program for the iPhone? I was told I need this, how can I get a UUID</p>
[ { "answer_id": 293012, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "boost::asio::detail::socket_option boost/asio/socket_base.hpp typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>\n send_timeout;\ntypedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>\n receive_timeout;\n timeval boost::asio::detail::socket_option socket_option::timeval socket_option::integer // Helper template for implementing timeval options.\ntemplate <int Level, int Name>\nclass timeval\n{\npublic:\n // Default constructor.\n timeval()\n : value_(zero_timeval())\n {\n }\n\n // Construct with a specific option value.\n explicit timeval(::timeval v)\n : value_(v)\n {\n }\n\n // Set the value of the timeval option.\n timeval& operator=(::timeval v)\n {\n value_ = v;\n return *this;\n }\n\n // Get the current value of the timeval option.\n ::timeval value() const\n {\n return value_;\n }\n\n // Get the level of the socket option.\n template <typename Protocol>\n int level(const Protocol&) const\n {\n return Level;\n }\n\n // Get the name of the socket option.\n template <typename Protocol>\n int name(const Protocol&) const\n {\n return Name;\n }\n\n // Get the address of the timeval data.\n template <typename Protocol>\n ::timeval* data(const Protocol&)\n {\n return &value_;\n }\n\n // Get the address of the timeval data.\n template <typename Protocol>\n const ::timeval* data(const Protocol&) const\n {\n return &value_;\n }\n\n // Get the size of the timeval data.\n template <typename Protocol>\n std::size_t size(const Protocol&) const\n {\n return sizeof(value_);\n }\n\n // Set the size of the timeval data.\n template <typename Protocol>\n void resize(const Protocol&, std::size_t s)\n {\n if (s != sizeof(value_))\n throw std::length_error(\"timeval socket option resize\");\n }\n\nprivate:\n static ::timeval zero_timeval()\n {\n ::timeval result = {};\n return result;\n }\n\n ::timeval value_;\n};\n" }, { "answer_id": 390279, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 3, "selected": true, "text": "boost::asio::ip::tcp::socket my_socket;\n open bind my_socket SOCKET native_sock = my_socket.native();\nint result = SOCKET_ERROR;\n\nif (INVALID_SOCKET != native_sock)\n{\n result = setsockopt(native_sock, SOL_SOCKET, <the pertinent params you want to use>);\n}\n" }, { "answer_id": 46366008, "author": "Andrea Bondavalli", "author_id": 7069627, "author_profile": "https://Stackoverflow.com/users/7069627", "pm_score": 1, "selected": false, "text": "struct timeval tv = { 1, 0 };\nsetsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));\nssize_t nsent = ::write(socket->native_handle(), buff, size);\nif (nsent > 0) {\n BOOST_LOG_TRIVIAL(debug) << \"Sent \" << nsent << \" bytes to remote client \" << ep;\n} else if (nsent == 0) {\n BOOST_LOG_TRIVIAL(info) << \"Client \" << ep << \" closed connection\";\n} else if (errno != EAGAIN) {\n BOOST_LOG_TRIVIAL(info) << \"Client \" << ep << \" error: \" << strerror(errno);\n}\n struct timeval tv = { 1, 0 };\nsetsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\nssize_t nread = ::read(socket.native_handle(), buff, audio_buff_size);\nif (nread > 0) {\n} else if (nread == 0) {\n BOOST_LOG_TRIVIAL(info) << \"Source \" << source << \" server \" << host << \" closed connection\";\n break;\n} else if (errno != EAGAIN) {\n BOOST_LOG_TRIVIAL(info) << \"Source \" << source << \" server \" << host << \" error: \" << strerror(errno);\n break;\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/292998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,000
<p>I need an algorithm to determine if a sentence, paragraph or article is negative or positive in tone... or better yet, how negative or positive.</p> <p>For instance:</p> <blockquote> <blockquote> <p>Jason is the worst SO user I have ever witnessed (-10)</p> <p>Jason is an SO user (0)</p> <p>Jason is the best SO user I have ever seen (+10)</p> <p>Jason is the best at sucking with SO (-10)</p> <p>While, okay at SO, Jason is the worst at doing bad (+10)</p> </blockquote> </blockquote> <p>Not easy, huh? :)</p> <p>I don't expect somebody to explain this algorithm to me, but I assume there is already much work on something like this in academia somewhere. If you can point me to some articles or research, I would love it.</p> <p>Thanks.</p>
[ { "answer_id": 7154888, "author": "user906811", "author_id": 906811, "author_profile": "https://Stackoverflow.com/users/906811", "pm_score": -1, "selected": false, "text": " use Algorithm::NaiveBayes;\n my $nb = Algorithm::NaiveBayes->new;\n\n $nb->add_instance\n (attributes => {foo => 1, bar => 1, baz => 3},\n label => 'sports');\n\n $nb->add_instance\n (attributes => {foo => 2, blurp => 1},\n label => ['sports', 'finance']);\n\n ... repeat for several more instances, then:\n $nb->train;\n\n # Find results for unseen instances\n my $result = $nb->predict\n (attributes => {bar => 3, blurp => 2});\n" }, { "answer_id": 9377705, "author": "aliv faizal muhammad", "author_id": 1223344, "author_profile": "https://Stackoverflow.com/users/1223344", "pm_score": 2, "selected": false, "text": " Jason is the worst SO user I have ever witnessed (-10)\n Jason is an SO user (0)\n Jason is the best SO user I have ever seen (+10)\n Jason is the best at sucking with SO (-10)\n While, okay at SO, Jason is the worst at doing bad (+10)\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ]
293,006
<p>We've trying to separate a big code base into logical modules. I would like some recommendations for tools as well as whatever experiences you might have had with this sort of thing. </p> <p>The application consists of a server WAR and several rich-clients distributed in JARs. The trouble is that it's all in one big, hairy code base, one source tree of > 2k files war. Each JAR has a dedicated class with a <code>main</code> method, but the tangle of dependencies ensnares quickly. It's not all that bad, good practices were followed consistently and there are components with specific tasks. It just needs some improvement to help our team scale as it grows.</p> <p>The modules will each be in a maven project, built by a parent POM. The process has already started on moving each JAR/WAR into it's own project, but it's obvious that this will only scratch the surface: a few classes in each app JAR and a mammoth "legacy" project with everything else. Also, there are already some unit and integration tests.</p> <p>Anyway, I'm interesting in tools, techniques, and general advice to breaking up an overly large and entangled code base into something more manageable. Free/open source is preferred.</p>
[ { "answer_id": 293032, "author": "mmr", "author_id": 21981, "author_profile": "https://Stackoverflow.com/users/21981", "pm_score": 1, "selected": false, "text": "COleDateTime const char*" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
293,007
<p>I want do something like this:</p> <pre><code>Button btn1 = new Button(); btn1.Click += new EventHandler(btn1_Click); Button btn2 = new Button(); // Take whatever event got assigned to btn1 and assign it to btn2. btn2.Click += btn1.Click; // The compiler says no... </code></pre> <p>Where btn1_Click is already defined in the class:</p> <pre><code>void btn1_Click(object sender, EventArgs e) { // } </code></pre> <p>This won't compile, of course ("The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -="). Is there a way to take the event handler from one control and assign it to another at runtime? If that's not possible, is duplicating the event handler and assigning it to another control at runtime doable?</p> <p>A couple of points: I have googled the heck out of this one for awhile and found no way of doing it yet. Most of the attempted approaches involve reflection, so if you read my question and think the answer is incredibly obvious, please try to compile the code in Visual Studio first. Or if the answer really is incredibly obvious, please feel free to slap me with it. Thanks, I'm really looking forward to seeing if this is possible.</p> <p>I know I could just do this:</p> <pre><code>btn2.Click += new EventHandler(btn1_Click); </code></pre> <p>That's not what I'm looking for here.</p> <p>This is also not what I'm looking for:</p> <pre><code>EventHandler handy = new EventHandler(btn1_Click); Button btn1 = new Button(); btn1.Click += handy; Button btn2 = new Button(); btn2.Click += handy; </code></pre>
[ { "answer_id": 293010, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "OnClick btn1 btn2 btn1.RaiseClickEvent() using System;\nusing System.Drawing;\nusing System.Reflection;\nusing System.Windows.Forms;\n\nclass Test\n{\n static void Main()\n {\n\n TextBox output = new TextBox \n { \n Multiline = true,\n Height = 350,\n Width = 200,\n Location = new Point (5, 15)\n };\n Button original = new Button\n { \n Text = \"Original\",\n Location = new Point (210, 15)\n };\n original.Click += Log(output, \"Click!\");\n original.MouseEnter += Log(output, \"MouseEnter\");\n original.MouseLeave += Log(output, \"MouseLeave\");\n\n Button copyCat = new Button\n {\n Text = \"CopyCat\",\n Location = new Point (210, 50)\n };\n\n CopyEvents(original, copyCat, \"Click\", \"MouseEnter\", \"MouseLeave\");\n\n Form form = new Form \n { \n Width = 400, \n Height = 420,\n Controls = { output, original, copyCat }\n };\n\n Application.Run(form);\n }\n\n private static void CopyEvents(object source, object target, params string[] events)\n {\n Type sourceType = source.GetType();\n Type targetType = target.GetType();\n MethodInfo invoker = typeof(MethodAndSource).GetMethod(\"Invoke\");\n foreach (String eventName in events)\n {\n EventInfo sourceEvent = sourceType.GetEvent(eventName);\n if (sourceEvent == null)\n {\n Console.WriteLine(\"Can't find {0}.{1}\", sourceType.Name, eventName);\n continue;\n }\n\n // Note: we currently assume that all events are compatible with\n // EventHandler. This method could do with more error checks...\n\n MethodInfo raiseMethod = sourceType.GetMethod(\"On\"+sourceEvent.Name, \n BindingFlags.Instance | \n BindingFlags.Public | \n BindingFlags.NonPublic);\n if (raiseMethod == null)\n {\n Console.WriteLine(\"Can't find {0}.On{1}\", sourceType.Name, sourceEvent.Name);\n continue;\n }\n EventInfo targetEvent = targetType.GetEvent(sourceEvent.Name);\n if (targetEvent == null)\n {\n Console.WriteLine(\"Can't find {0}.{1}\", targetType.Name, sourceEvent.Name);\n continue;\n }\n MethodAndSource methodAndSource = new MethodAndSource(raiseMethod, source);\n Delegate handler = Delegate.CreateDelegate(sourceEvent.EventHandlerType,\n methodAndSource,\n invoker);\n\n targetEvent.AddEventHandler(target, handler);\n }\n }\n\n private static EventHandler Log(TextBox output, string text)\n {\n return (sender, args) => output.Text += text + \"\\r\\n\";\n }\n\n private class MethodAndSource\n {\n private readonly MethodInfo method;\n private readonly object source;\n\n internal MethodAndSource(MethodInfo method, object source)\n {\n this.method = method;\n this.source = source;\n }\n\n public void Invoke(object sender, EventArgs args)\n {\n method.Invoke(source, new object[] { args });\n }\n }\n}\n" }, { "answer_id": 293031, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 6, "selected": true, "text": "using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Reflection;\n\nnamespace WindowsFormsApplication1 {\n public partial class Form1 : Form {\n public Form1() {\n InitializeComponent();\n button1.Click += new EventHandler(button1_Click);\n // Get secret click event key\n FieldInfo eventClick = typeof(Control).GetField(\"EventClick\", BindingFlags.NonPublic | BindingFlags.Static);\n object secret = eventClick.GetValue(null);\n // Retrieve the click event\n PropertyInfo eventsProp = typeof(Component).GetProperty(\"Events\", BindingFlags.NonPublic | BindingFlags.Instance);\n EventHandlerList events = (EventHandlerList)eventsProp.GetValue(button1, null);\n Delegate click = events[secret];\n // Remove it from button1, add it to button2\n events.RemoveHandler(secret, click);\n events = (EventHandlerList)eventsProp.GetValue(button2, null);\n events.AddHandler(secret, click);\n }\n\n void button1_Click(object sender, EventArgs e) {\n MessageBox.Show(\"Yada\");\n }\n }\n}\n" }, { "answer_id": 293058, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 1, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var d = new Dummy();\n var d2 = new Dummy();\n\n // Use anonymous methods without saving any references\n d.MyEvents += (sender, e) => { Console.WriteLine(\"One!\"); };\n d.MyEvents += (sender, e) => { Console.WriteLine(\"Two!\"); };\n\n // Find the backing field and get its value\n var theType = d.GetType();\n var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;\n\n var backingField = theType.GetField(\"MyEvents\", bindingFlags);\n var backingDelegate = backingField.GetValue(d) as Delegate;\n\n var handlers = backingDelegate.GetInvocationList();\n\n // Bind the handlers to the second instance\n foreach (var handler in handlers)\n d2.MyEvents += handler as EventHandler;\n\n // See if the handlers are fired\n d2.DoRaiseEvent();\n\n Console.ReadKey();\n }\n}\n\nclass Dummy\n{\n public event EventHandler MyEvents;\n\n public void DoRaiseEvent() { MyEvents(this, new EventArgs()); }\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
293,021
<p>I have a working TYPO3 extension. It is attached <a href="http://wiki.orbeon.com/forms/doc/developer-guide/form-runner-typo3-extension" rel="nofollow noreferrer">this wiki page</a>. How can I change the code of this extension so it is of the USER_INT type? I.e. I don't want TYPO3 to cache the output of this plugin, and want TYPO3 to invoke the extension ever time a page that uses the extension, i.e. disable the caching for this extension.</p>
[ { "answer_id": 560914, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 3, "selected": false, "text": "var $pi_checkCHash = true;\n $this->pi_USER_INT_obj=1; // Configuring so caching is not expected. This value means that no cHash params are ever set. We do this, because it's a USER_INT object!\n" }, { "answer_id": 715194, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',0);\n t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',1);\n" }, { "answer_id": 715534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',1);\n t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',0);\n" }, { "answer_id": 21938530, "author": "Jpsy", "author_id": 430742, "author_profile": "https://Stackoverflow.com/users/430742", "pm_score": 1, "selected": false, "text": "addPItoST43() var $pi_checkCHash = true; $this->pi_USER_INT_obj=1;" }, { "answer_id": 25340498, "author": "Franz Holzinger", "author_id": 3930829, "author_profile": "https://Stackoverflow.com/users/3930829", "pm_score": 0, "selected": false, "text": "plugin.tx_myext = USER_INT\nplugin.tx_myxt {\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
293,029
<p>I'm creating a rather "dirty" business connector of my own here, and I'm having trouble finding those "custom fields" that have been created. </p> <p>They show up in AX - but in the SQL-database, they are not mentioned at all... I have a hunch that all custom fields are stored somewhere else in the database, so that the original state of the tables does not get alterd - but where? </p>
[ { "answer_id": 560914, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 3, "selected": false, "text": "var $pi_checkCHash = true;\n $this->pi_USER_INT_obj=1; // Configuring so caching is not expected. This value means that no cHash params are ever set. We do this, because it's a USER_INT object!\n" }, { "answer_id": 715194, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',0);\n t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',1);\n" }, { "answer_id": 715534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',1);\n t3lib_extMgm::addPItoST43($_EXTKEY,'piX/class.tx_yourextension_piX.php','_piX','list_type',0);\n" }, { "answer_id": 21938530, "author": "Jpsy", "author_id": 430742, "author_profile": "https://Stackoverflow.com/users/430742", "pm_score": 1, "selected": false, "text": "addPItoST43() var $pi_checkCHash = true; $this->pi_USER_INT_obj=1;" }, { "answer_id": 25340498, "author": "Franz Holzinger", "author_id": 3930829, "author_profile": "https://Stackoverflow.com/users/3930829", "pm_score": 0, "selected": false, "text": "plugin.tx_myext = USER_INT\nplugin.tx_myxt {\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37280/" ]
293,040
<p>Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.</p>
[ { "answer_id": 293118, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 3, "selected": true, "text": "cl-user(1): (compile (defun hello () (format t \"~&Hello~%\")))\nhello\nnil\nnil\ncl-user(2): (excl:fasl-write (symbol-function 'hello) \"/tmp/hello.fasl\")\nt\ncl-user(3): (excl:fasl-read \"/tmp/hello.fasl\")\n(#<Function hello @ #x1000a964d2>)\n" }, { "answer_id": 298174, "author": "kmkaplan", "author_id": 24774, "author_profile": "https://Stackoverflow.com/users/24774", "pm_score": 2, "selected": false, "text": "COMPILE LOAD (defvar *anon*)\n\n(defun save-anonymous-function (fname args body)\n (let ((fname (make-pathname :type \"LISP\" :case :common :defaults fname)))\n (with-open-file (src fname :direction :output\n :if-does-not-exist :create :if-exists :supersede)\n (print `(defparameter *anon* (lambda ,args ,body)) src))\n (compile-file fname)))\n (defun load-anonymous-function (fname)\n (let ((*load-verbose* nil)\n (*anon* nil)) ; to avoid modifying the global one.\n (load fname)\n *anon*))\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34479/" ]
293,070
<p>I'm trying to build a Java regular expression to match "<code>.jar!</code>"</p> <p>The catch is that I don't want the matcher to consume the exclamation mark. I tried using <code>Pattern.compile("\\.jar(?=!)")</code> but that failed. As did escaping the exclamation mark.</p> <p>Can anyone get this to work or is this a JDK bug?</p> <p><strong>UPDATE</strong>: I feel like an idiot, <code>Pattern.compile("\\.jar(?=!)")</code> does work. I was using Matcher.matches() instead of Matcher.find().</p>
[ { "answer_id": 293077, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "Pattern.compile(\"\\\\.jar(?=[!])\")\n use strict;\nuse warnings;\n\n\nmy @data = qw( .jar .jar! .jarx .jarx! );\n\n\nmy @patterns = (\n \"\\\\.jar(?=!)\",\n \"\\\\.jar(?=\\\\!)\",\n \"\\\\.jar(?=[!])\",\n);\n\n\nfor my $pat ( @patterns ){\n for my $inp ( @data ) {\n if ( $inp =~ /$pat/ ) {\n print \"$inp =~ $pat \\n\";\n }\n }\n}\n .jar! =~ \\.jar(?=!) \n.jar! =~ \\.jar(?=\\!) \n.jar! =~ \\.jar(?=[!]) \n" }, { "answer_id": 293087, "author": "Avi", "author_id": 1605, "author_profile": "https://Stackoverflow.com/users/1605", "pm_score": 2, "selected": true, "text": "import java.util.regex.*;\n\npublic class Regex {\n private static final String text = \".jar!\";\n\n private static final String regex = \"\\\\.jar(?=!)\";\n\n public static void main(String[] args) {\n Pattern pat = Pattern.compile(regex, Pattern.DOTALL);\n Matcher matcher = pat.matcher(text);\n if (matcher.find()) {\n System.out.println(\"Match: \" + matcher.group());\n } else {\n System.out.println(\"No match.\");\n }\n }\n}\n Match: .jar\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ]
293,081
<p>So standard Agile philosophy would recommend making your domain classes simple POCOs which are Persisted using a separate proxy layer via data access objects (like NHibernate does it). It also recommends getting as high unit test coverage as possible. </p> <p>Does it make any sense to write tests for these simple POCO objects? Say I have a class which looks like this:</p> <pre><code>public class Container { public int ContainerId { get; set;} public string Name { get; set;} public IList&lt;Item&gt; Contents { get; set;} } </code></pre> <p>What useful unit tests can I write for this?</p>
[ { "answer_id": 293093, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 1, "selected": false, "text": "Contents" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
293,090
<p>I think I'm pretty good at using semantic markup on my pages but I still have a handful of classes like this:</p> <pre><code>/**** Aligns ****/ .right_align { text-align: right; } .left_align { text-align: left; } .center_align { text-align: center; } </code></pre> <p>Which, technically, is a no-no. But when you just want to position some text in a table, how crazy am I supposed to get with the semantic markup?</p>
[ { "answer_id": 293099, "author": "Jeromy Irvine", "author_id": 8223, "author_profile": "https://Stackoverflow.com/users/8223", "pm_score": 1, "selected": false, "text": "right_align style" }, { "answer_id": 293102, "author": "alex", "author_id": 26787, "author_profile": "https://Stackoverflow.com/users/26787", "pm_score": 5, "selected": true, "text": "table .price {\n text-align: right\n}\n" }, { "answer_id": 293104, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "style=\"text-align:right\"" }, { "answer_id": 293210, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": -1, "selected": false, "text": "matcher \nmatcher, \n{\n attribute property \n attribute\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
293,100
<p>I have a do-while loop that's supposed to do three things, go through a text file line by line, the text file contains pathnames and filenames (C:\Folder\file1.txt).</p> <p>If the line contains a certain string, it then copies a file to that location, renames it to what it is named in the text file, and then replaces a string within the copied file.<br /> If not, it goes on to the next line.</p> <p>I thought this would be fairly straight forward but it doesn't seem to be working. I'm currently unable to even compile as I'm getting errors saying the loop's syntax is wrong.</p> <p>Any help would be appreciated, here's the entire function's code:</p> <pre class="lang-vb prettyprint-override"><code>Private Sub Command2_Click() Dim LineData As String Dim FileHandle As Integer FileHandle = FreeFile Open &quot;C:\textfile.txt&quot; For Input As #FileHandle Do While Not EOF(FileHandle) Line Input #FileHandle, LineData If InStr(LineData, &quot;.log&quot;) Then FileCopy &quot;C:\thefile.log&quot;,LineData Open LineData For Input As #3 #3 = Replace$(#3, &quot;abc&quot;, &quot;xyz&quot;) Else End If Loop Close #FileHandle Close #3 MsgBox &quot;Copy, Replace, Complete!&quot; End Sub </code></pre> <p>Thanks in Advance!</p>
[ { "answer_id": 293124, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 1, "selected": false, "text": "#3 = Replace$(#3, \"abc\", \"xyz\")\n Private Sub Command2_Click()\n Dim LineData As String\n Dim FileHandle As Integer\n Dim sourceHandle as Integer\n Dim destHandle as Integer\n dim temp as string\n FileHandle = FreeFile\n Open \"C:\\textfile.txt\" For Input As #FileHandle\n Do While Not EOF(FileHandle)\n Line Input #FileHandle, LineData\n If InStr(LineData, \".log\") Then\n sourceHandle=FreeFile\n Open \"C:\\thefile.log\" For Input as #sourceHandle\n destHandle=FreeFile\n Open LineData For Output as #destHandle\n Do while Not EOF(sourceHandle)\n Line Input #sourceHandle,temp\n temp=replace$(temp,\"abc\",\"xyz\")\n Print #destHandle,temp\n Loop\n Close #destHandle\n Close #sourceHandle\n End If\n Loop\nClose #FileHandle\nMsgBox \"Copy, Replace, Complete!\"\nEnd Sub\n" }, { "answer_id": 293811, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 1, "selected": false, "text": "Private Sub Command2_Click()\n Dim LineData As String\n Dim FileHandle As Integer\n Dim Buffer As String\n FileHandle = FreeFile\n Open \"C:\\thefile.log\" For Binary Access Read As #FileHandle\n Buffer = Space(LOF(FileHandle))\n Get #FileHandle, , Buffer\n Buffer = Replace(Buffer, \"abc\", \"xyz\")\n Close #FileHandle\n FileHandle = FreeFile\n Open \"C:\\textfile.txt\" For Input As #FileHandle\n Do Until EOF(FileHandle)\n Line Input #FileHandle, LineData\n If InStr(LineData, \".log\") Then\n Open LineData For Output As #3\n Print #3, Buffer;\n Close #3\n End If\n Loop\n Close #FileHandle\n MsgBox \"Copy, Replace, Complete!\"\nEnd Sub\n Private Sub Command2_Click()\n ''// This code requires a reference to Microsoft Scripting runtime (Project -> References)\n Dim FSO As New Scripting.FileSystemObject\n Dim Files() As String\n Dim File As String\n Dim Data As String\n Data = Replace(FSO.OpenTextFile(\"C:\\thefile.log\").ReadAll(), \"abc\", \"xyz\")\n Files = Split(FSO.OpenTextFile(\"C:\\textfile.txt\").ReadAll(), vbCrLf)\n For Each File In Files\n If InStr(File, \".log\") > 0 Then FSO.CreateTextFile(File, True).Write Data\n Next\n MsgBox \"Copy, Replace, Complete!\"\nEnd Sub\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,114
<p>I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance</p>
[ { "answer_id": 293116, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "java -jar archive.jar" }, { "answer_id": 293122, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "package archiveFolder\n org/jc/tests/TestClass.class\n package org.jc.tests;\n\npublic class TestClass {\n public static void main(String[] args) {\n System.out.printf(\"This is a test class!\\n\");\n }\n}\n $ jar -cf testJar.jar org/jc/tests/*.class\n$ java -cp testJar.jar org.jc.tests.TestClass\n" }, { "answer_id": 293143, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "MainClass.java src package archiveFolder;\n\npublic class MainClass\n{\n public static void main(String[] args)\n {\n System.out.println(\"I'm MainClass\");\n }\n}\n # Compile the source\njavac -d . src/MainClass.java\n\n# Build the jar file\njar cf archive.jar archiveFolder\n\n# Remove the unpackaged binary, to prove it's not being used\nrm -rf archiveFolder # Or rmdir /s /q archiveFolder on Windows\n\n# Execute the class\njava -cp archive.jar achiveFolder.MainClass\n I'm MainClass\n" }, { "answer_id": 293930, "author": "Olaf Kock", "author_id": 13447, "author_profile": "https://Stackoverflow.com/users/13447", "pm_score": 1, "selected": false, "text": "public class MyClass {\n private static Logger log = Logger.getLogger(\"com.example\");\n}\n public class MyClass {\n static {\n // <b>any</b> error caused here will cause the class to \n // not be loaded. Demonstrating with stupid typecast.\n Object o = new String();\n Integer i = (Integer) o;\n }\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23486/" ]
293,117
<p>By convention our DB only alows the use of stored procedures for INSERT, UPDATE and DELETE. For some tables / types there is no DELETE stored procedure, because it is not allowed to delete rows. (You can only update the status of such a type to "deleted"). e.g. a customer may be marked as deleted but is never really removed from the DB.</p> <p><strong>How do I prevent the use of Delete() for certain types in the Data Access Layer = in the DMBL?</strong></p> <p>The "Default Methods" for Insert and Update are mapped to the corresponding stored procedure. But for Delete it says <strong>"use runtime"</strong>. I would like to set it to "not allowed".</p> <p>Is there a way to achieve this on the DB model layer?</p> <p>Many thanks</p>
[ { "answer_id": 293174, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 0, "selected": false, "text": "DeleteOnSubmit Table<TEntity> OnValidate InvalidOperationException DataContext DataContext" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36546/" ]
293,134
<p>Let's say I have a line of text like this</p> <pre><code>Small 0.0..20.0 0.00 1.49 25.71 41.05 12.31 0.00 80.56 </code></pre> <p>I want to capture the last six numbers and ignore the <em>Small</em> and the first two groups of numbers.</p> <p>For this exercise, let's ignore the fact that it might be easier to just do some sort of string-split instead of a regular expression.</p> <p>I have this regex that works but is kind of horrible looking</p> <pre><code>^(Small).*?[0-9.]+.*?[0-9.]+.*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+) </code></pre> <p>Is there some way to compact that?</p> <p>For example, is it possible to combine the check for the last 6 numbers into a single statement that still stores the results as 6 separate group matches?</p>
[ { "answer_id": 293150, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 3, "selected": false, "text": "^Small\\s+[0-9.]+\\s+[0-9.]+\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\\s+([0-9.]+)\n >>> pieces = \"Small 0.0..20.0 0.00 1.49 25.71 41.05 12.31 0.00 80.56\".split()[-6:]\n>>> print pieces\n['1.49', '25.71', '41.05', '12.31', '0.00', '80.56']\n" }, { "answer_id": 293175, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "$d = \"[0-9.]+\"; \n$s = \".*?\"; \n\n$re = \"^(Small)$s$d$s$d$s($d)$s($d)$s($d)$s($d)$s($d)$s($d)\";\n $re = \"^(Small)_#D_#D_(#D)_(#D)_(#D)_(#D)_(#D)_(#D)\"; \n$re = str_replace('#D','[0-9.]+',$re); \n$re = str_replace('_', '.*?' , $re ); \n" }, { "answer_id": 293195, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": true, "text": "^Small\\s+(?:[\\d.]+\\s+){2}([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s*$\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
293,158
<p>I'm attempting to create a Wizard type control in VB6 and have run into a stumbling block.</p> <p>I'd like to allow users of the control to be able to add and manage CWizardPage(s) to the design time control using a property page.</p> <p>The first approach I used was to add the Wizard pages to the OCX directly using a Collection, however I ran into two problems in that the Collection class is not persistable (and I couldn't find an easy way to make it so) and that VB6 seems very limited in it's ability to instantiate controls at run time - so it would seem to be a struggle to actually re-instantiate them.</p> <p>My next thought was to just allow the users to draw the wizard pages at design time. This sort of works, however it's far too easy to draw one of the wizard pages inside another wizard page instead of inside the CWizardContainer.</p> <p>So can anyone please tell me how to add controls to a form at design time without using drag 'n' drop?</p>
[ { "answer_id": 294665, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 1, "selected": false, "text": "Add Controls myTextBox frmMyForm.Controls.Add \"VB.TextBox\", \"myTextBox\"" }, { "answer_id": 294778, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 0, "selected": false, "text": "Private Sub Form_Load()\n\n Dim newIndex As Integer\n\n newIndex = Text1.UBound + 1\n Load Text1(newIndex)\n Text1(newIndex).Top = Text1(newIndex - 1).Top + Text1(newIndex - 1).Height\n Text1(newIndex).Visible = True\n\nEnd Sub\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293123/" ]
293,160
<p>I'm writing an application that includes a plugin system in a different assembly.</p> <p>The problem is that the plugin system needs to get application settings from the main app (like the directory to look for plugins).</p> <p>How is this done, or am I going about this the wrong way?</p> <p>Edit: I was encouraged to add some details about how the plugin system works. I haven't completely worked that out and I've only just begun implementing it, but I basically went by <a href="http://divil.co.uk/net/articles/plugins/plugins.asp" rel="nofollow noreferrer">this article</a>.</p>
[ { "answer_id": 293197, "author": "Frode Lillerud", "author_id": 33431, "author_profile": "https://Stackoverflow.com/users/33431", "pm_score": 2, "selected": false, "text": "//Get the configuration for the current appDomain\nSystem.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\n//Create the plugin, and pass in the configuration\nIPlugin myPlugin = new AlfaPlugin(config);\n" }, { "answer_id": 293209, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 2, "selected": false, "text": "System.Configuration.ConfigurationSection System.Configuration ConfigurationManager.GetSection(...) Configuration" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13395/" ]
293,168
<p>Suppose I have an interval (a,b), and a number of subintervals {(a<sub>i</sub>,b<sub>i</sub>)}<sub>i</sub> whose union is all of (a,b). Is there an efficient way to choose a minimal-cardinality subset of these subintervals which still covers (a,b)?</p>
[ { "answer_id": 293184, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 1, "selected": false, "text": "//works backwards from the end\nint minCard(int current, int must_end_after)\n{\n if (current < 0)\n if (must_end_after == 0)\n return 0; //no more intervals needed\n else\n return infinity; //doesn't cover (a,b)\n \n if (intervals[current].end < must_end_after)\n return infinity; //doesn't cover (a,b)\n \n return min( 1 + minCard(current - 1, intervals[current].start),\n minCard(current - 1, must_end_after) );\n //include current interval or not?\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1941213/" ]
293,208
<p>I am making some plots in Perl using <a href="http://search.cpan.org/dist/GD-Graph" rel="nofollow noreferrer">GD::Graph</a> and some of the data is outside the area I would like to display, but instead of being truncated off the chart outside the graphing area, it is being drawn over the title, legend, and axis labels. Does anyone know how to stop this from happening?</p>
[ { "answer_id": 294605, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 0, "selected": false, "text": "y_max_value y_max_value use Tie::RangeHash ;\nmy $y_ranges = new Tie::RangeHash Type => Tie::RangeHash::TYPE_NUMBER;\n$y_ranges->add(' -500, -101', '-25');\n$y_ranges->add(' -100, -26', '-10');\n$y_ranges->add(' -25, -1', '-5');\n$y_ranges->add(' 0, 25', '5');\n$y_ranges->add(' 26, 100', '10');\n$y_ranges->add(' 101, 500', '25');\n$y_ranges->add(' 501, 1000', '100');\n$y_ranges->add(' 1001, 5000', '250');\n$y_ranges->add(' 5001, 10000','1000');\n$y_ranges->add('10001, 50000','2500');\n$y_ranges->add('50001,' ,'5000');\n\nsub set_y_axis {\n # This routine over-rides the y_max_value calculation in GD::Graph, which produces double the\n # required limit, and therefore a lot of white-space...\n return 1 unless @_ ; #no point going any further if no arguments were provided, however result has to be\n #non-zero to avoid /0 errors in GD::Graph\n my @a = map { $_ || 0 } @_ ; #array may have undefs in it. Set null to zero for calc of max\n my ($y_max) = sort { $b <=> $a } @a ; # Get largest total for y-axis\n my $y_range = $y_ranges->fetch($y_max);\n my $y_axis = ($y_max%$y_range==0) ? $y_max+$y_range : ($y_max - ($y_max%$y_range) + $y_range);\n sprintf(\"%d\", $y_axis);\n}\n\nsub my_graph {\n my @ymax;\n # generate data... foreach loop etc\n push(@ymax, $this_y_value); # append y-value or cumulative y-value as appropriate\n # etc.\n my $graph = GD::Graph::lines->new(750, 280);\n $graph->set(\n y_max_value => set_y_axis(@ymax),\n x_labels_vertical => 1,\n transparent => 1,\n # etc\n );\n # etc\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13912/" ]
293,213
<p>What are the best and worst emacs key bindings in development software? Ever since I learned it, I find myself trying to use C-p and C-n to move up and down in everything that has a text box on it.</p> <p>I'm perpetually annoyed by software that has an emacs mode that's pretty obviously either put together by someone who's never used emacs before or it's done in a crappy manner. So let's recognize the winners and losers in this thread.</p>
[ { "answer_id": 293688, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 4, "selected": true, "text": "G^%$&^% F^%$ C-k (kill-line) is bound to (insert-this-crap `print(\"code sample\");`)\nC-b (backward-char) is bound to (insert-this-crap **strong text**)\nC-e, C-a, C-p, C-f, C-n work as expected.\n" }, { "answer_id": 293856, "author": "Matt Curtis", "author_id": 17221, "author_profile": "https://Stackoverflow.com/users/17221", "pm_score": 2, "selected": false, "text": "C-p C-s" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
293,215
<p>In the early days of .NET, I <i>believe</i> there was an attribute you could decorate a class with to specify a default property.</p> <p>According to some articles I've found, this appears to have been yanked from the framework at some point, because it was a little confusing, and I can see how that is the case. </p> <p>Still, is there another way to get the functionality it provided?</p> <p>It looked something like this:</p> <pre><code>&lt;DefaultProperty("Value")&gt; _ Public Class GenericStat ... Public Property Value() As Integer ... End Property ... End Class </code></pre> <p>This allowed you to do <code>Response.Write(MyObject)</code> instead of <code>Response.Write(MyObject.Value)</code>... This is not a terribly clunky example, but in some complex object-oriented contexts it gets a little hideous. Please let me know if there is a better way. </p> <p><b>Note:</b> I am not looking for the Default keyword, which can only be used on properties that take a parameter.</p>
[ { "answer_id": 293225, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 1, "selected": false, "text": "DefaultProperty" }, { "answer_id": 293248, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": " Public Overrides Function ToString() As String\n Return Me.Value.ToString \n End Function\n Public Class MyClass\n Private m_Stats(100) As Stats ' or some other collection'\n\n Public Property StatValue(ByVal stat_number As Integer) As _\n Integer\n Get\n Return m_Stats(stat_number)\n End Get\n Set(ByVal Value As Integer)\n m_Stats(stat_number) = Value\n End Set\n End Property\nEnd Class\n" }, { "answer_id": 293334, "author": "Brian MacKay", "author_id": 16082, "author_profile": "https://Stackoverflow.com/users/16082", "pm_score": 1, "selected": false, "text": "= Dim x as Integer = MyObject.Stats(Stat.Health)" }, { "answer_id": 294405, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 6, "selected": true, "text": " Public Class Sample\n Private mValue As Integer\n Default Public ReadOnly Property Test(ByVal index As Integer) As Integer\n Get\n Return index\n End Get\n End Property\n End Class\n Sub Main()\n Dim s As New Sample\n Console.WriteLine(s(42))\n Console.ReadLine()\n End Sub\n <System.Reflection.DefaultMember(\"AnotherTest\")> _\n Public Class Sample\n Public ReadOnly Property AnotherTest() As Integer\n Get\n Return 42\n End Get\n End Property\n End Class\n public class Sample {\n public int this[int index] {\n get { return index; }\n }\n }\n" }, { "answer_id": 298137, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 3, "selected": false, "text": "b c Foo a.Foo(1) a.b.Foo(1) a.b.c.Foo(1) Set Set" }, { "answer_id": 298150, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "Widening Operator CType" }, { "answer_id": 8083813, "author": "Richard", "author_id": 425809, "author_profile": "https://Stackoverflow.com/users/425809", "pm_score": 0, "selected": false, "text": "Imports System.ComponentModel" }, { "answer_id": 19481017, "author": "John", "author_id": 2880821, "author_profile": "https://Stackoverflow.com/users/2880821", "pm_score": 3, "selected": false, "text": "Widening Operator CType Public Class GenericStat\n ...\n Public Property Value() As Integer\n ...\n End Property\n ...\n 'this could be overloaded if needed\n Public Sub New(ByVal Value As Integer)\n _Value = Value\n End Sub\n '\n Public Shared Widening Operator CType(ByVal val As Integer) As GenericStat\n Return New GenericStat(val)\n End Operator\n '\n Public Shared Widening Operator CType(ByVal val As GenericStat) As Integer\n Return val.Value\n End Operator\nEnd Class\n Dim MyObject as GenericStat\nMyObject = 123\n Dim Int as Integer\nInt = MyObject \n .Value myobject(1)" }, { "answer_id": 23136757, "author": "Vinicius", "author_id": 3179032, "author_profile": "https://Stackoverflow.com/users/3179032", "pm_score": 1, "selected": false, "text": "Public Class GenericStat(Of Ttype)\n\nPublic Property Value As Ttype\n'\nPublic Sub New()\n\nEnd Sub\n'\n'this could be overloaded if needed\nPublic Sub New(ByVal Value As Ttype)\n _Value = Value\nEnd Sub\n'\nPublic Shared Widening Operator CType(ByVal val As Ttype) As GenericStat(Of Ttype)\n Return New GenericStat(Of Ttype)(val)\nEnd Operator\n'\nPublic Shared Widening Operator CType(ByVal val As GenericStat(Of Ttype)) As Ttype\n Return val.Value\nEnd Operator\n\nEnd Class\n Dim MyInteger As GenericStat(Of Integer)\nMyInteger = 123\n\nDim Int As Integer\nInt = MyInteger\n\nDim MyString As GenericStat(Of String)\nMyString = \"MyValue\"\n\nDim Str As String\nStr = MyString\n" }, { "answer_id": 25428303, "author": "Marko Pareigis", "author_id": 3964365, "author_profile": "https://Stackoverflow.com/users/3964365", "pm_score": 2, "selected": false, "text": "Dim myVal as Integer\nmyVal = 15\nIf myVal = 15 then\n ...\nEnd If\n myVal.SomeReadOnlyProperty (as String)\nmyVal.SomeOtherReadOnlyProperty (as Integer)\n GetSomeReadOnlyProperty(ByVal pVal as Integer) as String\nGetSomeOtherReadOnlyProperty(ByVal pVal as Integer) as Integer\n 'The first two give me the assignment operator like John suggested\nPublic Shared Widening Operator CType(ByVal val As Integer) As MySpecialIntType\n Return New MySpecialIntType(val)\nEnd Operator\n\n'As opposed to John's suggestion I think this should be Narrowing?\nPublic Shared Narrowing Operator CType(ByVal val As MySpecialIntType) As Integer\n Return val.Value\nEnd Operator\n\n'These two give me the comparison operator\n'other operators can be added as needed\nPublic Shared Operator =(ByVal pSpecialTypeParameter As MySpecialIntType, ByVal pInt As Integer) As Boolean\n Return pSpecialTypeParameter.Value = pInt\nEnd Operator\n\nPublic Shared Operator <>(ByVal pSpecialTypeParameter As MySpecialIntType, ByVal pInt As Integer) As Boolean\n Return pSpecialTypeParameter.Value <> pInt\nEnd Operator\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16082/" ]
293,216
<p>I ran into a scenario where LINQ to SQL acts very strangely. I would like to know if I'm doing something wrong. But I think there is a real possibility that it's a bug.</p> <p>The code pasted below isn't my real code. It is a simplified version I created for this post, using the Northwind database.</p> <p>A little background: I have a method that takes an <code>IQueryable</code> of <code>Product</code> and a "filter object" (which I will describe in a minute). It should run some "Where" extension methods on the <code>IQueryable</code>, based on the "filter object", and then return the <code>IQueryable</code>.</p> <p>The so-called "filter object" is a <code>System.Collections.Generic.List</code> of an anonymous type of this structure: <code>{ column = fieldEnum, id = int }</code></p> <p>The fieldEnum is an enum of the different columns of the <code>Products</code> table that I would possibly like to use for the filtering.</p> <p>Instead of explaining further how my code works, it's easier if you just take a look at it. It's simple to follow.</p> <pre><code>enum filterType { supplier = 1, category } public IQueryable&lt;Product&gt; getIQueryableProducts() { NorthwindDataClassesDataContext db = new NorthwindDataClassesDataContext(); IQueryable&lt;Product&gt; query = db.Products.AsQueryable(); //this section is just for the example. It creates a Generic List of an Anonymous Type //with two objects. In real life I get the same kind of collection, but it isn't hard coded like here var filter1 = new { column = filterType.supplier, id = 7 }; var filter2 = new { column = filterType.category, id = 3 }; var filterList = (new[] { filter1 }).ToList(); filterList.Add(filter2); foreach(var oFilter in filterList) { switch (oFilter.column) { case filterType.supplier: query = query.Where(p =&gt; p.SupplierID == oFilter.id); break; case filterType.category: query = query.Where(p =&gt; p.CategoryID == oFilter.id); break; default: break; } } return query; } </code></pre> <p>So here is an example. Let's say the List contains two items of this anonymous type, <code>{ column = fieldEnum.Supplier, id = 7 }</code> and <code>{ column = fieldEnum.Category, id = 3}</code>.</p> <p>After running the code above, the underlying SQL query of the <code>IQueryable</code> object should contain:</p> <pre><code>WHERE SupplierID = 7 AND CategoryID = 3 </code></pre> <p>But in reality, after the code runs the SQL that gets executed is</p> <pre><code>WHERE SupplierID = 3 AND CategoryID = 3 </code></pre> <p>I tried defining <code>query</code> as a property and setting a breakpoint on the setter, thinking I could catch what's changing it when it shouldn't be. But everything was supposedly fine. So instead I just checked the underlying SQL after every command. I realized that the first <code>Where</code> runs fine, and <code>query</code> stays fine (meaning <code>SupplierID = 7</code>) until right after the <code>foreach</code> loop runs the second time. Right after <code>oFilter</code> becomes the second anonymous type item, and not the first, the 'query' SQL changes to <code>Supplier = 3</code>. So what must be happening here under-the-hood is that instead of just remembering that <code>Supplier</code> should equal 7, LINQ to SQL remembers that Supplier should equal <code>oFilter.id</code>. But <code>oFilter</code> is a name of a single item of a <code>foreach</code> loop, and it means something different after it iterates.</p>
[ { "answer_id": 293227, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 4, "selected": true, "text": "oFilter foreach foreach(var oFilter in filterList)\n{\n var filter = oFilter; // add this\n switch (oFilter.column) // this doesn't have to change, but can for consistency\n {\n case filterType.supplier:\n query = query.Where(p => p.SupplierID == filter.id); // use `filter` here\n break;\n filter" }, { "answer_id": 293241, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "foreach(var oFilter in filterList)\n{\n var o = oFilter;\n switch (o.column)\n {\n case filterType.supplier:\n query = query.Where(p => p.SupplierID == o.id);\n break;\n case filterType.category:\n query = query.Where(p => p.CategoryID == o.id);\n break;\n default:\n break;\n }\n}\n oFilter o" }, { "answer_id": 2023148, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 0, "selected": false, "text": "{\n IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator();\n try\n {\n int m; // OUTSIDE THE ACTUAL LOOP\n while(e.MoveNext())\n {\n m = (int)(int)e.Current;\n funcs.Add(()=>m);\n }\n }\n finally\n {\n if (e != null) ((IDisposable)e).Dispose();\n }\n}\n try\n{\n while(e.MoveNext())\n {\n int m; // INSIDE\n m = (int)(int)e.Current;\n funcs.Add(()=>m);\n }\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30725/" ]
293,236
<p>I'm slowly moving from PHP5 to Python on some personal projects, and I'm currently loving the experience. Before choosing to go down the Python route I looked at Ruby. What I did notice from the ruby community was that monkey-patching was both common and highly-regarded. I also came across a <strong>lot</strong> of horror stories regarding the trials of debugging ruby s/w because someone included a relatively harmless library to do a little job but which patched some heavily used core object without telling anyone. </p> <p>I chose Python for (among other reasons) its cleaner syntax and the fact that it could do everything Ruby can. Python is making OO click much better than PHP ever has, and I'm reading more and more on OO principles to enhance this better understanding.</p> <p>This evening I've been reading about <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="noreferrer">Robert Martin's SOLID</a> principles:</p> <ul> <li><strong>S</strong>ingle responsibility principle,</li> <li><strong>O</strong>pen/closed principle,</li> <li><strong>L</strong>iskov substitution principle,</li> <li><strong>I</strong>nterface segregation principle, and</li> <li><strong>D</strong>ependency inversion principle</li> </ul> <p>I'm currently up to <strong>O</strong>: <em>SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION</em>. </p> <p>My head's in a spin over the conflict between ensuring consistency in OO design and the whole monkey-patching thing. I understand that its possible to do monkey-patching in Python. I also understand that being "pythonic" is to follow common, well-tested, oop best-practices &amp; principles.</p> <p><strong>What I'd like to know is the community's opinion on the two opposing subjects;</strong> how they interoperate, when its best to use one over the other, whether the monkey-patching should be done at all... hopefully you can provide a resolution to the matter for me.</p>
[ { "answer_id": 293253, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "setTimeout(function(){ \n foo(args); \n}, 5000 ); \n foo.delay( 5000 , args );\n foo.delay.delay( 500, [ 500, args ] ); \n x = foo.delay( 500, args ); \nx.clear(); \n x.clear.delay(10); \n clearTimeout(x); \n" }, { "answer_id": 296775, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "class SomeClass\n alias original_dostuff dostuff\n def dostuff\n # extra stuff, eg logging, opening a transaction, etc\n original_dostuff\n end\nend\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
293,239
<p>I'm trying to complete the last part of my Haskell homework and I'm stuck, my code so far:</p> <pre><code>data Entry = Entry (String, String) class Lexico a where (&lt;!), (=!), (&gt;!) :: a -&gt; a -&gt; Bool instance Lexico Entry where Entry (a,_) &lt;! Entry (b,_) = a &lt; b Entry (a,_) =! Entry (b,_) = a == b Entry (a,_) &gt;! Entry (b,_) = a &gt; b entries :: [(String, String)] entries = [("saves", "en vaut"), ("time", "temps"), ("in", "&lt;`a&gt;"), ("{", "{"), ("A", "Un"), ("}", "}"), ("stitch", "point"), ("nine.", "cent."), ("Zazie", "Zazie")] build :: (String, String) -&gt; Entry build (a, b) = Entry (a, b) diction :: [Entry] diction = quiksrt (map build entries) size :: [a] -&gt; Integer size [] = 0 size (x:xs) = 1+ size xs quiksrt :: Lexico a =&gt; [a] -&gt; [a] quiksrt [] = [] quiksrt (x:xs) |(size [y|y &lt;- xs, y =! x]) &gt; 0 = error "Duplicates not allowed." |otherwise = quiksrt [y|y &lt;- xs, y &lt;! x]++ [x] ++ quiksrt [y|y &lt;- xs, y &gt;! x] english :: String english = "A stitch in time save nine." show :: Entry -&gt; String show (Entry (a, b)) = "(" ++ Prelude.show a ++ ", " ++ Prelude.show b ++ ")" showAll :: [Entry] -&gt; String showAll [] = [] showAll (x:xs) = Main.show x ++ "\n" ++ showAll xs main :: IO () main = do putStr (showAll ( diction )) </code></pre> <p>The question asks:</p> <blockquote> <p>Write a Haskell programs that takes the English sentence 'english', looks up each word in the English-French dictionary using binary search, performs word-for-word substitution, assembles the French translation, and prints it out.</p> <p>The function 'quicksort' rejects duplicate entries (with 'error'/abort) so that there is precisely one French definition for any English word. Test 'quicksort' with both the original 'raw_data' and after having added '("saves", "sauve")' to 'raw_data'.</p> <p>Here is a von Neumann late-stopping version of binary search. Make a literal transliteration into Haskell. Immediately upon entry, the Haskell version must verify the recursive "loop invariant", terminating with 'error'/abort if it fails to hold. It also terminates in the same fashion if the English word is not found.</p> <pre><code>function binsearch (x : integer) : integer local j, k, h : integer j,k := 1,n do j+1 &lt;&gt; k ---&gt; h := (j+k) div 2 {a[j] &lt;= x &lt; a[k]} // loop invariant if x &lt; a[h] ---&gt; k := h | x &gt;= a[h] ---&gt; j := h fi od {a[j] &lt;= x &lt; a[j+1]} // termination assertion found := x = a[j] if found ---&gt; return j | not found ---&gt; return 0 fi </code></pre> <p>In the Haskell version</p> <pre><code>binsearch :: String -&gt; Integer -&gt; Integer -&gt; Entry </code></pre> <p>as the constant dictionary 'a' of type '[Entry]' is globally visible. Hint: Make your string (English word) into an 'Entry' immediately upon entering 'binsearch'.</p> <p>The programming value of the high-level data type 'Entry' is that, if you can design these two functions over the integers, it is trivial to lift them to to operate over Entry's.</p> </blockquote> <p>Anybody know how I'm supposed to go about my binarysearch function?</p>
[ { "answer_id": 293286, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "Array listArray" }, { "answer_id": 293555, "author": "ja.", "author_id": 15467, "author_profile": "https://Stackoverflow.com/users/15467", "pm_score": 2, "selected": false, "text": " *Main> map bs (words english)\n[Entry (\"A\",\"Un\"),Entry (\"stitch\",\"point\"),Entry (\"in\",\"<`a>\"),Entry (\"time\",\"te\nmps\"),*** Exception: Not found\n*Main> map bs (words englishFixed)\n[Entry (\"A\",\"Un\"),Entry (\"stitch\",\"point\"),Entry (\"in\",\"<`a>\"),Entry (\"time\",\"te\nmps\"),Entry (\"saves\",\"en vaut\"),Entry (\"nine.\",\"cent.\")]\n*Main>\n" }, { "answer_id": 1698199, "author": "Reza", "author_id": 206460, "author_profile": "https://Stackoverflow.com/users/206460", "pm_score": 0, "selected": false, "text": "(!!) :: [a] -> Integer -> a\n-- xs!!n returns the nth element of xs, starting at the left and\n-- counting from 0.\n [14,7,3]!!1" }, { "answer_id": 1703281, "author": "Reza", "author_id": 206460, "author_profile": "https://Stackoverflow.com/users/206460", "pm_score": 1, "selected": false, "text": "module Main where\n\nclass Lex a where\n (<!), (=!), (>!) :: a -> a -> Bool\n\ndata Entry = Entry String String\n\ninstance Lex Entry where\n (Entry a _) <! (Entry b _) = a < b\n (Entry a _) =! (Entry b _) = a == b\n (Entry a _) >! (Entry b _) = a > b\n -- at this point, three binary (infix) operators on values of type 'Entry'\n -- have been defined\n\ntype Raw = (String, String)\n\nraw_data :: [Raw]\nraw_data = [(\"than a\", \"qu'un\"), (\"saves\", \"en vaut\"), (\"time\", \"temps\"),\n (\"in\", \"<`a>\"), (\"worse\", \"pire\"), (\"{\", \"{\"), (\"A\", \"Un\"),\n (\"}\", \"}\"), (\"stitch\", \"point\"), (\"crime;\", \"crime,\"),\n (\"a\", \"une\"), (\"nine.\", \"cent.\"), (\"It's\", \"C'est\"),\n (\"Zazie\", \"Zazie\"), (\"cat\", \"chat\"), (\"it's\", \"c'est\"),\n (\"raisin\", \"raisin sec\"), (\"mistake.\", \"faute.\"),\n (\"blueberry\", \"myrtille\"), (\"luck\", \"chance\"),\n (\"bad\", \"mauvais\")]\n\ncook :: Raw -> Entry\ncook (x, y) = Entry x y\n\na :: [Entry]\na = map cook raw_data\n\nquicksort :: Lex a => [a] -> [a]\nquicksort [] = []\nquicksort (x:xs) = quicksort (filter (<! x) xs) ++ [x] ++ quicksort (filter (=! x) xs) ++ quicksort (filter (>! x) xs) \n\ngetfirst :: Entry -> String\ngetfirst (Entry x y) = x\n\ngetsecond :: Entry -> String\ngetsecond (Entry x y) = y\n\nbinarysearch :: String -> [Entry] -> Int -> Int -> String\nbinarysearch s e low high \n | low > high = \" NOT fOUND \"\n | getfirst ((e)!!(mid)) > s = binarysearch s (e) low (mid-1)\n | getfirst ((e)!!(mid)) < s = binarysearch s (e) (mid+1) high\n | otherwise = getsecond ((e)!!(mid))\n where mid = (div (low+high) 2)\n\ntranslator :: [String] -> [Entry] -> [String]\ntranslator [] y = []\ntranslator (x:xs) y = (binarysearch x y 0 ((length y)-1):translator xs y)\n\nenglish :: String\nenglish = \"A stitch in time saves nine.\"\n\ncompute :: String -> [Entry] -> String\ncompute x y = unwords(translator (words (x)) y)\n\nmain = do\n putStr (compute english (quicksort a))\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5387/" ]
293,247
<p>I've read a lot about the pros and cons of sizing with either relative or absolute font sizes. Fixed sizes don't zoom in IE6 but that's not much of an issue these days. Accessibility is important, but I assume that all good accessibility software is built to deal with these issues?</p> <p>I guess it mainly comes down to whether you want to be able to change all font sizes with one rule (i.e. the default font size you set) or whether you want to be able to change a font size somewhere without affecting nested elements (this is the thing that frustrates me most!).</p> <p>Anyone have any tips?</p>
[ { "answer_id": 293308, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "pt em %" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37947/" ]
293,254
<p>I'm using C# and .NET 3.5. I need to generate and store some T-SQL insert statements which will be executed later on a remote server.</p> <p>For example, I have an array of Employees:</p> <pre><code>new Employee[] { new Employee { ID = 5, Name = "Frank Grimes" }, new Employee { ID = 6, Name = "Tim O'Reilly" } } </code></pre> <p>and I need to end up with an array of strings, like this:</p> <pre><code>"INSERT INTO Employees (id, name) VALUES (5, 'Frank Grimes')", "INSERT INTO Employees (id, name) VALUES (6, 'Tim O''Reilly')" </code></pre> <p>I'm looking at some code that creates the insert statements with String.Format, but that doesn't feel right. I considered using SqlCommand (hoping to do <a href="https://stackoverflow.com/questions/265192/how-to-get-the-generated-sql-statment-from-a-sqlcommand-object">something like this</a>), but it doesn't offer a way to combine the command text with parameters.</p> <p>Is it enough just to replace single quotes and build a string?</p> <pre><code>string.Format("INSERT INTO Employees (id, name) VALUES ({0}, '{1}')", employee.ID, replaceQuotes(employee.Name) ); </code></pre> <p>What should I be concerned about when doing this? The source data is fairly safe, but I don't want to make too many assumptions.</p> <p>EDIT: Just want to point out that in this case, I don't have a SqlConnection or any way to directly connect to SQL Server. This particular app needs to generate sql statements and queue them up to be executed somewhere else - otherwise I'd be using SqlCommand.Parameters.AddWithValue()</p>
[ { "answer_id": 293272, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": false, "text": "SqlCommand cmd = new SqlCommand(\n \"INSERT INTO Employees (id, name) VALUES (@id, @name)\", conn);\n\nSqlParameter param = new SqlParameter();\nparam.ParameterName = \"@id\";\nparam.Value = employee.ID;\n\ncmd.Parameters.Add(param);\n\nparam = new SqlParameter();\nparam.ParameterName = \"@name\";\nparam.Value = employee.Name;\n\ncmd.Parameters.Add(param);\n\ncmd.ExecuteNonQuery();\n" }, { "answer_id": 10826895, "author": "KMX", "author_id": 1150916, "author_profile": "https://Stackoverflow.com/users/1150916", "pm_score": 2, "selected": false, "text": "void string replaceQuotes(string value) {\n string tmp = value;\n tmp = tmp.Replace(\"'\", \"''\");\n return tmp;\n}\n" } ]
2008/11/15
[ "https://Stackoverflow.com/questions/293254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142/" ]
293,275
<p>I am trying to <strong>synchronize</strong> the horizontal <strong>scroll position</strong> of 2 <strong>WPF DataGrid</strong> controls.</p> <p>I am subscribing to the <strong>ScrollChanged</strong> event of the first DataGrid:</p> <pre><code>&lt;toolkit:DataGrid x:Name="SourceGrid" ScrollViewer.ScrollChanged="SourceGrid_ScrollChanged"&gt; </code></pre> <p>I have a second DataGrid:</p> <pre><code>&lt;toolkit:DataGrid x:Name="TargetGrid"&gt; </code></pre> <p>In the event handler I was attempting to use the <strong><code>IScrollInfo.SetHorizontalOffset</code></strong>, but alas, DataGrid doesn't expose <code>IScrollInfo</code>:</p> <pre><code>private void SourceGrid_ScrollChanged(object sender, ScrollChangedEventArgs e) { ((IScrollInfo)TargetGrid).SetHorizontalOffset(e.HorizontalOffset); // cast to IScrollInfo fails } </code></pre> <p>Is there another way to accomplish this? Or is there another element on TargetGrid that exposes the necessary <code>IScrollInfo</code> to achieve the synchronization of the scroll positions?</p> <p>BTW, I am <strong>using frozen columns</strong>, so I cannot wrap both DataGrid controls with ScrollViewers.</p>
[ { "answer_id": 293766, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 1, "selected": false, "text": "ScrollViewer" }, { "answer_id": 17308608, "author": "JJ_Coder4Hire", "author_id": 1944063, "author_profile": "https://Stackoverflow.com/users/1944063", "pm_score": 1, "selected": false, "text": "<DataGrid.Resources>\n <Style TargetType=\"ScrollViewer\">\n <Setter Property=\"scroll:ScrollSynchronizer.ScrollGroup\" Value=\"Group1\" />\n </Style>\n</DataGrid.Resources>\n" }, { "answer_id": 21300932, "author": "mithocondria", "author_id": 2754083, "author_profile": "https://Stackoverflow.com/users/2754083", "pm_score": 1, "selected": false, "text": " public ScrollViewer Scroller { get; set; } // exposed ScrollViewer from the grid\n private bool _isFirstTimeLoaded = true; \n\n private void innerGridControl_ScrollChanged(object sender, ScrollChangedEventArgs e)\n {\n if (_isFirstTimeLoaded) // just to save the code from casting and assignment after 1st time loaded\n {\n var scroller = (e.OriginalSource) as ScrollViewer;\n Scroller = scroller;\n _isFirstTimeLoaded = false;\n }\n }\n <Views:innerGridView Grid.Row=\"1\" Margin=\"2,0,2,2\" DataContext=\"{Binding someCollection}\" \n x:Name=\"grid1Control\"\n ScrollViewer.ScrollChanged=\"Grid1Attached_ScrollChanged\"\n ></Views:innerGridView>\n\n<Views:innerGridView Grid.Row=\"3\" Margin=\"2,0,2,2\" DataContext=\"{Binding someCollection}\" \n x:Name=\"grid2Control\"\n ScrollViewer.ScrollChanged=\"Grid2Attached_ScrollChanged\"\n ></Views:innerGridView>\n private void Grid1Attached_ScrollChanged(object sender, ScrollChangedEventArgs e)\n {\n if (e != null && !e.Handled)\n {\n if (e.HorizontalChange != 0.0)\n {\n grid2Control.Scroller.ScrollToHorizontalOffset(e.HorizontalOffset);\n }\n e.Handled = true;\n }\n }\nprivate void Grid2Attached_ScrollChanged(object sender, ScrollChangedEventArgs e)\n {\n if (e != null && !e.Handled)\n {\n if (e.HorizontalChange != 0.0)\n {\n grid1Control.Scroller.ScrollToHorizontalOffset(e.HorizontalOffset);\n }\n e.Handled = true;\n }\n }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33272/" ]
293,276
<p>I have a custom security principal object which I set in the global.asax for the current thread and all is well, no problems normally.</p> <p>However, I'm just adding a dynamic image feature by having a page serve up the image and whenever that dynamic image page is loaded the System.Web.HttpContext.Current.Session is null in global.asax which prevents me from setting the security principal as normal and cascading problems from that point onwards.</p> <p>Normally the Session is null in global.asax only once during a session at the start when the user logs in, afterwards it's always available with this single exception.</p> <p>The dynamic image page is loaded when the browser comes across an image tage in the original page i.e. </p> <p>I'm guessing that this is some aspect of the fact that the browser is requesting that page without sending some credentials with it?</p> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 293354, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 6, "selected": true, "text": "public class Images : IHttpHandler, System.Web.SessionState.IRequiresSessionState\n{ }\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8939/" ]
293,285
<p>Basically I'm about to start work on a site and I'd like something that I can add into my .htaccess file (or elsewhere) that'll work like this pseudo code: (my ip will be in place of 127.0.0.1)</p> <pre><code>if (visitors_ip &lt;&gt; 127.0.0.1) redirectmatch ^(.*)$ http://www.example.com/under-construction.html </code></pre> <p>Hopefully that makes sense...</p>
[ { "answer_id": 293298, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 6, "selected": true, "text": "RewriteEngine On\nRewriteBase /\nRewriteCond %{REMOTE_ADDR} !^127\\.0\\.0\\.1\n\nRewriteCond %{REQUEST_URI} !/mypage\\.html$ \n\nRewriteRule .* http://www.anothersite.com/mypage.html [R=302,L]\n REMOTE_HOST REMOTE_ADDR REMOTE_HOST REMOTE_ADDR" }, { "answer_id": 296652, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 2, "selected": false, "text": "RewriteEngine On\nRewriteBase /\nRewriteCond %{REMOTE_HOST} !^127\\.0\\.0\\.1\nRewriteCond %{REQUEST_URI} !/coming-soon\\.html$ \nRewriteRule .* http://www.andrewgjohnson.com/coming-soon.html [R=302,L]\n" }, { "answer_id": 15993207, "author": "CoRe", "author_id": 2271906, "author_profile": "https://Stackoverflow.com/users/2271906", "pm_score": 2, "selected": false, "text": "<IfModule mod_rewrite.c>\nRewriteEngine On\n# Redirect all except allowed IP\nReWriteCond %{REMOTE_ADDR} !^000\\.000\\.000\\.001$\nRewriteCond %{REMOTE_ADDR} !000\\.000\\.000\\.002$\nReWriteCond %{REMOTE_ADDR} !^000\\.000\\.000\\.003$\nRewriteRule (.*) http://YourOtherWebsite.com/$1 [R=301,L] \n</IfModule>\n" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
293,300
<p>I'm having an error where I am not sure what caused it.</p> <p>Here is the error:</p> <pre><code>Exception Type: OperationalError Exception Value: (1054, "Unknown column 'user_id' in 'field list'") </code></pre> <p>Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. </p> <p>My view code is below:</p> <pre><code>if "login" in request.session: t = request.POST.get('title', '') d = request.POST.get('description', '') fid = request.session["login"] fuser = User.objects.get(id=fid) i = Idea(user=fuser, title=t, description=d, num_votes=1) i.save() return HttpResponse("true", mimetype="text/plain") else: return HttpResponse("false", mimetype="text/plain") </code></pre> <p>I appreciate any help! Thanks!</p> <p>Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?</p> <p>Edit: Here are the relevant models:</p> <pre><code>class User (models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=200) class Idea (models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=200) description = models.CharField(max_length=255) num_votes = models.IntegerField() </code></pre>
[ { "answer_id": 293335, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "user_id Idea User id id pk id pk" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
293,302
<p>I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I know I can do that with the test hooks, but I'm not sure that makes sense here.</p> <p>I'm not sure what this task should look like, how I can invoke it, or where it should go in my source tree (lib\tasks?).</p> <p>For example, here's my first try:</p> <pre><code>require 'active_record' require '../app/models/mymodel.rb' test = MyModel.new test.name = 'test' test.save </code></pre> <p>This fails because it can't get a connection to the database. This makes sense in a vague way to my newbie brain, since presumably Rails is doing all the magic work behind the scenes to set all that stuff up. So how do I set up my little script?</p>
[ { "answer_id": 293346, "author": "Hates_", "author_id": 3410, "author_profile": "https://Stackoverflow.com/users/3410", "pm_score": 1, "selected": false, "text": "ActiveRecord::Base.establish_connection(\n :adapter => \"mysql\",\n :username => \"root\",\n :host => \"localhost\",\n :password => \"******\",\n :database => \"******\" \n)\n" }, { "answer_id": 293372, "author": "Michael Larocque", "author_id": 3859, "author_profile": "https://Stackoverflow.com/users/3859", "pm_score": 2, "selected": false, "text": "namespace :foo do\n desc 'do something cool'\n def something_cool\n test = MyModel.new\n test.name = 'test'\n test.save\n end\nend\n $ rake -T foo\nrake foo:something_cool # do something cool\n" }, { "answer_id": 293491, "author": "csexton", "author_id": 19839, "author_profile": "https://Stackoverflow.com/users/19839", "pm_score": 4, "selected": false, "text": "require \"#{ENV['RAILS_ROOT']}/config/environment\" \n" }, { "answer_id": 293707, "author": "Tim Harding", "author_id": 38021, "author_profile": "https://Stackoverflow.com/users/38021", "pm_score": 4, "selected": true, "text": "namespace :send do\n namespace :trial do\n namespace :expiry do\n desc \"Sends out emails to people who's accounts are about to expire\"\n task :warnings => :environment do\n User.trial_about_to_expire.has_not_been_notified_of_trial_expiry.each do |user|\n UserMailer.deliver_trial_expiring_warning(user)\n user.notified_of_trial_expiry = true\n user.save\n end\n end\n end\n end\nend\n" }, { "answer_id": 300017, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 1, "selected": false, "text": "script/runner" }, { "answer_id": 31737915, "author": "Shaunak", "author_id": 726239, "author_profile": "https://Stackoverflow.com/users/726239", "pm_score": 0, "selected": false, "text": "rails g task my_namespace my_task lib/tasks/my_namespace.rake namespace :my_namespace do\ndesc \"TODO: Describe your task here\"\n task :my_task1 => :environment do\n #write any ruby code here and also work with your models\n puts User.find(1).name\n end\nend\n rake my_namespace:my_task" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
293,311
<p>What's the best method to pass parameters to SQLCommand? You can do:</p> <pre><code>cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "Bob"; </code></pre> <p>or</p> <pre><code>cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "Bob"; </code></pre> <p>or</p> <pre><code>cmd.Parameters.Add("@Name").Value = "Bob"; </code></pre> <p>It seems like the first one might be somehow "better" either performance-wise or error checking-wise. But I would like to know more definitively.</p>
[ { "answer_id": 293315, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 7, "selected": true, "text": "AddWithValue() cmd.Parameters.AddWithValue(\"@Name\", \"Bob\");\n" }, { "answer_id": 294978, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 6, "selected": false, "text": "Add SqlParameter SqlParameterCollection.Add(SqlParameter) SqlParameter foo = new SqlParameter(parameterName, dbType, size);\nthis.Add(foo);\n AddWithValue Add SqlParameterCollection.Add String SqlDbType SqlDbType AddWithValue SqlParameter Size AddWithValue AddWithValue" } ]
2008/11/16
[ "https://Stackoverflow.com/questions/293311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36400/" ]