qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
139,670
<p>In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.</p> <p>Eg:</p> <pre><code>insert into table values ('test1 test2 test3 test4'); </code></pre> <p>When I retrieve it, I get the message in a line </p> <p>test1 test2 test3 test4</p> <p>The carriage return is treated as a single character.</p> <p>Is there way to get the carriage returns or its just the way its going to be stored?</p> <p>Thanks for the help guys!!!</p> <p>Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.</p> <p>I return the data to the app development (C++) and may be some data or report viewer.</p> <p>I don't want to manipulate on the data.</p>
[ { "answer_id": 139701, "author": "Axeman", "author_id": 22108, "author_profile": "https://Stackoverflow.com/users/22108", "pm_score": 2, "selected": false, "text": "insert into table values ('test1' + chr(13) + chr(10) + 'test2' );\n" }, { "answer_id": 139706, "author": "Cirieno", "author_id": 17615, "author_profile": "https://Stackoverflow.com/users/17615", "pm_score": 0, "selected": false, "text": "<br />" }, { "answer_id": 139758, "author": "huo73", "author_id": 15657, "author_profile": "https://Stackoverflow.com/users/15657", "pm_score": 3, "selected": false, "text": "INSERT INTO table values('test1' + CHAR(10) + 'test2' + CHAR(10) + 'test3' + CHAR(10) + 'test4')\n" }, { "answer_id": 18869060, "author": "Mario", "author_id": 1018005, "author_profile": "https://Stackoverflow.com/users/1018005", "pm_score": 0, "selected": false, "text": " protected void Page_Load(object sender, EventArgs e)\n {\n String str = Request.QueryString[\"idNoticia\"];\n this.dsNewsDetails.FilterExpression = \"idNoticia=\" + str;\n }\n <asp:Label ID=\"BodyLabel\" \n runat=\"server\" style=\"font-size: medium\" \n Text='<%# Eval(\"body\").ToString().Replace(Environment.NewLine,\"<br/>\") %>' Width=\"100%\" />\n" }, { "answer_id": 47196096, "author": "Ankit Mahajan", "author_id": 4495887, "author_profile": "https://Stackoverflow.com/users/4495887", "pm_score": 0, "selected": false, "text": "Tools>Options>Query Results Ctrl+p" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21968/" ]
139,683
<p>I'm dealing with huge glassfish log files (in windows, eek!) and well ... Wordpad isn't cutting it. </p> <p>Are there any tools out there that can handle these log files in a more intelligent manner? Functionality that would be welcome:</p> <ul> <li>View all lines of a certain log level (info, warning, severe)</li> <li>Show logs between two timestamps</li> <li>Occurency counter (this exception was thrown 99 times between time x and time y)</li> </ul>
[ { "answer_id": 655675, "author": "fredarin", "author_id": 25038, "author_profile": "https://Stackoverflow.com/users/25038", "pm_score": 2, "selected": false, "text": "getline $ awk '/^java.*:\\W/ {print $1}' server.log* |sort|uniq -c|sort -nr\n 60 javax.ejb.EJBException:\n 45 java.rmi.ServerException:\n 2 javax.persistence.PersistenceException:\n 2 javax.ejb.ObjectNotFoundException:\n 1 java.lang.Error:\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18673/" ]
139,686
<p>The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification.</p> <p>It's easy to demonstrate in c that redundant initialisation is optimised out:</p> <pre><code>$ less test.c #include &lt;stdio.h&gt; main() { #ifdef INIT_LOC int a = 33; int b; memset(&amp;b,66,sizeof(b)); #else int a; int b; #endif a = 0; b = 0; printf ("a = %i, b = %i\n", a, b); } $ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) </code></pre> <p>[Not Optimised:]</p> <pre><code>$ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in it.s init.s 22a23,28 &gt; movl $33, -4(%ebp) &gt; movl $4, 8(%esp) &gt; movl $66, 4(%esp) &gt; leal -8(%ebp), %eax &gt; movl %eax, (%esp) &gt; call _memset 33a40 &gt; .def _memset; .scl 3; .type 32; .endef </code></pre> <p>[Optimised:]</p> <pre><code>$ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff no_init.s init.s $ </code></pre> <p>So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea?</p> <p>IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!)</p>
[ { "answer_id": 139731, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "ftime uninitialized time_t t;\ntime( &t );\n" }, { "answer_id": 139766, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": " float x = sqrt(0);\n" }, { "answer_id": 139806, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "my ($val1, $val2, $val3, $val4);\nprint $val1, \"\\n\";\nprint $val1 + 1, \"\\n\";\nprint $val2 + 2, \"\\n\";\nprint $val3 = $val3 . 'Hello, SO!', \"\\n\";\nprint ++$val4 +4, \"\\n\";\n [jeremy@localhost Code]$ ./undef.pl\n\n1\n2\nHello, SO!\n5\n my($x, $y, $z);\n my $x = 0;\n my $y = 0;\n my $z = 0;\n" }, { "answer_id": 139868, "author": "kervin", "author_id": 16549, "author_profile": "https://Stackoverflow.com/users/16549", "pm_score": 1, "selected": false, "text": "int i = 0;\nstruct myStruct m = {0};\n" }, { "answer_id": 139936, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": false, "text": "struct stat s;\ns.st_dev = -1;\ns.st_ino = -1;\ns.st_mode = S_IRWXU;\ns.st_nlink = 0;\ns.st_size = 0;\n// etc...\ns.st_st_ctime = -1;\nif(stat(path, &s) != 0) {\n // handle error\n return;\n}\n" }, { "answer_id": 140040, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 2, "selected": false, "text": " MyStuff // Initialize MyStuff instance y\n// ...\nMyStuff x = y;\n// ...\n MyStuff x(y);\n MyStuff x; // This calls the MyStuff default constructor.\nx = y; // This calls the MyStuff assignment operator.\n" }, { "answer_id": 140250, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "bool myVar;\n" }, { "answer_id": 140901, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 0, "selected": false, "text": "\nvoid func(int n)\n{\n int i = 0;\n\n ... // Many lines of code\n\n for (;i < n; i++)\n do_something(i);\n \nvoid func(int n)\n{\n int i = 0;\n\n for (i = 0; i < 3; i++)\n do_something_else(i);\n\n ... // Many lines of code\n\n for (;i < n; i++)\n do_something(i);\n" }, { "answer_id": 153289, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 0, "selected": false, "text": "void foo(int x)\n delete instance;\n\nreturn;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22640/" ]
139,739
<p>I've been doing a massive code review and one pattern I notice all over the place is this:</p> <pre><code>public bool MethodName() { bool returnValue = false; if (expression) { // do something returnValue = MethodCall(); } else { // do something else returnValue = Expression; } return returnValue; } </code></pre> <p>This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?</p> <p>I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.</p>
[ { "answer_id": 139754, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "\nreturn expression ? MethodCall() : Expression;\n" }, { "answer_id": 139788, "author": "Nenad Dobrilovic", "author_id": 22062, "author_profile": "https://Stackoverflow.com/users/22062", "pm_score": 1, "selected": false, "text": "return expression ? MethodCall() : Expression;\n" }, { "answer_id": 139797, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "function MethodName : boolean;\nbegin\n Result := False;\n if Expression then begin\n //do something\n Result := MethodCall;\n end\n else begin\n //do something else\n Result := Expression;\n end;\n\n //possibly more code\nend;\n" }, { "answer_id": 217592, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 1, "selected": false, "text": "if (node.next = null) return NO_VALUE_FOUND; if (listeners == null) return null; if (nodes[i].value == searchValue) return i; if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount(); result(s)" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
139,752
<p>I'm starting to get comfortable with the idea of fakes, stubs, mocks, and dynamic mocks. But I am still a little iffy in my understanding of when to use partial mocks. </p> <p>It would seem that if you're planning on mocking a service and need to resort to a partial mock then it is a sign of bad design. Is it that partial mocks are mostly for getting legacy code under test coverage?</p> <p>On the flip side of this, say I am testing a class which has a Reset() method. If I have already confirmed in a separate test that the Reset() method works, and I have some functionality of the class that should end with a call to this method, is it poor test design to do a partial mock of the object and run tests against the partial mock, defining an Expectation on the Reset() method. </p> <p>I currently have several tests set up in this manner, is this sort of thing going to get me in trouble later on?</p>
[ { "answer_id": 378720, "author": "James Mead", "author_id": 2025138, "author_profile": "https://Stackoverflow.com/users/2025138", "pm_score": 2, "selected": false, "text": "Reset Reset Reset" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
139,759
<p>Is there any way to list all the files that have changed between two tags in CVS?</p> <p>Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.</p> <p>It would also work if I could find all files that had changed between two dates.</p>
[ { "answer_id": 139871, "author": "Decio Lira", "author_id": 12423, "author_profile": "https://Stackoverflow.com/users/12423", "pm_score": 6, "selected": true, "text": "cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs\n RELEASE_1_0 RELEASE_1_1 ;)" }, { "answer_id": 139923, "author": "roomaroo", "author_id": 3464, "author_profile": "https://Stackoverflow.com/users/3464", "pm_score": 2, "selected": false, "text": "cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 | grep \"Index:\" > diffs\n" }, { "answer_id": 140164, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 1, "selected": false, "text": "cvs2cl.pl --delta dev_release_1_2_3:dev_release_1_6_8\n cvs2cl.pl --delta dev_release_1_2_3:HEAD\n" }, { "answer_id": 212972, "author": "Sally", "author_id": 6539, "author_profile": "https://Stackoverflow.com/users/6539", "pm_score": 5, "selected": false, "text": "rdiff -s cvs rdiff -s -r RELEASE_1_0 -r RELEASE_1_1 module > diffs\n rdiff -s" }, { "answer_id": 1622631, "author": "Taufiq", "author_id": 102076, "author_profile": "https://Stackoverflow.com/users/102076", "pm_score": 4, "selected": false, "text": "cvs -q log -NSR -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt\n -R cvs -q log -NS -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt\n V-1-0-69 V-1-0-70" }, { "answer_id": 2343054, "author": "Michael", "author_id": 48767, "author_profile": "https://Stackoverflow.com/users/48767", "pm_score": 4, "selected": false, "text": "cvs diff -N -c -D YYYY-MM-DD -D YYYY-MM-DD | grep \"Index:\" > diff.out\n" }, { "answer_id": 3222641, "author": "tkrille", "author_id": 388804, "author_profile": "https://Stackoverflow.com/users/388804", "pm_score": 3, "selected": false, "text": "cvs log -d \">=DATE\" -N -S -R > cvs.log\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
139,794
<p>Let's say we have <code>index.php</code> and it is stored in <code>/home/user/public/www</code> and <code>index.php</code> calls the class <code>Foo-&gt;bar()</code> from the file <code>inc/app/Foo.class.php</code>. </p> <p>I'd like the bar function in the <code>Foo</code> class to get a hold of the path <code>/home/user/public/www</code> in this instance — I don't want to use a global variable, pass a variable, etc.</p>
[ { "answer_id": 139830, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 4, "selected": false, "text": "class Foo {\n function bar() { \n $trace = debug_backtrace();\n echo \"calling file was \".$trace[0]['file'].\"\\n\";\n }\n}\n" }, { "answer_id": 139845, "author": "Philip Reynolds", "author_id": 1087, "author_profile": "https://Stackoverflow.com/users/1087", "pm_score": 2, "selected": false, "text": "getcwd() chdir() debug_backtrace()" }, { "answer_id": 139874, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 5, "selected": true, "text": "$dir=dirname($_SERVER[\"SCRIPT_FILENAME\"])\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ]
139,809
<p>I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?</p>
[ { "answer_id": 139886, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 5, "selected": true, "text": "ServiceHost ServiceHost ServiceHost MyService svc = new MyService();\nsvc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);\nServiceHost host = new ServiceHost(svc);\nhost.Open();\n" }, { "answer_id": 4295649, "author": "Pankaj Awasthi", "author_id": 522781, "author_profile": "https://Stackoverflow.com/users/522781", "pm_score": 0, "selected": false, "text": "using ...\nusing ...\n\nnamespace MyWCFNamespace\n{\n class Program {\n\n static void Main(string[] args){\n //instantiate the event receiver\n Consumer c = new Consumer();\n\n // instantiate the event source\n WCFService svc = new WCFService();\n svc.WCFEvent += new SomeEventHandler(c.ProcessTheRaisedEvent);\n\n using(ServiceHost host = new ServiceHost(svc))\n {\n host.Open();\n Console.Readline();\n }\n }\n }\n\n\n public class Consumer()\n {\n public void ProcessTheRaisedEvent(object sender, MyEventArgs e)\n {\n Console.WriteLine(e.From.toString() + \"\\t\" + e.To.ToString());\n }\n }\n}\n\n\nnamespace MyWCFNamespace\n{\n public delegate void SomeEventHandler(object sender,MyEventArgs e)\n\n [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]\n public class WCFService : IWCFService \n {\n public event SomeEventHandler WCFEvent;\n\n public void someMethod(Message message)\n {\n MyEventArgs e = new MyEventArgs(message);\n OnWCFEvent(e);\n }\n\n public void OnWCFEvent(MyEventArgs e)\n {\n SomeEventHandler handler = WCFEvent;\n if(handler!=null)\n {\n handler(this,e);\n }\n }\n\n // to do \n // Implement WCFInterface methods here\n }\n\n\n public class MyEventArgs:EventArgs\n {\n private Message _message;\n public MyEventArgs(Message message) \n {\n this._message=message;\n }\n }\n public class Message\n {\n string _from;\n string _to;\n public string From {get{return _from;} set {_from=value;}}\n public string To {get{return _to;} set {_to=value;}}\n public Message(){}\n public Message(string from,string to)\n this._from=from;\n this._to=to;\n }\n}\n InstanceContextMode = InstanceContextMode.Single TestService svc = new TestService();\nsvc.SomeEvent += new MyEventHandler(receivingObject.OnSomeEvent);\nServiceHost host = new ServiceHost(svc);\nhost.Open();\n\n[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] // so that a single service instance is created\n public class TestService : ITestService\n {\n public event MyEventHandler SomeEvent;\n ...\n ...\n }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8033/" ]
139,811
<p>What is an algorithm to compare multiple sets of numbers against a target set to determine which ones are the most "similar"?</p> <p>One use of this algorithm would be to compare today's hourly weather forecast against historical weather recordings to find a day that had similar weather.</p> <p>The similarity of two sets is a bit subjective, so the algorithm really just needs to diferentiate between good matches and bad matches. We have a lot of historical data, so I would like to try to narrow down the amount of days the users need to look through by automatically throwing out sets that aren't close and trying to put the "best" matches at the top of the list.</p> <p><strong>Edit</strong>: Ideally the result of the algorithm would be comparable to results using different data sets. For example using the mean square error as suggested by <a href="https://stackoverflow.com/questions/139811/algorithm-to-score-similarness-of-sets-of-numbers#139842">Niles</a> produces pretty good results, but the numbers generated when comparing the temperature can not be compared to numbers generated with other data such as Wind Speed or Precipitation because the scale of the data is different. Some of the non-weather data being is very large, so the mean square error algorithm generates numbers in the hundreds of thousands compared to the tens or hundreds that is generated by using temperature.</p>
[ { "answer_id": 140244, "author": "Adam Hughes", "author_id": 3863, "author_profile": "https://Stackoverflow.com/users/3863", "pm_score": 0, "selected": false, "text": "function calculate_score(historical_set, forecast_set)\n{\n double c = correlation(historical_set, forecast_set);\n double avg_history = average(historical_set);\n double avg_forecast = average(forecast_set);\n double penalty = abs(avg_history - avg_forecast) / avg_forecast\n return c - penalty;\n}\n" }, { "answer_id": 142046, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 1, "selected": false, "text": "for each historicalpoint\n\n distance = sqrt(\n pow(currentpoint.temp - historicalpoint.temp, 2) + \n pow(currentpoint.wind - historicalpoint.wind, 2) +\n pow(currentpoint.precip - historicalpoint.precip, 2))\n\n if distance is smaller than the largest distance in our match collection\n add historicalpoint to our match collection\n remove the match with the largest distance from our match collection\n\nnext\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3863/" ]
139,819
<p>The following test fails:</p> <pre><code>#!/usr/bin/env python def f(*args): """ &gt;&gt;&gt; t = 1, -1 &gt;&gt;&gt; f(*map(lambda i: lambda: i, t)) [1, -1] &gt;&gt;&gt; f(*(lambda: i for i in t)) # -&gt; [-1, -1] [1, -1] &gt;&gt;&gt; f(*[lambda: i for i in t]) # -&gt; [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__main__': import doctest; doctest.testmod() </code></pre> <p>In other words:</p> <pre><code>&gt;&gt;&gt; t = 1, -1 &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append(lambda: i) ... &gt;&gt;&gt; map(lambda a: a(), args) [-1, -1] &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append((lambda i: lambda: i)(i)) ... &gt;&gt;&gt; map(lambda a: a(), args) [1, -1] &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append(lambda i=i: i) ... &gt;&gt;&gt; map(lambda a: a(), args) [1, -1] </code></pre>
[ { "answer_id": 139880, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "lambda : i\n >>> f(*(lambda i=i: i for i in t)) # -> [-1, -1]\n[1, -1]\n>>> f(*[lambda i=i: i for i in t]) # -> [-1, -1]\n[1, -1]\n" }, { "answer_id": 139899, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": true, "text": "i f i t x = []\ni = 1 # 1. from t\nx.append(lambda: i)\ni = -1 # 2. from t\nx.append(lambda: i)\n i i i f(*[lambda u=i: u for i in t])\n i" }, { "answer_id": 141113, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "f = lambda: i def f():\n return i\n g = lambda i=i: i def g(i=i):\n return i\n i i i lambda i f(*(lambda: i for i in (1, -1)) # -> [-1, -1]\n i lambda i: ... f(*map(lambda i: lambda: i, (1,-1))) # -> [1, -1]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
139,821
<p>What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.</p>
[ { "answer_id": 139965, "author": "willem", "author_id": 22702, "author_profile": "https://Stackoverflow.com/users/22702", "pm_score": 2, "selected": false, "text": " <endpoint address=\"\" binding=\"webHttpBinding\" bindingConfiguration=\"\"\n contract=\"WcfCore.ICustomer\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n" }, { "answer_id": 140017, "author": "kgriffs", "author_id": 21784, "author_profile": "https://Stackoverflow.com/users/21784", "pm_score": 4, "selected": true, "text": "Factory=\"System.ServiceModel.Activation.WebServiceHostFactory\"\n" }, { "answer_id": 140047, "author": "Ta01", "author_id": 7280, "author_profile": "https://Stackoverflow.com/users/7280", "pm_score": 1, "selected": false, "text": "<services>\n <service name=\"SomeLib.SomeService\">\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8080/somebase\"/>\n </baseAddresses>\n </host>\n<!-- And one EndPoint **basicHttpBinding** WILL WORK !!! -->\n\n <endpoint \n address=\"basic\"\n binding=\"basicHttpBinding\"\n contract=\"SomeLib.SomeContract\"/>\n</service>\n</services>\n WebChannelFactory<IServiceContract> factory =\n new WebChannelFactory<IServiceContract>(\n new Uri(\"http://localhost:8080/somebase\"));\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
139,833
<p>I am using StringReplace to replace &amp;gt and &amp;lt by the char itself in a generated XML like this:</p> <pre><code>StringReplace(xml.Text,'&amp;gt;','&gt;',[rfReplaceAll]) ; StringReplace(xml.Text,'&amp;lt;','&lt;',[rfReplaceAll]) ; </code></pre> <p>The thing is it takes way tooo long to replace every occurence of &amp;gt.</p> <p>Do you purpose any better idea to make it faster?</p>
[ { "answer_id": 139876, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "String s = \"&lt;xml&gt;test&lt;/xml&gt;\";\nchar[] input = s.ToCharArray();\nchar[] res = new char[s.Length];\nint j = 0;\nfor (int i = 0, count = input.Length; i < count; ++i)\n{\n if (input[i] == '&')\n {\n if (i < count - 3)\n {\n if (input[i + 1] == 'l' || input[i + 1] == 'g')\n {\n if (input[i + 2] == 't' && input[i + 3] == ';')\n {\n res[j++] = input[i + 1] == 'l' ? '<' : '>';\n i += 3;\n continue;\n }\n }\n }\n }\n\n res[j++] = input[i];\n}\nConsole.WriteLine(new string(res, 0, j));\n <xml>test</xml>\n" }, { "answer_id": 140022, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "function ReplaceLtGt(const s: string): string;\nvar\n inPtr, outPtr: integer;\nbegin\n SetLength(Result, Length(s));\n inPtr := 1;\n outPtr := 1;\n while inPtr <= Length(s) do begin\n if (s[inPtr] = '&') and ((inPtr + 3) <= Length(s)) and\n (s[inPtr+1] in ['l', 'g']) and (s[inPtr+2] = 't') and\n (s[inPtr+3] = ';') then\n begin\n if s[inPtr+1] = 'l' then\n Result[outPtr] := '<'\n else\n Result[outPtr] := '>';\n Inc(inPtr, 3);\n end\n else begin\n Result[outPtr] := Result[inPtr];\n Inc(inPtr);\n end;\n Inc(outPtr);\n end;\n SetLength(Result, outPtr - 1);\nend;\n" }, { "answer_id": 142511, "author": "Bruce McGee", "author_id": 19183, "author_profile": "https://Stackoverflow.com/users/19183", "pm_score": 3, "selected": false, "text": "\"&lt;\" \"&gt;\" function TForm1.TestStringBuilder(const aString: string): string;\nvar\n sb: TStringBuilder;\nbegin\n StartTimer;\n sb := TStringBuilder.Create;\n sb.Append(aString);\n sb.Replace('&gt;', '>');\n sb.Replace('&lt;', '<');\n Result := sb.ToString();\n FreeAndNil(sb);\n StopTimer;\nend;\n\nfunction TForm1.TestStringReplace(const aString: string): string;\nbegin\n StartTimer;\n Result := StringReplace(aString,'&gt;','>',[rfReplaceAll]) ;\n Result := StringReplace(Result,'&lt;','<',[rfReplaceAll]) ;\n StopTimer;\nend;\n" }, { "answer_id": 41981197, "author": "rkawano", "author_id": 1293235, "author_profile": "https://Stackoverflow.com/users/1293235", "pm_score": 2, "selected": false, "text": "procedure ReplaceMultilineString(xml: TStrings);\nvar\n i: Integer;\n line: String;\nbegin\n for i:=0 to xml.Count-1 do\n begin\n line := xml[i];\n line := StringReplace(line, '&gt;', '>', [rfReplaceAll]);\n line := StringReplace(line, '&lt;', '<', [rfReplaceAll]);\n xml[i] := line;\n end;\nend;\n" }, { "answer_id": 52686169, "author": "dawood karimy", "author_id": 1647162, "author_profile": "https://Stackoverflow.com/users/1647162", "pm_score": 0, "selected": false, "text": " Function NewStringReplace(const S, OldPattern, NewPattern: string; Flags: TReplaceFlags): string;\nvar\n OldPat,Srch: string; // Srch and Oldp can contain uppercase versions of S,OldPattern\n PatLength,NewPatLength,P,i,PatCount,PrevP: Integer;\n c,d: pchar;\nbegin\n PatLength:=Length(OldPattern);\n if PatLength=0 then begin\n Result:=S;\n exit;\n end;\n\n if rfIgnoreCase in Flags then begin\n Srch:=AnsiUpperCase(S);\n OldPat:=AnsiUpperCase(OldPattern);\n end else begin\n Srch:=S;\n OldPat:=OldPattern;\n end;\n\n PatLength:=Length(OldPat);\n if Length(NewPattern)=PatLength then begin\n //Result length will not change\n Result:=S;\n P:=1;\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n for i:=1 to PatLength do\n Result[P+i-1]:=NewPattern[i];\n if not (rfReplaceAll in Flags) then exit;\n inc(P,PatLength);\n end;\n until p=0;\n end else begin\n //Different pattern length -> Result length will change\n //To avoid creating a lot of temporary strings, we count how many\n //replacements we're going to make.\n P:=1; PatCount:=0;\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n inc(P,PatLength);\n inc(PatCount);\n if not (rfReplaceAll in Flags) then break;\n end;\n until p=0;\n if PatCount=0 then begin\n Result:=S;\n exit;\n end;\n NewPatLength:=Length(NewPattern);\n SetLength(Result,Length(S)+PatCount*(NewPatLength-PatLength));\n P:=1; PrevP:=0;\n c:=pchar(Result); d:=pchar(S);\n repeat\n P:=PosEx(OldPat,Srch,P);\n if P>0 then begin\n for i:=PrevP+1 to P-1 do begin\n c^:=d^;\n inc(c); inc(d);\n end;\n for i:=1 to NewPatLength do begin\n c^:=NewPattern[i];\n inc(c);\n end;\n if not (rfReplaceAll in Flags) then exit;\n inc(P,PatLength);\n inc(d,PatLength);\n PrevP:=P-1;\n end else begin\n for i:=PrevP+1 to Length(S) do begin\n c^:=d^;\n inc(c); inc(d);\n end;\n end;\n until p=0;\n end;\nend;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
139,835
<p>I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.</p> <p>This form uses these styles:</p> <pre><code>this.SetStyle( ControlStyles.AllPaintingInWmPaint, true ); this.SetStyle( ControlStyles.UserPaint, true ); this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true ); this.SetStyle( ControlStyles.ResizeRedraw, true ); </code></pre> <p>And has these non-default property values:</p> <pre><code>this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; </code></pre> <p>I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.</p>
[ { "answer_id": 159897, "author": "Bill", "author_id": 14547, "author_profile": "https://Stackoverflow.com/users/14547", "pm_score": 4, "selected": true, "text": "GetWindowLong SetWindowLong OnHandleCreated using System.Runtime.InteropServices;\n\nprotected override void OnHandleCreated(EventArgs e) {\n uint dwWindowProperty;\n\n User32.SetParent(this.Handle, IntPtr.Zero);\n\n dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE );\n dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE;\n User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty );\n\n dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE );\n dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP; \n User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty );\n base.OnHandleCreated (e);\n}\n\n\n//this is a fragment of my User32 library wrapper needed for the previous code segment.\nclass User32 \n{\n [DllImport(\"user32.dll\", SetLastError = true)]\n static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]\n public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong); \n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]\n public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex );\n\n [FlagsAttribute] \n public enum WS: uint { \n POPUP = 0x80000000,\n CHILD = 0x40000000,\n }\n\n public enum GWL {\n STYLE = -16,\n EXSTYLE = -20\n }\n\n [FlagsAttribute]\n public enum WSEX: uint {\n TOP = 0x0,\n TOPMOST = 0x8,\n TOOLWINDOW = 0x80,\n NOACTIVATE = 0x08000000,\n }\n}\n SysMenu Caption" }, { "answer_id": 450149, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " protected override void WndProc( ref System.Windows.Forms.Message m )\n { // RightClickMenu\n if ( m.Msg == 0x313 )\n {\n this.contextMenuStrip1.Show(this, this.PointToClient(new Point(m.LParam.ToInt32())));\n }}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898/" ]
139,837
<p>I know it's possible, and I've seen simple examples in the documentation, but are they being used in the wild? </p> <p>I use attributes at the class and method level all the time, but have never used them on method parameters. What are some real-world examples, and the reasons for the usage?</p> <p>I'm not interested in seeing a textbook example, mind you. There are plenty of those out there. I want to see an actual reason why it solved a particular problem for you.</p> <p>EDIT: Let's place aside the discussion about whether or not to use attributes in the first place. I understand some people don't like them because they "dirty" their code. That's for a different discussion!</p>
[ { "answer_id": 140890, "author": "Kevin Dostalek", "author_id": 22732, "author_profile": "https://Stackoverflow.com/users/22732", "pm_score": 2, "selected": false, "text": " public class ShellController : ControllerBase, IShellController\n {\n public ShellController([StateDependency(\"State\")] StateValue<ShuttleState> state,\n [ServiceDependency] IHttpContextLocatorService contextLocator,\n [ServiceDependency] IAuthorizationService authService)\n : base(state, contextLocator, authService)\n {\n // code goes here\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ]
139,859
<p>On <strong>Linux/NPTL</strong>, threads are created as some kind of process.</p> <p>I can see some of my process have a weird cmdline:</p> <pre><code>cat /proc/5590/cmdline hald-addon-storage: polling /dev/scd0 (every 2 sec) </code></pre> <p>Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.</p> <p><em>/me now investigating in HAL source</em></p>
[ { "answer_id": 139935, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "argv #include <string.h>\n#include <unistd.h>\n\nint\nmain(int argc, char** argv)\n{\n strcpy(argv[0], \"Hello, world!\");\n sleep(10);\n return 0;\n}\n" }, { "answer_id": 139963, "author": "elmarco", "author_id": 1277510, "author_profile": "https://Stackoverflow.com/users/1277510", "pm_score": 0, "selected": false, "text": "memset (argv_buffer[0] + len, 0, argv_size - len);\nargv_buffer[1] = NULL;\n" }, { "answer_id": 140001, "author": "miguel.de.icaza", "author_id": 16929, "author_profile": "https://Stackoverflow.com/users/16929", "pm_score": 4, "selected": true, "text": "argv [0] exec -a \"This is my cute name\" bash\n \"This is my cute name\" sendmail setproctitle(3) argv [0]" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277510/" ]
139,867
<p>Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.</p>
[ { "answer_id": 140235, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 6, "selected": false, "text": "String[] countryCodes = Locale.getISOCountries();\n" }, { "answer_id": 2298525, "author": "Christophe Desguez", "author_id": 277209, "author_profile": "https://Stackoverflow.com/users/277209", "pm_score": 2, "selected": false, "text": " /**\n * This is the code used to generate the enum content\n */\n public static void main(String[] args) {\n String[] codes = java.util.Locale.getISOLanguages();\n for (String isoCode: codes) {\n Locale locale = new Locale(isoCode);\n System.out.println(isoCode.toUpperCase() + \"(\\\"\" + locale.getDisplayLanguage(locale) + \"\\\"),\");\n }\n }\n" }, { "answer_id": 3782185, "author": "Bozho", "author_id": 203907, "author_profile": "https://Stackoverflow.com/users/203907", "pm_score": 4, "selected": false, "text": "package countryenum;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Locale;\n\npublic class CountryEnumGenerator {\n public static void main(String[] args) {\n String[] countryCodes = Locale.getISOCountries();\n List<Country> list = new ArrayList<Country>(countryCodes.length);\n\n for (String cc : countryCodes) {\n list.add(new Country(cc.toUpperCase(), new Locale(\"\", cc).getDisplayCountry()));\n }\n\n Collections.sort(list);\n\n for (Country c : list) {\n System.out.println(\"/**\" + c.getName() + \"*/\");\n System.out.println(c.getCode() + \"(\\\"\" + c.getName() + \"\\\"),\");\n }\n\n }\n}\n\nclass Country implements Comparable<Country> {\n private String code;\n private String name;\n\n public Country(String code, String name) {\n super();\n this.code = code;\n this.name = name;\n }\n\n public String getCode() {\n return code;\n }\n\n\n public void setCode(String code) {\n this.code = code;\n }\n\n\n public String getName() {\n return name;\n }\n\n\n public void setName(String name) {\n this.name = name;\n }\n\n\n @Override\n public int compareTo(Country o) {\n return this.name.compareTo(o.name);\n }\n}\n" }, { "answer_id": 8264635, "author": "bruno.braga", "author_id": 1015901, "author_profile": "https://Stackoverflow.com/users/1015901", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python\nf = open(\"data.txt\", 'r')\ndata = []\ncc = {}\n\nfor l in f:\n t = l.split('\\t')\n cc = { 'code': str(t[0]).strip(), \n 'name': str(t[1]).strip()\n }\n data.append(cc)\nf.close()\n\nfor c in data:\n print \"\"\"\n/**\n * Defines the <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a> \n * for <b><i>%(name)s</i></b>.\n * <p>\n * This constant holds the value of <b>{@value}</b>.\n *\n * @since 1.0\n *\n */\n public static final String %(code)s = \\\"%(code)s\\\";\"\"\" % c\n /**\n * Holds <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a>\n * constant values for all countries. \n * \n * @since 1.0\n * \n * </p>\n */\npublic class CountryCode {\n\n /**\n * Constructor defined as <code>private</code> purposefully to ensure this \n * class is only used to access its static properties and/or methods. \n */\n private CountryCode() { }\n\n /**\n * Defines the <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\">ISO_3166-1_alpha-2</a> \n * for <b><i>Andorra</i></b>.\n * <p>\n * This constant holds the value of <b>{@value}</b>.\n *\n * @since 1.0\n *\n */\n public static final String AD = \"AD\";\n\n //\n // and the list goes on! ...\n //\n}\n" }, { "answer_id": 11084479, "author": "Takahiko Kawasaki", "author_id": 1174054, "author_profile": "https://Stackoverflow.com/users/1174054", "pm_score": 7, "selected": false, "text": "CountryCode cc = CountryCode.getByCode(\"JP\");\n\nSystem.out.println(\"Country name = \" + cc.getName()); // \"Japan\"\nSystem.out.println(\"ISO 3166-1 alpha-2 code = \" + cc.getAlpha2()); // \"JP\"\nSystem.out.println(\"ISO 3166-1 alpha-3 code = \" + cc.getAlpha3()); // \"JPN\"\nSystem.out.println(\"ISO 3166-1 numeric code = \" + cc.getNumeric()); // 392\n <dependency>\n <groupId>com.neovisionaries</groupId>\n <artifactId>nv-i18n</artifactId>\n <version>1.29</version>\n</dependency>\n dependencies {\n compile 'com.neovisionaries:nv-i18n:1.29'\n}\n Bundle-SymbolicName: com.neovisionaries.i18n\nExport-Package: com.neovisionaries.i18n;version=\"1.28.0\"\n" }, { "answer_id": 19428277, "author": "sskular", "author_id": 1158832, "author_profile": "https://Stackoverflow.com/users/1158832", "pm_score": 3, "selected": false, "text": "private HashMap<String, String> countries = new HashMap<String, String>();\nString[] countryCodes = Locale.getISOCountries();\n\nfor (String cc : countryCodes) {\n // country name , country code map\n countries.put(new Locale(\"\", cc).getDisplayCountry(), cc.toUpperCase());\n}\n" }, { "answer_id": 33394455, "author": "abdielou", "author_id": 3984100, "author_profile": "https://Stackoverflow.com/users/3984100", "pm_score": 2, "selected": false, "text": "com.amazonaws.services.route53domains.model.CountryCode nv-i18n" }, { "answer_id": 46319693, "author": "Hervian", "author_id": 6095334, "author_profile": "https://Stackoverflow.com/users/6095334", "pm_score": 0, "selected": false, "text": "getLocale() public enum Country{\n\n ANDORRA(new Locale(\"AD\")),\n AFGHANISTAN(new Locale(\"AF\")),\n ANTIGUA_AND_BARBUDA(new Locale(\"AG\")),\n ANGUILLA(new Locale(\"AI\")),\n //etc\n ZAMBIA(new Locale(\"ZM\")),\n ZIMBABWE(new Locale(\"ZW\"));\n\n private Locale locale;\n\n private Country(Locale locale){\n this.locale = locale;\n }\n\n public Locale getLocale(){\n return locale;\n }\n" }, { "answer_id": 71560055, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 0, "selected": false, "text": "java.util.Locale.IsoCountryCode" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12531/" ]
139,884
<p>Google results on this one are a bit thin, but suggest that it is not easily possible.</p> <p>My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables.</p> <p>I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't.</p> <p>Thanks!</p>
[ { "answer_id": 139943, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 5, "selected": true, "text": "DEFERRABLE CREATE TABLE" }, { "answer_id": 139960, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 3, "selected": false, "text": "alter table drop constraint alter table add constraint" }, { "answer_id": 2740017, "author": "zzzeek", "author_id": 34549, "author_profile": "https://Stackoverflow.com/users/34549", "pm_score": 3, "selected": false, "text": "pg_get_constraintdef class no_constraints(object):\n def __init__(self, connection):\n self.connection = connection\n\n def __enter__(self):\n self.transaction = self.connection.begin()\n try:\n self._drop_constraints()\n except:\n self.transaction.rollback()\n raise\n\n def __exit__(self, exc_type, exc_value, traceback):\n if exc_type is not None:\n self.transaction.rollback()\n else:\n try:\n self._create_constraints()\n self.transaction.commit()\n except:\n self.transaction.rollback()\n raise\n\n def _drop_constraints(self):\n self._constraints = self._all_constraints()\n\n for schemaname, tablename, name, def_ in self._constraints:\n self.connection.execute('ALTER TABLE \"%s.%s\" DROP CONSTRAINT %s' % (schemaname, tablename, name))\n\n def _create_constraints(self):\n for schemaname, tablename, name, def_ in self._constraints:\n self.connection.execute('ALTER TABLE \"%s.%s\" ADD CONSTRAINT %s %s' % (schamename, tablename, name, def_))\n\n def _all_constraints(self):\n return self.connection.execute(\"\"\"\n SELECT n.nspname AS schemaname, c.relname, conname, pg_get_constraintdef(r.oid, false) as condef\n FROM pg_constraint r, pg_class c\n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE r.contype = 'f'\n and r.conrelid=c.oid\n \"\"\").fetchall()\n\nif __name__ == '__main__':\n # example usage\n\n from sqlalchemy import create_engine\n\n engine = create_engine('postgresql://user:pass@host/dbname', echo=True)\n\n conn = engine.connect()\n with no_contraints(conn):\n r = conn.execute(\"delete from table1\")\n print \"%d rows affected\" % r.rowcount\n r = conn.execute(\"delete from table2\")\n print \"%d rows affected\" % r.rowcount\n" }, { "answer_id": 10794952, "author": "Dimitris", "author_id": 426399, "author_profile": "https://Stackoverflow.com/users/426399", "pm_score": 5, "selected": false, "text": "SELECT 'ALTER TABLE \"'||nspname||'\".\"'||relname||'\" DROP CONSTRAINT \"'||conname||'\";'\nFROM pg_constraint \nINNER JOIN pg_class ON conrelid=pg_class.oid \nINNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace \nORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname\n SELECT 'ALTER TABLE \"'||nspname||'\".\"'||relname||'\" ADD CONSTRAINT \"'||conname||'\" '|| pg_get_constraintdef(pg_constraint.oid)||';'\nFROM pg_constraint\nINNER JOIN pg_class ON conrelid=pg_class.oid\nINNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace\nORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END DESC,contype DESC,nspname DESC,relname DESC,conname DESC;\n" }, { "answer_id": 30055131, "author": "Sean the Bean", "author_id": 814160, "author_profile": "https://Stackoverflow.com/users/814160", "pm_score": 0, "selected": false, "text": "DEFERRABLE BEGIN;\n\nSET CONSTRAINTS\n table_1_parent_id_foreign, \n table_2_parent_id_foreign,\n -- etc\nDEFERRED;\n\n-- do all your renumbering\n\nCOMMIT;\n NOT DEFERRABLE DEFERRABLE ALTER TABLE table_1 ALTER CONSTRAINT table_1_parent_id_foreign DEFERRABLE;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22715/" ]
139,889
<p>I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with <a href="http://httpd.apache.org/docs/2.0/mod/core.html#serveralias" rel="noreferrer">ServerAlias</a>) or do I <a href="http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect" rel="noreferrer">Redirect</a> the request? </p> <p>Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used?</p> <p>Common vhost examples will have:</p> <pre><code>ServerName example.net ServerAlias www.example.net </code></pre> <p>Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site?</p> <p>UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load.</p> <p>UPDATE and ANSWER: Thanks Paul for finding the <a href="http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html" rel="noreferrer">Google link</a> which instructs us to "help your fellow webmasters by <strong>not</strong> perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&amp;brand=riedell or www.example.com/skates.asp?brand=riedell&amp;color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."</p>
[ { "answer_id": 139911, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 6, "selected": true, "text": "RewriteCond %{HTTP_HOST} !^www\\.foobar\\.com [NC]\nRewriteCond %{HTTP_HOST} !^$\nRewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15948/" ]
139,891
<p>This question is not so much programming related as it is deployment related.</p> <p>I find myself conversing a lot with the group in my company whose job it is to maintain our production Windows servers and deploy our code on them. For legal and compliance reasons, I do not have direct visibility or any control over the servers so the only way I can tell which version(s) of .NET are installed on any of them is through directions I give to that group. </p> <p>So far, all of the methods I can think of to tell which version(s) are installed (check for Administrative Tools matching 1.1 or 2.0, check for the entries in the "Add/Remove Programs" list, check for the existence of the directories under c:\Windows\Microsoft.NET) are flawed (I've seen at least one machine with 2.0 but no 2.0 entries under Administrative Tools - and that method tells you nothing about 3.0+, the "Add/Remove Programs" list can get out of sync with reality, and the existence of the directories doesn't necessarily mean anything).</p> <p>Given that I generally need to know these things are in place in advance (discovering that "oops, this one doesn't have all the versions and service packs you need" doesn't really work well with short maintenance windows) and I have to do the checking "by proxy" since I can't get on the servers directly, what's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server? Preferably some intrinsic way to do so using what the framework installs since it will be quicker and not need some sort of utility to be loaded and also a method which will definitely fail if the frameworks are not properly installed but still have files in place (i.e., there's a directory and gacutil.exe is inded there but that version of the framework is not really "installed")</p> <p><strong>EDIT:</strong> In the absence of a good foolproof intrinsic way to do this built into the Framework(s), does anyone know of a good, lightweight, no-install-required program that can find this out? I can imagine someone could easily write one but if one already exists, that would be even better.</p>
[ { "answer_id": 139912, "author": "Dean", "author_id": 11802, "author_profile": "https://Stackoverflow.com/users/11802", "pm_score": 0, "selected": false, "text": "<root>:\\WINDOWS\\Microsoft.NET\\Framework v2.0.50727" }, { "answer_id": 139916, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 5, "selected": false, "text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\...]\n" }, { "answer_id": 140041, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 4, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\..." }, { "answer_id": 140816, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 2, "selected": false, "text": "CLRVer.exe" }, { "answer_id": 499483, "author": "Bruno Costa", "author_id": 40077, "author_profile": "https://Stackoverflow.com/users/40077", "pm_score": 0, "selected": false, "text": "MSCorEE.dll %SystemRoot%\\System32" }, { "answer_id": 2693608, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)\n{\n DWORD dwHandle;\n DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);\n if (dwLen) {\n LPBYTE lpData = new BYTE[dwLen];\n if (lpData) {\n if (GetFileVersionInfo(filename,0,dwLen,lpData)) {\n UINT uLen; \n VS_FIXEDFILEINFO *lpBuffer; \n VerQueryValue(lpData,_T(\"\\\\\"),(LPVOID*)&lpBuffer,&uLen); \n *majorPart = HIWORD(lpBuffer->dwFileVersionMS);\n *minorPart = LOWORD(lpBuffer->dwFileVersionMS);\n *buildPart = HIWORD(lpBuffer->dwFileVersionLS);\n *privatePart = LOWORD(lpBuffer->dwFileVersionLS);\n delete[] lpData;\n return true;\n }\n }\n }\n return false;\n}\n\nint _tmain(int argc,_TCHAR* argv[])\n{\n _TCHAR filename[MAX_PATH];\n _TCHAR frameworkroot[MAX_PATH];\n if (!GetEnvironmentVariable(_T(\"systemroot\"),frameworkroot,MAX_PATH))\n return 1;\n _tcscat_s(frameworkroot,_T(\"\\\\Microsoft.NET\\\\Framework\\\\*\"));\n WIN32_FIND_DATA FindFileData;\n HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);\n if (hFind == INVALID_HANDLE_VALUE)\n return 2;\n do {\n if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&\n _tcslen(FindFileData.cAlternateFileName) != 0) {\n _tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);\n filename[_tcslen(frameworkroot)] = 0;\n _tcscat_s(filename,FindFileData.cFileName);\n _tcscat_s(filename,_T(\"\\\\mscorlib.dll\"));\n WORD majorPart,minorPart,buildPart,privatePart;\n if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {\n _tprintf(_T(\"%d.%d.%d.%d\\r\\n\"),majorPart,minorPart,buildPart,privatePart);\n }\n }\n } while (FindNextFile(hFind,&FindFileData) != 0);\n FindClose(hFind);\n return 0;\n}\n" }, { "answer_id": 3088319, "author": "anon", "author_id": 372548, "author_profile": "https://Stackoverflow.com/users/372548", "pm_score": 1, "selected": false, "text": "mscorlib.dll mscorlib.dll" }, { "answer_id": 18791843, "author": "K.Dias", "author_id": 2777342, "author_profile": "https://Stackoverflow.com/users/2777342", "pm_score": 4, "selected": false, "text": "dir %WINDIR%\\Microsoft.Net\\Framework\\v*\n dir %WINDIR%\\Microsoft.Net\\Framework\\v* /O:-N /B\n" }, { "answer_id": 20291190, "author": "Ronnie Petty", "author_id": 3050316, "author_profile": "https://Stackoverflow.com/users/3050316", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Security.Permissions;\nusing Microsoft.Win32;\n\nnamespace findNetVersion\n{\n class Program\n {\n static void Main(string[] args)\n {\n using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,\n RegistryView.Registry32).OpenSubKey(@\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\\"))\n {\n foreach (string versionKeyName in ndpKey.GetSubKeyNames())\n {\n if (versionKeyName.StartsWith(\"v\"))\n {\n\n RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);\n string name = (string)versionKey.GetValue(\"Version\", \"\");\n string sp = versionKey.GetValue(\"SP\", \"\").ToString();\n string install = versionKey.GetValue(\"Install\", \"\").ToString();\n if (install == \"\") //no install info, must be later version\n Console.WriteLine(versionKeyName + \" \" + name);\n else\n {\n if (sp != \"\" && install == \"1\")\n {\n Console.WriteLine(versionKeyName + \" \" + name + \" SP\" + sp);\n }\n }\n if (name != \"\")\n {\n continue;\n }\n foreach (string subKeyName in versionKey.GetSubKeyNames())\n {\n RegistryKey subKey = versionKey.OpenSubKey(subKeyName);\n name = (string)subKey.GetValue(\"Version\", \"\");\n if (name != \"\")\n sp = subKey.GetValue(\"SP\", \"\").ToString();\n install = subKey.GetValue(\"Install\", \"\").ToString();\n if (install == \"\") //no install info, ust be later\n Console.WriteLine(versionKeyName + \" \" + name);\n else\n {\n if (sp != \"\" && install == \"1\")\n {\n Console.WriteLine(\" \" + subKeyName + \" \" + name + \" SP\" + sp);\n }\n else if (install == \"1\")\n {\n Console.WriteLine(\" \" + subKeyName + \" \" + name);\n }\n }\n }\n }\n }\n }\n }\n }\n}\n private static void Get45or451FromRegistry()\n{\n using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,\n RegistryView.Registry32).OpenSubKey(@\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\\"))\n {\n int releaseKey = (int)ndpKey.GetValue(\"Release\");\n {\n if (releaseKey == 378389)\n\n Console.WriteLine(\"The .NET Framework version 4.5 is installed\");\n\n if (releaseKey == 378758)\n\n Console.WriteLine(\"The .NET Framework version 4.5.1 is installed\");\n\n }\n }\n}\n" }, { "answer_id": 23937734, "author": "dave_k_smith", "author_id": 874824, "author_profile": "https://Stackoverflow.com/users/874824", "pm_score": 1, "selected": false, "text": "using System.Web.Mvc;\n\nnamespace DotnetVersionTest.Controllers\n{\n public class DefaultController : Controller\n {\n public string Index()\n {\n return \"simple .NET version test...\";\n }\n }\n}\n targetFramework <system.web>\n <customErrors mode=\"Off\"/>\n <compilation debug=\"true\" targetFramework=\"4.5.2\"/>\n <httpRuntime targetFramework=\"4.5.2\"/>\n</system.web>\n <app deploy URL>/Default" }, { "answer_id": 39913068, "author": "Metallic Skeleton", "author_id": 4002198, "author_profile": "https://Stackoverflow.com/users/4002198", "pm_score": 1, "selected": false, "text": "using Microsoft.Win32;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication2\n{\n public class GetDotNetVersion\n {\n public static void Get45PlusFromRegistry()\n {\n const string subkey = @\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\\";\n using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))\n {\n if (ndpKey != null && ndpKey.GetValue(\"Release\") != null)\n {\n Console.WriteLine(\".NET Framework Version: \" + CheckFor45PlusVersion((int)ndpKey.GetValue(\"Release\")));\n }\n else\n {\n Console.WriteLine(\".NET Framework Version 4.5 or later is not detected.\");\n }\n }\n }\n\n // Checking the version using >= will enable forward compatibility.\n private static string CheckFor45PlusVersion(int releaseKey)\n {\n if (releaseKey >= 394802)\n return \"4.6.2 or later\";\n if (releaseKey >= 394254)\n {\n return \"4.6.1\";\n }\n if (releaseKey >= 393295)\n {\n return \"4.6\";\n }\n if ((releaseKey >= 379893))\n {\n return \"4.5.2\";\n }\n if ((releaseKey >= 378675))\n {\n return \"4.5.1\";\n }\n if ((releaseKey >= 378389))\n {\n return \"4.5\";\n }\n // This code should never execute. A non-null release key shoul\n // that 4.5 or later is installed.\n return \"No 4.5 or later version detected\";\n }\n }\n // Calling the GetDotNetVersion.Get45PlusFromRegistry method produces \n // output like the following:\n // .NET Framework Version: 4.6.1\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
139,909
<p>I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0</p>
[ { "answer_id": 139917, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 4, "selected": true, "text": "-Djava.net.preferIPv4Stack=true\n" }, { "answer_id": 20336403, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 0, "selected": false, "text": "java.net.preferIPv4Stack=true ret := dbms_java.set_property('java.net.preferIPv4Stack','true');\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
139,921
<p>I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application). I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed. When I try this the page reloads (the action is #) but any new text typed in the fields is not passed in the REQUEST, so I don't get to put it in the DB. Is there some fundamental reason why this happens or is my code just not playing nice together (I'm using the EXTJS grid view to show the form and a library for tracking idle time)? Thanks, Robert</p>
[ { "answer_id": 140035, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<form action=\"/page.cgi\">\n ...\n <input name=\"Fieldx\" value=\"\"/>\n</form>\n <input name=\"Fieldx\" value=\"#{bean.nullProperty}\"/>\n" }, { "answer_id": 140065, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 0, "selected": false, "text": "submit HTMLFormElement action # method get post" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22719/" ]
139,926
<p>I was writing some Unit tests last week for a piece of code that generated some SQL statements.</p> <p>I was trying to figure out a regex to match <code>SELECT</code>, <code>INSERT</code> and <code>UPDATE</code> syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.</p> <p>I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.</p> <p>Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.</p> <p>By the way it's C# RegEx that I'm after.</p> <p><strong>Clarification</strong></p> <p>I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.</p>
[ { "answer_id": 139959, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": ".\\* [^\"]* \\" }, { "answer_id": 140094, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "select * from non_existant_table;\n select * frm non_existant_table;\n" }, { "answer_id": 35067789, "author": "jebabli ilyes", "author_id": 5475332, "author_profile": "https://Stackoverflow.com/users/5475332", "pm_score": -1, "selected": false, "text": "public bool IsValid(string sql)\n{\nstring pattern = @\"SELECT\\s.*FROM\\s.*WHERE\\s.*\";\nRegex rgx = new Regex(pattern, RegexOptions.IgnoreCase);\nreturn rgx.IsMatch(sql);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
139,927
<p>I have several projects where I need to append strings to a BSTR/CComBSTR/_bstr_t object (e.g. building a dynamic SQL statement). Is there an out-of-the-box type in the WinAPI to buffer the concatenation (like StringBuilder in .NET), or do I have to write my own? From what I know about the append methods, they perform re-allocation.</p>
[ { "answer_id": 139959, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": ".\\* [^\"]* \\" }, { "answer_id": 140094, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 0, "selected": false, "text": "select * from non_existant_table;\n select * frm non_existant_table;\n" }, { "answer_id": 35067789, "author": "jebabli ilyes", "author_id": 5475332, "author_profile": "https://Stackoverflow.com/users/5475332", "pm_score": -1, "selected": false, "text": "public bool IsValid(string sql)\n{\nstring pattern = @\"SELECT\\s.*FROM\\s.*WHERE\\s.*\";\nRegex rgx = new Regex(pattern, RegexOptions.IgnoreCase);\nreturn rgx.IsMatch(sql);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133/" ]
139,948
<p>I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.</p> <p>How can this be accomplished? Ive included a sample of my current code below.</p> <p>sample.aspx</p> <pre><code>&lt;asp:textbox id=foo runat=server /&gt; &lt;asp:requiredfieldvalidator id=val runat=server controltovalidate=foo /&gt; &lt;asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') /&gt; </code></pre> <p>sample.aspx.vb</p> <pre><code>Sub Page_Load() If Page.IsPostback() Then Page.Validate() If Page.IsValid Then 'process page here' End If End If End Sub </code></pre> <p>Thanks for any help.</p>
[ { "answer_id": 490584, "author": "cofiem", "author_id": 31567, "author_profile": "https://Stackoverflow.com/users/31567", "pm_score": 3, "selected": false, "text": "confirm onclick confirm <asp:Button ID=\"btnSubmit\" runat=\"server\" Text=\"Submit\" OnClientClick=\"if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}\" CausesValidation=\"false\" />\n" }, { "answer_id": 10314013, "author": "Aniruddha Ghosh", "author_id": 1355916, "author_profile": "https://Stackoverflow.com/users/1355916", "pm_score": 0, "selected": false, "text": "function validate()\n{\n Page_ClientValidate();\n if (Page_IsValid)\n // do your processing here\n\n return Page_IsValid;\n}\n protected void SubmitButton_Click(object sender, EventArgs e) \n{ \n if (!this.isValid)\n return;\n\n // do the processing here\n}\n" }, { "answer_id": 17341235, "author": "Raghubir Singh", "author_id": 1049297, "author_profile": "https://Stackoverflow.com/users/1049297", "pm_score": 2, "selected": false, "text": " <asp:Button ID=\"btnSave\" runat=\"server\" OnClientClick=\"javascript:return ConfirmSubmit()\" OnClick=\"btnSave_Click\" Text=\"Save\" /> \n\n\n//---javascript -----\nfunction ConfirmSubmit()\n{\n Page_ClientValidate();\n if(Page_IsValid) {\n return confirm('Are you sure?');\n }\n return Page_IsValid;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
139,954
<p>I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.</p> <p>Basically, i have an URL like /products.aspx?categoryid=foo&amp;productid=bar</p> <p>Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.</p> <p>But i need to map it to /products/foo/bar. (without "category")</p> <p>Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)</p> <p>P.S. Sorry for my bad English.</p>
[ { "answer_id": 139986, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "routes.MapRoute(\"productsByCategory\", \"products/{category}/{productid}\",\n new { controller=\"products\", action=\"findByCategory\" })\n products/foo/bar public class ProductsController : Controller\n{\n ...\n\n public ActionResult FindByCategory(string category, string productid)\n {\n ....\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19610/" ]
139,964
<p>Does anyone have a method to overcome the 260 character limit of the MSBuild tool for building Visual Studio projects and solutions from the command line? I'm trying to get the build automated using CruiseControl (CruiseControl.NET isn't an option, so I'm trying to tie it into normal ant scripts) and I keep on running into problems with the length of the paths. To clarify, the problem is in the length of paths of projects referenced in the solution file, as the tool doesn't collapse paths down properly :(</p> <p>I've also tried using DevEnv which sometimes works and sometimes throws an exception, which isn't good for an automated build on a separate machine. So please don't suggest using this as a replacement.</p> <p>And to top it all, the project builds fine when using Visual Studio through the normal IDE.</p>
[ { "answer_id": 9635709, "author": "doomer", "author_id": 423665, "author_profile": "https://Stackoverflow.com/users/423665", "pm_score": 3, "selected": false, "text": "<BaseIntermediateOutputPath>$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)\\..\\..\\..\\Intermediate\\$(AssemblyName)_$(ProjectGuid)\\'))</BaseIntermediateOutputPath>\n" }, { "answer_id": 18742450, "author": "kmort", "author_id": 309502, "author_profile": "https://Stackoverflow.com/users/309502", "pm_score": 0, "selected": false, "text": "msbuild msbuild vcvarsall.bat msbuild The input line is too long. msbuild cmd.exe" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16035/" ]
139,972
<p>Kind of a newbie question, but I am having problems using SNVKit. </p> <p>I am using SVNKit in an application to commit changes to files. I have it successfully adding the files and folders to the working copy, but I am having problems committing it to the respository.</p> <p>The command I am trying to run is 'commit -m "Test Add" /svnroot/project1/' but I keep getting "svn: '/home/user' is not a working copy"</p> <p>I have a structure similar to this:</p> <ul> <li>/svnroot/</li> <li>/svnroot/project1/</li> <li>/svnroot/project1/grouping1/</li> <li>/svnroot/project1/grouping1/myfilesarehere</li> </ul> <p>If I try to commit the file, I get the following message: "'/svnroot/project1/grouping1' is not under version control and is not part of the commit, yet its child is part of the commit."</p> <p>What might I be doing wrong?</p> <p>EDIT: Fixed the directories.</p>
[ { "answer_id": 140116, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 1, "selected": false, "text": "import checkout add commit -m \"message\"" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
139,979
<p>I have a C# interface with certain method parameters declared as <code>object</code> types. However, the actual type passed around can differ depending on the class implementing the interface:</p> <pre><code>public interface IMyInterface { void MyMethod(object arg); } public class MyClass1 : IMyInterface { public void MyMethod(object arg) { MyObject obj = (MyObject) arg; // do something with obj... } } public class MyClass2 : IMyInterface { public void MyMethod(object arg) { byte[] obj = (byte[]) arg; // do something with obj... } } </code></pre> <p>The problem with MyClass2 is that the conversion of <code>byte[]</code> to and from <code>object</code> is <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx" rel="noreferrer">boxing and unboxing</a>, which are computationally expensive operations affecting performance.</p> <p>Would solving this problem with a <a href="http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx" rel="noreferrer">generic interface</a> avoid boxing/unboxing?</p> <pre><code>public interface IMyInterface&lt;T&gt; { void MyMethod(T arg); } public class MyClass1 : IMyInterface&lt;MyObject&gt; { public void MyMethod(MyObject arg) { // typecast no longer necessary //MyObject obj = (MyObject) arg; // do something with arg... } } public class MyClass2 : IMyInterface&lt;byte[]&gt; { public void MyMethod(byte[] arg) { // typecast no longer necessary //byte[] obj = (byte[]) arg; // do something with arg... } } </code></pre> <p>How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?</p> <p>Thank you!</p>
[ { "answer_id": 176441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " void Bla<T> (T a, T b);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2576/" ]
139,991
<p>I have two functions, <code>f</code> and <code>g</code>, which call each other recursively. Unfortunately, when <code>f</code> calls <code>g</code>, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?</p>
[ { "answer_id": 140386, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "and fun" }, { "answer_id": 140405, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 4, "selected": true, "text": "and fun f x = ... \nand g x = ...\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/139991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10307/" ]
140,002
<p>I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.</p> <p>Here is the relevant part of my function:</p> <pre><code>Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuff End Function </code></pre> <p>How do I call this function and use the returned dictionary?</p> <p>EDIT: I've tried this:</p> <pre><code>Dim someStuff someStuff = GetSomeStuff </code></pre> <p>and</p> <pre><code>Dim someStuff Set someStuff = GetSomeStuff </code></pre> <p>When I try to access someStuff, I get an error:</p> <pre><code>Microsoft VBScript runtime error: Object required: 'GetSomeStuff' </code></pre> <p>EDIT 2: Trying this in the function:</p> <pre><code>Set GetSomeStuff = stuff </code></pre> <p>Results in this error:</p> <pre><code>Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment. </code></pre>
[ { "answer_id": 140064, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "Dim returnedStuff\nSet returnedStuff = GetSomeStuff()\n" }, { "answer_id": 140141, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "\nset GetSomeStuff = stuff" }, { "answer_id": 140163, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": true, "text": "set Function GetSomeStuff\n Dim stuff\n Set stuff = CreateObject(\"Scripting.Dictionary\")\n stuff.Add \"A\", \"Anaconda\"\n stuff.Add \"B\", \"Boa\"\n stuff.Add \"C\", \"Cobra\"\n\n Set GetSomeStuff = stuff\nEnd Function\n\nSet d = GetSomeStuff\nWscript.Echo d.Item(\"A\")\nWscript.Echo d.Exists(\"B\")\nitems = d.Items\nFor i = 0 To UBound(items)\n Wscript.Echo items(i)\nNext\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441/" ]
140,012
<p>I am currently creating an overnight job that calls a Unix script which in turn creates and transfers a file using <code>ftp</code>. I would like to check all possible return codes. The man page for <code>ftp</code> doesn't list return codes. Does anyone know where to find a list? Anyone with experience with this? We have other scripts that grep for certain return strings in the log, and they send an email when in error. However, they often miss unanticipated codes. I am then putting the reason into the log and the email.</p>
[ { "answer_id": 140071, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 4, "selected": true, "text": "ftp" }, { "answer_id": 140390, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 2, "selected": false, "text": "# ...\nftp -i -n $HOST 2>&1 1> $FTPLOG << EOF\nquote USER $USER\nquote PASS $PASSWD\ncd $RFOLDER\nbinary\nput $FOLDER/$FILE.sql.Z $FILE.sql.Z\nbye\nEOF\n\n# Check the ftp util exit code (0 is ok, every else means an error occurred!)\nEXITFTP=$?\nif test $EXITFTP -ne 0; then echo \"$D ERROR FTP\" >> $LOG; exit 3; fi\nif (grep \"^Not connected.\" $FTPLOG); then echo \"$D ERROR FTP CONNECT\" >> $LOG; fi \nif (grep \"No such file\" $FTPLOG); then echo \"$D ERROR FTP NO SUCH FILE\" >> $LOG; fi \nif (grep \"access denied\" $FTPLOG ); then echo \"$D ERROR FTP ACCESS DENIED\" >> $LOG; fi\nif (grep \"^Please login\" $FTPLOG ); then echo \"$D ERROR FTP LOGIN\" >> $LOG; fi\n #!/usr/bin/perl -w\nuse Net::FTP;\n$ftp = Net::FTP->new(\"example.net\") or die \"Cannot connect to example.net: $@\";\n$ftp->login(\"username\", \"password\") or die \"Cannot login \", $ftp->message;\n$ftp->cwd(\"/pub\") or die \"Cannot change working directory \", $ftp->message;\n$ftp->binary;\n$ftp->put(\"foo.bar\") or die \"Failed to upload \", $ftp->message;\n$ftp->quit;\n ftp -i -n $HOST >$FTPLOG 2>&1 << EOF\n EXITFTP=$?\n" }, { "answer_id": 168454, "author": "Glenn Wark", "author_id": 12646, "author_profile": "https://Stackoverflow.com/users/12646", "pm_score": 0, "selected": false, "text": "echo \"open ftp_ip\npwd\nbinary \nlcd /out\ncd /in\nmput datafile.csv\nquit\"|ftp -iv > ftpreturn.log\n\nftpresult=$?\n\nbytesindatafile=`wc -c datafile.csv | cut -d \" \" -f 1` \nbytestransferred=`grep -e '^[0-9]* bytes sent' ftpreturn.log | cut -d \" \" -f 1` \nftptransfercomplete=`grep -e '226 ' ftpreturn.log | cut -d \" \" -f 1`\n\necho \"-- FTP result code: $ftpresult\" >> ftpreturn.log\necho \"-- bytes in datafile: $bytesindatafile bytes\" >> ftpreturn.log\necho \"-- bytes transferred: $bytestransferred bytes sent\" >> ftpreturn.log\n\nif [ \"$ftpresult\" != \"0\" ] || [ \"$bytestransferred\" != \"$bytesindatafile\" ] || [\"$ftptransfercomplete\" != \"226\" ] \nthen \n echo \"-- *abend* FTP Error occurred\" >> ftpreturn.log \n mailx -s 'FTP error' `cat email.lst` < ftpreturn.log\nelse \n echo \"-- file sent via ftp successfully\" >> ftpreturn.log \nfi\n" }, { "answer_id": 4442763, "author": "David Lapchuk", "author_id": 542361, "author_profile": "https://Stackoverflow.com/users/542361", "pm_score": 3, "selected": false, "text": "grep 226 Transfer complete grep ftp -niv < \"$2\"_ftp.tmp | grep \"^226 \"\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12646/" ]
140,026
<p>I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server.</p> <p>Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime.</p> <p>What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal.</p> <p>The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together.</p> <p>I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable.</p> <p>Edit: Expanded description to clear up some misconceptions.</p>
[ { "answer_id": 46762714, "author": "Vikas", "author_id": 137228, "author_profile": "https://Stackoverflow.com/users/137228", "pm_score": 0, "selected": false, "text": "SQLite3 from functools import partial\ndef select_keys(keys, from_):\n return ({k : fun(v, row) for k, (v, fun) in keys.items()}\n for row in from_)\n\ndef select_where(from_, where):\n return (row for row in from_\n if where(row))\n\ndef default_keys_transform(keys, transform=lambda v, row: row[v]):\n return {k : (k, transform) for k in keys}\n\ndef select(keys=None, from_=None, where=None):\n \"\"\"\n SELECT v1 AS k1, 2*v2 AS k2 FROM table WHERE v1 = a AND v2 >= b OR v3 = c\n\n translates to \n\n select(dict(k1=(v1, lambda v1, r: r[v1]), k2=(v2, lambda v2, r: 2*r[v2])\n , from_=table\n , where= lambda r : r[v1] = a and r[v2] >= b or r[v3] = c)\n \"\"\"\n assert from_ is not None\n idfunc = lambda k, t : t\n select_k = idfunc if keys is None else select_keys\n if isinstance(keys, list):\n keys = default_keys_transform(keys)\n idfunc = lambda t, w : t\n select_w = idfunc if where is None else select_where\n return select_k(keys, select_w(from_, where))\n ALLOWED_FUNCS = [ operator.mul, operator.add, ...] # List of allowed funcs\n\ndef select_secure(keys=None, from_=None, where=None):\n if keys is not None and isinstance(keys, dict):\n for v, fun keys.values:\n assert fun in ALLOWED_FUNCS\n if where is not None:\n assert_composition_of_allowed_funcs(where, ALLOWED_FUNCS)\n return select(keys=keys, from_=from_, where=where)\n assert_composition_of_allowed_funcs where=(operator.add, (operator.getitem, row, v1), 2) where=(operator.mul, (operator.add, (opreator.getitem, row, v2), 2), 3) apply_lisp def apply_lisp(where, rowsym, rowval, ALLOWED_FUNCS):\n assert where[0] in ALLOWED_FUNCS\n return apply(where[0],\n [ (apply_lisp(w, rowsym, rowval, ALLOWED_FUNCS)\n if isinstance(w, tuple)\n else rowval if w is rowsym\n else w if isinstance(w, (float, int, str))\n else None ) for w in where[1:] ])\n isinstance type in (float, int, str)" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12030/" ]
140,033
<p>Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:</p> <pre><code>class foo; typedef boost::shared_ptr&lt;foo&gt; foo_sp; typeded std::map&lt;int, foo_sp&gt; foo_sp_map; foo_sp_map m; </code></pre> <p>If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example:</p> <pre><code>foo_sp_map m; void func1() { foo_sp p(new foo); m[0] = p; } void func2() { foo_sp p2(new foo); m[0] = p2; } </code></pre> <p>Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.</p>
[ { "answer_id": 140112, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 1, "selected": false, "text": "m[0] = p2; p foo_sp p(new foo);" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
140,043
<p>How do I loop into all the resources in the resourcemanager?</p> <p>Ie: foreach (string resource in ResourceManager) //Do something with the recource.</p> <p>Thanks</p>
[ { "answer_id": 140060, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 6, "selected": true, "text": "IEnumerable IEnumerable<object> Enumerable.Count<T>() using System.Linq;\n\n...\n\nvar resourceSet = resourceManager.GetResourceSet(..);\nvar count = resSet.Cast<object>().Count();\n" }, { "answer_id": 140257, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 1, "selected": false, "text": "ResourceManager Type ResourceSet CultureInfo" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
140,044
<p>I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.</p> <p>Any sample code would be greatly appreciated!</p> <p>Link to API: <a href="http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf" rel="nofollow noreferrer">http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf</a></p>
[ { "answer_id": 148494, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 1, "selected": false, "text": "using System.Net;\nusing System.Text;\nusing System;\n\nnamespace RightNowSample\n{\n class Program\n {\n static void Main(string[] args)\n {\n string serviceUrl = \"http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php\";\n WebClient webClient = new WebClient();\n string requestXml = \n@\"<connector>\n<function name=\"\"ans_get\"\">\n<parameter name=\"\"args\"\" type=\"\"pair\"\">\n<pair name=\"\"id\"\" type=\"\"integer\"\">33</pair>\n<pair name=\"\"sub_tbl\"\" type='pair'>\n<pair name=\"\"tbl_id\"\" type=\"\"integer\"\">164</pair>\n</pair>\n</parameter>\n</function>\n</connector>\";\n\n string secString = \"\";\n string postData = string.Format(\"xml_doc={0}, sec_string={1}\", requestXml, secString);\n byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);\n\n byte[] responseDataBytes = webClient.UploadData(serviceUrl, \"POST\", postDataBytes);\n string responseData = Encoding.UTF8.GetString(responseDataBytes);\n\n Console.WriteLine(responseData);\n }\n }\n}\n" }, { "answer_id": 24749911, "author": "Friyank", "author_id": 3065532, "author_profile": "https://Stackoverflow.com/users/3065532", "pm_score": 0, "selected": false, "text": " class Program\n{\n private RightNowSyncPortClient _Service;\n public Program()\n {\n _Service = new RightNowSyncPortClient();\n _Service.ClientCredentials.UserName.UserName = \"Rightnow UID\";\n _Service.ClientCredentials.UserName.Password = \"Right now password\";\n }\n private Contact Contactinfo()\n {\n Contact newContact = new Contact();\n PersonName personName = new PersonName();\n personName.First = \"conatctname\";\n personName.Last = \"conatctlastname\";\n newContact.Name = personName;\n Email[] emailArray = new Email[1];\n emailArray[0] = new Email();\n emailArray[0].action = ActionEnum.add;\n emailArray[0].actionSpecified = true;\n emailArray[0].Address = \"mail@mail.com\";\n NamedID addressType = new NamedID();\n ID addressTypeID = new ID();\n addressTypeID.id = 1;\n addressType.ID = addressTypeID;\n addressType.ID.idSpecified = true;\n emailArray[0].AddressType = addressType;\n emailArray[0].Invalid = false;\n emailArray[0].InvalidSpecified = true;\n newContact.Emails = emailArray;\n return newContact;\n }\n public long CreateContact()\n {\n Contact newContact = Contactinfo();\n //Set the application ID in the client info header\n ClientInfoHeader clientInfoHeader = new ClientInfoHeader();\n clientInfoHeader.AppID = \".NET Getting Started\";\n //Set the create processing options, allow external events and rules to execute\n CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions();\n createProcessingOptions.SuppressExternalEvents = false;\n createProcessingOptions.SuppressRules = false;\n RNObject[] createObjects = new RNObject[] { newContact };\n //Invoke the create operation on the RightNow server\n RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions);\n\n //We only created a single contact, this will be at index 0 of the results\n newContact = createResults[0] as Contact;\n return newContact.ID.id;\n }\n\n static void Main(string[] args)\n {\n Program RBSP = new Program();\n try\n {\n long newContactID = RBSP.CreateContact();\n System.Console.WriteLine(\"New Contact Created with ID: \" + newContactID);\n }\n catch (FaultException ex)\n {\n Console.WriteLine(ex.Code);\n Console.WriteLine(ex.Message);\n }\n\n System.Console.Read();\n\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
140,054
<p>I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently.</p> <p>Is there are way to do something like this:</p> <pre><code>installutil.exe myservice.exe /customarg1=username /customarg2=password </code></pre>
[ { "answer_id": 140285, "author": "Dean Hill", "author_id": 3106, "author_profile": "https://Stackoverflow.com/users/3106", "pm_score": 7, "selected": true, "text": "installutil.exe /user=uname /password=pw myservice.exe\n namespace Test\n{\n [RunInstaller(true)]\n public class TestInstaller : Installer\n {\n private ServiceInstaller serviceInstaller;\n private ServiceProcessInstaller serviceProcessInstaller;\n\n public OregonDatabaseWinServiceInstaller()\n {\n serviceInstaller = new ServiceInstaller();\n serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;\n serviceInstaller.ServiceName = \"Test\";\n serviceInstaller.DisplayName = \"Test Service\";\n serviceInstaller.Description = \"Test\";\n serviceInstaller.StartType = ServiceStartMode.Automatic;\n Installers.Add(serviceInstaller);\n\n serviceProcessInstaller = new ServiceProcessInstaller();\n serviceProcessInstaller.Account = ServiceAccount.User; \n Installers.Add(serviceProcessInstaller);\n }\n\n public string GetContextParameter(string key)\n {\n string sValue = \"\";\n try\n {\n sValue = this.Context.Parameters[key].ToString();\n }\n catch\n {\n sValue = \"\";\n }\n return sValue;\n }\n\n\n // Override the 'OnBeforeInstall' method.\n protected override void OnBeforeInstall(IDictionary savedState)\n {\n base.OnBeforeInstall(savedState);\n\n string username = GetContextParameter(\"user\").Trim();\n string password = GetContextParameter(\"password\").Trim();\n\n if (username != \"\")\n serviceProcessInstaller.Username = username;\n if (password != \"\")\n serviceProcessInstaller.Password = password;\n }\n }\n}\n" }, { "answer_id": 1613862, "author": "william", "author_id": 195358, "author_profile": "https://Stackoverflow.com/users/195358", "pm_score": -1, "selected": false, "text": "public class MyServiceInstaller : Installer\n{\n /// Public Constructor for WindowsServiceInstaller\n public MyServiceInstaller()\n {\n ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();\n ServiceInstaller serviceInstaller = new ServiceInstaller();\n\n //# Service Account Information\n serviceProcessInstaller.Account = ServiceAccount.User; // and not LocalSystem;\n ....\n" }, { "answer_id": 17425522, "author": "Josua", "author_id": 948287, "author_profile": "https://Stackoverflow.com/users/948287", "pm_score": 2, "selected": false, "text": "InstallUtil.exe sc config MyServiceName start= auto" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3106/" ]
140,061
<p>When creating a class library in C++, you can choose between dynamic (<code>.dll</code>, <code>.so</code>) and static (<code>.lib</code>, <code>.a</code>) libraries. What is the difference between them and when is it appropriate to use which?</p>
[ { "answer_id": 140444, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 8, "selected": false, "text": "mylib.lib a.obj b.obj a.obj b.obj b.obj type_info type_info &typeid() type_info::before()" }, { "answer_id": 1900692, "author": "Vijay", "author_id": 134713, "author_profile": "https://Stackoverflow.com/users/134713", "pm_score": 4, "selected": false, "text": "$$:~/static [32]> cat foo.c\n#include<stdio.h>\nvoid foo()\n{\nprintf(\"\\nhello world\\n\");\n}\n$$:~/static [33]> cat foo.h\n#ifndef _H_FOO_H\n#define _H_FOO_H\n\nvoid foo();\n\n#endif\n$$:~/static [34]> cat foo2.c\n#include<stdio.h>\nvoid foo2()\n{\nprintf(\"\\nworld\\n\");\n}\n$$:~/static [35]> cat foo2.h\n#ifndef _H_FOO2_H\n#define _H_FOO2_H\n\nvoid foo2();\n\n#endif\n$$:~/static [36]> cat hello.c\n#include<foo.h>\n#include<foo2.h>\nvoid main()\n{\nfoo();\nfoo2();\n}\n$$:~/static [37]> cat makefile\nhello: hello.o libtest.a\n cc -o hello hello.o -L. -ltest\nhello.o: hello.c\n cc -c hello.c -I`pwd`\nlibtest.a:foo.o foo2.o\n ar cr libtest.a foo.o foo2.o\nfoo.o:foo.c\n cc -c foo.c\nfoo2.o:foo.c\n cc -c foo2.c\nclean:\n rm -f foo.o foo2.o libtest.a hello.o\n\n$$:~/static [38]>\n $$:~/dynamic [44]> cat foo.c\n#include<stdio.h>\nvoid foo()\n{\nprintf(\"\\nhello world\\n\");\n}\n$$:~/dynamic [45]> cat foo.h\n#ifndef _H_FOO_H\n#define _H_FOO_H\n\nvoid foo();\n\n#endif\n$$:~/dynamic [46]> cat foo2.c\n#include<stdio.h>\nvoid foo2()\n{\nprintf(\"\\nworld\\n\");\n}\n$$:~/dynamic [47]> cat foo2.h\n#ifndef _H_FOO2_H\n#define _H_FOO2_H\n\nvoid foo2();\n\n#endif\n$$:~/dynamic [48]> cat hello.c\n#include<foo.h>\n#include<foo2.h>\nvoid main()\n{\nfoo();\nfoo2();\n}\n$$:~/dynamic [49]> cat makefile\nhello:hello.o libtest.sl\n cc -o hello hello.o -L`pwd` -ltest\nhello.o:\n cc -c -b hello.c -I`pwd`\nlibtest.sl:foo.o foo2.o\n cc -G -b -o libtest.sl foo.o foo2.o\nfoo.o:foo.c\n cc -c -b foo.c\nfoo2.o:foo.c\n cc -c -b foo2.c\nclean:\n rm -f libtest.sl foo.o foo\n\n2.o hello.o\n$$:~/dynamic [50]>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ]
140,104
<p>If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?</p>
[ { "answer_id": 140154, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 8, "selected": true, "text": "WebOperationContext OutgoingResponse OutgoingWebResponseContext StatusCode WebOperationContext ctx = WebOperationContext.Current;\nctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;\n" }, { "answer_id": 4266353, "author": "Graeme Bradbury", "author_id": 5889, "author_profile": "https://Stackoverflow.com/users/5889", "pm_score": 6, "selected": false, "text": "throw new WebFaultException<string>(\"Bar wasn't Foo'd\", HttpStatusCode.BadRequest );\n" }, { "answer_id": 5354506, "author": "Hydtechie", "author_id": 666306, "author_profile": "https://Stackoverflow.com/users/666306", "pm_score": 2, "selected": false, "text": "catch (ArgumentException ex)\n{\n WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;\n WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message;\n return null;\n}\n" }, { "answer_id": 32045262, "author": "user5234326", "author_id": 5234326, "author_profile": "https://Stackoverflow.com/users/5234326", "pm_score": 1, "selected": false, "text": "WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;\nthrow new WebException(\"令牌码不正确\", new InvalidTokenException());\n" }, { "answer_id": 50505480, "author": "eitzo", "author_id": 4338015, "author_profile": "https://Stackoverflow.com/users/4338015", "pm_score": 3, "selected": false, "text": "WebOperationContext context = WebOperationContext.Current;\ncontext.OutgoingResponse.StatusCode = HttpStatusCode.OK;\ncontext.OutgoingResponse.StatusDescription = \"Your Message\";\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
140,111
<p>Linux supports sending an arbitrary Posix-Signal such as <code>SIGINT</code> or <code>SIGTERM</code> to a process using the <code>kill</code>-Command. While <code>SIGINT</code> and <code>SIGTERM</code> are just boring old ways to end a process in a friendly or not-so-friendly kind of way, <code>SIGQUIT</code> is meant to trigger a core dump. This can be used to trigger a running Java VM to print out a thread dump, including the stacktraces of all running threads -- neat! After printing the debugging info, the Java VM will continue doing whatever it was doing before; in fact the thread dump just happens in another spawned thread of maximum priority. (You can try this out yourself by using <code>kill -3 &lt;VM-PID&gt;</code>.)</p> <p>Note that you can also register your own signal handlers using the (unsupported!) <code>Signal</code> and <code>SignalHandler</code> classes in the <code>sun.misc</code>-package, so you can have all kinds of fun with it.</p> <p><em>However, I have yet to find a way to send a signal to a Windows process.</em> Signals are created by certain user inputs: <code>Ctrl-C</code> triggers a <code>SIGINT</code> on both platforms, for instance. But there does not seem to be any utility to manually send a signal to a running, but non-interactive process on Windows. The obvious solution is to use the Cygwin <code>kill</code> executable, but while it can end Windows processes using the appropriate Windows API, I could not send a <code>SIGBREAK</code> (the Windows equivalent to <code>SIGQUIT</code>) with it; in fact I think the only signal it is able to send to Windows processes is <code>SIGTERM</code>.</p> <p>So, to make a long story short and to repeat the headline: How to I send an arbitrary signal to a process in Windows?</p>
[ { "answer_id": 140174, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": false, "text": "SetConsoleCtrlHandler" }, { "answer_id": 140229, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "#define WM_MYMSG ( WM_USER+0x100 )\nHWND h = ::FindWindow(NULL,_T(\"Win32App\"));\nif (h) {\n ::PostMessage(h, WM_MYMSG, 0, 0);\n}\n" }, { "answer_id": 9723985, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 0, "selected": false, "text": "TerminateProcess" }, { "answer_id": 64166692, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 2, "selected": false, "text": "windows-kill -SIGINT PID PID" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19256/" ]
140,113
<p>I want to consume a web service over https from a java client. What steps will i need to take in order to do this?</p>
[ { "answer_id": 163759, "author": "Ian McLaird", "author_id": 18796, "author_profile": "https://Stackoverflow.com/users/18796", "pm_score": 2, "selected": false, "text": "keytool -importcert -v -trustcacerts -alias ServerName -file server_cert_file.crt -keystore client_keystore_file\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
140,115
<p>So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network. I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidden share. I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted.</p>
[ { "answer_id": 140156, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 0, "selected": false, "text": "DirectoryInfo di = new DirectoryInfo(@\"\\\\machineName\\c$\\temp\");\n\nFileInfo[] files = di.GetFiles();\n\nforeach (FileInfo f in files)\n{\n Debug.WriteLine(f.Name);\n}\n" }, { "answer_id": 140327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "net use SERVERNAME\\IPC$ /user:USERNAME PASSWORD\n ProcessStartInfo psi = new ProcessStartInfo(\n \"net\", \"use \" + SERVERNAME + @\"\\IPC$ /user:\" + USERNAME + \" \" + PASSWORD);\nProcess p = new Process();\np.StartInfo = psi;\np.Start();\np.WaitForExit();\np.Close();\n// The code to access the share follows...\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634/" ]
140,131
<p>I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.</p> <p>I couldn't have phrased it better than the person that posted <a href="http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html" rel="noreferrer">the same question here</a>.</p> <p>But to keep it original, I'll phrase it my own way: suppose I have a string <code>"00A0BF"</code> that I would like interpreted as the</p> <pre><code>byte[] {0x00,0xA0,0xBf} </code></pre> <p>what should I do?</p> <p>I am a Java novice and ended up using <code>BigInteger</code> and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. </p>
[ { "answer_id": 140147, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 7, "selected": false, "text": "import org.apache.commons.codec.binary.Hex;\n...\nbyte[] decoded = Hex.decodeHex(\"00A0BF\");\n// 0x00 0xA0 0xBF\n" }, { "answer_id": 140166, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 2, "selected": false, "text": "public static final byte[] fromHexString(final String s) {\n String[] v = s.split(\" \");\n byte[] arr = new byte[v.length];\n int i = 0;\n for(String val: v) {\n arr[i++] = Integer.decode(\"0x\" + val).byteValue();\n\n }\n return arr;\n}\n" }, { "answer_id": 140181, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": -1, "selected": false, "text": "private static byte[] decode(String encoded) {\n byte result[] = new byte[encoded/2];\n char enc[] = encoded.toUpperCase().toCharArray();\n StringBuffer curr;\n for (int i = 0; i < enc.length; i += 2) {\n curr = new StringBuffer(\"\");\n curr.append(String.valueOf(enc[i]));\n curr.append(String.valueOf(enc[i + 1]));\n result[i] = (byte) Integer.parseInt(curr.toString(), 16);\n }\n return result;\n}\n" }, { "answer_id": 140188, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 3, "selected": false, "text": "public static final byte[] fromHexString(final String s) {\n byte[] arr = new byte[s.length()/2];\n for ( int start = 0; start < s.length(); start += 2 )\n {\n String thisByte = s.substring(start, start+2);\n arr[start/2] = Byte.parseByte(thisByte, 16);\n }\n return arr;\n}\n" }, { "answer_id": 140430, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 4, "selected": false, "text": "private static byte[] fromHexString(final String encoded) {\n if ((encoded.length() % 2) != 0)\n throw new IllegalArgumentException(\"Input string must contain an even number of characters\");\n\n final byte result[] = new byte[encoded.length()/2];\n final char enc[] = encoded.toCharArray();\n for (int i = 0; i < enc.length; i += 2) {\n StringBuilder curr = new StringBuilder(2);\n curr.append(enc[i]).append(enc[i + 1]);\n result[i/2] = (byte) Integer.parseInt(curr.toString(), 16);\n }\n return result;\n}\n" }, { "answer_id": 140592, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 5, "selected": false, "text": "new BigInteger(\"00A0BF\", 16).toByteArray();\n" }, { "answer_id": 140861, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 11, "selected": true, "text": "java.util.HexFormat HexFormat.of().parseHex(s) /* s must be an even-length string. */\npublic static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i+1), 16));\n }\n return data;\n}\n char[] assert" }, { "answer_id": 1703094, "author": "Sniper", "author_id": 207215, "author_profile": "https://Stackoverflow.com/users/207215", "pm_score": 3, "selected": false, "text": "BigInteger() Integer.parseInt(HEXString, 16) Integer.decode(\"0xXX\") .byteValue()\n public static byte[] HexStringToByteArray(String s) {\n byte data[] = new byte[s.length()/2];\n for(int i=0;i < s.length();i+=2) {\n data[i/2] = (Integer.decode(\"0x\"+s.charAt(i)+s.charAt(i+1))).byteValue();\n }\n return data;\n}\n" }, { "answer_id": 2448414, "author": "David V", "author_id": 294072, "author_profile": "https://Stackoverflow.com/users/294072", "pm_score": 0, "selected": false, "text": "public static byte[] hex2ba(String sHex) throws Hex2baException {\n if (1==sHex.length()%2) {\n throw(new Hex2baException(\"Hex string need even number of chars\"));\n }\n\n byte[] ba = new byte[sHex.length()/2];\n for (int i=0;i<sHex.length()/2;i++) {\n ba[i] = (Integer.decode(\n \"0x\"+sHex.substring(i*2, (i+1)*2))).byteValue();\n }\n return ba;\n}\n" }, { "answer_id": 3408174, "author": "Kernel Panic", "author_id": 411092, "author_profile": "https://Stackoverflow.com/users/411092", "pm_score": 2, "selected": false, "text": "public byte[] hex2ByteArray( String hexString ) {\n String hexVal = \"0123456789ABCDEF\";\n byte[] out = new byte[hexString.length() / 2];\n\n int n = hexString.length();\n\n for( int i = 0; i < n; i += 2 ) {\n //make a bit representation in an int of the hex value \n int hn = hexVal.indexOf( hexString.charAt( i ) );\n int ln = hexVal.indexOf( hexString.charAt( i + 1 ) );\n\n //now just shift the high order nibble and add them together\n out[i/2] = (byte)( ( hn << 4 ) | ln );\n }\n\n return out;\n}\n" }, { "answer_id": 4586527, "author": "GrkEngineer", "author_id": 118999, "author_profile": "https://Stackoverflow.com/users/118999", "pm_score": 5, "selected": false, "text": "HexBinaryAdapter String byte[] import javax.xml.bind.annotation.adapters.HexBinaryAdapter;\n\npublic byte[] hexToBytes(String hexString) {\n HexBinaryAdapter adapter = new HexBinaryAdapter();\n byte[] bytes = adapter.unmarshal(hexString);\n return bytes;\n}\n" }, { "answer_id": 5942951, "author": "Vladislav Rastrusny", "author_id": 173677, "author_profile": "https://Stackoverflow.com/users/173677", "pm_score": 8, "selected": false, "text": "import javax.xml.bind.DatatypeConverter;\n\npublic static String toHexString(byte[] array) {\n return DatatypeConverter.printHexBinary(array);\n}\n\npublic static byte[] toByteArray(String s) {\n return DatatypeConverter.parseHexBinary(s);\n}\n eckes Fabian javax.xml Bert Regelink" }, { "answer_id": 9854133, "author": "Clayton Balabanov", "author_id": 1149783, "author_profile": "https://Stackoverflow.com/users/1149783", "pm_score": 1, "selected": false, "text": "boolean isOdd(int value)\n{\n return (value & 0x01) !=0;\n}\n\nprivate int hexToByte(byte[] out, int value)\n{\n String hexVal = \"0123456789ABCDEF\"; \n String hexValL = \"0123456789abcdef\";\n String st = Integer.toHexString(value);\n int len = st.length();\n if (isOdd(len))\n {\n len+=1; // need length to be an even number.\n st = (\"0\" + st); // make it an even number of chars\n }\n out[0]=(byte)(len/2);\n for (int i =0;i<len;i+=2)\n {\n int hh = hexVal.indexOf(st.charAt(i));\n if (hh == -1) hh = hexValL.indexOf(st.charAt(i));\n int lh = hexVal.indexOf(st.charAt(i+1));\n if (lh == -1) lh = hexValL.indexOf(st.charAt(i+1));\n out[(i/2)+1] = (byte)((hh << 4)|lh);\n }\n return (len/2)+1;\n}\n" }, { "answer_id": 11139098, "author": "Bert Regelink", "author_id": 1239858, "author_profile": "https://Stackoverflow.com/users/1239858", "pm_score": 5, "selected": false, "text": "import javax.xml.bind.DatatypeConverter;\n\npublic static String toHexString(byte[] array) {\n return DatatypeConverter.printHexBinary(array);\n}\n\npublic static byte[] toByteArray(String s) {\n return DatatypeConverter.parseHexBinary(s);\n}\n public byte[] parseHexBinary(String s) {\n final int len = s.length();\n\n // \"111\" is not a valid hex encoding.\n if( len%2 != 0 )\n throw new IllegalArgumentException(\"hexBinary needs to be even-length: \"+s);\n\n byte[] out = new byte[len/2];\n\n for( int i=0; i<len; i+=2 ) {\n int h = hexToBin(s.charAt(i ));\n int l = hexToBin(s.charAt(i+1));\n if( h==-1 || l==-1 )\n throw new IllegalArgumentException(\"contains illegal character for hexBinary: \"+s);\n\n out[i/2] = (byte)(h*16+l);\n }\n\n return out;\n}\n\nprivate static int hexToBin( char ch ) {\n if( '0'<=ch && ch<='9' ) return ch-'0';\n if( 'A'<=ch && ch<='F' ) return ch-'A'+10;\n if( 'a'<=ch && ch<='f' ) return ch-'a'+10;\n return -1;\n}\n\nprivate static final char[] hexCode = \"0123456789ABCDEF\".toCharArray();\n\npublic String printHexBinary(byte[] data) {\n StringBuilder r = new StringBuilder(data.length*2);\n for ( byte b : data) {\n r.append(hexCode[(b >> 4) & 0xF]);\n r.append(hexCode[(b & 0xF)]);\n }\n return r.toString();\n}\n" }, { "answer_id": 13296284, "author": "Sean Coffey", "author_id": 1810344, "author_profile": "https://Stackoverflow.com/users/1810344", "pm_score": 2, "selected": false, "text": "import javax.xml.bind.DatatypeConverter;\nimport java.io.*;\n\npublic class Test\n{ \n @Test\n public void testObjectStreams( ) throws IOException, ClassNotFoundException\n { \n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n\n String stringTest = \"TEST\";\n oos.writeObject( stringTest );\n\n oos.close();\n baos.close();\n\n byte[] bytes = baos.toByteArray();\n String hexString = DatatypeConverter.printHexBinary( bytes);\n byte[] reconvertedBytes = DatatypeConverter.parseHexBinary(hexString);\n\n assertArrayEquals( bytes, reconvertedBytes );\n\n ByteArrayInputStream bais = new ByteArrayInputStream(reconvertedBytes);\n ObjectInputStream ois = new ObjectInputStream(bais);\n\n String readString = (String) ois.readObject();\n\n assertEquals( stringTest, readString);\n }\n }\n" }, { "answer_id": 15656440, "author": "jontro", "author_id": 429972, "author_profile": "https://Stackoverflow.com/users/429972", "pm_score": 5, "selected": false, "text": "guava BaseEncoding.base16().decode(string);\n BaseEncoding.base16().encode(bytes);\n" }, { "answer_id": 16590535, "author": "Philip Helger", "author_id": 15254, "author_profile": "https://Stackoverflow.com/users/15254", "pm_score": 1, "selected": false, "text": " public static byte [] hexStringToByteArray (final String s) {\n if (s == null || (s.length () % 2) == 1)\n throw new IllegalArgumentException ();\n final char [] chars = s.toCharArray ();\n final int len = chars.length;\n final byte [] data = new byte [len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));\n }\n return data;\n }\n" }, { "answer_id": 27326948, "author": "Alejandro", "author_id": 4330776, "author_profile": "https://Stackoverflow.com/users/4330776", "pm_score": -1, "selected": false, "text": "private static byte[] BytesEncode(String encoded) {\n //System.out.println(encoded.length());\n byte result[] = new byte[encoded.length() / 2];\n char enc[] = encoded.toUpperCase().toCharArray();\n String curr = \"\";\n for (int i = 0; i < encoded.length(); i=i+2) {\n curr = encoded.substring(i,i+2);\n System.out.println(curr);\n if(i==0){\n result[i]=((byte) Integer.parseInt(curr, 16));\n }else{\n result[i/2]=((byte) Integer.parseInt(curr, 16));\n }\n\n }\n return result;\n}\n" }, { "answer_id": 33523093, "author": "Miao1007", "author_id": 4016014, "author_profile": "https://Stackoverflow.com/users/4016014", "pm_score": 4, "selected": false, "text": "byte[] bytes = ByteString.decodeHex(\"c000060000\").toByteArray();\n [-64, 0, 6, 0, 0]\n" }, { "answer_id": 39970426, "author": "Conor Svensson", "author_id": 3211687, "author_profile": "https://Stackoverflow.com/users/3211687", "pm_score": 2, "selected": false, "text": "public static byte[] hexStringToByteArray(String input) {\n int len = input.length();\n\n if (len == 0) {\n return new byte[] {};\n }\n\n byte[] data;\n int startIdx;\n if (len % 2 != 0) {\n data = new byte[(len / 2) + 1];\n data[0] = (byte) Character.digit(input.charAt(0), 16);\n startIdx = 1;\n } else {\n data = new byte[len / 2];\n startIdx = 0;\n }\n\n for (int i = startIdx; i < len; i += 2) {\n data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4)\n + Character.digit(input.charAt(i+1), 16));\n }\n return data;\n}\n" }, { "answer_id": 43799515, "author": "Daniel De León", "author_id": 980442, "author_profile": "https://Stackoverflow.com/users/980442", "pm_score": 0, "selected": false, "text": "/**\n * Decodes a hexadecimally encoded binary string.\n * <p>\n * Note that this function does <em>NOT</em> convert a hexadecimal number to a\n * binary number.\n *\n * @param hex Hexadecimal representation of data.\n * @return The byte[] representation of the given data.\n * @throws NumberFormatException If the hexadecimal input string is of odd\n * length or invalid hexadecimal string.\n */\npublic static byte[] hex2bin(String hex) throws NumberFormatException {\n if (hex.length() % 2 > 0) {\n throw new NumberFormatException(\"Hexadecimal input string must have an even length.\");\n }\n byte[] r = new byte[hex.length() / 2];\n for (int i = hex.length(); i > 0;) {\n r[i / 2 - 1] = (byte) (digit(hex.charAt(--i)) | (digit(hex.charAt(--i)) << 4));\n }\n return r;\n}\n\nprivate static int digit(char ch) {\n int r = Character.digit(ch, 16);\n if (r < 0) {\n throw new NumberFormatException(\"Invalid hexadecimal string: \" + ch);\n }\n return r;\n}\n String data = new String(hex2bin(\"6578616d706c65206865782064617461\"));\n// data value: \"example hex data\"\n" }, { "answer_id": 49853711, "author": "Andy Brown", "author_id": 1763035, "author_profile": "https://Stackoverflow.com/users/1763035", "pm_score": 1, "selected": false, "text": "String hex = \"0001027f80fdfeff\";\n\nbyte[] converted = IntStream.range(0, hex.length() / 2)\n .map(i -> Character.digit(hex.charAt(i * 2), 16) << 4 | Character.digit(hex.charAt((i * 2) + 1), 16))\n .collect(ByteArrayOutputStream::new,\n ByteArrayOutputStream::write,\n (s1, s2) -> s1.write(s2.toByteArray(), 0, s2.size()))\n .toByteArray();\n , 0, s2.size() IOException" }, { "answer_id": 52015636, "author": "DrPhill", "author_id": 7347085, "author_profile": "https://Stackoverflow.com/users/7347085", "pm_score": 0, "selected": false, "text": "public final class HexString {\n private static final char[] digits = \"0123456789ABCDEF\".toCharArray();\n\n private HexString() {}\n\n public static final String fromBytes(final byte[] bytes) {\n final StringBuilder buf = new StringBuilder();\n for (int i = 0; i < bytes.length; i++) {\n buf.append(HexString.digits[(bytes[i] >> 4) & 0x0f]);\n buf.append(HexString.digits[bytes[i] & 0x0f]);\n }\n return buf.toString();\n }\n\n public static final byte[] toByteArray(final String hexString) {\n if ((hexString.length() % 2) != 0) {\n throw new IllegalArgumentException(\"Input string must contain an even number of characters\");\n }\n final int len = hexString.length();\n final byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)\n + Character.digit(hexString.charAt(i + 1), 16));\n }\n return data;\n }\n}\n public class TestHexString {\n\n @Test\n public void test() {\n String[] tests = {\"0FA1056D73\", \"\", \"00\", \"0123456789ABCDEF\", \"FFFFFFFF\"};\n\n for (int i = 0; i < tests.length; i++) {\n String in = tests[i];\n byte[] bytes = HexString.toByteArray(in);\n String out = HexString.fromBytes(bytes);\n System.out.println(in); //DEBUG\n System.out.println(out); //DEBUG\n Assert.assertEquals(in, out);\n\n }\n\n }\n\n}\n" }, { "answer_id": 52501458, "author": "tigger", "author_id": 5758166, "author_profile": "https://Stackoverflow.com/users/5758166", "pm_score": 0, "selected": false, "text": "public static byte[] hexToBinary(String s){\n\n /*\n * skipped any input validation code\n */\n\n byte[] data = new byte[s.length()/2];\n\n for( int i=0, j=0; \n i<s.length() && j<data.length; \n i+=2, j++)\n {\n data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16);\n }\n\n return data;\n}\n" }, { "answer_id": 71455588, "author": "lbruun", "author_id": 2282938, "author_profile": "https://Stackoverflow.com/users/2282938", "pm_score": 0, "selected": false, "text": "byte[] byteArray = Hex.hexStrToBytes(\"00A0BF\");\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11798/" ]
140,133
<p>I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.</p> <pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); </code></pre> <p>Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.</p> <p><strong>UPDATE:</strong><br> I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. </p> <pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); $(popupWindow.window).unload(function() { alert('hello'); }); </code></pre> <p>Does anybody have any idea as to why the unload event could be raised when the window is loading?</p> <p>One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:</p> <pre><code>popupWindow.onunload = function(){alert('hello')}; </code></pre> <p>It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the <code>popupWindow.closed</code> property inside of the event to ensure the window was really closed.</p>
[ { "answer_id": 140318, "author": "Philip Tinney", "author_id": 14930, "author_profile": "https://Stackoverflow.com/users/14930", "pm_score": 2, "selected": false, "text": "$(window).unload( function () { alert(\"Bye now!\"); } );" }, { "answer_id": 1164449, "author": "Elzo Valugi", "author_id": 95353, "author_profile": "https://Stackoverflow.com/users/95353", "pm_score": 0, "selected": false, "text": "$(document).ready(function(){\n $(window).unload( function (){\n alert('preget');\n $.get(\n '/some.php',\n { request: 'some' }\n );\n alert('postget');\n });\n});\n" }, { "answer_id": 2199551, "author": "Magnus Ottosson", "author_id": 266169, "author_profile": "https://Stackoverflow.com/users/266169", "pm_score": 4, "selected": false, "text": "var w = window.open(\"http://www.google.com\", \"_blank\", 'top=442,width=480,height=460,resizable=yes', true);\nvar watchClose = setInterval(function() {\n if (w.closed) {\n clearTimeout(watchClose);\n //Do something here...\n }\n }, 200);\n" }, { "answer_id": 2381646, "author": "rmoorman", "author_id": 286499, "author_profile": "https://Stackoverflow.com/users/286499", "pm_score": 3, "selected": false, "text": "var w = window.open(\"http://www.google.com\", \"_blank\", 'top=442,width=480,height=460,resizable=yes', true);\n\nvar watchClose = setInterval(function() {\n try {\n if (w.closed) {\n clearTimeout(watchClose);\n //Do something here...\n }\n } catch (e) {}\n}, 200);\n" }, { "answer_id": 6267685, "author": "Rodrigo Waltenberg", "author_id": 443395, "author_profile": "https://Stackoverflow.com/users/443395", "pm_score": 2, "selected": false, "text": "window.open $(function(){\n var win = window.open('http://url-at-same-domain.com','Test', 'width=600,height=500');\n $(win).unload(function(){\n if(this.location == 'about:blank')\n {\n $(this).unload(function(){\n // do something here\n });\n }\n });\n});\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
140,137
<p>I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that. </p> <p>Does anyone know how to create a custom 404 error page in Umbraco? Is there a way to create a custom error page for runtime errors?</p>
[ { "answer_id": 140169, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 4, "selected": false, "text": "/config/umbracoSettings.config <error404>1</error404> <errors>\n <error404>1</error404> \n</errors>\n" }, { "answer_id": 1129888, "author": "Dirk De Grave", "author_id": 137107, "author_profile": "https://Stackoverflow.com/users/137107", "pm_score": 3, "selected": false, "text": "<errors>\n <error404>1050</error404>\n</errors>\n <errors>\n <errorPage culture=\"default\">1</errorPage>-->\n <errorPage culture=\"en-US\">200</errorPage>-->\n</errors>\n" }, { "answer_id": 3837977, "author": "Shri Ganesh", "author_id": 463711, "author_profile": "https://Stackoverflow.com/users/463711", "pm_score": 1, "selected": false, "text": "Under <errors> section\n <error404>1111</error404>\n In <appSettings> section\n change <customErrors mode as show below:\n<customErrors mode=\"RemoteOnly\" defaultRedirect=\"~/Error.aspx\"/>\n" }, { "answer_id": 5789295, "author": "marapet", "author_id": 63733, "author_profile": "https://Stackoverflow.com/users/63733", "pm_score": 0, "selected": false, "text": "umbracoSettings.conf <errors>\n <!-- the id of the page that should be shown if the page is not found -->\n <!-- <errorPage culture=\"default\">1</errorPage>-->\n <!-- <errorPage culture=\"en-US\">200</errorPage>-->\n <error404>\n <errorPage culture=\"default\">1</errorPage>\n <errorPage culture=\"ru-RU\">1</errorPage>\n <errorPage culture=\"en-US\">2</errorPage>\n </error404>\n </errors>\n error404 errorPage" }, { "answer_id": 10881390, "author": "Sprague", "author_id": 143095, "author_profile": "https://Stackoverflow.com/users/143095", "pm_score": 3, "selected": false, "text": "<errors>\n <!-- the id of the page that should be shown if the page is not found -->\n <!-- <errorPage culture=\"default\">1</errorPage>-->\n <!-- <errorPage culture=\"en-US\">200</errorPage>-->\n <error404>2664</error404>\n</errors>\n <system.webServer>\n <!-- Some other existing stuff -->\n <httpErrors existingResponse=\"PassThrough\" />\n</system.webServer>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
140,149
<p>I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete?</p>
[ { "answer_id": 140185, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 6, "selected": true, "text": "[Diagnostics.PerformanceCounterCategory]::Delete( \"Your Category Name\" )\n HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Inventory [Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto\n [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like \"*network*\" } | Format-Table -auto\n[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match \"^SQL.*Stat.*\" } | Format-Table -auto\n" }, { "answer_id": 1017515, "author": "Kieran Benton", "author_id": 5777, "author_profile": "https://Stackoverflow.com/users/5777", "pm_score": 4, "selected": false, "text": "System.Diagnostics.PerformanceCounterCategory.Delete(\"Name of category to delete\");" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
140,161
<p>How can I find out which column and value is violating the constraint? The exception message isn't helpful at all:</p> <blockquote> <p>Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.</p> </blockquote>
[ { "answer_id": 140679, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": false, "text": "...\ntry\n{\n adapter.Fill(dataTable); // or dataSet\n}\ncatch (ConstraintException)\n{\n LogErrors(dataTable);\n throw;\n}\n...\n\nprivate static void LogErrors(DataSet dataSet)\n{\n foreach (DataTable dataTable in dataSet.Tables)\n {\n LogErrors(dataTable);\n }\n}\n\nprivate static void LogErrors(DataTable dataTable)\n{\n if (!dataTable.HasErrors) return;\n StringBuilder sb = new StringBuilder();\n sb.AppendFormat(\n CultureInfo.CurrentCulture,\n \"ConstraintException while filling {0}\",\n dataTable.TableName);\n DataRow[] errorRows = dataTable.GetErrors();\n for (int i = 0; (i < MAX_ERRORS_TO_LOG) && (i < errorRows.Length); i++)\n {\n sb.AppendLine();\n sb.Append(errorRows[i].RowError);\n }\n _logger.Error(sb.ToString());\n}\n" }, { "answer_id": 37167976, "author": "Olivier de Rivoyre", "author_id": 740362, "author_profile": "https://Stackoverflow.com/users/740362", "pm_score": 2, "selected": false, "text": "try\n{\n ds.EnforceConstraints = true;\n}\ncatch (ConstraintException ex)\n{\n string details = string.Join(\"\",\n ds.Tables.Cast<DataTable>()\n .Where(t => t.HasErrors)\n .SelectMany(t => t.GetErrors())\n .Take(50)\n .Select(r => \"\\n - \" + r.Table.TableName + \"[\" + string.Join(\", \", r.Table.PrimaryKey.Select(c => r[c])) + \"]: \" + r.RowError));\n throw new ConstraintException(ex.Message + details);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11547/" ]
140,162
<p>In a servlet I do the following:</p> <pre><code> Context context = new InitialContext(); value = (String) context.lookup("java:comp/env/propertyName"); </code></pre> <p>On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key <em>propertyName</em>?</p> <p>In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.</p>
[ { "answer_id": 143749, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 1, "selected": false, "text": "<env-entry> <env-entry>\n <description>My string property</descriptor>\n <env-entry-name>propertyName</env-entry-name>\n <env-entry-type>java.lang.String</env-entry-type>\n <env-entry-value>Your string goes here</env-entry-value>\n</env-entry>\n java:comp/env env-entry" }, { "answer_id": 5325475, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 0, "selected": false, "text": "<resource-ref>\n <res-ref-name>configFileName</res-ref-name>\n <res-type>java.net.URL</res-type>\n</resource-ref>\n <name:resource-ref>\n <name:ref-name>configFileName</name:ref-name>\n <name:url>file:///etc/myConfigFile</name:url>\n</name:resource-ref>\n initialContext = new InitialContext();\nURL url = (URL) initialContext.lookup(\"java:comp/env/configFileName\");\nString configFileName = url.getPath();\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2985/" ]
140,182
<p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p> <p>Right now I'm doing this...</p> <pre><code>def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in here. """ return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \ text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):] </code></pre> <p>so if I do sth like</p> <pre><code>&gt;&gt;&gt; getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo") 'hola aaaooobbb como estas?' </code></pre> <p>It changes the (...) with 'ooo'.</p> <p>Do you guys know whether with python regular expressions we can do this?</p> <p>thanks a lot guys!!</p>
[ { "answer_id": 140209, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 4, "selected": true, "text": "sub (replacement, string[, count = 0])\n p = re.compile( '(blue|white|red)')\n >>> p.sub( 'colour', 'blue socks and red shoes')\n 'colour socks and colour shoes'\n >>> p.sub( 'colour', 'blue socks and red shoes', count=1)\n 'colour socks and red shoes'\n" }, { "answer_id": 140218, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 2, "selected": false, "text": ">>> import re\n>>> re.sub(r'aaa...bbb', 'aaaooobbb', \"hola aaaiiibbb como estas?\")\n'hola aaaooobbb como estas?'\n \\g<n> () >>> re.sub( \"(svcOrdNbr +)..\", \"\\g<1>XX\", \"svcOrdNbr IASZ0080\")\n'svcOrdNbr XXSZ0080'\n" }, { "answer_id": 140776, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 0, "selected": false, "text": "def getExpandedText(pattern, text, replaceValue):\n m = re.search(pattern, text)\n expandedText = text[:m.start(1)] + replaceValue + text[m.end(1):]\n return expandedText\n" }, { "answer_id": 142188, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "def getExpandedText(pattern,text,*group):\n r\"\"\" Searches for pattern in the text and replaces\n all captures with the values in group.\n\n Tag renaming:\n >>> html = '<div> abc <span id=\"x\"> def </span> ghi </div>'\n >>> getExpandedText(r'</?(span\\b)[^>]*>', html, 'div')\n '<div> abc <div id=\"x\"> def </div> ghi </div>'\n\n Nested groups, capture-references:\n >>> getExpandedText(r'A(.*?Z(.*?))B', \"abAcdZefBgh\", r'<\\2>')\n 'abA<ef>Bgh'\n \"\"\"\n pattern = re.compile(pattern)\n ret = []\n last = 0\n for m in pattern.finditer(text):\n for i in xrange(0,len(m.groups())):\n start,end = m.span(i+1)\n\n # nested or skipped group\n if start < last or group[i] is None:\n continue\n\n # text between the previous and current match\n if last < start:\n ret.append(text[last:start])\n\n last = end\n ret.append(m.expand(group[i]))\n\n ret.append(text[last:])\n return ''.join(ret)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293/" ]
140,204
<p>Given a typical class:</p> <pre> struct Whatever { void Doit(); }; Whatever w; </pre> <p>what is the best way to get the member function to be called by a C void* based callback such as pthread_create() or a signal handler ?</p> <pre> pthread_t pid; pthread_create(&pid, 0, ... &w.Doit() ... ); </pre>
[ { "answer_id": 140232, "author": "Ian G", "author_id": 5764, "author_profile": "https://Stackoverflow.com/users/5764", "pm_score": 3, "selected": false, "text": "int pthread_create(pthread_t *thread, const pthread_attr_t *attr,\n void *(*start_routine)(void*), void *arg);\n void myclass_doit(void* x)\n{\n MyClass* c = reinterpret_cast<MyClass*>(x);\n c->doit();\n}\n\npthread_create(..., &myclass_doit, (void*)(&obj));\n" }, { "answer_id": 140238, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 2, "selected": false, "text": "struct Whatever\n{\n void Doit();\n};\n\nextern \"C\" static int DoItcallback (void * arg)\n{\n Whatever * w = (Whatever *) arg;\n w->DoIt();\n return something;\n}\n" }, { "answer_id": 140274, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "void* pthread_foo_caller(void* arg) {\n Foo* foo = static_cast<Foo*>(arg);\n foo->bar();\n return NULL;\n}\n class Foo {\n public:\n static pthread_foo_caller(void* arg);\n ...\n};\n\nvoid* Foo::pthread_foo_caller(void* arg) {\n Foo* foo = static_cast<Foo*>(arg);\n foo->private_bar();\n return NULL;\n}\n" }, { "answer_id": 140514, "author": "Torbjörn Gyllebring", "author_id": 21182, "author_profile": "https://Stackoverflow.com/users/21182", "pm_score": 1, "selected": false, "text": "#include \n\nclass MyClass\n{\npublic:\n void DoStuff()\n {\n printf(\"Doing Stuff!\");\n }\n};\n\nstruct MemberFunction\n{\n virtual ~MemberFunction(){}\n virtual void Invoke() = 0;\n};\n\nvoid InvokeMember(void *ptr)\n{\n static_cast(ptr)->Invoke();\n}\n\ntemplate \nstruct MemberFunctionOnT : MemberFunction\n{\n typedef void (T::*function_t)();\npublic:\n MemberFunctionOnT(T* obj, function_t fun)\n {\n m_obj = obj;\n m_fun = fun;\n }\n\n void Invoke()\n {\n (m_obj->*m_fun)();\n }\nprivate:\n T *m_obj;\n function_t m_fun;\n};\n\ntemplate \n\nMemberFunction* NewMemberFunction(T *obj, void (T::*fun)())\n{ \n return new MemberFunctionOnT(obj, fun); \n}\n\n//simulate a C-style function offering callback functionality.\nvoid i_will_call_you_later(void (*fun)(void*), void *arg)\n{\n fun(arg);\n}\n\nint main()\n{\n //Sample usage.\n MyClass foo;\n\n MemberFunction *arg = NewMemberFunction(&foo, &MyClass::DoStuff);\n i_will_call_you_later(&InvokeMember, arg);\n return 0;\n}" }, { "answer_id": 141549, "author": "keraba", "author_id": 22725, "author_profile": "https://Stackoverflow.com/users/22725", "pm_score": 3, "selected": false, "text": "* *" }, { "answer_id": 141662, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "try {\n CallIntoCFunctionThatCallsMeBack((void *)this, fCallTheDoItFunction);\n} catch (MyException &err)\n{\n stderr << \"badness.\";\n}\n\nvoid fCallTheDoItFunction(void *cookie)\n{\n MyClass* c = reinterpret_cast<MyClass*>(cookie);\n if (c->IsInvalid())\n throw MyException;\n c->DoIt();\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22725/" ]
140,205
<p>I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like</p> <pre><code>StudentID StartDate EndDate Field1 Field2 1 9/3/2007 10/20/2007 3 True 1 10/21/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True </code></pre> <p>The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like</p> <pre><code>StudentID StartDate EndDate Field1 Field2 1 9/3/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True </code></pre> <p>What would be the SELECT statement for this query?</p>
[ { "answer_id": 140226, "author": "Scott Bevington", "author_id": 9544, "author_profile": "https://Stackoverflow.com/users/9544", "pm_score": 0, "selected": false, "text": "SELECT StudentID, MIN(startdate) AS startdate, MAX(enddate), field1, field2\nFROM tablex\nGROUP BY StudentID, field1, field2\n" }, { "answer_id": 140227, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 0, "selected": false, "text": "select StudentID, min(StartDate) StartDate, max(EndDate) EndDate, Field1, Field2 \n from table\n group by StudentID, Field1, Field2\n" }, { "answer_id": 140504, "author": "CindyH", "author_id": 12897, "author_profile": "https://Stackoverflow.com/users/12897", "pm_score": 0, "selected": false, "text": "select \nstudentid, min(startdate) as Starter, max(enddate) as Ender, field1, field2, \nmax(startDate) - Min(endDate) as MaxGap \ninto tempIDs\nfrom student \ngroup by studentid, field1, field2 ; \n\ndelete from tempIDs where MaxGap > 1;\n\nUPDATE student INNER JOIN TempIDs ON Student.studentID = TempIDS.StudentID\nSET Student.StartDate = [TempIDs].[Starter],\n Student.EndDate = [TempIDs].[Ender];\n select \nstudentid, min(startdate) as StartDate, max(enddate) as EndDate, field1, field2, \ndatediff(dd, Min(endDate),max(startDate)) as MaxGap \ninto #tempIDs\nfrom #student \ngroup by studentid, field1, field2 \n\n-- Update the relevant records. Keeps two copies of the massaged record \n-- - extra will need to be deleted.\n\nupdate #student \nset startdate = #TempIDS.startdate, enddate = #tempIDS.EndDate\nfrom #tempIDS \nwhere #student.studentid = #TempIDs.StudentID and MaxGap < 2\n" }, { "answer_id": 140596, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 3, "selected": true, "text": "CREATE VIEW dbo.StudentStartDates\nAS\n SELECT\n S.StudentID,\n S.StartDate,\n S.Field1,\n S.Field2\n FROM\n dbo.Students S\n LEFT OUTER JOIN dbo.Students PREV ON\n PREV.StudentID = S.StudentID AND\n PREV.Field1 = S.Field1 AND\n PREV.Field2 = S.Field2 AND\n PREV.EndDate = DATEADD(dy, -1, S.StartDate)\n WHERE PREV.StudentID IS NULL\nGO\n\nCREATE VIEW dbo.StudentEndDates\nAS\n SELECT\n S.StudentID,\n S.EndDate,\n S.Field1,\n S.Field2\n FROM\n dbo.Students S\n LEFT OUTER JOIN dbo.Students NEXT ON\n NEXT.StudentID = S.StudentID AND\n NEXT.Field1 = S.Field1 AND\n NEXT.Field2 = S.Field2 AND\n NEXT.StartDate = DATEADD(dy, 1, S.EndDate)\n WHERE NEXT.StudentID IS NULL\nGO\n\n\nSELECT\n SD.StudentID,\n SD.StartDate,\n ED.EndDate,\n SD.Field1,\n SD.Field2\nFROM\n dbo.StudentStartDates SD\nINNER JOIN dbo.StudentEndDates ED ON\n ED.StudentID = SD.StudentID AND\n ED.Field1 = SD.Field1 AND\n ED.Field2 = SD.Field2 AND\n ED.EndDate > SD.StartDate AND\n NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate)\nGO\n" }, { "answer_id": 141443, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": "SELECT A.StudentID, A.StartDate, A.EndDate, A.Field1, A.Field2\nFROM tblEnrollment AS A LEFT JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) \n AND (A.EndDate=B.StartDate-1)\nWHERE B.StudentID Is Null;\n SELECT A.StudentID, A.StartDate, B.EndDate, A.Field1, A.Field2\nFROM tblEnrollment AS A INNER JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) \n AND (A.EndDate= B.StartDate-1)\n" }, { "answer_id": 141585, "author": "Eric Ness", "author_id": 18891, "author_profile": "https://Stackoverflow.com/users/18891", "pm_score": 0, "selected": false, "text": "SELECT\n SD.StudentID,\n SD.StartDate,\n MIN(ED.EndDate),\n SD.Field1,\n SD.Field2\nFROM\n dbo.StudentStartDates SD\nINNER JOIN dbo.StudentEndDates ED ON\n ED.StudentID = SD.StudentID AND\n ED.Field1 = SD.Field1 AND\n ED.Field2 = SD.Field2 AND\n ED.EndDate > SD.StartDate\nGROUP BY\n SD.StudentID, SD.Field1, SD.Field2, SD.StartDate\n" }, { "answer_id": 2878224, "author": "Daniel P", "author_id": 346593, "author_profile": "https://Stackoverflow.com/users/346593", "pm_score": 0, "selected": false, "text": "DECLARE @Data TABLE(\n CalendarDate datetime )\n\nINSERT INTO @Data( CalendarDate )\n-- range start\nSELECT '1 Jan 2010'\nUNION ALL SELECT '2 Jan 2010'\nUNION ALL SELECT '3 Jan 2010'\n-- range start\nUNION ALL SELECT '5 Jan 2010'\n-- range start\nUNION ALL SELECT '7 Jan 2010'\nUNION ALL SELECT '8 Jan 2010'\nUNION ALL SELECT '9 Jan 2010'\nUNION ALL SELECT '10 Jan 2010'\n\nSELECT DateGroup, Min( CalendarDate ) AS StartDate, Max( CalendarDate ) AS EndDate\nFROM( SELECT NextDay.CalendarDate, \n DateDiff( d, RangeStart.CalendarDate, NextDay.CalendarDate ) - ROW_NUMBER() OVER( ORDER BY NextDay.CalendarDate ) AS DateGroup\n FROM( SELECT Min( CalendarDate ) AS CalendarDate\n FROM @data ) AS RangeStart\n JOIN @data AS NextDay\n ON NextDay.CalendarDate >= RangeStart.CalendarDate ) A\nGROUP BY DateGroup\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18891/" ]
140,217
<p>As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?</p>
[ { "answer_id": 140316, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 2, "selected": false, "text": "gdb> p show_my_struct(struct)\n\nMy custom display of Foo:\n ...\n gdb> watch foo\nWatchpoint4: foo\ngdb>\n" }, { "answer_id": 270911, "author": "Emerick Rogul", "author_id": 33837, "author_profile": "https://Stackoverflow.com/users/33837", "pm_score": 2, "selected": false, "text": "Program terminated with signal 11, Segmentation fault.\n#0 0x08048364 in foo () at foo.c:4\n4 *x = 100;\n (gdb) backtrace\n#0 0x08048364 in foo () at foo.c:4\n#1 0x0804837f in main () at foo.c:9\n main() foo() foo() *x" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16044/" ]
140,303
<p>What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links).</p> <p>FWIW, I'm not running a web farm.</p> <h2>Exception</h2> <blockquote> <p>Error Message: Unable to validate data.</p> <p>Error Source: System.Web</p> <p>Error Target Site: Byte[] GetDecodedData(Byte[], Byte[], Int32, Int32, Int32 ByRef)</p> </blockquote> <h2>Post Data</h2> <blockquote> <p><em>VIEWSTATE:</em></p> <p>/wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB</p> <p><em>EVENTVALIDATION:</em></p> <p>/wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg=</p> </blockquote> <h2>Exception Stack Trace</h2> <pre><code> at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) </code></pre> <p>~ William Riley-Land</p>
[ { "answer_id": 141419, "author": "Raelshark", "author_id": 19678, "author_profile": "https://Stackoverflow.com/users/19678", "pm_score": 2, "selected": false, "text": "enableViewStateMac=\"false\" page" }, { "answer_id": 254581, "author": "Jeffrey Harrington", "author_id": 4307, "author_profile": "https://Stackoverflow.com/users/4307", "pm_score": 3, "selected": false, "text": "<configuration>\n\n <system.web>\n\n <pages renderAllHiddenFieldsAtTopOfForm=\"true\"></pages>\n\n </system.web>\n\n</configuration>\n" }, { "answer_id": 2963301, "author": "ileon", "author_id": 269595, "author_profile": "https://Stackoverflow.com/users/269595", "pm_score": 2, "selected": false, "text": "enableViewStateMac=\"false\"" }, { "answer_id": 7155976, "author": "Todd", "author_id": 830424, "author_profile": "https://Stackoverflow.com/users/830424", "pm_score": 2, "selected": false, "text": "<machineKey validationKey=\"1619AB2FDEE6B943AD5D31DD68B7EBDAB32682A5891481D9403A6A55C4F91A340131CB4F4AD26A686DF5911A6C05CAC89307663656B62BE304EA66605156E9B5\" decryptionKey=\"C9D165260E6A697B2993D45E05BD64386445DE01031B790A60F229F6A2656ECF\" validation=\"SHA1\" decryption=\"AES\" />\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17847/" ]
140,329
<p>I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help.</p> <p>Thanks!</p>
[ { "answer_id": 140425, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "<customErrors defaultRedirect=\"url\" mode=\"RemoteOnly\">\n <error statusCode=\"408\" redirect=\"~/SessionExpired.aspx\"/>\n</customErrors>\n" }, { "answer_id": 140435, "author": "Gabe Sumner", "author_id": 12689, "author_profile": "https://Stackoverflow.com/users/12689", "pm_score": 2, "selected": false, "text": "void Session_OnStart() {\n if (Session.IsNewSession == false )\n {\n }\n else \n {\n Server.Transfer(\"SessionExpired.aspx\", False);\n }\n}\n" }, { "answer_id": 140703, "author": "Micky McQuade", "author_id": 12908, "author_profile": "https://Stackoverflow.com/users/12908", "pm_score": 1, "selected": false, "text": "Session(\"UserID\") = 1234\n Dim UserID As Integer = 0\nInteger.TryParse(Session(\"UserID\"), UserID)\n\nIf UserID = 0 Then\n Response.Redirect(\"/sessionExpired.aspx\")\nEnd If\n" }, { "answer_id": 140792, "author": "CSharpAtl", "author_id": 11907, "author_profile": "https://Stackoverflow.com/users/11907", "pm_score": 2, "selected": false, "text": "private bool IsValidSession()\n {\n bool isValidSession = true;\n if (Context.Session != null)\n {\n if (Session.IsNewSession)\n {\n string cookieHeader = Request.Headers[\"Cookie\"];\n if ((null != cookieHeader) && (cookieHeader.IndexOf(\"ASP.NET_SessionId\") >= 0))\n {\n isValidSession = false;\n if (User.Identity.IsAuthenticated)\n FormsAuthentication.SignOut();\n FormsAuthentication.RedirectToLoginPage();\n }\n }\n }\n return isValidSession;\n }\n" }, { "answer_id": 140801, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 4, "selected": true, "text": " public void Session_OnStart()\n {\n if (HttpContext.Current.Request.Cookies.Contains(\"ASP.NET_SessionId\") != null)\n {\n HttpContext.Current.Response.Redirect(\"SessionTimeout.aspx\")\n }\n\n }\n" }, { "answer_id": 141009, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 0, "selected": false, "text": " System.Text.StringBuilder sb = new System.Text.StringBuilder();\n String timeoutPage = \"SessionExpired.aspx\"; // your page here\n int timeoutPeriod = Session.Timeout * 60 * 1000;\n\n sb.AppendFormat(\"setTimeout(\\\"location.href = {0};\\\",{1});\", timeoutPage, timeoutPeriod);\n Page.ClientScript.RegisterStartupScript(this.GetType(), \"timeourRedirect\", sb.ToString(), true);\n" }, { "answer_id": 202691, "author": "TheEmirOfGroofunkistan", "author_id": 1874, "author_profile": "https://Stackoverflow.com/users/1874", "pm_score": 0, "selected": false, "text": "namespace PAB.WebControls\n [DefaultProperty(\"Text\"),\n\n ToolboxData(\"<{0}:SessionTimeoutControl runat=server></{0}:SessionTimeoutControl>\")]\n\npublic class SessionTimeoutControl : Control\n{\n private string _redirectUrl;\n\n [Bindable(true),\n Category(\"Appearance\"),\n DefaultValue(\"\")]\n public string RedirectUrl\n {\n get { return _redirectUrl; }\n\n set { _redirectUrl = value; }\n }\n\n public override bool Visible\n {\n get { return false; }\n\n }\n\n public override bool EnableViewState\n {\n get { return false; }\n }\n\n protected override void Render(HtmlTextWriter writer)\n {\n if (HttpContext.Current == null)\n\n writer.Write(\"[ *** SessionTimeout: \" + this.ID + \" *** ]\");\n\n base.Render(writer);\n }\n\n\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (this._redirectUrl == null)\n\n throw new InvalidOperationException(\"RedirectUrl Property Not Set.\");\n\n if (Context.Session != null)\n {\n if (Context.Session.IsNewSession)\n {\n string sCookieHeader = Page.Request.Headers[\"Cookie\"];\n\n if ((null != sCookieHeader) && (sCookieHeader.IndexOf(\"ASP.NET_SessionId\") >= 0))\n {\n if (Page.Request.IsAuthenticated)\n {\n FormsAuthentication.SignOut();\n }\n\n Page.Response.Redirect(this._redirectUrl);\n }\n }\n }\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14710/" ]
140,331
<p>I have a following SQL Server 2005 database schema:</p> <pre><code>CREATE TABLE Messages ( MessageID int, Subject varchar(500), Text varchar(max) NULL, UserID NULL ) </code></pre> <p>The column "UserID" - which can be null - is a foreign key and links to the table</p> <pre><code>CREATE TABLE Users ( UserID int, ... ) </code></pre> <p>Now I have several POCO classes with names Message, User etc. that I use in the following query:</p> <pre><code>public IList&lt;Message&gt; GetMessages(...) { var q = (from m in dataContext.Messages.Include("User") where ... select m); // could call ToList(), but... return (from m in q select new Message { ID = m.MessageID, User = new User { ID = m.User.UserID, FirstName = m.User.FirstName, ... } }).ToList(); } </code></pre> <p>Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. </p> <p>Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL.</p> <p>If I change the last couple of lines to</p> <pre><code>return (from m in q select new Message { ID = m.MessageID, User = m.User == null ? null : new User { ID = m.User.UserID, ... } }).ToList() </code></pre> <p>then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported.</p> <p>Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks.</p>
[ { "answer_id": 140424, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": ".Include(\"Users\") User Message" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
140,347
<p>I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!</p> <p>Does anyone know what it is?</p> <p>It will do something similar to:</p> <pre><code>const CRect client(0, 0, 200, 200); const CRect window = ClientRectToWindowRect(client); SetWindowPos(...) </code></pre>
[ { "answer_id": 140373, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "AdjustWindowRectEx() GetWindowRect()" }, { "answer_id": 21004956, "author": "aMarCruz", "author_id": 3174665, "author_profile": "https://Stackoverflow.com/users/3174665", "pm_score": 0, "selected": false, "text": "RECT client;\n::SetRect(&client, 0, 0, 200, 200);\n::MapWindowPoints(hwndControl, ::GetParent(hwndControl), (POINT*)&client, 2);\n::SetWindowPos(...)\n" }, { "answer_id": 66902466, "author": "akovar", "author_id": 3688137, "author_profile": "https://Stackoverflow.com/users/3688137", "pm_score": 0, "selected": false, "text": "CRect rectFrame;\nGetWindowRect(&rectFrame);\nScreenToClient(&rectFrame);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
140,406
<p>Does anyone know of existing software or algorithms to calculate a package size for shipping multiple items?</p> <p>I have a bunch of items in our inventory database with length, width and height dimesions defined. Given these dimensions I need to calculate how many of the purchased items will fit into predefined box sizes.</p>
[ { "answer_id": 46173005, "author": "Ammar", "author_id": 3427844, "author_profile": "https://Stackoverflow.com/users/3427844", "pm_score": 0, "selected": false, "text": "PackingService.Pack() Container Item" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8754/" ]
140,422
<p>I'm looking for pseudocode, or sample code, to convert higher bit ascii characters (like, Ü which is extended ascii 154) into U (which is ascii 85).</p> <p>My initial guess is that since there are only about 25 ascii characters that are similar to 7bit ascii characters, a translation array would have to be used.</p> <p>Let me know if you can think of anything else.</p>
[ { "answer_id": 140531, "author": "Derek Clegg", "author_id": 19783, "author_profile": "https://Stackoverflow.com/users/19783", "pm_score": 1, "selected": false, "text": "static const char xlate[256] = { ..., ['é'] = 'e', ..., ['Ü'] = 'U', ... }\n...\nnew_c = xlate[old_c];\n" }, { "answer_id": 148137, "author": "Michel", "author_id": 17316, "author_profile": "https://Stackoverflow.com/users/17316", "pm_score": 3, "selected": false, "text": "public string RemoveDiacritics(string text)\n{\n\n return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(text));\n\n}\n" }, { "answer_id": 962324, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Function FixAccents(ByVal Valor As String) As String\n\n Dim x As Long\n Valor = Replace(Valor, Chr$(38), \"&#\" & 38 & \";\")\n\n For x = 127 To 255\n Valor = Replace(Valor, Chr$(x), \"&#\" & x & \";\")\n Next\n\n FixAccents = Valor\n\nEnd Function\n FileName = HttpContext.Current.Server.HtmlDecode(FileName)\n" }, { "answer_id": 10036907, "author": "sinelaw", "author_id": 562906, "author_profile": "https://Stackoverflow.com/users/562906", "pm_score": 5, "selected": false, "text": "// Based on http://www.codeproject.com/Articles/13503/Stripping-Accents-from-Latin-Characters-A-Foray-in\nprivate static string LatinToAscii(string inString)\n{\n var newStringBuilder = new StringBuilder();\n newStringBuilder.Append(inString.Normalize(NormalizationForm.FormKD)\n .Where(x => x < 128)\n .ToArray());\n return newStringBuilder.ToString();\n}\n FormKD" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ]
140,439
<p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p> <p>I can't even bind to perform a simple query:</p> <pre><code>import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&amp;(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displayName"] l = ldap.initialize(Server) l.protocol_version = 3 print l.simple_bind_s(DN, Secret) r = l.search(Base, Scope, Filter, Attrs) Type,user = l.result(r,60) Name,Attrs = user[0] if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayName sys.exit() </code></pre> <p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p> <p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p> <blockquote> <p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p> </blockquote> <p>Or </p> <blockquote> <p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p> </blockquote> <p>What am I missing out to bind properly?</p> <p>I am getting the same errors on fedora and windows.</p>
[ { "answer_id": 140495, "author": "1729", "author_id": 4319, "author_profile": "https://Stackoverflow.com/users/4319", "pm_score": 7, "selected": true, "text": "l.set_option(ldap.OPT_REFERRALS, 0)\n" }, { "answer_id": 140737, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 0, "selected": false, "text": "\"CN=Your user,CN=Users,DC=b2t,DC=local\"" }, { "answer_id": 141729, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 5, "selected": false, "text": "import win32security\ntoken = win32security.LogonUser(\n username,\n domain,\n password,\n win32security.LOGON32_LOGON_NETWORK,\n win32security.LOGON32_PROVIDER_DEFAULT)\nauthenticated = bool(token)\n" }, { "answer_id": 3920712, "author": "lanoxx", "author_id": 474034, "author_profile": "https://Stackoverflow.com/users/474034", "pm_score": 1, "selected": false, "text": "l.simple_bind l.simple_bind_s import ldap\nlocal = ldap.initialize(\"ldap://127.0.0.1\")\nlocal.simple_bind(\"CN=staff,DC=mydomain,DC=com\")\n#my pc is not actually connected to this domain \nresult_id = local.search(\"CN=staff,DC=mydomain,DC=com\", ldap.SCOPE_SUBTREE, \"cn=foobar\", None)\nlocal.set_option(ldap.OPT_REFERRALS, 0)\nresult_type, result_data = local.result(result_id, 0)\n" }, { "answer_id": 6902892, "author": "Dima Pasechnik", "author_id": 557937, "author_profile": "https://Stackoverflow.com/users/557937", "pm_score": 2, "selected": false, "text": "import kerberos\nkerberos.checkPassword('joe','pizza','krbtgt/x.pizza.com','X.PIZZA.COM')`\n" }, { "answer_id": 9943894, "author": "xcl", "author_id": 1303347, "author_profile": "https://Stackoverflow.com/users/1303347", "pm_score": 0, "selected": false, "text": "simple_bind_s() bind()" }, { "answer_id": 18282435, "author": "JohnMudd", "author_id": 487992, "author_profile": "https://Stackoverflow.com/users/487992", "pm_score": 3, "selected": false, "text": "import ldap # run 'pip install python-ldap' to install ldap module.\nconn = ldap.open(\"ldaphost.company.com\")\nconn.simple_bind_s(\"myuser@company.com\", \"mypassword\")\n" }, { "answer_id": 38348468, "author": "Dr.Ü", "author_id": 2250744, "author_profile": "https://Stackoverflow.com/users/2250744", "pm_score": 1, "selected": false, "text": ".encode('iso-8859-1')\n" }, { "answer_id": 54416600, "author": "Nagev", "author_id": 5362795, "author_profile": "https://Stackoverflow.com/users/5362795", "pm_score": 2, "selected": false, "text": "from ldap3 import Server, Connection, ALL, NTLM\nserver = Server('server_name_or_ip', get_info=ALL)\nconn = Connection(server, user=\"user_name\", password=\"password\", auto_bind=True)\nconn.extend.standard.who_am_i()\nserver.info\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319/" ]
140,453
<p>My company is considering changing continuous integration servers (I won't say which one we have now, so I won't skew your responses in anyway :) ) I wondering if anybody has any recommendations? Best user experience, level of difficulty to maintain, etc...</p> <p>Our code is all in java, and we use ANT as a build tool.</p>
[ { "answer_id": 4008659, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 0, "selected": false, "text": "ant" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22221/" ]
140,460
<p>We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).</p> <p>I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?</p>
[ { "answer_id": 140508, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "/**\n * Determines if a form is dirty by comparing the current value of each element\n * with its default value.\n *\n * @param {Form} form the form to be checked.\n * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>\n * otherwise.\n */\nfunction formIsDirty(form)\n{\n for (var i = 0; i < form.elements.length; i++)\n {\n var element = form.elements[i];\n var type = element.type;\n if (type == \"checkbox\" || type == \"radio\")\n {\n if (element.checked != element.defaultChecked)\n {\n return true;\n }\n }\n else if (type == \"hidden\" || type == \"password\" || type == \"text\" ||\n type == \"textarea\")\n {\n if (element.value != element.defaultValue)\n {\n return true;\n }\n }\n else if (type == \"select-one\" || type == \"select-multiple\")\n {\n for (var j = 0; j < element.options.length; j++)\n {\n if (element.options[j].selected !=\n element.options[j].defaultSelected)\n {\n return true;\n }\n }\n }\n }\n return false;\n}\n window.onbeforeunload = function(e)\n{\n e = e || window.event; \n if (formIsDirty(document.forms[\"someFormOfInterest\"]))\n {\n // For IE and Firefox\n if (e)\n {\n e.returnValue = \"You have unsaved changes.\";\n }\n // For Safari\n return \"You have unsaved changes.\";\n }\n};\n var confirmExitIfModified = (function()\n{\n function formIsDirty(form)\n {\n // ...as above\n }\n\n return function(form, message)\n {\n window.onbeforeunload = function(e)\n {\n e = e || window.event;\n if (formIsDirty(document.forms[form]))\n {\n // For IE and Firefox\n if (e)\n {\n e.returnValue = message;\n }\n // For Safari\n return message;\n }\n };\n };\n})();\n\nconfirmExitIfModified(\"someForm\", \"You have unsaved changes.\");\n beforeunload LIBRARY_OF_CHOICE" }, { "answer_id": 736800, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "$('input:text,input:checkbox,input:radio,textarea,select').one('change',function() {\n $('BODY').attr('onbeforeunload',\"return 'Leaving this page will cause any unsaved data to be lost.';\");\n});\n $('BODY').removeAttr('onbeforeunload');\n" }, { "answer_id": 1018862, "author": "Lance Larsen - Microsoft MVP", "author_id": 88665, "author_profile": "https://Stackoverflow.com/users/88665", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n\n //----------------------------------------------------------------------\n // Don't allow us to navigate away from a page on which we're changed\n // values on any control without a warning message. Need to class our \n // save buttons, links, etc so they can do a save without the message - \n // ie. CssClass=\"noWarn\"\n //----------------------------------------------------------------------\n $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() {\n $('BODY').attr('onbeforeunload',\n \"return 'Leaving this page will cause any unsaved data to be lost.';\");\n });\n\n $('.noWarn').click(function() { $('BODY').removeAttr('onbeforeunload'); });\n\n});\n" }, { "answer_id": 2220100, "author": "Ben McIntyre", "author_id": 208465, "author_profile": "https://Stackoverflow.com/users/208465", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n $(\":input\").one(\"change\", function() {\n window.onbeforeunload = function() { return 'You will lose data changes.'; }\n });\n $('.noWarn').click(function() { window.onbeforeunload = null; });\n});\n" }, { "answer_id": 2402725, "author": "Adam Nofsinger", "author_id": 18524, "author_profile": "https://Stackoverflow.com/users/18524", "pm_score": 1, "selected": false, "text": "onBeforeLeave no-warn-validate no-warn CausesValidation=false function removeCheck() { window.onbeforeunload = null; }\n\n$(document).ready(function() {\n //-----------------------------------------------------------------------------------------\n // Don't allow navigating away from page if changes to form are made. Save buttons, links,\n // etc, can be given \"no-warn\" or \"no-warn-validate\" css class to prevent warning on submit.\n // \"no-warn-validate\" inputs/links will only remove warning after successful validation\n //-----------------------------------------------------------------------------------------\n $(':input').one('change', function() {\n window.onbeforeunload = function() {\n return 'Leaving this page will cause edits to be lost.';\n }\n });\n\n $('.no-warn-validate').click(function() {\n if (Page_ClientValidate == null || Page_ClientValidate()) { removeCheck(); }\n });\n\n $('.no-warn').click(function() { removeCheck() });\n});\n" }, { "answer_id": 2556304, "author": "Ken Browning", "author_id": 53162, "author_profile": "https://Stackoverflow.com/users/53162", "pm_score": 2, "selected": false, "text": "onbeforeunload" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22732/" ]
140,462
<p>Is it possible to tell if the user of a website is using multiple monitors? I need to find the position of a popup but it's quite likely the user will have a multiple monitor setup. Whilst <code>window.screenX</code> etc. will give the position of the browser window it's useless for multiple monitors.</p>
[ { "answer_id": 140523, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "screen.width .availWidth screen.height .availHeight" }, { "answer_id": 21305365, "author": "Algy Taylor", "author_id": 1842033, "author_profile": "https://Stackoverflow.com/users/1842033", "pm_score": 1, "selected": false, "text": "var newWindow,\n screenSpaceLeft = window.screenX,\n screenSpaceTop = window.screenY,\n screenSpaceRight = screen.availWidth - (window.screenX + window.outerWidth),\n screenSpaceBottom = screen.availHeight - (window.screenY + window.outerHeight),\n minScreenSpaceSide = 800,\n minScreenSpaceTop = 600,\n screenMargin = 8,\n\n width = (screen.availWidth / 2.05),\n height = screen.availHeight,\n posX = (screen.availWidth / 2),\n posY = 0;\n\ne.preventDefault();\n\nif (screenSpaceRight > screenSpaceLeft && screenSpaceRight > screenSpaceTop && screenSpaceRight > screenSpaceBottom && screenSpaceRight > minScreenSpaceSide) {\n if (width > screenSpaceRight) {\n width = screenSpaceRight - screenMargin;\n }\n if (posX < (screen.availWidth - screenSpaceRight)) {\n posX = window.screenX + window.outerWidth + screenMargin;\n }\n} else if (screenSpaceLeft > screenSpaceRight && screenSpaceLeft > screenSpaceTop && screenSpaceLeft > screenSpaceBottom && screenSpaceLeft > minScreenSpaceSide) {\n if (width > screenSpaceLeft) {\n width = screenSpaceLeft - screenMargin;\n }\n\n posX = 0;\n} else if (screenSpaceTop > screenSpaceRight && screenSpaceTop > screenSpaceLeft && screenSpaceTop > screenSpaceBottom && screenSpaceTop > minScreenSpaceTop) {\n posX = 0;\n posY = 0;\n width = screen.availWidth;\n height = (screen.availHeight / 2.05);\n if (height > screenSpaceTop) {\n height = screenSpaceTop - screenMargin;\n }\n} else if (screenSpaceBottom > screenSpaceRight && screenSpaceBottom > screenSpaceLeft && screenSpaceBottom > screenSpaceTop && screenSpaceBottom > minScreenSpaceTop) {\n posX = 0;\n width = screen.availWidth;\n if (window.screenY + window.outerHeight + screenMargin > (screen.availHeight / 2)) {\n posY = window.screenY + window.outerHeight + screenMargin;\n } else {\n posY = (screen.availHeight / 2);\n }\n height = (screen.availHeight / 2.05);\n if (height > screenSpaceBottom) {\n height = screenSpaceBottom - screenMargin;\n }\n}\n\nnewWindow = window.open(this.href, \"_blank\", \"width=\" + width + \",height=\" + height + \",location=yes,menubar=no,resizable=yes,scrollbars=yes,status=yes,menubar=yes,top=\" + posY + \",left=\" + posX);\n" }, { "answer_id": 72706925, "author": "Lou Groshek", "author_id": 590107, "author_profile": "https://Stackoverflow.com/users/590107", "pm_score": 2, "selected": false, "text": "window.screen.isExtended await window.getScreenDetails()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21030/" ]
140,468
<p>What is the longest string that can be created in .NET? The docs for the <code>String</code> class are silent on this question as far as I can see, so an authoritative answer might require some knowledge of internals. Would the maximum change on a 64-bit system?</p> <p>[This is asked more for curiosity than for practical use - I don't intend to create any code that uses gigantic strings!]</p>
[ { "answer_id": 140492, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 6, "selected": false, "text": "Length System.String Int32 Int32" }, { "answer_id": 140506, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "String.Length Int32 Int32.MaxValue" }, { "answer_id": 140704, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 6, "selected": false, "text": "System.OutOfMemoryException using System;\nusing System.Collections.Generic;\n\npublic class MyClass\n{\n public static void Main()\n {\n int i = 100000000;\n try\n {\n for (i = i; i <= int.MaxValue; i += 5000)\n {\n string value = new string('x', i);\n //WL(i);\n }\n }\n catch (Exception exc)\n {\n WL(i);\n WL(exc);\n }\n WL(i);\n RL();\n }\n\n #region Helper methods\n\n private static void WL(object text, params object[] args)\n {\n Console.WriteLine(text.ToString(), args); \n }\n\n private static void RL()\n {\n Console.ReadLine(); \n }\n\n private static void Break() \n {\n System.Diagnostics.Debugger.Break();\n }\n\n #endregion\n}\n" }, { "answer_id": 141034, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 0, "selected": false, "text": "static void Main(string[] args)\n{\n string s = \"hello world\";\n for(;;)\n {\n s = s + s.Substring(0, s.Length/10);\n Console.WriteLine(s.Length);\n }\n}\n\n12\n13\n14\n15\n16\n17\n18\n...\n158905664\n174796230\n192275853\n211503438\n" }, { "answer_id": 25247459, "author": "user922020", "author_id": 922020, "author_profile": "https://Stackoverflow.com/users/922020", "pm_score": 5, "selected": false, "text": "s += \"stuff\" s += \"stuff\" StringBuilder sb = new StringBuilder(5000);\nfor (; ; )\n {\n sb.Append(\"stuff\");\n }\n StringBuilder" }, { "answer_id": 31803489, "author": "WonderWorker", "author_id": 1271898, "author_profile": "https://Stackoverflow.com/users/1271898", "pm_score": 4, "selected": false, "text": "static void Main(string[] args)\n{\n Console.WriteLine(\"String test, by Nicholas John Joseph Taylor\");\n\n Console.WriteLine(\"\\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.\");\n\n Console.WriteLine(\"\\nThis is a quickish test to narrow down results to find the max supported length of a string.\");\n\n Console.WriteLine(\"\\nThe test starts ...now:\\n\");\n\n int Length = 0;\n\n string s = \"\";\n\n int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.\n\n LoopPoint:\n\n // Make a string appendage the length of the value of Increment\n\n StringBuilder StringAppendage = new StringBuilder();\n\n for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)\n {\n StringAppendage.Append(\"0\");\n\n }\n\n // Repeatedly append string appendage until an out of memory exception is thrown.\n\n try\n {\n if (Increment > 0)\n while (Length < int.MaxValue)\n {\n Length += Increment;\n\n s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment\n\n Console.WriteLine(\"s.Length = \" + s.Length + \" at \" + DateTime.Now.ToString(\"dd/MM/yyyy HH:mm\"));\n\n }\n\n }\n catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.\n {\n Console.WriteLine(\"\\n\" + ex.Message + \" at \" + DateTime.Now.ToString(\"dd/MM/yyyy HH:mm\") + \".\");\n\n Length -= Increment;\n\n Increment /= 10;\n\n Console.WriteLine(\"After decimation, the value of Increment is \" + Increment + \".\");\n\n }\n catch (Exception ex2)\n {\n Console.WriteLine(\"\\n\" + ex2.Message + \" at \" + DateTime.Now.ToString(\"dd/MM/yyyy HH:mm\") + \".\");\n\n Console.WriteLine(\"Press a key to continue...\");\n\n Console.ReadKey();\n\n }\n\n if (Increment > 0)\n {\n goto LoopPoint;\n\n }\n\n Console.WriteLine(\"Test complete.\");\n\n Console.WriteLine(\"\\nThe max length of a string is \" + s.Length + \".\");\n\n Console.WriteLine(\"\\nPress any key to continue.\");\n\n Console.ReadKey();\n\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3776/" ]
140,490
<p>Which gets called first - the base constructor or "other stuff here"?</p> <pre><code>public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } </code></pre>
[ { "answer_id": 140497, "author": "Mastermind", "author_id": 22213, "author_profile": "https://Stackoverflow.com/users/22213", "pm_score": 3, "selected": false, "text": "using System;\nclass Base\n{\n\npublic Base()\n{\n Console.WriteLine(\"BASE 1\");\n}\npublic Base(int x)\n{\n Console.WriteLine(\"BASE 2\");\n}\n}\n\nclass Derived : Base\n{\npublic Derived():base(10)\n{\n Console.WriteLine(\"DERIVED CLASS\");\n}\n}\n\nclass MyClient\n{\npublic static void Main()\n{\n Derived d1 = new Derived();\n}\n}\n" }, { "answer_id": 140505, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 8, "selected": true, "text": "public class MyBase\n{\n public MyBase()\n {\n Console.WriteLine(\"MyBase\");\n }\n}\n\npublic class MyDerived : MyBase\n{\n public MyDerived():base()\n {\n Console.WriteLine(\"MyDerived\");\n }\n}\n" }, { "answer_id": 140541, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 7, "selected": false, "text": "public class BaseClass {\n\n private string sentenceOne = null; // A\n\n public BaseClass() {\n sentenceOne = \"The quick brown fox\"; // B\n }\n}\n\npublic class SubClass : BaseClass {\n\n private string sentenceTwo = null; // C\n\n public SubClass() {\n sentenceTwo = \"jumps over the lazy dog\"; // D\n }\n}\n" }, { "answer_id": 140551, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 0, "selected": false, "text": "public Child()\n{\n super(); // this line is always the first line in a child constructor even if you don't put it there! ***\n}\n" }, { "answer_id": 140553, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 3, "selected": false, "text": "class A {}\n\nclass B : A {}\n\nclass C : B {}\n C B A A B C" }, { "answer_id": 41008785, "author": "zwcloud", "author_id": 3427520, "author_profile": "https://Stackoverflow.com/users/3427520", "pm_score": 2, "selected": false, "text": "using System;\nclass A\n{\n public A() {\n PrintFields();\n }\n public virtual void PrintFields() {}\n}\nclass B: A\n{\n int x = 1;\n int y;\n public B() {\n y = -1;\n }\n public override void PrintFields() {\n Console.WriteLine(\"x = {0}, y = {1}\", x, y);\n }\n}\n new B() B x = 1, y = 0\n x y int y using System;\nusing System.Collections;\nclass A\n{\n int x = 1, y = -1, count;\n public A() {\n count = 0;\n }\n public A(int n) {\n count = n;\n }\n}\nclass B: A\n{\n double sqrt2 = Math.Sqrt(2.0);\n ArrayList items = new ArrayList(100);\n int max;\n public B(): this(100) {\n items.Add(\"default\");\n }\n public B(int n): base(n – 1) {\n max = n;\n }\n}\n using System.Collections;\nclass A\n{\n int x, y, count;\n public A() {\n x = 1; // Variable initializer\n y = -1; // Variable initializer\n object(); // Invoke object() constructor\n count = 0;\n }\n public A(int n) {\n x = 1; // Variable initializer\n y = -1; // Variable initializer\n object(); // Invoke object() constructor\n count = n;\n }\n}\nclass B: A\n{\n double sqrt2;\n ArrayList items;\n int max;\n public B(): this(100) {\n B(100); // Invoke B(int) constructor\n items.Add(\"default\");\n }\n public B(int n): base(n – 1) {\n sqrt2 = Math.Sqrt(2.0); // Variable initializer\n items = new ArrayList(100); // Variable initializer\n A(n – 1); // Invoke A(int) constructor\n max = n;\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16872/" ]
140,550
<p>What is the best way to store a large amount of text in a table in SQL server?</p> <p>Is varchar(max) reliable?</p>
[ { "answer_id": 140652, "author": "Mark Stock", "author_id": 19737, "author_profile": "https://Stackoverflow.com/users/19737", "pm_score": 2, "selected": false, "text": "id text_chunk text_chunk_id CREATE TABLE text_chunk (\n id NUMBER,\n chunk_sequence NUMBER,\n text BIGTEXT)\n" }, { "answer_id": 47523879, "author": "user9018039", "author_id": 9018039, "author_profile": "https://Stackoverflow.com/users/9018039", "pm_score": 0, "selected": false, "text": "nvarchar(max) {{UserId: Date and time}}<Chat Text>. \n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17648/" ]
140,579
<p>How do I detect if my program runs in an Active Directory environment?</p> <p>I'm using C# and .Net 2.0</p>
[ { "answer_id": 140603, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 2, "selected": false, "text": "string ADServer = Environment.GetEnvironmentVariable(\"LOGONSERVER\"); \n" }, { "answer_id": 140823, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 1, "selected": false, "text": "use System.DirectoryServices; // add reference to system.directoryservices.dll\n\n...\n\nDirectoryEntry ent = new DirectoryEntry(\"LDAP://RootDSE\");\nString str = ent.Properties[\"defaultNamingContext\"][0];\nDirectoryEntry domain = new DirectoryEntry(\"LDAP://\" + str);\n" }, { "answer_id": 140895, "author": "Ollie", "author_id": 4453, "author_profile": "https://Stackoverflow.com/users/4453", "pm_score": 2, "selected": false, "text": "using System.DirectoryServices.ActiveDirectory;\n\n\nbool isDomain = false;\n\ntry\n{\n Domain.GetComputerDomain();\n isDomain = true;\n}\ncatch (ActiveDirectoryObjectNotFoundException)\n{\n}\n Domain.GetCurrentDomain()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
140,614
<p>My Ubuntu server has Apache and Subversion installed. I use this server as a staging server, purely for testing purposes. I use Apache to host the web application, and Subversion to keep versioned copies of the source code.</p> <p>My current workflow:</p> <ul> <li>Make changes to a file</li> <li>Commit the file to the Subversion repository</li> <li>Upload the file new over SFTP to the Apache public directory</li> <li>View the changes in my web browser</li> </ul> <p>I would be much happier if my workflow was like this:</p> <ul> <li>Make changes to a file</li> <li>Commit the file to the Subversion repository</li> <li><em>In the background, Subversion puts a copy of the committed file into the Apache public directory</em></li> <li>View the changes in my web browser</li> </ul> <p>I have very little server admin experience, and any help or pointers are appreciated. I heard that post-commit hooks are what I need, and that I can write bash scripts to do this, but I'm not sure where to start and didn't really find anything after quite a lot of Googling.</p> <p>Thank you!</p>
[ { "answer_id": 908042, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 0, "selected": false, "text": "/home/richardhenry/src/mywebsite" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326176/" ]
140,616
<p>Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant <a href="http://ant.apache.org/manual/Tasks/echoproperties.html" rel="noreferrer">echoproperties</a> task maybe?</p>
[ { "answer_id": 141174, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 6, "selected": true, "text": "<project>\n <property name=\"foo\" value=\"bar\"/>\n <property name=\"fiz\" value=\"buz\"/>\n\n <script language=\"C#\" prefix=\"util\" >\n <code>\n <![CDATA[\n public static void ScriptMain(Project project) \n {\n foreach (DictionaryEntry entry in project.Properties)\n {\n Console.WriteLine(\"{0}={1}\", entry.Key, entry.Value);\n }\n }\n ]]>\n </code>\n </script>\n</project>\n" }, { "answer_id": 13772601, "author": "Brad C", "author_id": 1886864, "author_profile": "https://Stackoverflow.com/users/1886864", "pm_score": 3, "selected": false, "text": "<script language=\"C#\" prefix=\"util\" >\n <references>\n <include name=\"System.dll\" />\n </references> \n <imports>\n <import namespace=\"System.Collections.Generic\" />\n </imports> \n <code>\n <![CDATA[\n public static void ScriptMain(Project project) \n {\n SortedDictionary<string, string> sorted = new SortedDictionary<string, string>();\n foreach (DictionaryEntry entry in project.Properties){\n sorted.Add((string)entry.Key, (string)entry.Value);\n }\n foreach (KeyValuePair<string, string> entry in sorted)\n {\n project.Log(Level.Info, \"{0}={1}\", entry.Key, entry.Value);\n }\n }\n ]]>\n </code>\n</script>\n" }, { "answer_id": 20248647, "author": "Ben Corpus", "author_id": 3042791, "author_profile": "https://Stackoverflow.com/users/3042791", "pm_score": 2, "selected": false, "text": "<target name=\"echo-properties\" verbose=\"false\" description=\"Echo property values\" inheritall=\"true\">\n<script language=\"C#\">\n <code>\n <![CDATA[\n public static void ScriptMain(Project project)\n {\n System.Collections.SortedList sortedByKey = new System.Collections.SortedList();\n foreach(DictionaryEntry de in project.Properties)\n {\n sortedByKey.Add(de.Key, de.Value);\n }\n\n NAnt.Core.Tasks.EchoTask echo = new NAnt.Core.Tasks.EchoTask();\n echo.Project = project;\n\n foreach(DictionaryEntry de in sortedByKey)\n {\n if(de.Key.ToString().StartsWith(\"nant.\"))\n {\n continue;\n }\n echo.Message = String.Format(\"{0}: {1}\", de.Key,de.Value);\n echo.Execute();\n }\n }\n ]]>\n </code>\n</script>\n</target>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
140,627
<p>I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice??</p>
[ { "answer_id": 140656, "author": "Metro", "author_id": 18978, "author_profile": "https://Stackoverflow.com/users/18978", "pm_score": 5, "selected": true, "text": "[WebMethod(EnableSession = true)]\npublic void MyWebService()\n{\n Foo foo;\n Session[\"MyObjectName\"] = new Foo();\n foo = Session[\"MyObjectName\"] as Foo;\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
140,640
<p>Is there an NSIS var to get the path of the currently running installer?</p>
[ { "answer_id": 43888176, "author": "Maxim Suslov", "author_id": 3364871, "author_profile": "https://Stackoverflow.com/users/3364871", "pm_score": 4, "selected": false, "text": "$EXEPATH $EXEDIR $EXEDIR" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
140,643
<p>When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing?</p>
[ { "answer_id": 140665, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 5, "selected": true, "text": "grant SELECT on TABLE_NAME to READ_USERNAME;\n" }, { "answer_id": 141219, "author": "Igor Zelaya", "author_id": 22769, "author_profile": "https://Stackoverflow.com/users/22769", "pm_score": 5, "selected": false, "text": "GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;\n [READ_USERNAME]" }, { "answer_id": 1133087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "a) that view selects from a table in another schema (FDR.balance)\nb) a third shema X_WORK tries to select from that view\n grant select on fdr.balance to dsdw with grant option;\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22769/" ]
140,677
<p>I had a discussion a few weeks back with some co-workers on refactoring, and I seem to be in a minority that believes "Refactor early, refactor often" is a good approach that keeps code from getting messy and unmaintainable. A number of other people thought that it just belongs in the maintenance phases of a project.</p> <p>If you have an opinion, please defend it.</p>
[ { "answer_id": 140766, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "temp = array[i];\narray[i] = array[j];\narray[j] = temp;\n" }, { "answer_id": 150433, "author": "Craig P. Motlin", "author_id": 23572, "author_profile": "https://Stackoverflow.com/users/23572", "pm_score": 2, "selected": false, "text": "List Integer List<Integer>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6897/" ]
140,696
<p>I'm wondering which languages support (or don't support) native multithreading, and perhaps get some details about the implementation. Hopefully we can produce a complete overview of this specific functionality.</p>
[ { "answer_id": 59979349, "author": "Umair Riaz", "author_id": 10570437, "author_profile": "https://Stackoverflow.com/users/10570437", "pm_score": 1, "selected": false, "text": "Go Goroutine C-language" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14032/" ]
140,728
<p>It often happens that characters such as <em>é</em> gets transformed to <em>é</em>, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the <em>Content-Type</em> for the page is also set to UTF8.</p> <p>I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.</p> <p>I have read the &quot;<a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>&quot; article, but I need some MySQL / PHP specific pointers.</p> <p>How do I ensure that user entered data containing international characters doesn't get corrupted?</p>
[ { "answer_id": 141011, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": true, "text": "SET NAMES utf8\n $db=new PDO($dsn, $user, $pass);\n$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, \"SET NAMES utf8\");\n" }, { "answer_id": 143565, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 2, "selected": false, "text": "header() SET NAMES utf8 mb_string utf8_encode/decode" }, { "answer_id": 143627, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 3, "selected": false, "text": "Content-Type header accept-charset utf8_encode strlen magic_quotes" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
140,734
<p>What would be the best practice way to handle the caching of images using PHP.</p> <p>The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag.</p> <p>When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. </p> <p>The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner,</p> <p>Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)</p>
[ { "answer_id": 141164, "author": "user18334", "author_id": 18334, "author_profile": "https://Stackoverflow.com/users/18334", "pm_score": 0, "selected": false, "text": "<img src=\"/phpThumb.php?src=/path/to/image.jpg&w=200&amp;h=200\" alt=\"thumbnail\"/>\n" }, { "answer_id": 141224, "author": "phatduckk", "author_id": 3896, "author_profile": "https://Stackoverflow.com/users/3896", "pm_score": 3, "selected": false, "text": "/images/get/200x200/1234.jpg\n /images/get/0x1/1234.jpg\n/images/get/0x2/1234.jpg\n...\n/images/get/0x9999999/1234.jpg\n/images/get/1x1/1234.jpg\n...\netc\n <?php\n\n $pathOnDisk = getImageDiskPath($_SERVER['REQUEST_URI']);\n\n if(file_exists($pathOnDisk)) {\n // send header with image mime type \n echo file_get_contents($pathOnDisk);\n exit;\n } else {\n $matches = array();\n $ok = preg_match(\n '/\\/images\\/get\\/(\\d+)x(\\d+)\\/(\\w+)\\.jpg/', \n $_SERVER['REQUEST_URI'], $matches);\n\n if(! $ok) {\n // invalid url\n handleInvalidRequest();\n } else {\n list(, $width, $height, $guid) = $matches;\n\n // you should do this!\n if(isSupportedSize($width, $height)) {\n // size is supported. all good\n // generate the resized image, save it & output it\n } else {\n // invalid size requested!!!\n handleInvalidRequest();\n }\n }\n }\n\n // snip\n function handleInvalidRequest() {\n // do something w/ invalid request \n // show a default graphic, log it etc\n }\n?>\n" }, { "answer_id": 141378, "author": "Dan Udey", "author_id": 21450, "author_profile": "https://Stackoverflow.com/users/21450", "pm_score": 5, "selected": false, "text": "mod_rewrite RewriteCond %{REQUEST_URI} ^/images/cached/\nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f\nRewriteRule (.*) /images/generate.php?$1 [L]\n /images/cached/<something> /images/generate.php?/images/cached/<something> mod_expires mod_xsendfile" }, { "answer_id": 615675, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if (!file_exists($filename)) { \n\n // *** Insert code that generates image ***\n\n // Content type\n header('Content-type: image/jpeg'); \n\n // Output\n readfile($filename); \n\n} else {\n // Redirect\n $host = $_SERVER['HTTP_HOST'];\n $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\\\');\n $extra = $filename;\n header(\"Location: http://$host$uri/$extra\");\n}\n" }, { "answer_id": 1975086, "author": "Sensi", "author_id": 240240, "author_profile": "https://Stackoverflow.com/users/240240", "pm_score": 4, "selected": true, "text": "RewriteCond %{REQUEST_URI} ^/images/cached/\nRewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f\nRewriteRule (.*) /images/generate.php?$1 [L]\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22776/" ]
140,758
<p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p> <p>Is there an analogous way to do this in Python?</p>
[ { "answer_id": 140778, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": ">>> import glob\n>>> glob.glob('./[0-9].*')\n['./1.gif', './2.txt']\n>>> glob.glob('*.gif')\n['1.gif', 'card.gif']\n>>> glob.glob('?.gif')\n['1.gif']\n" }, { "answer_id": 140795, "author": "Big Dave Diode", "author_id": 9448, "author_profile": "https://Stackoverflow.com/users/9448", "pm_score": 2, "selected": false, "text": "import os\nprint os.listdir('.')\n" }, { "answer_id": 140805, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 2, "selected": false, "text": "os.walk() os.walk() # Delete everything reachable from the directory named in 'top',\n# assuming there are no symbolic links.\n# CAUTION: This is dangerous! For example, if top == '/', it\n# could delete all your disk files.\nimport os\nfor root, dirs, files in os.walk(top, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n" }, { "answer_id": 140818, "author": "dmeister", "author_id": 4194, "author_profile": "https://Stackoverflow.com/users/4194", "pm_score": 6, "selected": true, "text": " files = glob.glob('/usr/joe/*.gif')\n import os\nfrom os.path import join\nfor root, dirs, files in os.walk('/usr'):\n print \"Current directory\", root\n print \"Sub directories\", dirs\n print \"Files\", files\n" }, { "answer_id": 141277, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 2, "selected": false, "text": "os.path.walk os.walk" }, { "answer_id": 143227, "author": "Max Maximus", "author_id": 19627, "author_profile": "https://Stackoverflow.com/users/19627", "pm_score": 3, "selected": false, "text": "dir = path(os.environ['HOME'])\nfor f in dir.walk():\n if f.isfile() and f.endswith('~'):\n f.remove()\n" }, { "answer_id": 18465955, "author": "metakermit", "author_id": 544059, "author_profile": "https://Stackoverflow.com/users/544059", "pm_score": 1, "selected": false, "text": "os os.path shutil >>> from unipath import Path\n>>> p = Path('/Users/kermit')\n>>> p.listdir()\nPath(u'/Users/kermit/Applications'),\nPath(u'/Users/kermit/Desktop'),\nPath(u'/Users/kermit/Documents'),\nPath(u'/Users/kermit/Downloads'),\n...\n $ pip install unipath\n" }, { "answer_id": 35705659, "author": "Hazim Sager", "author_id": 5998003, "author_profile": "https://Stackoverflow.com/users/5998003", "pm_score": 0, "selected": false, "text": "import os\n\ndef PrintFiles(direc):\n files = os.listdir(direc)\n for x in range(len(files)):\n print(\"File no. \"+str(x+1)+\": \"+files[x])\n\nPrintFiles(direc)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
140,765
<p>I am writing a web server in Java and I want it to support HTTP 1.1 Keep-Alive connections. But how can I tell when the client is done sending requests for a given connection? (like a double end-of-line or something). </p> <p>Lets see how stackoverflow handles this very obscure question -- answers for which, on Google, are mired in technical specifications and obscure language. I want a plain-english answer for a non-C programmer :)</p> <hr> <p>I see. that confirms my suspicion of having to rely on the SocketTimeoutException. But i wasn't sure if there was something i could rely on from the client that indicates it is done with the connection--which would allow me to close the connections sooner in most cases--instead of waiting for the timeout. Thanks</p>
[ { "answer_id": 140889, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "Connection: close" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/982630/" ]
140,786
<p>The code is</p> <pre><code>return min + static_cast&lt;int&gt;(static_cast&lt;double&gt;(max - min + 1.0) * (number / (UINT_MAX + 1.0))); </code></pre> <p>number is a random number obtained by rand_s. min and max are ints and represent minimum and maximum values (inclusive).</p> <p>If you provide a solution not using unsigned int as a number, please also explain how to make it be random.</p> <p>Please do not submit solutions using rand().</p>
[ { "answer_id": 140826, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": -1, "selected": false, "text": "min + number % (max - min + 1)\n" }, { "answer_id": 140848, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 2, "selected": false, "text": "j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0))); j = 1 + (rand() % 10); man 3 rand" }, { "answer_id": 140865, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 3, "selected": true, "text": "static_cast<double>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
140,820
<p>Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?</p> <p>[Update 2]</p> <p>Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:</p> <pre><code>using System.Threading; [...] /// &lt;summary&gt; /// Wait (up to a timeout) for the MSI installer service to become free. /// &lt;/summary&gt; /// &lt;returns&gt; /// Returns true for a successful wait, when the installer service has become free. /// Returns false when waiting for the installer service has exceeded the timeout. /// &lt;/returns&gt; public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime) { // The _MSIExecute mutex is used by the MSI installer service to serialize installations // and prevent multiple MSI based installations happening at the same time. // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx const string installerServiceMutexName = "Global\\_MSIExecute"; try { Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName, System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify); bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false); MSIExecuteMutex.ReleaseMutex(); return waitSuccess; } catch (WaitHandleCannotBeOpenedException) { // Mutex doesn't exist, do nothing } catch (ObjectDisposedException) { // Mutex was disposed between opening it and attempting to wait on it, do nothing } return true; } </code></pre>
[ { "answer_id": 22026461, "author": "NBPC77", "author_id": 235100, "author_profile": "https://Stackoverflow.com/users/235100", "pm_score": 2, "selected": false, "text": " /// <summary>\n/// Wait (up to a timeout) for the MSI installer service to become free.\n/// </summary>\n/// <returns>\n/// Returns true for a successful wait, when the installer service has become free.\n/// Returns false when waiting for the installer service has exceeded the timeout.\n/// </returns>\npublic static bool IsMsiExecFree(TimeSpan maxWaitTime)\n{\n // The _MSIExecute mutex is used by the MSI installer service to serialize installations\n // and prevent multiple MSI based installations happening at the same time.\n // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx\n const string installerServiceMutexName = \"Global\\\\_MSIExecute\";\n Mutex MSIExecuteMutex = null;\n var isMsiExecFree = false;\n try\n {\n MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName,\n System.Security.AccessControl.MutexRights.Synchronize);\n isMsiExecFree = MSIExecuteMutex.WaitOne(maxWaitTime, false);\n }\n catch (WaitHandleCannotBeOpenedException)\n {\n // Mutex doesn't exist, do nothing\n isMsiExecFree = true;\n }\n catch (ObjectDisposedException)\n {\n // Mutex was disposed between opening it and attempting to wait on it, do nothing\n isMsiExecFree = true;\n }\n finally\n {\n if(MSIExecuteMutex != null && isMsiExecFree)\n MSIExecuteMutex.ReleaseMutex();\n }\n return isMsiExecFree;\n\n}\n" }, { "answer_id": 33652559, "author": "Roadie", "author_id": 2412770, "author_profile": "https://Stackoverflow.com/users/2412770", "pm_score": 2, "selected": false, "text": "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\nCheck = False\nDo While Not Check\n WScript.Sleep 3000\n Set colServices = objWMIService.ExecQuery(\"Select * From Win32_Service Where Name=\"'msiserver'\")\n For Each objService In colServices\n If (objService.Started And Not objService.AcceptStop) \n WScript.Echo \"Another .MSI is running.\"\n ElseIf ((objService.Started And objService.AcceptStop) Or Not objService.Started) Then\n WScript.Echo \"Ready to install an .MSI application.\"\n Check = True\n End If\n Next\nLoop\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332/" ]
140,825
<p>Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?</p> <pre><code>struct myobj { int value; } /* This macro does not satisfy the read-only requirement */ #define VALUE(o) (o)-&gt;value /* This macro uses a function, unfortunately */ int getvalue(struct myobj *o) { return o-&gt;value; } #define VALUE(o) getvalue(o) void dostuff(struct myobj *foo) { printf("The value of foo is %d.\n", VALUE(foo)); /* OK */ VALUE(foo) = 1; /* We want a compile error here */ foo-&gt;value = 1; /* This is ok. */ } </code></pre>
[ { "answer_id": 140853, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "#define VALUE(x) (x+0)\n #define VALUE(x) (x->value+0)\n" }, { "answer_id": 140870, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": false, "text": "#define VALUE(o) (const int)((o)->value)\n" }, { "answer_id": 140894, "author": "Joshua Swink", "author_id": 14732, "author_profile": "https://Stackoverflow.com/users/14732", "pm_score": 4, "selected": false, "text": "#define VALUE(o) (1 ? (o)->value : 0)\n" }, { "answer_id": 4854735, "author": "J. C. Salomon", "author_id": 95580, "author_profile": "https://Stackoverflow.com/users/95580", "pm_score": 3, "selected": false, "text": "#define VALUE(x) (0, x)\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ]
140,850
<p>I'm using SQL Server 2005, and creating ftp tasks within SSIS. </p> <p>Sometimes there will be files to ftp over, sometimes not. If there are no files, I don't want the task nor the package to fail. I've changed the arrow going from the ftp task to the next to "completion", so the package runs through. I've changed the allowed number of errors to 4 (because there are 4 ftp tasks, and any of the 4 directories may or may not have files). </p> <p>But, when I run the package from a job in agent, it marks the job as failing. Since this will be running every 15 minutes, I don't want a bunch of red x's in my job history, which will cause us to not see a problem when it really does occur. </p> <p>How do I set the properties in the ftp task so that not finding files to ftp is not a failure? The operation I am using is "Send files".</p> <p>Here is some more information: the files are on a server that I don't have any access through except ftp. And, I don't know the filenames ahead of time. The user can call them whatever they want. So I can't check for specific files, nor, I think, can I check at all. Except through using the ftp connection and tasks based upon that connection. The files are on a remote server, and I want to copy them over to my server, to get them from that remote server.</p> <p>I can shell a command level ftp in a script task. Perhaps that is what I need to use instead of a ftp task. (I have changed to use the ftp command line, with a parameter file, called from a script task. It gives no errors when there are no files to get. I think this solution is going to work for me. I'm creating the parameter file dynamically, which means I don't need to have connection information in the plain text file, but rather can be stored in my configuration file, which is in a more secure location.)</p>
[ { "answer_id": 165000, "author": "thursdaysgeek", "author_id": 22523, "author_profile": "https://Stackoverflow.com/users/22523", "pm_score": 2, "selected": false, "text": " Dim ftpStream As StreamWriter = ftpFile.CreateText()\n ftpStream.WriteLine(ftpUser)\n ftpStream.WriteLine(ftpPassword)\n ftpStream.WriteLine(\"prompt off\")\n ftpStream.WriteLine(\"binary\")\n ftpStream.WriteLine(\"cd \" & ftpDestDir)\n ftpStream.WriteLine(\"mput \" & ftpSourceDir)\n ftpStream.WriteLine(\"quit 130\")\n ftpStream.Close()\n ftpParameters = \"-s:\" & ftpParameterLoc & ftpParameterFile & \" \" & ftpServer\n proc = System.Diagnostics.Process.Start(\"ftp\", ftpParameters)\n" }, { "answer_id": 6715972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "Script Task *.txt FTP Connection RemotePath LocalPath FilePattern FileName Foreach loop container DelayValidation Script Task Foreach Loop container FTP Task Foreach Loop container Main() Script Task Foreach Loop container FTP Task *.txt C:\\temp\\ *.xls /Practice/Directory_New C:\\temp\\ SSIS 2008 and above using public void Main()\n{\n Variables varCollection = null;\n ConnectionManager ftpManager = null;\n FtpClientConnection ftpConnection = null;\n string[] fileNames = null;\n string[] folderNames = null;\n System.Collections.ArrayList listOfFiles = null;\n string remotePath = string.Empty;\n string filePattern = string.Empty;\n Regex regexp;\n int counter;\n\n Dts.VariableDispenser.LockForWrite(\"User::RemotePath\");\n Dts.VariableDispenser.LockForWrite(\"User::FilePattern\");\n Dts.VariableDispenser.LockForWrite(\"User::ListOfFiles\");\n Dts.VariableDispenser.GetVariables(ref varCollection);\n\n try\n {\n remotePath = varCollection[\"User::RemotePath\"].Value.ToString();\n filePattern = varCollection[\"User::FilePattern\"].Value.ToString();\n\n ftpManager = Dts.Connections[\"FTP\"];\n ftpConnection = new FtpClientConnection(ftpManager.AcquireConnection(null));\n ftpConnection.Connect();\n ftpConnection.SetWorkingDirectory(remotePath);\n ftpConnection.GetListing(out folderNames, out fileNames);\n ftpConnection.Close();\n\n listOfFiles = new System.Collections.ArrayList();\n if (fileNames != null)\n {\n regexp = new Regex(\"^\" + filePattern + \"$\");\n for (counter = 0; counter <= fileNames.GetUpperBound(0); counter++)\n {\n if (regexp.IsMatch(fileNames[counter]))\n {\n listOfFiles.Add(remotePath + fileNames[counter]);\n }\n }\n }\n\n varCollection[\"User::ListOfFiles\"].Value = listOfFiles;\n }\n catch (Exception ex)\n {\n Dts.Events.FireError(-1, string.Empty, ex.ToString(), string.Empty, 0);\n Dts.TaskResult = (int) ScriptResults.Failure;\n }\n finally\n {\n varCollection.Unlock();\n ftpConnection = null;\n ftpManager = null;\n }\n\n Dts.TaskResult = (int)ScriptResults.Success;\n}\n SSIS 2005 and above Imports Public Sub Main()\n Dim varCollection As Variables = Nothing\n Dim ftpManager As ConnectionManager = Nothing\n Dim ftpConnection As FtpClientConnection = Nothing\n Dim fileNames() As String = Nothing\n Dim folderNames() As String = Nothing\n Dim listOfFiles As Collections.ArrayList\n Dim remotePath As String = String.Empty\n Dim filePattern As String = String.Empty\n Dim regexp As Regex\n Dim counter As Integer\n\n Dts.VariableDispenser.LockForRead(\"User::RemotePath\")\n Dts.VariableDispenser.LockForRead(\"User::FilePattern\")\n Dts.VariableDispenser.LockForWrite(\"User::ListOfFiles\")\n Dts.VariableDispenser.GetVariables(varCollection)\n\n Try\n\n remotePath = varCollection(\"User::RemotePath\").Value.ToString()\n filePattern = varCollection(\"User::FilePattern\").Value.ToString()\n\n ftpManager = Dts.Connections(\"FTP\")\n ftpConnection = New FtpClientConnection(ftpManager.AcquireConnection(Nothing))\n\n ftpConnection.Connect()\n ftpConnection.SetWorkingDirectory(remotePath)\n ftpConnection.GetListing(folderNames, fileNames)\n ftpConnection.Close()\n\n listOfFiles = New Collections.ArrayList()\n If fileNames IsNot Nothing Then\n regexp = New Regex(\"^\" & filePattern & \"$\")\n For counter = 0 To fileNames.GetUpperBound(0)\n If regexp.IsMatch(fileNames(counter)) Then\n listOfFiles.Add(remotePath & fileNames(counter))\n End If\n Next counter\n End If\n\n varCollection(\"User::ListOfFiles\").Value = listOfFiles\n\n Dts.TaskResult = ScriptResults.Success\n\n Catch ex As Exception\n Dts.Events.FireError(-1, String.Empty, ex.ToString(), String.Empty, 0)\n Dts.TaskResult = ScriptResults.Failure\n Finally\n varCollection.Unlock()\n ftpConnection = Nothing\n ftpManager = Nothing\n End Try\n\n Dts.TaskResult = ScriptResults.Success\nEnd Sub\n" }, { "answer_id": 9363496, "author": "Chad", "author_id": 44698, "author_profile": "https://Stackoverflow.com/users/44698", "pm_score": 0, "selected": false, "text": "Dts.Variables[\"FTP_Error\"].Value = \"ErrorCode:\" + Dts.Variables[\"ErrorCode\"].Value.ToString() + \", ErrorDescription=\" + Dts.Variables[\"ErrorDescription\"].Value.ToString();\n if (Dts.Variables[\"FTP_Error\"].Value.ToString().Contains(\"-1073573501\"))\n{\n // file not found - not a problem\n Dts.TaskResult = (int)ScriptResults.Success;\n}\nelse\n{\n // some other error - raise alarm!\n Dts.TaskResult = (int)ScriptResults.Failure;\n}\n" }, { "answer_id": 48816550, "author": "Todd Hoffert", "author_id": 9367125, "author_profile": "https://Stackoverflow.com/users/9367125", "pm_score": 1, "selected": false, "text": " public void Main()\n {\n // TODO: Add your code here\n\n int errorCode = (int)Dts.Variables[\"System::ErrorCode\"].Value;\n\n if (errorCode.ToString().Equals(\"-1073573501\"))\n {\n Dts.Variables[\"System::Propagate\"].Value = false;\n }\n else\n {\n Dts.Variables[\"System::Propagate\"].Value = true;\n }\n\n\n Dts.TaskResult = (int)ScriptResults.Success;\n }\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22523/" ]
140,852
<p>I have a nested class. I want to access the outer and nested classes in other class. How to access both class properties and methods and my condition is i want to create object for only one class plz provide the code snippet</p>
[ { "answer_id": 140881, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 0, "selected": false, "text": "public class Foo() {\n public Foo() { }\n\n private Bar m_Bar = new Bar(); \n\n public Bar TheBar { get { return m_Bar; } }\n\n public class Bar { ... }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
140,869
<p>I'm on a team maintaining a .Net web app with a SQL Server 2005 back end. The system's been running a little slow in places lately, so after doing all the tuning kind of stuff we could think of (adding indexes, cleaning up really badly written stored procedures, etc.) I ran a typical workload through the Tuning Advisor - and it spit out a huge list of additional Indexes and Statistics to create. My initial reaction was to say "sure, you got it, SQL Server," but is there ever any reason NOT to just do what the Advisor says?</p>
[ { "answer_id": 142668, "author": "Nicholas Head", "author_id": 22505, "author_profile": "https://Stackoverflow.com/users/22505", "pm_score": 2, "selected": false, "text": "SELECT\n migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,\n 'CREATE INDEX [missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)\n + '_' + LEFT (PARSENAME(mid.statement, 1), 32) + ']'\n + ' ON ' + mid.statement\n + ' (' + ISNULL (mid.equality_columns,'')\n + CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END\n + ISNULL (mid.inequality_columns, '')\n + ')'\n + ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,\n migs.*, mid.database_id, mid.[object_id]\nFROM sys.dm_db_missing_index_groups mig\nINNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle\nINNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle\nWHERE migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) > 10\nORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC \n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
140,908
<p>Is there any framework for querying XML SQL Syntax, I seriously tire of iterating through node lists. <hr> Or is this just wishful thinking (if not idiotic) and certainly not possible since XML isn't a relational database?</p>
[ { "answer_id": 140914, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 2, "selected": false, "text": "ReadXml()" }, { "answer_id": 142491, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "xml" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
140,926
<p>I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?</p> <p>So something that would yield this kind of translation table:</p> <pre><code>\r --&gt; \r\n \n --&gt; \r\n \n\n --&gt; \r\n\r\n \n\r --&gt; \r\n \r\n --&gt; \r\n \r\n\n --&gt; \r\n\r\n </code></pre>
[ { "answer_id": 140952, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "\\r => \\r \n\\n => \\n \n\\n\\n => \\n\\n \n\\n\\r => \\n\\r \n\\r\\n => \\r\\n \n\\r\\n => \\r\\n \n\\n => \\n \n" }, { "answer_id": 141016, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "char[] chunk = new char[X];\nStringBuffer output = new StringBuffer();\n\nbuffer.Read(chunk);\nforeach (char c in chunk)\n{\n switch (c)\n {\n case '\\r' : break; // ignore\n case '\\n' : output.Append(\"\\r\\n\");\n default : output.Append(c);\n }\n }\n" }, { "answer_id": 141069, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 6, "selected": true, "text": "using System.Text.RegularExpressions;\n// ...\nstring normalized = Regex.Replace(originalString, @\"\\r\\n|\\n\\r|\\n|\\r\", \"\\r\\n\");\n $str =~ s/\\r\\n|\\n\\r|\\n|\\r/\\r\\n/g;\n [bash$] ./test.pl\n\\r -> \\r\\n\n\\n -> \\r\\n\n\\n\\n -> \\r\\n\\r\\n\n\\n\\r -> \\r\\n\n\\r\\n -> \\r\\n\n\\r\\n\\n -> \\r\\n\\r\\n\n" }, { "answer_id": 41696844, "author": "Phil", "author_id": 5048621, "author_profile": "https://Stackoverflow.com/users/5048621", "pm_score": 2, "selected": false, "text": "\\r\\n var normalisedString =\n sourceString\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\\r\", \"\\n\")\n .Replace(\"\\r\", \"\\n\")\n .Replace(\"\\n\", \"\\r\\n\");\n" }, { "answer_id": 47349387, "author": "Roberto B", "author_id": 2641447, "author_profile": "https://Stackoverflow.com/users/2641447", "pm_score": 0, "selected": false, "text": "public static string NormalizeNewLine(this string val)\n{\n if (string.IsNullOrEmpty(val))\n return val;\n\n const int page = 6;\n int a = page;\n int j = 0;\n int len = val.Length;\n char[] res = new char[len];\n\n for (int i = 0; i < len; i++)\n {\n char ch = val[i];\n\n if (ch == '\\r')\n {\n int ni = i + 1;\n if (ni < len && val[ni] == '\\n')\n {\n res[j++] = '\\r';\n res[j++] = '\\n';\n i++;\n }\n else\n {\n if (a == page) //ensure capacity\n {\n char[] nres = new char[res.Length + page];\n Array.Copy(res, 0, nres, 0, res.Length);\n res = nres;\n a = 0;\n }\n\n res[j++] = '\\r';\n res[j++] = '\\n';\n a++;\n }\n }\n else if (ch == '\\n')\n {\n int ni = i + 1;\n if (ni < len && val[ni] == '\\r')\n {\n res[j++] = '\\r';\n res[j++] = '\\n';\n i++;\n }\n else\n {\n if (a == page) //ensure capacity\n {\n char[] nres = new char[res.Length + page];\n Array.Copy(res, 0, nres, 0, res.Length);\n res = nres;\n a = 0;\n }\n\n res[j++] = '\\r';\n res[j++] = '\\n';\n a++;\n }\n }\n else\n {\n res[j++] = ch;\n }\n }\n\n return new string(res, 0, j);\n}\n" }, { "answer_id": 64300331, "author": "GDavoli", "author_id": 5429854, "author_profile": "https://Stackoverflow.com/users/5429854", "pm_score": 2, "selected": false, "text": "\\r \\n \\r \\r \\r\\n normalized = \n original.Replace(\"\\r\\n\", \"\\r\").\n Replace(\"\\n\\r\", \"\\r\").\n Replace(\"\\n\", \"\\r\").\n Replace(\"\\r\", \"\\r\\n\"); // last step\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13154/" ]
140,935
<p>Anyone knows if is possible to have partial class definition on C++ ?</p> <p>Something like:</p> <p>file1.h:</p> <pre> class Test { public: int test1(); }; </pre> <p>file2.h: </p> <pre> class Test { public: int test2(); }; </pre> <p>For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.</p> <p>I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. </p> <p>Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:</p> <pre> class genericTest { public: int genericMethod(); }; </pre> <p>Then let's say for win32:</p> <pre> class win32Test: public genericTest { public: int win32Method(); }; </pre> <p>And maybe:</p> <pre> class macTest: public genericTest { public: int macMethod(); }; </pre> <p>Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:</p> <pre> #ifdef _WIN32 genericTest *test = new win32Test(); #elif MAC genericTest *test = new macTest(); #endif test->genericMethod(); </pre> <p>Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.</p> <p>That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.</p>
[ { "answer_id": 140942, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 4, "selected": false, "text": "class AllPlatforms {\npublic:\n int common();\n};\n class PlatformA : public AllPlatforms {\npublic:\n int specific();\n};\n" }, { "answer_id": 141085, "author": "PiNoYBoY82", "author_id": 13646, "author_profile": "https://Stackoverflow.com/users/13646", "pm_score": 4, "selected": false, "text": "class Test\n{\npublic:\n ...\n void common();\n ...\nprivate:\n class TestImpl;\n TestImpl* m_customImpl;\n};\n" }, { "answer_id": 141092, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 2, "selected": false, "text": "class WindowsFuncs { public: int f(); int winf(); };\nclass MacFuncs { public: int f(); int macf(); }\n\nclass Funcs\n#ifdef Windows \n : public WindowsFuncs\n#else\n : public MacFuncs\n#endif\n{\npublic:\n Funcs();\n int g();\n};\n Funcs" }, { "answer_id": 141482, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "#include will work as that is preprocessor stuff.\n\nclass Foo\n{\n#include \"FooFile_Private.h\"\n}\n\n////////\n\nFooFile_Private.h:\n\nprivate:\n void DoSg();\n" }, { "answer_id": 150018, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 4, "selected": false, "text": "template <typename T>\nclass genericTest {\npublic:\n void genericMethod() {\n // do some generic things\n std::cout << \"Could be any platform, I don't know\" << std::endl;\n // base class can call a method in the child with static_cast\n (static_cast<T*>(this))->doClassDependentThing();\n }\n};\n\n#ifdef _WIN32\n typedef Win32Test Test;\n#elif MAC\n typedef MacTest Test;\n#endif\n class Win32Test : public genericTest<Win32Test> {\npublic:\n void win32Method() {\n // windows-specific stuff:\n std::cout << \"I'm in windows\" << std::endl;\n // we can call a method in the base class\n genericMethod();\n // more windows-specific stuff...\n }\n void doClassDependentThing() {\n std::cout << \"Yep, definitely in windows\" << std::endl;\n }\n};\n class MacTest : public genericTest<MacTest> {\npublic:\n void macMethod() {\n // mac-specific stuff:\n std::cout << \"I'm in MacOS\" << std::endl;\n // we can call a method in the base class\n genericMethod();\n // more mac-specific stuff...\n }\n void doClassDependentThing() {\n std::cout << \"Yep, definitely in MacOS\" << std::endl;\n }\n};\n #ifdef _WIN32\n typedef genericTest<Win32Test> BaseTest;\n#elif MAC\n typedef genericTest<MacTest> BaseTest;\n#endif\n" }, { "answer_id": 9195739, "author": "jessn", "author_id": 1197478, "author_profile": "https://Stackoverflow.com/users/1197478", "pm_score": 1, "selected": false, "text": "partial class UserAuthentication {\n private string user;\n private string password;\n public bool signon(string usr, string pwd);\n}\n\npartial class UserAuthentication {\n private string getPassword() { return password; }\n}\n" }, { "answer_id": 21412322, "author": "SONIC3D", "author_id": 1758069, "author_profile": "https://Stackoverflow.com/users/1758069", "pm_score": 2, "selected": false, "text": "#ifndef TEST_H\n#define TEST_H\n\nclass Test\n{\npublic:\n Test(void);\n virtual ~Test(void);\n\n#include \"Test_Partial_Win32.h\"\n#include \"Test_Partial_OSX.h\"\n\n};\n\n#endif // !TEST_H\n // This file should be included in Test.h only.\n\n#ifdef MAC\n public:\n int macMethod();\n#endif // MAC\n // This file should be included in Test.h only.\n\n#ifdef _WIN32\n public:\n int win32Method();\n#endif // _WIN32\n // Implement common member function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\nTest::Test(void)\n{\n}\n\nTest::~Test(void)\n{\n}\n // Implement OSX platform specific function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\n#ifdef MAC\nint Test::macMethod()\n{\n return 0;\n}\n#endif // MAC\n // Implement WIN32 platform specific function of class Test in this file.\n\n#include \"stdafx.h\"\n#include \"Test.h\"\n\n#ifdef _WIN32\nint Test::win32Method()\n{\n return 0;\n}\n#endif // _WIN32\n" }, { "answer_id": 27894388, "author": "orfdorf", "author_id": 3734880, "author_profile": "https://Stackoverflow.com/users/3734880", "pm_score": 1, "selected": false, "text": "template <typename TResource, typename TParams, typename TKey>\nclass IResource\n{\npublic:\n virtual TKey GetKey() const = 0;\nprotected:\n static shared_ptr<TResource> Create(const TParams& params)\n {\n return ResourceManager::GetInstance().Load(params);\n }\n virtual Status Initialize(const TParams& params, const TKey key, shared_ptr<Viewer> pViewer) = 0;\n};\n Create template <typename TResource, typename TParams, typename TKey>\nclass TResourceManager\n{\n sptr<TResource> Load(const TParams& params) { ... }\n};\n Load Initialize class Texture2D : public IResource<Texture2D , Params::Texture2D , Key::Texture2D >\n{\n typedef TResourceManager<Texture2D , Params::Texture2D , Key::Texture2D > ResourceManager;\n friend class ResourceManager;\n\npublic:\n virtual Key::Texture2D GetKey() const override final;\n void GetWidth() const;\nprivate:\n virtual Status Initialize(const Params::Texture2D & params, const Key::Texture2D key, shared_ptr<Texture2D > pTexture) override final;\n\n struct Impl;\n unique_ptr<Impl> m;\n};\n GetWidth Create Create #ifdef #ifdef // D3DTexture2DImpl.h\n#include \"Texture2D.h\"\nstruct Texture2D::Impl\n{\n /* insert D3D-specific stuff here */\n};\n\n// OGLTexture2DImpl.h\n#include \"Texture2D.h\"\nstruct Texture2D::Impl\n{\n /* insert OGL-specific stuff here */\n};\n\n// Texture2D.cpp\n#include \"Texture2D.h\"\n\n#ifdef USING_D3D\n#include \"D3DTexture2DImpl.h\"\n#else\n#include \"OGLTexture2DImpl.h\"\n#endif\n\nKey::Texture2D Texture2D::GetKey() const\n{\n return m->key;\n}\n// etc...\n" }, { "answer_id": 57608411, "author": "user11962338", "author_id": 11962338, "author_profile": "https://Stackoverflow.com/users/11962338", "pm_score": 2, "selected": false, "text": "class MyClass\n{\n #include <MyClass_Part1.hpp>\n #include <MyClass_Part2.hpp>\n #include <MyClass_Part3.hpp>\n};\n #include <MyClass.hpp>" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ]
140,996
<p>In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:</p> <pre><code>&lt;TextBlock&gt;&lt;Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}"&gt;Object Name&lt;/Hyperlink&gt;&lt;/TextBlock&gt; </code></pre> <p>But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:</p> <pre><code>&lt;TextBlock&gt;&lt;Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/&gt;&lt;/TextBlock&gt; </code></pre> <p>However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).</p> <p>Any ideas?</p>
[ { "answer_id": 141008, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 9, "selected": true, "text": "Hyperlink <Run/> <Run/> TextBlock <TextBlock>\n <Hyperlink Command=\"local:MyCommands.ViewDetails\" CommandParameter=\"{Binding}\">\n <TextBlock Text=\"{Binding Path=Name}\"/>\n </Hyperlink>\n</TextBlock>\n <Run Text=\"{Binding Path=Name}\" />\n" }, { "answer_id": 1801586, "author": "Jamie Clayton", "author_id": 219119, "author_profile": "https://Stackoverflow.com/users/219119", "pm_score": 4, "selected": false, "text": "<TextBlock>\n <Hyperlink NavigateUri=\"{Binding Path}\">\n <TextBlock Text=\"{Binding Path=Path}\" />\n </Hyperlink>\n</TextBlock>\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/140996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22789/" ]
141,002
<p>I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"</p> <p>Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field. So we have the destination field: <code>&lt;input id="dest" name="dest" value="0"&gt;</code> <br>And the source field: <code>&lt;input id="source" name="source" value="1"&gt;</code> <br>Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <code>&lt;input id="source" name="source" value="2"&gt;</code></p> <p>Ok after the javascript line that copies the ajax data to innerHTML the next line is: <code>document.getElementById('dest').value = document.getElementById('source').value;</code></p> <p>I get the following error: <code>Error: document.getElementById("source") has no properties</code></p> <p>(I also tried <code>document.formname.source</code> and <code>document.formname.dest</code> and same problem)</p> <p>What am I missing?</p> <p>Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.</p> <p>Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.</p> <p>Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.</p> <p>Extra pair of eyes FTW.</p> <p>Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...</p> <p>Thanks for the help guys.</p>
[ { "answer_id": 141075, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 2, "selected": false, "text": "<div id=\"test2\">\n <input id=\"source\" value=\"0\" />\n</div>\n<input id=\"dest\" value=\"1\" />\n\n<script type=\"text/javascript\" charset=\"utf-8\">\n//<![CDATA[\nfunction pageLoad()\n{\n var container = document.getElementById('test2');\n container.innerHTML = \"<input id='source' value='2' />\";\n var source = document.getElementById('source');\n var dest = document.getElementById('dest');\n dest.value = source.value;\n}\n//]]>\n</script>\n" }, { "answer_id": 141101, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 0, "selected": false, "text": "setTimeout(function() {\n document.getElementById(\"dest\").value = document.getElementById(\"source\").value;\n}, 10);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153/" ]
141,007
<p>Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key?</p> <p>For instance, I have this resource in XAML:</p> <pre><code>&lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}" ItemsSource="{Binding Path=Value.Values}"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;HierarchicalDataTemplate&gt; &lt;/TreeView.Resources&gt; </code></pre> <p>I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types?</p> <p>Here's what I've done in C# so far:</p> <pre><code>HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo"); fieldPropertyTemplate.ItemsSource = new Binding("Value.Values"); this.Resources.Add(null, fieldPropertyTemplate); </code></pre> <p>Obviously, adding a resource to the ResourceDictionary the key null doesn't work.</p>
[ { "answer_id": 141018, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);\n" }, { "answer_id": 141032, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 4, "selected": true, "text": "HierarchicalDataTemplate fieldPropertyTemplate = new \n HierarchicalDataTemplate(\"FieldProperyInfo\");\n\nfieldPropertyTemplate.SetBinding(\n HierarchialDataTemplate.ItemSourceProperty, \n new Binding(\"Value.Values\");\nthis.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
141,045
<p>I want to replace the first occurrence in a given string. </p> <p>How can I accomplish this in .NET?</p>
[ { "answer_id": 141076, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 7, "selected": false, "text": "string ReplaceFirst(string text, string search, string replace)\n{\n int pos = text.IndexOf(search);\n if (pos < 0)\n {\n return text;\n }\n return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);\n}\n string str = \"The brown brown fox jumps over the lazy dog\";\n\nstr = ReplaceFirst(str, \"brown\", \"quick\");\n public static class StringExtension\n{\n public static string ReplaceFirst(this string text, string search, string replace)\n {\n // ...same as above...\n }\n}\n str = str.ReplaceFirst(\"brown\", \"quick\");\n" }, { "answer_id": 141089, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "int loc = original.IndexOf(oldValue);\nif( loc < 0 ) {\n return original;\n}\nreturn original.Remove(loc, oldValue.Length).Insert(loc, newValue);\n" }, { "answer_id": 141100, "author": "mortenbpost", "author_id": 17577, "author_profile": "https://Stackoverflow.com/users/17577", "pm_score": 3, "selected": false, "text": "public static class StringExt\n{\n public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)\n {\n int i = s.IndexOf(oldValue);\n return s.Remove(i, oldValue.Length).Insert(i, newValue); \n } \n}\n" }, { "answer_id": 141196, "author": "Anthony Potts", "author_id": 22777, "author_profile": "https://Stackoverflow.com/users/22777", "pm_score": 2, "selected": false, "text": "Private Function ReplaceFirst(ByVal text As String, ByVal search As String, ByVal replace As String) As String\n Dim pos As Integer = text.IndexOf(search)\n If pos >= 0 Then\n Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)\n End If\n Return text \nEnd Function\n" }, { "answer_id": 146747, "author": "Wes Haggard", "author_id": 12784, "author_profile": "https://Stackoverflow.com/users/12784", "pm_score": 6, "selected": false, "text": "using System.Text.RegularExpressions;\n...\nRegex regex = new Regex(\"foo\");\nstring result = regex.Replace(\"foo1 foo2 foo3 foo4\", \"bar\", 1); \n// result = \"bar1 foo2 foo3 foo4\"\n" }, { "answer_id": 3012392, "author": "Deenesh", "author_id": 363194, "author_profile": "https://Stackoverflow.com/users/363194", "pm_score": 4, "selected": false, "text": "using System.Text.RegularExpressions;\n\nRegEx MyRegEx = new RegEx(\"F\");\nstring result = MyRegex.Replace(InputString, \"R\", 1);\n F InputString R" }, { "answer_id": 4086812, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "int index = input.IndexOf(\"AA\");\nif (index >= 0) output = input.Substring(0, index) + \"XQ\" +\n input.Substring(index + 2);\n public static string ReplaceFirstInstance(this string source,\n string find, string replace)\n{\n int index = source.IndexOf(find);\n return index < 0 ? source : source.Substring(0, index) + replace +\n source.Substring(index + find.Length);\n}\n string output = input.ReplaceFirstInstance(\"AA\", \"XQ\");\n" }, { "answer_id": 4086818, "author": "Oded", "author_id": 1583, "author_profile": "https://Stackoverflow.com/users/1583", "pm_score": 3, "selected": false, "text": "AA var newString;\nif(myString.StartsWith(\"AA\"))\n{\n newString =\"XQ\" + myString.Substring(2);\n}\n AA" }, { "answer_id": 4086855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "string abc = \"AAAAX1\";\n\n if(abc.IndexOf(\"AA\") == 0)\n {\n abc.Remove(0, 2);\n abc = \"XQ\" + abc;\n }\n" }, { "answer_id": 4086902, "author": "AakashM", "author_id": 71059, "author_profile": "https://Stackoverflow.com/users/71059", "pm_score": 2, "selected": false, "text": "Regex.Replace int Regex.Replace string output = (new Regex(\"AA\")).Replace(input, \"XQ\", 1);\n" }, { "answer_id": 37401160, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var parts = contents.ToString().Split(new string[] { \"needle\" }, 2, StringSplitOptions.None);\nreturn parts[0] + \"replacement\" + parts[1];\n" }, { "answer_id": 42533240, "author": "Slai", "author_id": 1383168, "author_profile": "https://Stackoverflow.com/users/1383168", "pm_score": 2, "selected": false, "text": "Microsoft.VisualBasic Replace string result = Microsoft.VisualBasic.Strings.Replace(\"111\", \"1\", \"0\", 2, 1); // \"101\"\n" }, { "answer_id": 63457947, "author": "Brad Patton", "author_id": 27989, "author_profile": "https://Stackoverflow.com/users/27989", "pm_score": 0, "selected": false, "text": "Span public static string ReplaceFirstOccurrence(this string source, string search, string replace) {\n int index = source.IndexOf(search);\n if (index < 0) return source;\n var sourceSpan = source.AsSpan();\n return string.Concat(sourceSpan.Slice(0, index), replace, sourceSpan.Slice(index + search.Length));\n }\n" }, { "answer_id": 72287953, "author": "Matěj Štágl", "author_id": 9250482, "author_profile": "https://Stackoverflow.com/users/9250482", "pm_score": 0, "selected": false, "text": "public static string ReplaceFirst(this string text, string search, string replace)\n{\n int pos = text.IndexOf(search, StringComparison.Ordinal);\n return pos < 0 ? text : string.Concat(text[..pos], replace, text.AsSpan(pos + search.Length));\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
141,052
<p>I have been looking for documentation related to interacting with MSPaint from the command line. I have only found references to /p, /pt and /wia, but no guidance as to how to use them and their limitations.</p> <p>I am trying to send some graphics files to the printer and when I drop the file on my printer driver I get a different print output than if I call paint from the command line. I am using the UDC print driver to convert graphics, and I am using paint to send my graphics file to the printer driver in order for my file to convert. </p> <p>Any ideas? </p>
[ { "answer_id": 141087, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 3, "selected": true, "text": "mspaint /p filename mspaint /pt filename /wia" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178/" ]
141,068
<p>I have an Image column (Allow Null = true) in SQL Server 2005. I am using Crystal Reports designer (ver 10.5) that comes with Visual Studio 2008. Crystal sees the column as blob field and puts an image object for the column. When I am trying to limit the record selection by using </p> <pre><code> NOT ISNULL({Employee.Picture}) </code></pre> <p>as Selection Formula, I get the following error:</p> <blockquote> <p>Error in formula .<br> 'NOT (ISNULL({Employee.Picture}))'<br> This function cannot be used because it must be evaluated later.</p> </blockquote> <p>Is there a way to filter out rows with out pictures?</p> <p>Thanks,<br> Kishore A</p>
[ { "answer_id": 268068, "author": "David T. Macknet", "author_id": 6850, "author_profile": "https://Stackoverflow.com/users/6850", "pm_score": 1, "selected": false, "text": "ISNULL SWITCH WHERE NOT Employee.Picture IS NULL\n IS NULL" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169/" ]
141,088
<p>I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?</p>
[ { "answer_id": 141098, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 13, "selected": true, "text": "foreach(KeyValuePair<string, string> entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n" }, { "answer_id": 141102, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 6, "selected": false, "text": "foreach foreach(var kvp in my_dictionary) {\n ...\n}\n" }, { "answer_id": 141105, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 10, "selected": false, "text": "foreach(var item in myDictionary)\n{\n foo(item.Key);\n bar(item.Value);\n}\n foreach(var item in myDictionary.Keys)\n{\n foo(item);\n}\n foreach(var item in myDictionary.Values)\n{\n foo(item);\n}\n var" }, { "answer_id": 141106, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 5, "selected": false, "text": "Dictionary<string, object> myDictionary = new Dictionary<string, object>();\n// Populate your dictionary here\n\nforeach (KeyValuePair<string,object> kvp in myDictionary)\n{\n // Do some interesting things\n}\n" }, { "answer_id": 141132, "author": "J Healy", "author_id": 5946, "author_profile": "https://Stackoverflow.com/users/5946", "pm_score": 7, "selected": false, "text": "Dictionary(TKey, TValue) // When you use foreach to enumerate dictionary elements,\n// the elements are retrieved as KeyValuePair objects.\nConsole.WriteLine();\nforeach( KeyValuePair<string, string> kvp in openWith )\n{\n Console.WriteLine(\"Key = {0}, Value = {1}\", \n kvp.Key, kvp.Value);\n}\n\n// To get the values alone, use the Values property.\nDictionary<string, string>.ValueCollection valueColl =\n openWith.Values;\n\n// The elements of the ValueCollection are strongly typed\n// with the type that was specified for dictionary values.\nConsole.WriteLine();\nforeach( string s in valueColl )\n{\n Console.WriteLine(\"Value = {0}\", s);\n}\n\n// To get the keys alone, use the Keys property.\nDictionary<string, string>.KeyCollection keyColl =\n openWith.Keys;\n\n// The elements of the KeyCollection are strongly typed\n// with the type that was specified for dictionary keys.\nConsole.WriteLine();\nforeach( string s in keyColl )\n{\n Console.WriteLine(\"Key = {0}\", s);\n}\n" }, { "answer_id": 351763, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public new IEnumerator<T> GetEnumerator()\n{\n return this.Values.GetEnumerator();\n}\n" }, { "answer_id": 559263, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "foreach (DictionaryEntry de in myDictionary)\n{\n //Do some stuff with de.Value or de.Key\n}" }, { "answer_id": 5265690, "author": "Maurício Fedatto", "author_id": 654288, "author_profile": "https://Stackoverflow.com/users/654288", "pm_score": 8, "selected": false, "text": "ElementAt for (int index = 0; index < dictionary.Count; index++) {\n var item = dictionary.ElementAt(index);\n var itemKey = item.Key;\n var itemValue = item.Value;\n}\n" }, { "answer_id": 24521742, "author": "ender", "author_id": 885175, "author_profile": "https://Stackoverflow.com/users/885175", "pm_score": 3, "selected": false, "text": "foreach(var value in dictionary.Values)\n{\n // do something with entry.Value only\n}\n" }, { "answer_id": 25035004, "author": "Liath", "author_id": 352176, "author_profile": "https://Stackoverflow.com/users/352176", "pm_score": 5, "selected": false, "text": "public static string Normal(Dictionary<string, string> dictionary)\n{\n string value;\n int count = 0;\n foreach (var kvp in dictionary)\n {\n value = kvp.Value;\n count++;\n }\n\n return \"Normal\";\n}\n public static string Keys(Dictionary<string, string> dictionary)\n{\n string value;\n int count = 0;\n foreach (var key in dictionary.Keys)\n {\n value = dictionary[key];\n count++;\n }\n\n return \"Keys\";\n}\n private static string RunTest<T>(T dictionary, Func<T, string> function)\n{ \n DateTime start = DateTime.Now;\n string name = null;\n for (int i = 0; i < 10; i++)\n {\n name = function(dictionary);\n }\n DateTime end = DateTime.Now;\n var duration = end.Subtract(start);\n return string.Format(\"{0} took {1} seconds\", name, duration.TotalSeconds);\n}\n" }, { "answer_id": 26152183, "author": "yazanpro", "author_id": 465495, "author_profile": "https://Stackoverflow.com/users/465495", "pm_score": 2, "selected": false, "text": "foreach(var entry in MyDic)\n{\n // do something with entry.Value or entry.Key\n}\n" }, { "answer_id": 30510215, "author": "Egor Okhterov", "author_id": 1509251, "author_profile": "https://Stackoverflow.com/users/1509251", "pm_score": -1, "selected": false, "text": "var dictionary = new Dictionary<string, int>\n{\n { \"Key\", 12 }\n};\n\nvar aggregateObjectCollection = dictionary.Select(\n entry => new AggregateObject(entry.Key, entry.Value));\n" }, { "answer_id": 30782291, "author": "Onur", "author_id": 2417052, "author_profile": "https://Stackoverflow.com/users/2417052", "pm_score": 6, "selected": false, "text": "dictionary\n.AsParallel()\n.ForAll(pair => \n{ \n // Process pair.Key and pair.Value here\n});\n" }, { "answer_id": 31918117, "author": "Stéphane Gourichon", "author_id": 1429390, "author_profile": "https://Stackoverflow.com/users/1429390", "pm_score": 7, "selected": false, "text": "foreach (var kvp in items)\n{\n // key is kvp.Key\n doStuff(kvp.Value)\n}\n item kvp.Value foreach (var item in items.Values)\n{\n doStuff(item)\n}\n foreach (var kvp in items.OrderBy(kvp => kvp.Key))\n{\n // key is kvp.Key\n doStuff(kvp.Value)\n}\n item kvp.Value foreach (var item in items.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))\n{\n doStuff(item)\n}\n" }, { "answer_id": 38634404, "author": "Nick", "author_id": 1815752, "author_profile": "https://Stackoverflow.com/users/1815752", "pm_score": 2, "selected": false, "text": "foreach (DictionaryEntry entry in myDictionary)\n{\n //Read entry.Key and entry.Value here\n}\n" }, { "answer_id": 39535791, "author": "Alex", "author_id": 1223276, "author_profile": "https://Stackoverflow.com/users/1223276", "pm_score": -1, "selected": false, "text": "Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();\n\n//Add some entries to the dictionary\n\nmyProductPrices.ToList().ForEach(kvP => \n{\n kvP.Value *= 1.15;\n Console.Writeline(String.Format(\"Product '{0}' has a new price: {1} $\", kvp.Key, kvP.Value));\n});\n var newProductPrices = myProductPrices.Select(kvp => new { Name = kvp.Key, Price = kvp.Value * 1.15 } );\n" }, { "answer_id": 39813726, "author": "Ron", "author_id": 672096, "author_profile": "https://Stackoverflow.com/users/672096", "pm_score": 4, "selected": false, "text": "foreach(var item in myDictionary)\n{ \n Console.WriteLine(item.Key);\n Console.WriteLine(item.Value);\n}\n" }, { "answer_id": 46793626, "author": "Pavel", "author_id": 6131611, "author_profile": "https://Stackoverflow.com/users/6131611", "pm_score": 4, "selected": false, "text": ".NET Framework 4.7 var fruits = new Dictionary<string, int>();\n...\nforeach (var (fruit, number) in fruits)\n{\n Console.WriteLine(fruit + \": \" + number);\n}\n System.ValueTuple NuGet package public static class MyExtensions\n{\n public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple,\n out T1 key, out T2 value)\n {\n key = tuple.Key;\n value = tuple.Value;\n }\n}\n" }, { "answer_id": 49856111, "author": "Sheo Dayal Singh", "author_id": 5736534, "author_profile": "https://Stackoverflow.com/users/5736534", "pm_score": 0, "selected": false, "text": "Dictionary<int, string> dict = new Dictionary<int, string>();\ndict.Add(1,\"One\");\ndict.Add(2,\"Two\");\ndict.Add(3,\"Three\");\n\nforeach (KeyValuePair<int, string> item in dict)\n{\n Console.WriteLine(\"Key: {0}, Value: {1}\", item.Key, item.Value);\n}\n" }, { "answer_id": 50552122, "author": "sɐunıɔןɐqɐp", "author_id": 823321, "author_profile": "https://Stackoverflow.com/users/823321", "pm_score": 4, "selected": false, "text": "public static class IDictionaryExtensions\n{\n public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(\n this IDictionary<TKey, TValue> dict)\n {\n foreach (KeyValuePair<TKey, TValue> kvp in dict)\n yield return (kvp.Key, kvp.Value);\n }\n}\n foreach (var(id, value) in dict.Tuples())\n{\n // your code using 'id' and 'value'\n}\n foreach ((string id, object value) in dict.Tuples())\n{\n // your code using 'id' and 'value'\n}\n foreach (KeyValuePair<string, object> kvp in dict)\n{\n string id = kvp.Key;\n object value = kvp.Value;\n\n // your code using 'id' and 'value'\n}\n KeyValuePair IDictionary<TKey, TValue> tuple tuples tuples tuple KeyValuePair KeyValuePair Key Value" }, { "answer_id": 50755179, "author": "Steven Delrue", "author_id": 1107617, "author_profile": "https://Stackoverflow.com/users/1107617", "pm_score": 2, "selected": false, "text": "public static class DictionaryExtension\n{\n public static void ForEach<T1, T2>(this Dictionary<T1, T2> dictionary, Action<T1, T2> action) {\n foreach(KeyValuePair<T1, T2> keyValue in dictionary) {\n action(keyValue.Key, keyValue.Value);\n }\n }\n}\n myDictionary.ForEach((x,y) => Console.WriteLine(x + \" - \" + y));\n" }, { "answer_id": 51291784, "author": "Domn Werner", "author_id": 4025444, "author_profile": "https://Stackoverflow.com/users/4025444", "pm_score": 4, "selected": false, "text": "KeyValuePair<TKey, TVal> public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value)\n{\n key = pair.Key;\n value = pair.Value;\n}\n Dictionary<TKey, TVal> // Dictionary can be of any types, just using 'int' and 'string' as examples.\nDictionary<int, string> dict = new Dictionary<int, string>();\n\n// Deconstructor gets called here.\nforeach (var (key, value) in dict)\n{\n Console.WriteLine($\"{key} : {value}\");\n}\n" }, { "answer_id": 51921755, "author": "BigChief", "author_id": 539251, "author_profile": "https://Stackoverflow.com/users/539251", "pm_score": -1, "selected": false, "text": "foreach(KeyValuePair<string, string> entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n foreach(var entry in myDictionary)\n{\n // do something with entry.Value or entry.Key\n}\n var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x\n\nforeach(var kvp in myDictionary)//iterate over dictionary\n{\n // do something with kvp.Value or kvp.Key\n}\n" }, { "answer_id": 54081425, "author": "Jaider", "author_id": 480700, "author_profile": "https://Stackoverflow.com/users/480700", "pm_score": 6, "selected": false, "text": "KeyValuePair<> Deconstruct() var dic = new Dictionary<int, string>() { { 1, \"One\" }, { 2, \"Two\" }, { 3, \"Three\" } };\nforeach (var (key, value) in dic) {\n Console.WriteLine($\"Item [{key}] = {value}\");\n}\n//Or\nforeach (var (_, value) in dic) {\n Console.WriteLine($\"Item [NO_ID] = {value}\");\n}\n//Or\nforeach ((int key, string value) in dic) {\n Console.WriteLine($\"Item [{key}] = {value}\");\n}\n" }, { "answer_id": 56601004, "author": "boca", "author_id": 251665, "author_profile": "https://Stackoverflow.com/users/251665", "pm_score": 3, "selected": false, "text": " public static void ForEach<T, U>(this Dictionary<T, U> d, Action<KeyValuePair<T, U>> a)\n {\n foreach (KeyValuePair<T, U> p in d) { a(p); }\n }\n\n public static void ForEach<T, U>(this Dictionary<T, U>.KeyCollection k, Action<T> a)\n {\n foreach (T t in k) { a(t); }\n }\n\n public static void ForEach<T, U>(this Dictionary<T, U>.ValueCollection v, Action<U> a)\n {\n foreach (U u in v) { a(u); }\n }\n myDictionary.ForEach(pair => Console.Write($\"key: {pair.Key}, value: {pair.Value}\"));\nmyDictionary.Keys.ForEach(key => Console.Write(key););\nmyDictionary.Values.ForEach(value => Console.Write(value););\n" }, { "answer_id": 59053661, "author": "Pixel_95", "author_id": 4636569, "author_profile": "https://Stackoverflow.com/users/4636569", "pm_score": 4, "selected": false, "text": "foreach ___.Values" }, { "answer_id": 61797855, "author": "Seçkin Durgay", "author_id": 975242, "author_profile": "https://Stackoverflow.com/users/975242", "pm_score": 2, "selected": false, "text": "for var keyList=new List<string>(dictionary.Keys);\nfor (int i = 0; i < keyList.Count; i++)\n{\n var key= keyList[i];\n var value = dictionary[key];\n}\n" }, { "answer_id": 62206867, "author": "rucamzu", "author_id": 3059191, "author_profile": "https://Stackoverflow.com/users/3059191", "pm_score": 5, "selected": false, "text": "KeyValuePair<TKey, TValue> Deconstruct KeyValuePair var dictionary = new Dictionary<int, string>();\n\n// ...\n\nforeach (var (key, value) in dictionary)\n{\n // ...\n}\n" }, { "answer_id": 65848494, "author": "Philm", "author_id": 1469896, "author_profile": "https://Stackoverflow.com/users/1469896", "pm_score": 0, "selected": false, "text": "SortedList<string, string> x = new SortedList<string, string>();\n\nx.Add(\"key1\", \"value1\");\nx.Add(\"key2\", \"value2\");\nx[\"key3\"] = \"value3\";\nforeach( KeyValuePair<string, string> kvPair in x )\n Console.WriteLine($\"{kvPair.Key}, {kvPair.Value}\");\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9311/" ]
141,108
<p>Is it possible to find the <code>foreach</code> index?</p> <p>in a <code>for</code> loop as follows:</p> <pre><code>for ($i = 0; $i &lt; 10; ++$i) { echo $i . ' '; } </code></pre> <p><code>$i</code> will give you the index.</p> <p>Do I have to use the <code>for</code> loop or is there some way to get the index in the <code>foreach</code> loop?</p>
[ { "answer_id": 141114, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 11, "selected": true, "text": "foreach($array as $key=>$value) {\n // do stuff\n}\n $key $array" }, { "answer_id": 141117, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 4, "selected": false, "text": "$i $i++" }, { "answer_id": 141120, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 8, "selected": false, "text": "foreach for foreach $key foreach $index = 0;\nforeach($data as $key=>$val) {\n // Use $key as an index, or...\n\n // ... manage the index this way..\n echo \"Index is $index\\n\";\n $index++;\n}\n" }, { "answer_id": 141220, "author": "The Brawny Man", "author_id": 11936, "author_profile": "https://Stackoverflow.com/users/11936", "pm_score": 3, "selected": false, "text": "$var = array(2,5);\n\nfor ($i = 0; $i < count($var); $i++) {\n echo $var[$i].\"\\n\";\n}\n 2\n5\n $var = array_push($var,10);\n\nfor ($i = 0; $i < count($var); $i++) {\n echo $var[$i].\"\\n\";\n}\n" }, { "answer_id": 142131, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 5, "selected": false, "text": "foreach(array_keys($array) as $key) {\n// do stuff\n}\n" }, { "answer_id": 244801, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "foreach($array as $key => $value){\n $index = current($array);\n}\n" }, { "answer_id": 4822812, "author": "Trev", "author_id": 593000, "author_profile": "https://Stackoverflow.com/users/593000", "pm_score": 3, "selected": false, "text": "for ($i=0; $i<count($things); $i++) { ... }\n\nforeach ($things as $i=>$thing) { ... }\n for ($i=0; $i<count($things); $i++) {\n echo \"Thing \".$i.\" is \".$things[$i];\n}\n\nforeach ($things as $i=>$thing) {\n echo \"Thing \".$i.\" is \".$thing;\n}\n" }, { "answer_id": 5193023, "author": "Bailey Parker", "author_id": 568785, "author_profile": "https://Stackoverflow.com/users/568785", "pm_score": 5, "selected": false, "text": "key() current() next()" }, { "answer_id": 24601593, "author": "Randy Greencorn", "author_id": 1925485, "author_profile": "https://Stackoverflow.com/users/1925485", "pm_score": 2, "selected": false, "text": "foreach ($assoc_array as $key => $value) {\n //do something\n}\n foreach ($array as $indx => $value) {\n //do something\n}\n" }, { "answer_id": 37189216, "author": "Rai Rz", "author_id": 6313904, "author_profile": "https://Stackoverflow.com/users/6313904", "pm_score": 3, "selected": false, "text": "foreach ($lists as $key=>$value) {\n echo $key+1;\n}\n" }, { "answer_id": 37856224, "author": "Ananda G", "author_id": 2256217, "author_profile": "https://Stackoverflow.com/users/2256217", "pm_score": -1, "selected": false, "text": "foreach(array_keys($array) as $key) {\n// do stuff\n}\n" }, { "answer_id": 55570634, "author": "Taranis", "author_id": 10523576, "author_profile": "https://Stackoverflow.com/users/10523576", "pm_score": -1, "selected": false, "text": "@foreach($resultsPerCountry->first()->studies as $result)\n <tr>\n <td>{{ ++$loop->index}}</td> \n </tr>\n@endforeach\n" }, { "answer_id": 62044349, "author": "Carlos Cavalchuki", "author_id": 7011539, "author_profile": "https://Stackoverflow.com/users/7011539", "pm_score": 2, "selected": false, "text": "$array = array('a', 'b', 'c');\nforeach ($array as $letter=>$index) {\n\n echo $letter; //Here $letter content is the actual index\n echo $array[$letter]; // echoes the array value\n\n}//foreach\n\n" }, { "answer_id": 67558030, "author": "jamiryo", "author_id": 11904361, "author_profile": "https://Stackoverflow.com/users/11904361", "pm_score": 3, "selected": false, "text": "++$key $key++ @foreach ($quiz->questions as $key => $question)\n <h2> Question: {{++$key}}</h2>\n <p>{{$question->question}}</p>\n@endforeach\n Question: 1\n......\nQuestion:2\n.....\n.\n.\n.\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18334/" ]
141,126
<p>What is important to keep in mind when designing a database?</p> <p>I don't want to limit your answer to my needs as I am sure that others can benefit from your insights as well. But I am planning a content management system for a multi-client community driven site.</p>
[ { "answer_id": 141226, "author": "jalbert", "author_id": 1360388, "author_profile": "https://Stackoverflow.com/users/1360388", "pm_score": 4, "selected": false, "text": "CHECK NOT NULL FOREIGN KEY PRIMARY KEY DEFAULT" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226/" ]
141,128
<p>Does TCP/IP prevent multiple copies of the same packet from reaching the destination? Or is it up to the endpoint to layer idempotency logic above it?</p> <p>Please reference specific paragraphs from the TCP/IP specification if possible.</p>
[ { "answer_id": 863227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// Combination of a double-linked-list and a hashset with a max bound; \n/// Works like a bounded queue where new incoming items force old items to be dequeued; \n/// Re-uses item containers to avoid GC'ing;\n/// Public Add() and Contains() methods are fully thread safe through a ReaderWriterLockSlim;\n/// </summary>\npublic class BoundedHashQueue<T>\n{\n private readonly int _maxSize = 100;\n private readonly HashSet<T> _hashSet = new HashSet<T>();\n private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();\n private readonly Item _head;\n private readonly Item _tail;\n private int _currentCount = 0;\n\n public BoundedHashQueue(int maxSize)\n {\n _maxSize = maxSize;\n _head = _tail = new Item();\n }\n\n private class Item\n {\n internal T Value;\n internal Item Next;\n internal Item Previous;\n }\n\n public void Add(T value)\n {\n _lock.Write(() =>\n {\n if (_currentCount == 0)\n {\n Item item = new Item();\n item.Value = value;\n _head.Next = item;\n item.Previous = _head;\n item.Next = _tail;\n _tail.Previous = item;\n _currentCount++;\n }\n else\n {\n Item item;\n if (_currentCount >= _maxSize)\n {\n item = _tail.Previous;\n _tail.Previous = item.Previous;\n _tail.Previous.Next = _tail;\n _hashSet.Remove(item.Value);\n }\n else\n {\n item = new Item();\n _currentCount++;\n }\n item.Value = value;\n item.Next = _head.Next;\n item.Next.Previous = item;\n item.Previous = _head;\n _head.Next = item;\n _hashSet.Add(value);\n }\n });\n }\n\n public bool Contains(T value)\n {\n return _lock.Read(() => _hashSet.Contains(value));\n }\n}}\n" }, { "answer_id": 2262525, "author": "jdizzle", "author_id": 70603, "author_profile": "https://Stackoverflow.com/users/70603", "pm_score": 2, "selected": false, "text": "write() read()" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ]
141,136
<p>I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows: </p> <p>txtStart.Text = 09/19/2008 07:00:00</p> <p>txtEnd.Text = 09/19/2008 05:00:00</p> <p>I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page. </p>
[ { "answer_id": 141159, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "stringToDate getTime() stringToDate: function(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3]);\n } else {\n return null;\n };\n}\n" }, { "answer_id": 141387, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <script type=\"text/javascript\">\n function stringToDate(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2}) (\\d{2,2}):(\\d{2,2}):(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);\n } else {\n return null;\n };\n }\n\n //Convert duration from milliseconds to 0000:00:00.00 format\n function MillisecondsToDuration(n) {\n var hms = \"\";\n var dtm = new Date();\n dtm.setTime(n);\n var h = \"000\" + Math.floor(n / 3600000);\n var m = \"0\" + dtm.getMinutes();\n var s = \"0\" + dtm.getSeconds();\n var cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);\n hms = h.substr(h.length-4) + \":\" + m.substr(m.length-2) + \":\";\n hms += s.substr(s.length-2) + \".\" + cs.substr(cs.length-2);\n return hms;\n }\n\n var beginDate = stringToDate('2008-09-19 07:14:00');\n var endDate = stringToDate('2008-09-19 17:35:00');\n\n var n = endDate.getTime() - beginDate.getTime();\n\n alert(MillisecondsToDuration(n));\n </script>\n </head>\n <body>\n </body>\n</html>\n" }, { "answer_id": 1701948, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 2, "selected": false, "text": "var start = new Date().getTime();\nwindow.setTimeout(function(){\n var diff = new Date(new Date().getTime() - start);\n // this will log 0 hours, 0 minutes, 1 second\n console.log(diff.getHours(), diff.getMinutes(),diff.getSeconds());\n},1000);\n" }, { "answer_id": 2971130, "author": "jassey", "author_id": 306548, "author_profile": "https://Stackoverflow.com/users/306548", "pm_score": 3, "selected": false, "text": "function stringToDate(string) {\n var matches;\n if (matches = string.match(/^(\\d{4,4})-(\\d{2,2})-(\\d{2,2}) (\\d{2,2}):(\\d{2,2}):(\\d{2,2})$/)) {\n return new Date(matches[1], matches[2] - 1, matches[3], matches[4], matches[5], matches[6]);\n } else {\n return null;\n };\n}\n\n function getTimeSpan(ticks) {\n var d = new Date(ticks);\n return {\n hour: d.getUTCHours(), \n minute: d.getMinutes(), \n second: d.getSeconds()\n }\n }\n\n var beginDate = stringToDate('2008-09-19 07:14:00');\n var endDate = stringToDate('2008-09-19 17:35:00');\n\n var sp = getTimeSpan(endDate - beginDate);\n alert(\"timeuse:\" + sp.hour + \" hour \" + sp.minute + \" minute \" + sp.second + \" second \");\n" }, { "answer_id": 4972895, "author": "Louis Kaplan", "author_id": 613520, "author_profile": "https://Stackoverflow.com/users/613520", "pm_score": 0, "selected": false, "text": "\nfunction MillisecondsToDuration(milliseconds) {\n var n = Math.abs(milliseconds);\n var hms = \"\";\n var dtm = new Date();\n dtm.setTime(n);\n var d = Math.floor(n / 3600000 / 24); // KK-MOD\n var h = \"0\" + (Math.floor(n / 3600000) - (d * 24)); // KK-MOD\n var m = \"0\" + dtm.getMinutes();\n var s = \"0\" + dtm.getSeconds();\n var cs = \"0\" + Math.round(dtm.getMilliseconds() / 10);\n hms = (milliseconds < 0 ? \" - \" : \"\");\n hms += (d > 0 ? d + \".\" : \"\") + h.substr(h.length - 2) + \":\" + m.substr(m.length - 2) + \":\"; // KK-MOD\n hms += s.substr(s.length - 2) + \".\" + cs.substr(cs.length - 2);\n return hms; }\n" }, { "answer_id": 12684673, "author": "Paul", "author_id": 1634810, "author_profile": "https://Stackoverflow.com/users/1634810", "pm_score": 1, "selected": false, "text": "function formatTimespan(from, to) {\n var text = '',\n span = { y: 0, m: 0, d: 0, h: 0, n: 0 };\n\n function calcSpan(n, fnMod) {\n while (from < to) {\n // Modify the date, and check if the from now exceeds the to:\n from = from[fnMod](1);\n if (from <= to) {\n span[n] += 1;\n } else {\n from = from[fnMod](-1);\n return;\n }\n }\n }\n\n function appendText(n, unit) {\n if (n > 0) {\n text += ((text.length > 0) ? ', ' : '') +\n n.toString(10) + ' ' + unit + ((n === 1) ? '' : 's');\n }\n }\n\n calcSpan('y', 'addYears');\n calcSpan('m', 'addMonths');\n calcSpan('d', 'addDays');\n calcSpan('h', 'addHours');\n calcSpan('n', 'addMinutes');\n\n appendText(span.y, 'year');\n appendText(span.m, 'month');\n appendText(span.d, 'day');\n appendText(span.h, 'hour');\n appendText(span.n, 'minute');\n\n if (text.lastIndexOf(',') < 0) {\n return text;\n }\n\n return text.substring(0, text.lastIndexOf(',')) + ', and' + text.substring(text.lastIndexOf(',') + 1);\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
141,140
<p>The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:</p> <pre><code>void methodName() { int i = 7; for (int j = 0; j &lt; 10; j++) { int i = j * 2; } } </code></pre> <p>Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!</p> <p>What's the rationale for this design decision for Java?</p> <p>Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)</p>
[ { "answer_id": 141289, "author": "Ricardo Massaro", "author_id": 98102, "author_profile": "https://Stackoverflow.com/users/98102", "pm_score": 5, "selected": false, "text": "void methodName() {\n for (int j = 0; j < 10; j++) {\n int i = j * 2;\n }\n System.out.println(i); // error\n}\n" }, { "answer_id": 141417, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "i for j public void methodName() {\n int i = 7;\n for (int j = 0; j < 10; j++) {\n i = j * 2;\n }\n\n //this would cause a compilation error!\n j++;\n}\n i i" }, { "answer_id": 37202735, "author": "user3197104", "author_id": 3197104, "author_profile": "https://Stackoverflow.com/users/3197104", "pm_score": 0, "selected": false, "text": "void methodName() {\n int i = 7;\n for (int j = 0; j < 10; j++) {\n int i = outer.i * 2;\n if(i > 10) {\n int i = outer.outer.i * 2 + outer.i;\n }\n }\n}\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
141,146
<p>I want to know if my server is running Subversion 1.5.</p> <p>How can I find that out?</p> <p>Also would be nice to know my SVN client version number. <code>svn help</code> hasn't been helpful.</p> <p><strong>Note:</strong> I don't want my <em>project's</em> revision number, etc. This question is about the <em>Subversion software</em> itself.</p>
[ { "answer_id": 141479, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 5, "selected": false, "text": "`svn --version`\n" }, { "answer_id": 142061, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": false, "text": "svnserve --version" }, { "answer_id": 209189, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<svn version=\"1.6.13 (r1002816)\" href=\"http://subversion.tigris.org/\"> \n svn --version\n" }, { "answer_id": 2742515, "author": "Christopher", "author_id": 193617, "author_profile": "https://Stackoverflow.com/users/193617", "pm_score": 5, "selected": false, "text": "wget -S --no-check-certificate \\\n --spider 'http://svn.server.net/svn/repository' 2>&1 \\\n | sed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p';\n wget --user --password wget -S --no-check-certificate \\\n --user='username' --password='password' \\\n --spider 'http://svn.server.net/svn/repository' 2>&1 \\\n | sed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p';\n" }, { "answer_id": 7079945, "author": "N0thing", "author_id": 158179, "author_profile": "https://Stackoverflow.com/users/158179", "pm_score": 2, "selected": false, "text": "<svn version=\"1.6. ...\" ...\n" }, { "answer_id": 9502906, "author": "Lars Nordin", "author_id": 570450, "author_profile": "https://Stackoverflow.com/users/570450", "pm_score": 7, "selected": false, "text": "svnadmin --version\n wget -S --spider 'http://svn.server.net/svn/repository' 2>&1 |\nsed -n '/SVN/s/.*\\(SVN[0-9\\/\\.]*\\).*/\\1/p'\n svnserve --version (run on svn server)\n ssh user@host svnserve --version\n Check out the current version in a FAQ: \n http://code.google.com/p/support/wiki/SubversionFAQ#What_version_of_Subversion_do_you_use?\n TBD\n svn --version\n" }, { "answer_id": 11345699, "author": "Jason H", "author_id": 1504173, "author_profile": "https://Stackoverflow.com/users/1504173", "pm_score": 2, "selected": false, "text": "Server: Apache/2.2.14 (Win32) DAV/2 SVN/1.X.X\n" }, { "answer_id": 14227707, "author": "mettkea", "author_id": 1468064, "author_profile": "https://Stackoverflow.com/users/1468064", "pm_score": 1, "selected": false, "text": "$ curl -s -D - http://svn.server.net/svn/repository\nHTTP/1.1 401 Authorization Required\nDate: Wed, 09 Jan 2013 03:01:43 GMT\nServer: Apache/2.2.9 (Unix) DAV/2 SVN/1.7.4\n" }, { "answer_id": 16527826, "author": "David W.", "author_id": 368630, "author_profile": "https://Stackoverflow.com/users/368630", "pm_score": 3, "selected": false, "text": "svn move svn move svn copy svn delete svn merge --reintegrate svn:global-ignores svn:auto-props" }, { "answer_id": 21335321, "author": "ejaenv", "author_id": 599971, "author_profile": "https://Stackoverflow.com/users/599971", "pm_score": 3, "selected": false, "text": "ssh your_user@your_server svnserve --version\n\nsvnserve, version 1.3.1 (r19032)\n compiled May 8 2006, 07:38:44\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
141,154
<p>I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.</p>
[ { "answer_id": 141166, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 6, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\90\\Tools\\ClientSetup\\CurrentVersion\n HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\n SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n" }, { "answer_id": 141211, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 9, "selected": true, "text": "SQLCMD -L\n OSQL -L\n svrnetcn\n" }, { "answer_id": 6431060, "author": "Dale Sykora", "author_id": 809149, "author_profile": "https://Stackoverflow.com/users/809149", "pm_score": 3, "selected": false, "text": "sc \\\\server_name query | grep MSSQL\n" }, { "answer_id": 9464754, "author": "Mohammed Ifteqar Ahmed", "author_id": 1235533, "author_profile": "https://Stackoverflow.com/users/1235533", "pm_score": 6, "selected": false, "text": "DECLARE @GetInstances TABLE\n( Value nvarchar(100),\n InstanceNames nvarchar(100),\n Data nvarchar(100))\n\nInsert into @GetInstances\nEXECUTE xp_regread\n @rootkey = 'HKEY_LOCAL_MACHINE',\n @key = 'SOFTWARE\\Microsoft\\Microsoft SQL Server',\n @value_name = 'InstalledInstances'\n\nSelect InstanceNames from @GetInstances \n" }, { "answer_id": 9813050, "author": "Ian", "author_id": 1266771, "author_profile": "https://Stackoverflow.com/users/1266771", "pm_score": 3, "selected": false, "text": "using System.Data.Sql;\n\nclass Program\n{\n static void Main()\n {\n // Retrieve the enumerator instance and then the data.\n SqlDataSourceEnumerator instance =\n SqlDataSourceEnumerator.Instance;\n System.Data.DataTable table = instance.GetDataSources();\n\n // Display the contents of the table.\n DisplayData(table);\n\n Console.WriteLine(\"Press any key to continue.\");\n Console.ReadKey();\n }\n\n private static void DisplayData(System.Data.DataTable table)\n {\n foreach (System.Data.DataRow row in table.Rows)\n {\n foreach (System.Data.DataColumn col in table.Columns)\n {\n Console.WriteLine(\"{0} = {1}\", col.ColumnName, row[col]);\n }\n Console.WriteLine(\"============================\");\n }\n }\n}\n" }, { "answer_id": 12065138, "author": "Anonymous", "author_id": 1615648, "author_profile": "https://Stackoverflow.com/users/1615648", "pm_score": 3, "selected": false, "text": "SELECT @@SERVERNAME, @@SERVICENAME\n" }, { "answer_id": 15688565, "author": "AbuTaareq", "author_id": 1460063, "author_profile": "https://Stackoverflow.com/users/1460063", "pm_score": 1, "selected": false, "text": "if (ServiceData.DisplayName == \"MSSQLSERVER\" || ServiceData.DisplayName == \"SQL Server (MSSQLSERVER)\")\n {\n InstanceData.Name = \"DEFAULT\";\n InstanceData.ConnectionName = CurrentMachine.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n else\n if (ServiceData.DisplayName.Contains(\"SQL Server (\") == true)\n {\n InstanceData.Name = ServiceData.DisplayName.Substring(\n ServiceData.DisplayName.IndexOf(\"(\") + 1,\n ServiceData.DisplayName.IndexOf(\")\") - ServiceData.DisplayName.IndexOf(\"(\") - 1\n );\n InstanceData.ConnectionName = CurrentMachine.Name + \"\\\\\" + InstanceData.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n else\n if (ServiceData.DisplayName.Contains(\"MSSQL$\") == true)\n {\n InstanceData.Name = ServiceData.DisplayName.Substring(\n ServiceData.DisplayName.IndexOf(\"$\") + 1,\n ServiceData.DisplayName.Length - ServiceData.DisplayName.IndexOf(\"$\") - 1\n );\n\n InstanceData.ConnectionName = CurrentMachine.Name + \"\\\\\" + InstanceData.Name;\n CurrentMachine.ListOfInstances.Add(InstanceData);\n }\n" }, { "answer_id": 19229905, "author": "jimbo", "author_id": 2855472, "author_profile": "https://Stackoverflow.com/users/2855472", "pm_score": 3, "selected": false, "text": "SC \\\\server_name query | find /I \"SQL Server (\"\n" }, { "answer_id": 32438789, "author": "Craig", "author_id": 5309093, "author_profile": "https://Stackoverflow.com/users/5309093", "pm_score": -1, "selected": false, "text": "SELECT @@Version\n" }, { "answer_id": 40598322, "author": "John Denton", "author_id": 4623995, "author_profile": "https://Stackoverflow.com/users/4623995", "pm_score": 5, "selected": false, "text": "> sqllocaldb i\n" }, { "answer_id": 40914787, "author": "akhil vangala", "author_id": 1133052, "author_profile": "https://Stackoverflow.com/users/1133052", "pm_score": 0, "selected": false, "text": "$MachineName = ‘.’ # Default local computer Replace . with server name for a remote computer\n\n$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’, $MachineName)\n$regKey= $reg.OpenSubKey(\"SOFTWARE\\\\Microsoft\\\\Microsoft SQL Server\\\\Instance Names\\\\SQL\" )\n$values = $regkey.GetValueNames()\n$values | ForEach-Object {$value = $_ ; $inst = $regKey.GetValue($value); \n $path = \"SOFTWARE\\\\Microsoft\\\\Microsoft SQL Server\\\\\"+$inst+\"\\\\MSSQLServer\\\\\"+\"CurrentVersion\";\n #write-host $path; \n $version = $reg.OpenSubKey($path).GetValue(\"CurrentVersion\");\n write-host \"Instance\" $value;\n write-host \"Version\" $version}\n" }, { "answer_id": 58435310, "author": "Erk", "author_id": 386587, "author_profile": "https://Stackoverflow.com/users/386587", "pm_score": 1, "selected": false, "text": "OSQL -L SQLCMD -L sqlsrvr.exe MSSQL$INSTANCE_NAME" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
141,162
<p>I need to see if a given process id is running, and it must work in either Java or JRuby (preferably a Ruby solution). It can be system dependent for Linux (specifically Debian and/or Ubuntu).</p> <p>I already have the PID I am looking for, just need to see if it is currently running.</p> <hr> <p>UPDATE:</p> <p>Thanks for all the responses everyone! I appreciate it, however it's not QUITE what I'm looking for... I am hoping for something in a standard Ruby library (or Java, but preferably Ruby)... if no such library call exists, I will probably stick with the procfs solution I already have.</p>
[ { "answer_id": 141663, "author": "Bribles", "author_id": 5916, "author_profile": "https://Stackoverflow.com/users/5916", "pm_score": 0, "selected": false, "text": "def pid_exists? (pid)\n system \"ps -p #{pid} > /dev/null\"\n return $? == 0\nend\n" }, { "answer_id": 141731, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 3, "selected": false, "text": "def pid_exists? (pid)\n system \"kill -0 #{pid}\"\n return $? == 0\nend\n" }, { "answer_id": 200568, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "#!/usr/bin/ruby \n\npid = ARGV[0].to_i\n\nbegin\n Process.kill(0, pid)\n puts \"#{pid} is running\"\nrescue Errno::EPERM # changed uid\n puts \"No permission to query #{pid}!\";\nrescue Errno::ESRCH\n puts \"#{pid} is NOT running.\"; # or zombied\nrescue\n puts \"Unable to determine status for #{pid} : #{$!}\"\nend\n" }, { "answer_id": 4279029, "author": "Martin Gross", "author_id": 520353, "author_profile": "https://Stackoverflow.com/users/520353", "pm_score": 0, "selected": false, "text": "jps >jps -l\n5960 org.jruby.Main\n2124 org.jruby.Main\n5376 org.jruby.Main\n4428 sun.tools.jps.Jps\n >> result = %x[jps -l]\n=> \"5960 org.jruby.Main\\n2264 sun.tools.jps.Jps\\n2124 org.jruby.Main\\n5376 org.jruby.Main\\n\"\n>> p result\n\"5960 org.jruby.Main\\n2264 sun.tools.jps.Jps\\n2124 org.jruby.Main\\n5376 org.jruby.Main\\n\"\n=> nil\n" } ]
2008/09/26
[ "https://Stackoverflow.com/questions/141162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]