qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
364,794
<p>My first instinct is to say each key is an object, and has a hash code, which is what is used to determine if a duplicate is being inserted. However, I can't find anything to back that up for sure. Can someone provide a link that says that, or provide the real answer here? Thanks!</p>
[ { "answer_id": 364823, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 5, "selected": true, "text": "Map null k key.equals(k) Map HashMap equals equals" }, { "answer_id": 365002, "author": "Apocalisp", "author_id": 3434, "author_profile": "https://Stackoverflow.com/users/3434", "pm_score": 1, "selected": false, "text": "java.util.Map java.util.HashMap equals hashCode" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
364,802
<p>What does generator comprehension do? How does it work? I couldn't find a tutorial about it.</p>
[ { "answer_id": 364818, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 3, "selected": false, "text": ">>> [x**2 for x in range(1,11)]\n[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n range(1,11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] range >>> (x**2 for x in xrange(1,11))\n<generator object at 0x7f0a79273488>\n range" }, { "answer_id": 364824, "author": "gotgenes", "author_id": 38140, "author_profile": "https://Stackoverflow.com/users/38140", "pm_score": 9, "selected": true, "text": ">>> my_list = [1, 3, 5, 9, 2, 6]\n>>> filtered_list = [item for item in my_list if item > 3]\n>>> print(filtered_list)\n[5, 9, 6]\n>>> len(filtered_list)\n3\n>>> # compare to generator expression\n... \n>>> filtered_gen = (item for item in my_list if item > 3)\n>>> print(filtered_gen) # notice it's a generator object\n<generator object <genexpr> at 0x7f2ad75f89e0>\n>>> len(filtered_gen) # So technically, it has no length\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: object of type 'generator' has no len()\n>>> # We extract each item out individually. We'll do it manually first.\n... \n>>> next(filtered_gen)\n5\n>>> next(filtered_gen)\n9\n>>> next(filtered_gen)\n6\n>>> next(filtered_gen) # Should be all out of items and give an error\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nStopIteration\n>>> # Yup, the generator is spent. No values for you!\n... \n>>> # Let's prove it gives the same results as our list comprehension\n... \n>>> filtered_gen = (item for item in my_list if item > 3)\n>>> gen_to_list = list(filtered_gen)\n>>> print(gen_to_list)\n[5, 9, 6]\n>>> filtered_list == gen_to_list\nTrue\n>>> \n" }, { "answer_id": 20820350, "author": "Cristian Garcia", "author_id": 2118130, "author_profile": "https://Stackoverflow.com/users/2118130", "pm_score": 3, "selected": false, "text": "generator your_list def allEvens( L ):\n for number in L:\n if number % 2 is 0:\n yield number\n\nevens = allEvens( yourList )\n evens = ( number for number in your_list if number % 2 == 0 )\n next(evens) your_list" }, { "answer_id": 45865455, "author": "AMIT KUMAR", "author_id": 8512516, "author_profile": "https://Stackoverflow.com/users/8512516", "pm_score": 2, "selected": false, "text": "print 'Generator comprehensions'\n\ndef sq_num(n):\n for num in (x**2 for x in range(n)): \n yield num\n\nfor x in sq_num(10):\n print x \n" }, { "answer_id": 64131768, "author": "Onkar Raut", "author_id": 13741633, "author_profile": "https://Stackoverflow.com/users/13741633", "pm_score": 0, "selected": false, "text": "#to get all the even numbers in given range\n \ndef allevens(n):\n for x in range(2,n):\n if x%2==0:\n yield x\n\nfor x in allevens(10)\nprint(x)\n\n#output\n2\n4\n6\n8\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44354/" ]
364,809
<p>I want to gather data from different data servers located in Europe and Asia. Rather than running a plain data query task that will clog up the undersea network I am thinking of a couple of machines that will be available for me at the local sites.</p> <p>I am thinking to design the master package so that I can:</p> <ol> <li>run remote setup tasks</li> <li>launch the data collection package locally using psexec dtexec ...</li> <li>get the data locally stored in multiple raw file (1 for each type of data)</li> <li>zipped and pulled back</li> <li>unzipped and bulkuploaded to local server</li> </ol> <p>Data collection is handled through custom script source since the data is available through a weird class library.</p> <p>Tasks can fail unpredictably. If a particular type of data is successfully captured while the others fail for a particular location, I don't want to run it again.</p> <p>How can I simplify this design if possible and make it more robust?</p>
[ { "answer_id": 365149, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": true, "text": "High+--------------------------+--------------------------+\n | | |\n | Kimball Model (low/high) | Enterprise Data Warehouse|\nH | Unified ODS model hard | (high/high) |\ne | to meaningfully design. | ODS both difficult and |\nt | Flat star schemas easier | probably necessary to |\ne | to fit disparate | make a manageable system |\nr | data into. | Better to separate trans-|\ng | | formation ahd history. |\ne +--------------------------+--------------------------+\nn | | |\ne | | Consolidated Reporting |\na | Data Mart (low/low) | (high/low) |\ni | | ODS easy to implement |\nt | ODS probably of | and will simplify the |\ny | little benefit | overall system |\n | | architecture |\n | | |\nLow +--------------------------+--------------------------+\nLow Number of data sources High\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30546/" ]
364,825
<p>I have a query to the effect of</p> <pre><code>SELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id LIMIT 10,20 </code></pre> <p>I want to know to many total rows this query would return without the LIMIT (so I can show pagination information).</p> <p>Normally, I would use this query:</p> <pre><code>SELECT COUNT(t3.id) FROM t1, t2, t3 WHERE (associate t1,t2, and t3 with each other) GROUP BY t3.id </code></pre> <p>However the GROUP BY changes the meaning of the COUNT, and instead I get a set of rows representing the number of unique t3.id values in each group.</p> <p>Is there a way to get a count for the total number of rows when I use a GROUP BY? I'd like to avoid having to execute the entire query and just counting the number of rows, since I only need a subset of the rows because the values are paginated. I'm using MySQL 5, but I think this pretty generic.</p>
[ { "answer_id": 364833, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff \nFROM t1, t2, t3 \nWHERE (associate t1,t2, and t3 with each other) \nGROUP BY t3.id \nLIMIT 10,20;\n\nSELECT FOUND_ROWS(); -- for most recent query\n" }, { "answer_id": 364837, "author": "Sylvain", "author_id": 45918, "author_profile": "https://Stackoverflow.com/users/45918", "pm_score": 7, "selected": true, "text": "SELECT SQL_CALC_FOUND_ROWS t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 \nWHERE (associate t1,t2, and t3 with each other) \nGROUP BY t3.id \nLIMIT 10,20\n SELECT FOUND_ROWS();\n" }, { "answer_id": 364838, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 6, "selected": false, "text": "SELECT\n COUNT(DISTINCT t3.id)\nFROM...\n SELECT\n COUNT(*)\nFROM\n (\n <Your query here>\n ) AS SQ\n" }, { "answer_id": 10533702, "author": "Silver Moon", "author_id": 936182, "author_profile": "https://Stackoverflow.com/users/936182", "pm_score": 4, "selected": false, "text": "SELECT COUNT(*) FROM \n(\nSELECT t3.id, a,bunch,of,other,stuff FROM t1, t2, t3 \nWHERE (associate t1,t2, and t3 with each other) \nGROUP BY t3.id \n) \nas temp;\n" }, { "answer_id": 36449637, "author": "Abhishek Goel", "author_id": 2439715, "author_profile": "https://Stackoverflow.com/users/2439715", "pm_score": 1, "selected": false, "text": "SELECT \n sum(1) as counttotal\nFROM (\n Your query with group by operator\n) as T\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36384/" ]
364,832
<p>So, I have the following rows in the DB:</p> <p>1 | /users/</p> <p>2 | /users/admin/</p> <p>3 | /users/admin/*</p> <p>4 | /users/admin/mike/</p> <p>5 | /users/admin/steve/docs/</p> <p>The input URL is <strong>/users/admin/steve/</strong>, and the goal is to find the URL match from the DB.</p> <p>I want to return #3 as the correct row, since the wildcard "*" specifies that anything can go in place of the asterisk. What would be the most efficient method for doing this?</p> <p><strong>Here's my initial thoughts, but I'm sure they could be improved upon:</strong></p> <ol> <li>Make a query to see if there's an exact URL match</li> <li>If no matches, then retrieve all rows with "*" as the last character, in reverse order (so the more specific URLs take precedence)</li> <li>For each row, if it (minus the "*") matches the input URL, then return it</li> <li>If nothing is found, then we're SOL</li> </ol>
[ { "answer_id": 364840, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "SELECT * FROM mytable AS m\nWHERE <input-url> = m.urlpattern\n OR <input-url> REGEXP REPLACE(m.urlpattern, '*', '.*');\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32881/" ]
364,842
<p>I've got a Perl script that needs to execute another Perl script. This second script can be executed directly on the command line, but I need to execute it from within my first program. I'll need to pass it a few parameters that would normally be passed in when it's run standalone (the first script runs periodically, and executes the second script under a certain set of system conditions).</p> <p>Preliminary Google searches suggest using backticks or a system() call. Are there any other ways to run it? (I'm guessing yes, since it's Perl we're talking about :P ) Which method is preferred if I need to capture output from the invoked program (and, if possible, pipe that output as it executes to stdout as though the second program were invoked directly)?</p> <p>(Edit: oh, <strong>now</strong> SO suggests some related questions. <a href="https://stackoverflow.com/questions/109124/run-external-process-from-perl-capture-stderr-stdout-and-the-process-exit-code">This one</a> is close, but not exactly the same as what I'm asking. The second program will likely take an hour or more to run (lots of I/O), so I'm not sure a one-off invocation is the right fit for this.)</p>
[ { "answer_id": 364858, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "system" }, { "answer_id": 364861, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl\nuse strict;\n\nopen(OUTPUT, \"date|\") or die \"Failed to create process: $!\\n\";\n\nwhile (<OUTPUT>)\n{\n print;\n}\n\nclose(OUTPUT);\n\nprint \"Process exited with value \" . ($? >> 8) . \"\\n\";\n date date" }, { "answer_id": 364884, "author": "Renaud Bompuis", "author_id": 3811, "author_profile": "https://Stackoverflow.com/users/3811", "pm_score": 3, "selected": false, "text": "# On Unix systems, either of these will execute and just carry-on\n# You can't collect output that way\n`myscript.pl &`;\nsystem ('myscript.pl &'); \n\n# On Windows systems the equivalent would be\n`start myscript.pl`;\nsystem ('start myscript.pl');\n\n# If you just want to execute another script and terminate the current one\nexec ('myscript.pl');\n" }, { "answer_id": 364897, "author": "Paul", "author_id": 37865, "author_profile": "https://Stackoverflow.com/users/37865", "pm_score": 4, "selected": false, "text": "$retVal = `perl somePerlScript.pl`; system() eval eval #!/usr/bin/perl\nopen PERLFILE, \"<somePerlScript.pl\";\nundef $/; # this allows me to slurp the file, ignoring newlines\nmy $program = <PERLFILE>;\neval $program;\n" }, { "answer_id": 364984, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 3, "selected": false, "text": "exec" }, { "answer_id": 365212, "author": "pjf", "author_id": 19422, "author_profile": "https://Stackoverflow.com/users/19422", "pm_score": 6, "selected": true, "text": "$^X $? use strict;\nuse warnings;\nuse IPC::System::Simple qw(system capture);\n\n# Run a command, wait until it finishes, and make sure it works.\n# Output from this program goes directly to STDOUT, and it can take input\n# from your STDIN if required.\nsystem($^X, \"yourscript.pl\", @ARGS);\n\n# Run a command, wait until it finishes, and make sure it works.\n# The output of this command is captured into $results.\nmy $results = capture($^X, \"yourscript.pl\", @ARGS);\n @ARGS # Both of these commands allow an exit value of 0, 1 or 2 to be considered\n # a successful execution of the command.\n\n system( [0,1,2], $^X, \"yourscript.pl\", @ARGS );\n # OR\n capture( [0,1,2, $^X, \"yourscript.pl\", @ARGS );\n" }, { "answer_id": 367307, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": false, "text": "{\n local @ARGV = qw<param1 param2 param3>;\n do '/home/buddy/myscript.pl';\n}\n" }, { "answer_id": 14714569, "author": "Robert", "author_id": 2044313, "author_profile": "https://Stackoverflow.com/users/2044313", "pm_score": 0, "selected": false, "text": "sub getcode($) {\n my @list;\n my $filename = shift;\n open (INFILE, \"< $filename\");\n @list = <INFILE>;\n close (INFILE);\n return \\@list;\n}\n\n# and to use it:\n\nmy $codelist = [];\n$codelist = getcode('sourcefile.pl');\neval join (\"\", @$codelist);\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774/" ]
364,847
<p>how to change connection string dynamically in object datasource in asp.net ?</p>
[ { "answer_id": 364850, "author": "Tarik", "author_id": 44852, "author_profile": "https://Stackoverflow.com/users/44852", "pm_score": 2, "selected": false, "text": "protected void ObjectDataSource1_ObjectCreated(object sender, ObjectDataSourceEventArgs e)\n{\n if (e.ObjectInstance != null)\n {\n SqlConnection conn = new SqlConnection();\n conn.ConnectionString = MyConnectionManager.ConnectionString;\n e.ObjectInstance.GetType().GetProperty(\"Connection\").SetValue(e.ObjectInstance, conn, null);\n }\n}\n" }, { "answer_id": 2015102, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " if (e.ObjectInstance != null)\n {\n ((ReportPrototype.ReleasedRatingsDataTableAdapters.RatingsViewTableAdapter)e.ObjectInstance).Connection.ConnectionString = ConfigurationManager.ConnectionStrings[\"RADSDataConnectionString\"].ConnectionString;\n }\n" }, { "answer_id": 27304671, "author": "Jared Thirsk", "author_id": 208304, "author_profile": "https://Stackoverflow.com/users/208304", "pm_score": 0, "selected": false, "text": "void OnObjectDataSourceObjectCreated(object sender, ObjectDataSourceEventArgs e)\n{\n if (e.ObjectInstance != null)\n {\n ((SqlConnection)e.ObjectInstance.GetType()\n .GetProperty(\"Connection\", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance )\n .GetValue(e.ObjectInstance, null)\n ).ConnectionString = ConfigurationManager.ConnectionStrings[\"MyConnectionString\"].ConnectionString;\n }\n}\n ObjectDataSource ObjectDataSource1 = new ObjectDataSource();\n...\nObjectDataSource1.ObjectCreated += OnObjectDataSourceObjectCreated;\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18709/" ]
364,895
<p>I know this is possible via a simple registry change to accomplish this as long as IE/firefox is being used. However, I am wondering if there is a reliable way to do so for other browsers,</p> <p>I am specifically looking for a way to do this via an installer, so editing a preference inside a specific browser will not cut it.</p>
[ { "answer_id": 49505885, "author": "ka3yc", "author_id": 3300376, "author_profile": "https://Stackoverflow.com/users/3300376", "pm_score": 2, "selected": false, "text": "<a href='myfile:\\\\mysharedserver\\sharedfolder\\' target='_self'>Shared server</a>\n const string prefix = \"myfile:\";\n\nstatic string ProcessInput(string s)\n{\n // TODO Verify and validate the input \n // string as appropriate for your application.\n if (s.StartsWith(prefix))\n s = s.Substring(prefix.Length);\n\n s = System.Net.WebUtility.UrlDecode(s);\n\n Process.Start(\"explorer\", s);\n\n return s;\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200558/" ]
364,925
<p>Say I have a git repository and I've been working on master, can I retroactively create a branch. For example:</p> <p>A - B - C - A1 - D - A2 - E</p> <p>I want to make it look like this:</p> <pre><code>A - A1 - A2 \ \ B - C - D - E </code></pre> <p>The specific use case is when I've cherry-picked a bunch of commits into an old version branch and it needs to go into multiple older versions and I don't want to repeat the cherry-pick on all those revision.</p> <p>Essentially it's something that would have been good as a feature or topic branch in the first place but wasn't created like that.</p>
[ { "answer_id": 365179, "author": "Bombe", "author_id": 43582, "author_profile": "https://Stackoverflow.com/users/43582", "pm_score": 6, "selected": true, "text": "git checkout -b new-branch hash-of-A\ngit cherry-pick hash-of-A1\ngit cherry-pick hash-of-A2\n A git checkout -b new-branch2 hash-of-A\ngit cherry-pick hash-of-B\ngit cherry-pick hash-of-C\ngit cherry-pick hash-of-D\ngit cherry-pick hash-of-E\ngit merge new-branch\n new-branch new-branch2" }, { "answer_id": 367229, "author": "Jakub Narębski", "author_id": 46058, "author_profile": "https://Stackoverflow.com/users/46058", "pm_score": 0, "selected": false, "text": "$ git checkout -b fixes A\n $ git cherry-pick A1\n$ git cherry-pick A2\n $ git rebase -i fixes master\n pick deadbee B\npick fa1afe1 C\npick a98d4ba A1\n...\n $ git merge fixes\n" }, { "answer_id": 4750829, "author": "alltom", "author_id": 129889, "author_profile": "https://Stackoverflow.com/users/129889", "pm_score": 7, "selected": false, "text": "$ git branch fixes # copies master to new branch\n$ git reset --hard XXX # resets master to XXX\n reset" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ]
364,936
<p>Does anyone have any good suggestions for creating a Pipe object in Java which <em>is</em> both an InputStream and and OutputStream since Java does not have multiple inheritance and both of the streams are abstract classes instead of interfaces?</p> <p>The underlying need is to have a single object that can be passed to things which need either an InputStream or an OutputStream to pipe output from one thread to input for another.</p>
[ { "answer_id": 365034, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 1, "selected": false, "text": "InputStream OutputStream InputStream.close() OutputStream.close() close()" }, { "answer_id": 19465966, "author": "Guido Medina", "author_id": 1666753, "author_profile": "https://Stackoverflow.com/users/1666753", "pm_score": 0, "selected": false, "text": "import java.io.IOException;\nimport java.io.OutputStream;\nimport java.util.concurrent.*;\n\npublic class QueueOutputStream extends OutputStream\n{\n private static final int DEFAULT_BUFFER_SIZE=1024;\n private static final byte[] END_SIGNAL=new byte[]{};\n\n private final BlockingQueue<byte[]> queue=new LinkedBlockingDeque<>();\n private final byte[] buffer;\n\n private boolean closed=false;\n private int count=0;\n\n public QueueOutputStream()\n {\n this(DEFAULT_BUFFER_SIZE);\n }\n\n public QueueOutputStream(final int bufferSize)\n {\n if(bufferSize<=0){\n throw new IllegalArgumentException(\"Buffer size <= 0\");\n }\n this.buffer=new byte[bufferSize];\n }\n\n private synchronized void flushBuffer()\n {\n if(count>0){\n final byte[] copy=new byte[count];\n System.arraycopy(buffer,0,copy,0,count);\n queue.offer(copy);\n count=0;\n }\n }\n\n @Override\n public synchronized void write(final int b) throws IOException\n {\n if(closed){\n throw new IllegalStateException(\"Stream is closed\");\n }\n if(count>=buffer.length){\n flushBuffer();\n }\n buffer[count++]=(byte)b;\n }\n\n @Override\n public synchronized void write(final byte[] b, final int off, final int len) throws IOException\n {\n super.write(b,off,len);\n }\n\n @Override\n public synchronized void close() throws IOException\n {\n flushBuffer();\n queue.offer(END_SIGNAL);\n closed=true;\n }\n\n public Future<Void> asyncSendToOutputStream(final ExecutorService executor, final OutputStream outputStream)\n {\n return executor.submit(\n new Callable<Void>()\n {\n @Override\n public Void call() throws Exception\n {\n try{\n byte[] buffer=queue.take();\n while(buffer!=END_SIGNAL){\n outputStream.write(buffer);\n buffer=queue.take();\n }\n outputStream.flush();\n } catch(Exception e){\n close();\n throw e;\n } finally{\n outputStream.close();\n }\n return null;\n }\n }\n );\n }\n" }, { "answer_id": 65030776, "author": "navid_gh", "author_id": 1309331, "author_profile": "https://Stackoverflow.com/users/1309331", "pm_score": 0, "selected": false, "text": "Pipe pipe = Pipe.open();\nPipe.SinkChannel sinkChannel = pipe.sink();\nString newData = \"New String to write to file...\" + System.currentTimeMillis();\n\nByteBuffer buf = ByteBuffer.allocate(48);\nbuf.clear();\nbuf.put(newData.getBytes());\n\nbuf.flip();\n\nwhile(buf.hasRemaining()) {\n sinkChannel.write(buf);\n}\nPipe.SourceChannel sourceChannel = pipe.source();\nByteBuffer buf = ByteBuffer.allocate(48);\n\nint bytesRead = inChannel.read(buf);\n //Shared class used by threads\npublic class Buffer {\n // ArrayBlockingQueue\n private BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(1);\n\n public void get() {\n // retrieve from ArrayBlockingQueue\n try {\n System.out.println(\"Consumer received - \" + blockingQueue.take());\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n public void put(int data) {\n try {\n // putting in ArrayBlockingQueue\n blockingQueue.put(data);\n System.out.println(\"Producer produced - \" + data);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}\n\npublic static void main(String[] args) {\n // Starting two threads\n ExecutorService executorService = null;\n try {\n Buffer buffer = new Buffer();\n executorService = Executors.newFixedThreadPool(2);\n executorService.execute(new Producer(buffer));\n executorService.execute(new Consumer(buffer));\n } catch (Exception e) {\n e.printStackTrace();\n }finally {\n if(executorService != null) {\n executorService.shutdown();\n }\n }\n }\n\npublic class Consumer implements Runnable {\n private Buffer buffer;\n\n public Consumer(Buffer buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n while (true) {\n try {\n buffer.get();\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n}\n\npublic class Producer implements Runnable {\n private Buffer buffer;\n\n public Producer(Buffer buffer) {\n this.buffer = buffer;\n }\n\n @Override\n public void run() {\n while (true) {\n Random random = new Random();\n int data = random.nextInt(1000);\n buffer.put(data);\n }\n }\n}\n\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45931/" ]
364,937
<p>Failed to create component 'User Control 1'. the error message follows:</p> <blockquote> <p>'System.NullReferenceException : Object reference not set to an instance of an object. at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object Component, Object Value) .............. etc..........</p> </blockquote> <p>What should I do to fix this error?</p>
[ { "answer_id": 371047, "author": "Tom Walker", "author_id": 6951, "author_profile": "https://Stackoverflow.com/users/6951", "pm_score": 2, "selected": false, "text": "Integer String" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
364,941
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance">What is the exact problem with multiple inheritance?</a> </p> </blockquote> <p>Why is multiple inheritance considered to be <em>evil</em> while implementing multiple interfaces is not? Especially when once considers that interfaces are simply pure abstract classes?</p> <p><strong>(More or less) duplicate of</strong> <a href="https://stackoverflow.com/questions/225929/what-is-the-exact-problem-with-multiple-inheritance" title="What is the exact problem with multiple inheritance?">What is the exact problem with multiple inheritance?</a>, <a href="https://stackoverflow.com/questions/178333/multiple-inheritance-in-c" title="Multiple Inheritance in C#">Multiple Inheritance in C#</a>, and some others...</p>
[ { "answer_id": 364945, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 6, "selected": true, "text": " A\n / \\\nB c\n \\ /\n D\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45931/" ]
364,946
<p>I am giving link of a pdf file on my web page for download, like below</p> <pre><code>&lt;a href="myfile.pdf"&gt;Download Brochure&lt;/a&gt; </code></pre> <p>The problem is when user clicks on this link then</p> <ul> <li>If the user have installed Adobe Acrobat, then it opens the file in the same browser window in Adobe Reader.</li> <li>If the Adobe Acrobat is not installed then it pop-up to the user for Downloading the file.</li> </ul> <p>But I want it always pop-up to the user for download, irrespective of "Adobe acrobat" is installed or not.</p> <p>Please tell me how i can do this?</p>
[ { "answer_id": 364950, "author": "TravisO", "author_id": 35116, "author_profile": "https://Stackoverflow.com/users/35116", "pm_score": 8, "selected": true, "text": "<a href=\"pdf_server.php?file=pdffilename\">Download my eBook</a>\n header(\"Content-Type: application/octet-stream\");\n\n$file = $_GET[\"file\"] .\".pdf\";\nheader(\"Content-Disposition: attachment; filename=\" . urlencode($file)); \nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Type: application/download\");\nheader(\"Content-Description: File Transfer\"); \nheader(\"Content-Length: \" . filesize($file));\nflush(); // this doesn't really matter.\n$fp = fopen($file, \"r\");\nwhile (!feof($fp))\n{\n echo fread($fp, 65536);\n flush(); // this is essential for large downloads\n} \nfclose($fp); \n" }, { "answer_id": 364957, "author": "Sudden Def", "author_id": 28121, "author_profile": "https://Stackoverflow.com/users/28121", "pm_score": 3, "selected": false, "text": "header(\"Content-Type: application/octet-stream\");\n" }, { "answer_id": 364971, "author": "btw", "author_id": 2293, "author_profile": "https://Stackoverflow.com/users/2293", "pm_score": -1, "selected": false, "text": "def index\n\n respond_to do |format|\n format.html # Your HTML view\n format.pdf { render :layout => false }\n end\nend\n" }, { "answer_id": 8122372, "author": "Alex V", "author_id": 327934, "author_profile": "https://Stackoverflow.com/users/327934", "pm_score": 6, "selected": false, "text": "$file = $_GET[\"file\"];\nif (file_exists($file)) {\n header('Content-Description: File Transfer');\n header('Content-Type: application/octet-stream');\n header(\"Content-Type: application/force-download\");\n header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));\n // header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n header('Content-Length: ' . filesize($file));\n ob_clean();\n flush();\n readfile($file);\n exit;\n}\n" }, { "answer_id": 9209074, "author": "Rob W", "author_id": 938089, "author_profile": "https://Stackoverflow.com/users/938089", "pm_score": 5, "selected": false, "text": ".htaccess myfile.pdf download.php?myfile <FilesMatch \"\\.pdf$\">\nForceType applicaton/octet-stream\nHeader set Content-Disposition attachment\n</FilesMatch>\n" }, { "answer_id": 11130689, "author": "Saill", "author_id": 1470853, "author_profile": "https://Stackoverflow.com/users/1470853", "pm_score": 0, "selected": false, "text": "<a href=\"pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/\">Download my eBook</a> header(\"Content-Type: application/octet-stream\");\n\n$file = $_GET[\"file\"] .\".pdf\";\n$path = $_GET[\"path\"];\n$fullfile = $path.$file;\n\nheader(\"Content-Disposition: attachment; filename=\" . Urlencode($file)); \nheader(\"Content-Type: application/force-download\");\nheader(\"Content-Type: application/octet-stream\");\nheader(\"Content-Type: application/download\");\nheader(\"Content-Description: File Transfer\"); \nheader(\"Content-Length: \" . Filesize($fullfile));\nflush(); // this doesn't really matter.\n$fp = fopen($fullfile, \"r\");\nwhile (!feof($fp))\n{\n echo fread($fp, 65536);\n flush(); // this is essential for large downloads\n} \nfclose($fp);\n" }, { "answer_id": 17011326, "author": "T_D", "author_id": 2140636, "author_profile": "https://Stackoverflow.com/users/2140636", "pm_score": 8, "selected": false, "text": "<a href=\"./directory/yourfile.pdf\" download=\"newfilename\">Download the pdf</a>\n newfilename <a href=\"./directory/yourfile.pdf\" download>Download the pdf</a>\n" }, { "answer_id": 18083730, "author": "Alex W", "author_id": 1399491, "author_profile": "https://Stackoverflow.com/users/1399491", "pm_score": 4, "selected": false, "text": "<p>Thanks for downloading! If your download doesn't start shortly, \n<a id=\"downloadLink\" href=\"...yourpdf.pdf\" target=\"_blank\" \ntype=\"application/octet-stream\" download=\"yourpdf.pdf\">click here</a>.</p>\n var delay = 3000;\nwindow.setTimeout(function(){$('#downloadLink')[0].click();},delay);\n window.open()" }, { "answer_id": 40871387, "author": "Evan Donovan", "author_id": 263877, "author_profile": "https://Stackoverflow.com/users/263877", "pm_score": 0, "selected": false, "text": "<FilesMatch \"\\.(?i:pdf)$\">\n Header set Content-Disposition attachment\n</FilesMatch>\n" }, { "answer_id": 42446149, "author": "Shivek Parmar", "author_id": 1779483, "author_profile": "https://Stackoverflow.com/users/1779483", "pm_score": 2, "selected": false, "text": "function downloadFile(src){\n var link=document.createElement('a');\n document.body.appendChild(link);\n link.href= src;\n link.download = '';\n link.click();\n}\n" }, { "answer_id": 54547140, "author": "Mehran Hooshangi", "author_id": 10079466, "author_profile": "https://Stackoverflow.com/users/10079466", "pm_score": -1, "selected": false, "text": "<?php\n$local_file = 'file.zip';\n$download_file = 'name.zip';\n\n// set the download rate limit (=> 20,5 kb/s)\n$download_rate = 20.5;\nif(file_exists($local_file) && is_file($local_file))\n{\nheader('Cache-control: private');\nheader('Content-Type: application/octet-stream');\nheader('Content-Length: '.filesize($local_file));\nheader('Content-Disposition: filename='.$download_file);\n\nflush();\n$file = fopen($local_file, \"r\");\nwhile(!feof($file))\n{\n // send the current file part to the browser\n print fread($file, round($download_rate * 1024));\n // flush the content to the browser\n flush();\n // sleep one second\n sleep(1);\n}\nfclose($file);}\nelse {\ndie('Error: The file '.$local_file.' does not exist!');\n}\n\n?>\n" }, { "answer_id": 54549465, "author": "user11021789", "author_id": 11021789, "author_profile": "https://Stackoverflow.com/users/11021789", "pm_score": -1, "selected": false, "text": "<!DOCTYPE html> \n<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n<head> \n <title>File Uploader</title> \n <script src=\"../Script/angular1.3.8.js\"></script> \n <script src=\"../Script/angular-route.js\"></script> \n <script src=\"../UserScript/MyApp.js\"></script> \n <script src=\"../UserScript/FileUploder.js\"></script> \n <> \n .percent { \n position: absolute; \n width: 300px; \n height: 14px; \n z-index: 1; \n text-align: center; \n font-size: 0.8em; \n color: white; \n } \n\n .progress-bar { \n width: 300px; \n height: 14px; \n border-radius: 10px; \n border: 1px solid #CCC; \n background-image: -webkit-gradient(linear, left top, left bottom, from(#6666cc), to(#4b4b95)); \n border-image: initial; \n } \n\n .uploaded { \n padding: 0; \n height: 14px; \n border-radius: 10px; \n background-image: -webkit-gradient(linear, left top, left bottom, from(#66cc00), to(#4b9500)); \n border-image: initial; \n } \n </> \n</head> \n<body ng-app=\"MyApp\" ng-controller=\"FileUploder\"> \n <div> \n <table =\"width:100%;border:solid;\"> \n <tr> \n <td>Select File</td> \n <td> \n <input type=\"file\" ng-model-instant id=\"fileToUpload\" onchange=\"angular.element(this).scope().setFiles(this)\" /> \n </td> \n </tr> \n <tr> \n <td>File Size</td> \n <td> \n <div ng-repeat=\"file in files.slice(0)\"> \n <span ng-switch=\"file.size > 1024*1024\"> \n <span ng-switch-when=\"true\">{{file.size / 1024 / 1024 | number:2}} MB</span> \n <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span> \n </span> \n </div> \n </td> \n </tr> \n <tr> \n <td> \n File Attach Status \n </td> \n <td>{{AttachStatus}}</td> \n </tr> \n <tr> \n <td> \n <input type=\"button\" value=\"Upload\" ng-click=\"fnUpload();\" /> \n </td> \n <td> \n <input type=\"button\" value=\"DownLoad\" ng-click=\"fnDownLoad();\" /> \n </td> \n </tr> \n </table> \n </div> \n</body> \n</html> \n" }, { "answer_id": 64910792, "author": "Okiemute Gold", "author_id": 14235396, "author_profile": "https://Stackoverflow.com/users/14235396", "pm_score": 3, "selected": false, "text": "<a href=\"myfile.pdf\">Download Brochure</a>\n <a href=\"myfile.pdf\" download>Download Brochure</a>\n <a href=\"myfile.pdf\" download=\"Brochure\">Download Brochure</a>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45261/" ]
364,952
<p>I would like to manipulate the HTML inside an iframe using jQuery.</p> <p>I thought I'd be able to do this by setting the context of the jQuery function to be the document of the iframe, something like:</p> <pre><code>$(function(){ //document ready $('some selector', frames['nameOfMyIframe'].document).doStuff() }); </code></pre> <p>However this doesn't seem to work. A bit of inspection shows me that the variables in <code>frames['nameOfMyIframe']</code> are <code>undefined</code> unless I wait a while for the iframe to load. However, when the iframe loads the variables are not accessible (I get <code>permission denied</code>-type errors).</p> <p>Does anyone know of a work-around to this?</p>
[ { "answer_id": 364983, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 2, "selected": false, "text": "$(document).ready(function() {\n $('some selector', frames['nameOfMyIframe'].document).doStuff()\n} );\n" }, { "answer_id": 364987, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 5, "selected": false, "text": "$().ready(function () {\n $(\"#iframeID\").ready(function () { //The function below executes once the iframe has finished loading\n $('some selector', frames['nameOfMyIframe'].document).doStuff();\n });\n};\n" }, { "answer_id": 1639342, "author": "Yasir Laghari", "author_id": 189197, "author_profile": "https://Stackoverflow.com/users/189197", "pm_score": 10, "selected": false, "text": "<iframe> $(\"#iFrame\").contents().find(\"#someDiv\").removeClass(\"hidden\");\n" }, { "answer_id": 2568403, "author": "davryusha", "author_id": 307870, "author_profile": "https://Stackoverflow.com/users/307870", "pm_score": 7, "selected": false, "text": ".contents() .contents() $(document).ready(function(){\n $('#frameID').load(function(){\n $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');\n });\n});\n" }, { "answer_id": 3127056, "author": "basysmith", "author_id": 377347, "author_profile": "https://Stackoverflow.com/users/377347", "pm_score": 6, "selected": false, "text": "<?php\n $URL = \"http://external.com\";\n\n $domain = file_get_contents($URL);\n\n echo $domain;\n?>\n <html>\n<head>\n <title>Test</title>\n </head>\n<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js\"></script>\n\n<script>\n\n$(document).ready(function(){ \n cleanit = setInterval ( \"cleaning()\", 500 );\n});\n\nfunction cleaning(){\n if($('#frametest').contents().find('.selector').html() == \"somthing\"){\n clearInterval(cleanit);\n $('#selector').contents().find('.Link').html('ideate tech');\n }\n}\n\n</script>\n\n<body>\n<iframe name=\"frametest\" id=\"frametest\" src=\"http://yourdomain.com/iframe_page.php\" ></iframe>\n</body>\n</html>\n" }, { "answer_id": 4333824, "author": "user", "author_id": 527805, "author_profile": "https://Stackoverflow.com/users/527805", "pm_score": 5, "selected": false, "text": "iframe.contentWindow.document\n iframe.contentDocument\n" }, { "answer_id": 11801977, "author": "zupa", "author_id": 926988, "author_profile": "https://Stackoverflow.com/users/926988", "pm_score": 5, "selected": false, "text": "var $iframe = $(\"#iframeID\").contents();\n$iframe.find('selector');\n" }, { "answer_id": 12237140, "author": "Evgeny Karpov", "author_id": 889745, "author_profile": "https://Stackoverflow.com/users/889745", "pm_score": 2, "selected": false, "text": "$ window.iframe_id.$ window.view.$('div').hide() $('#iframe_id')[0].contentWindow.$" }, { "answer_id": 21511756, "author": "B.Asselin", "author_id": 418229, "author_profile": "https://Stackoverflow.com/users/418229", "pm_score": 5, "selected": false, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>Page with an iframe</title>\n <meta charset=\"UTF-8\" />\n <script src=\"http://code.jquery.com/jquery-1.10.2.min.js\"></script>\n <script>\n var Page = {\n id:'page',\n variable:'This is the page.'\n };\n\n $(window).on('message', function(e) {\n var event = e.originalEvent;\n if(window.console) {\n console.log(event);\n }\n alert(event.origin + '\\n' + event.data);\n });\n function iframeReady(iframe) {\n if(iframe.contentWindow.postMessage) {\n iframe.contentWindow.postMessage('Hello ' + Page.id, '*');\n }\n }\n </script>\n</head>\n<body>\n <h1>Page with an iframe</h1>\n <iframe src=\"iframe.html\" onload=\"iframeReady(this);\"></iframe>\n</body>\n</html>\n <!DOCTYPE html>\n<html>\n<head>\n <title>iframe</title>\n <meta charset=\"UTF-8\" />\n <script src=\"http://code.jquery.com/jquery-1.10.2.min.js\"></script>\n <script>\n var Page = {\n id:'iframe',\n variable:'The iframe.'\n };\n\n $(window).on('message', function(e) {\n var event = e.originalEvent;\n if(window.console) {\n console.log(event);\n }\n alert(event.origin + '\\n' + event.data);\n });\n $(window).on('load', function() {\n if(window.parent.postMessage) {\n window.parent.postMessage('Hello ' + Page.id, '*');\n }\n });\n </script>\n</head>\n<body>\n <h1>iframe</h1>\n <p>It's the iframe.</p>\n</body>\n</html>\n" }, { "answer_id": 32757927, "author": "Zisu", "author_id": 5105089, "author_profile": "https://Stackoverflow.com/users/5105089", "pm_score": 2, "selected": false, "text": "<body id=\"page-top\" data-spy=\"scroll\" data-target=\".navbar-fixed-top\">\n<p>iframe from same domain</p>\n <iframe frameborder=\"0\" scrolling=\"no\" width=\"500\" height=\"500\"\n src=\"iframe.html\" name=\"imgbox\" class=\"iView\">\n\n</iframe>\n<p>iframe from same domain</p>\n<iframe frameborder=\"0\" scrolling=\"no\" width=\"500\" height=\"500\"\n src=\"iframe2.html\" name=\"imgbox\" class=\"iView1\">\n\n</iframe>\n<p>iframe from different domain</p>\n <iframe frameborder=\"0\" scrolling=\"no\" width=\"500\" height=\"500\"\n src=\"https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif\" name=\"imgbox\" class=\"iView2\">\n\n</iframe>\n\n<p>iframe from different domain</p>\n <iframe frameborder=\"0\" scrolling=\"no\" width=\"500\" height=\"500\"\n src=\"http://d1rmo5dfr7fx8e.cloudfront.net/\" name=\"imgbox\" class=\"iView3\">\n\n</iframe>\n\n<script type='text/javascript'>\n\n\n$(document).ready(function(){\n setTimeout(function(){\n\n\n var src = $('.iView').contents().find(\".shrinkToFit\").attr('src');\n console.log(src);\n }, 2000);\n\n\n setTimeout(function(){\n\n\n var src = $('.iView1').contents().find(\".shrinkToFit\").attr('src');\n console.log(src);\n }, 3000);\n\n\n setTimeout(function(){\n\n\n var src = $('.iView2').contents().find(\".shrinkToFit\").attr('src');\n console.log(src);\n }, 3000);\n\n setTimeout(function(){\n\n\n var src = $('.iView3').contents().find(\"img\").attr('src');\n console.log(src);\n }, 3000);\n\n\n })\n\n\n</script>\n</body>\n" }, { "answer_id": 53092453, "author": "Dominique Fortin", "author_id": 1571709, "author_profile": "https://Stackoverflow.com/users/1571709", "pm_score": 1, "selected": false, "text": "function getIframeWindow(iframe_object) {\n var doc;\n\n if (iframe_object.contentWindow) {\n return iframe_object.contentWindow;\n }\n\n if (iframe_object.window) {\n return iframe_object.window;\n } \n\n if (!doc && iframe_object.contentDocument) {\n doc = iframe_object.contentDocument;\n } \n\n if (!doc && iframe_object.document) {\n doc = iframe_object.document;\n }\n\n if (doc && doc.defaultView) {\n return doc.defaultView;\n }\n\n if (doc && doc.parentWindow) {\n return doc.parentWindow;\n }\n\n return undefined;\n}\n ...\nvar frame_win = getIframeWindow( frames['nameOfMyIframe'] );\n\nif (frame_win) {\n $(frame_win.contentDocument || frame_win.document).find('some selector').doStuff();\n ...\n}\n...\n" }, { "answer_id": 53982340, "author": "Jeff Davis", "author_id": 9249, "author_profile": "https://Stackoverflow.com/users/9249", "pm_score": 1, "selected": false, "text": "document.querySelector('iframe[name=iframename]').contentDocument\n" }, { "answer_id": 54197640, "author": "Ahsan Horani", "author_id": 4453224, "author_profile": "https://Stackoverflow.com/users/4453224", "pm_score": 1, "selected": false, "text": "<div id='myframe'>\n\n <?php \n /* \n Use below function to display final HTML inside this div\n */\n\n //Display Frame\n echo displayFrame(); \n ?>\n\n</div>\n\n<?php\n\n/* \n Function to display frame from another domain \n*/\n\nfunction displayFrame()\n{\n $webUrl = 'http://[external-web-domain.com]/';\n\n //Get HTML from the URL\n $content = file_get_contents($webUrl);\n\n //Add custom JS to returned HTML content\n $customJS = \"\n <script>\n\n /* Here I am writing a sample jQuery to hide the navigation menu\n You can write your own jQuery for this content\n */\n //Hide Navigation bar\n jQuery(\\\".navbar.navbar-default\\\").hide();\n\n </script>\";\n\n //Append Custom JS with HTML\n $html = $content . $customJS;\n\n //Return customized HTML\n return $html;\n}\n" }, { "answer_id": 69945468, "author": "Imran Zahoor", "author_id": 1843175, "author_profile": "https://Stackoverflow.com/users/1843175", "pm_score": 1, "selected": false, "text": "$(\"#iFrame\").contents().find(\"#someDiv\").removeClass(\"hidden\");\n $(document).ready(function(){ \n setTimeout(\n function () {\n $(\"#iFrame\").contents().find(\"#someDiv\").removeClass(\"hidden\");\n },\n 300\n );\n});\n iFrame iFrame 300ms" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7407/" ]
364,959
<p>Here I had build a HTML page with an <code>iFrame</code>. I had an id within the <code>iFrame</code> src page. Is it possible to access the id from my current page through JavaScript.</p> <p>Please help me.</p>
[ { "answer_id": 364972, "author": "Biswanath", "author_id": 41968, "author_profile": "https://Stackoverflow.com/users/41968", "pm_score": 0, "selected": false, "text": "<title>Untitled Page</title>\n<script type=\"text/javascript\" >\n function ShowVal() {\n alert(myIframe.document.getElementById('nameText').value);\n }\n\n</script>\n" }, { "answer_id": 364980, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 1, "selected": false, "text": "window.onload = function () {\n document.getElementById('iframeId').onload = function () { //Attach an onload function to the iframe\n //Do the stuff you want to do with the iframe here\n //because this function is executed once the iframe has finished loading\n };\n};\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38172/" ]
364,962
<p>My application is already developed and now we are going to change the connection string whatever stored in the session object (Bcoz of Distributed Database Management System (DDBMS))</p> <p>Problem is here.....</p> <blockquote> <pre><code>In that application There are so many **ObjectDataSource** which are </code></pre> <p>initialize with the using <strong>.XSD</strong> file. which is related to the <strong>TableAdapter</strong> and in which connection string of <strong>TableAdapter</strong> is assign from the Web.Config File. Now How to change the connection string to whatever stored in session object?</p> </blockquote> <p>Thanks in advance.</p>
[ { "answer_id": 416869, "author": "Bill Martin", "author_id": 46064, "author_profile": "https://Stackoverflow.com/users/46064", "pm_score": 0, "selected": false, "text": "myTableAdapter.Connection.ConnectionString = clsGlobals.gstrConnectionString;\n .ToString()" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45934/" ]
364,963
<p>I have an a aspx page, but all content is generated by hands(yes I know that I need to make a handler, I have another question)</p> <p>I want to cache output in client browser. Problem is that it's cached only for one query.</p> <pre><code> public static void ProceedCaching(string etag, string lastModify, string response, HttpResponse Response, HttpRequest Request) { Response.AddHeader("ETag", "\"" + etag + "\""); Response.AddHeader("Last-Modified", lastModify); Response.AppendHeader("Cache-Control", "Public"); Response.AppendHeader("Expires", DateTime.Now.AddMinutes(1).ToUniversalTime().ToString("r",DateTimeFormatInfo.InvariantInfo)); string ifModified = Request.Headers["If-Modified-Since"]; if (!string.IsNullOrEmpty(ifModified)) { if (ifModified.Contains(";")) ifModified = ifModified.Remove(ifModified.IndexOf(';')); } string incomingEtag = Request.Headers["If-None-Match"]; if (String.Compare(incomingEtag, etag) == 0 || string.Compare(ifModified, lastModify) == 0) { Response.StatusCode = 304; Response.End(); } Response.Write(response); Response.End(); } </code></pre> <p>it's become preaty messy. As I said it's cached only once. After recevieng HTTP 304 browser will send clean request without caching information(etag, lastmodified). Have any ideas? </p>
[ { "answer_id": 416869, "author": "Bill Martin", "author_id": 46064, "author_profile": "https://Stackoverflow.com/users/46064", "pm_score": 0, "selected": false, "text": "myTableAdapter.Connection.ConnectionString = clsGlobals.gstrConnectionString;\n .ToString()" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41483/" ]
364,978
<p>i want to check my server connection to know if its available or not to inform the user..</p> <p>so how to send a pkg or msg to the server (it's not SQL server; it's a server contains some serviecs) ...</p> <p>thnx in adcvance ..</p>
[ { "answer_id": 364992, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": true, "text": "select * from sysibm.sysdummy1" }, { "answer_id": 365139, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "import socket\n\nhost = ''\nport = 55555\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((host, port))\ns.listen(1)\n\nwhile 1:\n try:\n clientsock, clientaddr = s.accept()\n clientsock.sendall('alive')\n clientsock.close()\n except:\n pass\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42782/" ]
364,985
<p>I need to find the smallest power of two that's greater or equal to a given value. So far, I have this:</p> <pre><code>int value = 3221; // 3221 is just an example, could be any number int result = 1; while (result &lt; value) result &lt;&lt;= 1; </code></pre> <p>It works fine, but feels kind of naive. Is there a better algorithm for that problem?</p> <p>EDIT. There were some nice Assembler suggestions, so I'm adding those tags to the question.</p>
[ { "answer_id": 364993, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "ceil(log2(value))\n ilog2()" }, { "answer_id": 365042, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 1, "selected": false, "text": "int nextPow(int x) {\n int y = x\n while (x &= (x^(~x+1))) \n y = x << 1;\n return y\n}\n" }, { "answer_id": 365068, "author": "Larry Gritz", "author_id": 3832, "author_profile": "https://Stackoverflow.com/users/3832", "pm_score": 7, "selected": true, "text": "/// Round up to next higher power of 2 (return x if it's already a power\n/// of 2).\ninline int\npow2roundup (int x)\n{\n if (x < 0)\n return 0;\n --x;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n return x+1;\n}\n" }, { "answer_id": 373441, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 1, "selected": false, "text": "// fill in the table\nunsigned short tab[65536];\nunsigned short bit = tab[i];\n //\nunsigned long bitHigh = ((unsigned long)tab[(unsigned short)(i >> 16)]) << 16;\nunsigned long bitLow = 0;\nif (bitHigh == 0){\n bitLow = tab[(unsigned short)(i & 0xffff)];\n}\nunsigned long answer = bitHigh | bitLow;\n" }, { "answer_id": 462756, "author": "Tony Lee", "author_id": 5819, "author_profile": "https://Stackoverflow.com/users/5819", "pm_score": 4, "selected": false, "text": "int nextPow2(int n) \n{ \n if ( n <= 1 ) return n;\n double d = n-1; \n return 1 << ((((int*)&d)[1]>>20)-1022); \n} \n int nextPow2(int n) \n{ \n if ( n <= 1 ) return n;\n double d;\n n--;\n __asm {\n fild n \n mov eax,4\n fstp d \n mov ecx, dword ptr d[eax]\n sar ecx,14h \n rol eax,cl \n }\n} \n" }, { "answer_id": 2823568, "author": "natersoz", "author_id": 138264, "author_profile": "https://Stackoverflow.com/users/138264", "pm_score": 1, "selected": false, "text": "int pwr2Test(size_t x) {\n return (x & (x - 1))? 0 : 1; \n}\n\nsize_t pwr2Floor(size_t x) {\n // A lookup table for rounding up 4 bit numbers to\n // the nearest power of 2.\n static const unsigned char pwr2lut[] = {\n 0x00, 0x01, 0x02, 0x02, // 0, 1, 2, 3\n 0x04, 0x04, 0x04, 0x04, // 4, 5, 6, 7\n 0x08, 0x08, 0x08, 0x08, // 8, 9, 10, 11\n 0x08, 0x08, 0x08, 0x08 // 12, 13, 14, 15\n };\n\n size_t pwr2 = 0; // The return value\n unsigned int i = 0; // The nybble interator\n\n for( i = 0; x != 0; ++i ) { // Iterate through nybbles\n pwr2 = pwr2lut[x & 0x0f]; // rounding up to powers of 2.\n x >>= 4; // (i - 1) will contain the\n } // highest non-zero nybble index.\n\n i = i? (i - 1) : i;\n pwr2 <<= (i * 4);\n return pwr2; \n}\n\nsize_t pwr2Size(size_t x) {\n if( pwr2Test(x) ) { return x; }\n return pwr2Floor(x) * 2; \n }\n" }, { "answer_id": 7133699, "author": "Anonymous Guest", "author_id": 903962, "author_profile": "https://Stackoverflow.com/users/903962", "pm_score": -1, "selected": false, "text": "#include <iostream>\nint main(void) {\n int testinput,counter;\n std::cin >> testinput;\n while (testinput > 1) {\n testinput = testinput >> 1;\n counter++;\n }\n int finalnum = testinput << counter+1;\n printf(\"Is %i\\n\",finalnum);\n return 0;\n}\n" }, { "answer_id": 12043632, "author": "Kos Petoussis", "author_id": 1609960, "author_profile": "https://Stackoverflow.com/users/1609960", "pm_score": 0, "selected": false, "text": " int bufferPow = 1;\n while ( bufferPow<bufferSize && bufferPow>0) bufferPow <<= 1;\n" }, { "answer_id": 12060041, "author": "user1277476", "author_id": 1277476, "author_profile": "https://Stackoverflow.com/users/1277476", "pm_score": 0, "selected": false, "text": "$ /usr/local/pypy-1.9/bin/pypy\nPython 2.7.2 (341e1e3821ff, Jun 07 2012, 15:38:48)\n[PyPy 1.9.0 with GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\nAnd now for something completely different: ``<arigato> yes but there is not\nmuch sense if I explain all about today's greatest idea if tomorrow it's\ncompletely outdated''\n>>>> import math\n>>>> print math.log(65535)/math.log(2)\n15.9999779861\n>>>> print math.log(65536)/math.log(2)\n16.0\n>>>>\n" }, { "answer_id": 15479212, "author": "Zacrath", "author_id": 2182618, "author_profile": "https://Stackoverflow.com/users/2182618", "pm_score": 3, "selected": false, "text": "template<typename T> T next_power2(T value)\n{\n --value;\n for(size_t i = 1; i < sizeof(T) * CHAR_BIT; i*=2)\n value |= value >> i;\n return value+1;\n}\n template<typename T> T next_power2(T value)\n{\n return 1 << ((sizeof(T) * CHAR_BIT) - __builtin_clz(value-1));\n}\n" }, { "answer_id": 21842698, "author": "duncan.forster", "author_id": 3318694, "author_profile": "https://Stackoverflow.com/users/3318694", "pm_score": 2, "selected": false, "text": "template<uint32_t A, uint8_t B = 16>\nstruct Pow2RoundDown { enum{ value = Pow2RoundDown<(A | (A >> B)), B/2>::value }; };\ntemplate<uint32_t A>\nstruct Pow2RoundDown<A, 1> { enum{ value = (A | (A >> 1)) - ((A | (A >> 1)) >> 1) }; };\n\ntemplate<uint32_t A, uint8_t B = 16>\nstruct Pow2RoundUp { enum{ value = Pow2RoundUp<((B == 16 ? (A-1) : A) | ((B == 16 ? (A-1) : A) >> B)), B/2>::value }; };\ntemplate<uint32_t A >\nstruct Pow2RoundUp<A, 1> { enum{ value = ((A | (A >> 1)) + 1) }; };\n Pow2RoundDown<3221>::value, Pow2RoundUp<3221>::value\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38106/" ]
364,989
<p>I am considering Smarty as my web app templating solution, and I am now concerned with its performance against plain PHP. </p> <p>The Smarty site says it should be the same, however, I was not able to find anyone doing real benchmarking to prove the statement right or wrong.</p> <p>Did anyone do some benchmarking of Smarty vs plain PHP? Or maybe come across some resources on such tests?</p> <p>Thanks</p>
[ { "answer_id": 844692, "author": "Chad Scira", "author_id": 103696, "author_profile": "https://Stackoverflow.com/users/103696", "pm_score": 2, "selected": false, "text": "// with smarty (baseline)\n 0.014 seconds\n\n// with xsl/xslt-clientside\n 0.008 seconds\n 42% decrease in server stress\n\n// with xsl/xslt-serverside\n// this process would only be done if the users browser doesn't support client-side XSLT\n 0.016 seconds\n 14% increase in server stress\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/364989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19584/" ]
365,001
<p>In the app I am working on, I want to allow the user to upload static HTML pages to replace the default "user profile" MVC View page. Is this possible? That is, the user uploaded html pages will totally run out of MVC, and it can include its own CSS links, etc.</p> <p>Ideas? Suggestions?</p>
[ { "answer_id": 365032, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 5, "selected": false, "text": "routes.IgnoreRoute(\"UserPages/{*path}\");\n" }, { "answer_id": 365033, "author": "maxnk", "author_id": 45862, "author_profile": "https://Stackoverflow.com/users/45862", "pm_score": 0, "selected": false, "text": "<html>\n <body>\n <b><user:FirstName /></b>\n <b><user:LastName /></b>\n </body>\n</html>\n <html>\n <body>\n <b>First Name</b>\n <b>Last Name</b>\n </body>\n</html>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20067/" ]
365,006
<p>I have set up a version control system using <strong>TortoiseSVN</strong> at my home to manage my pet projects, school projects etc...and it works locally.</p> <p>Now I need to be able to access my code repository remotely, like from school, so that I will be able to update the source at school from the repository, and commit it again once I have finished working on it.</p> <p>The question is, <strong>how can I connect to my repository remotely</strong> ? What ports do I need to open on my router for example?</p> <p>Also, I cannot install the Tortoise client at school, so I will need some other <em>portable</em> application that does this task, be it GUI or <a href="http://en.wikipedia.org/wiki/Command-line_interface" rel="nofollow noreferrer">CLI</a>.</p>
[ { "answer_id": 374295, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "C++" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44084/" ]
365,012
<p>Extended Backus–Naur Form: <strong>EBNF</strong> </p> <p>I'm very new to parsing concepts. Where can I get sufficiently easy to read and follow material for writing a grammar for the boost::spirit library, which uses a grammar similar to EBNF?</p> <p>Currently I am looking into <a href="http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form" rel="noreferrer">EBNF</a> from Wikipedia. </p>
[ { "answer_id": 376753, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 4, "selected": true, "text": "while if if-then-else case" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
365,015
<p>I'm using Windows XP and I want to know if the local area is available or not?</p> <p>And if I'm using another OS would that affect on my code?</p>
[ { "answer_id": 14810573, "author": "NASSER", "author_id": 354974, "author_profile": "https://Stackoverflow.com/users/354974", "pm_score": 0, "selected": false, "text": "using System.Net.NetworkInformation; //(Add reference of System.Net.dll)\npublic partial class Form1: Form\n{\n public Form1()\n {\n InitializeComponent();\n NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;\n }\n private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)\n {\n if(e.IsAvailable)\n {\n //connected\n }\n else\n {\n //disconnected\n }\n }\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42782/" ]
365,028
<p>I'm not a JS guy so I'm kinda stumbling around in the dark. Basically, I wanted something that would add a link to a twitter search for @replies to a particular user while on that person's page. </p> <p>Two things I am trying to figure out:</p> <ol> <li>how to extract the user name from the page so that I can construct the right URL. ie. if I am on <a href="http://twitter.com/ev" rel="nofollow noreferrer">http://twitter.com/ev</a> , I should get "ev" back. </li> <li>how to manipulate the DOM to insert things at the right place</li> </ol> <p>Here's the HTML fragment I'm targetting:</p> <pre><code>&lt;ul id="tabMenu"&gt; &lt;li&gt; &lt;a href="/ev" id="updates_tab"&gt;Updates&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="/ev/favourites" id="favorites_tab"&gt;Favorites&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And here is the script (so far):</p> <pre><code>// ==UserScript== // @name Twitter Replies Search // @namespace http://jauderho.com/ // @description Find all the replies for a particular user // @include http://twitter.com/* // @include https://twitter.com/* // @exclude http://twitter.com/home // @exclude https://twitter.com/home // @author Jauder Ho // ==/UserScript== var menuNode = document.getElementById('tabMenu'); if (typeof(menuNode) != "undefined" &amp;&amp; menuNode != null) { var html = []; html[html.length] = '&lt;li&gt;'; html[html.length] = '&lt;a href="http://search.twitter.com/search?q=to:ev" class="section-links" id="replies_search_tab"&gt;@Replies Search&lt;/a&gt;'; html[html.length] = '&lt;/li&gt;'; // this is obviously wrong var div = document.createElement('div'); div.className = 'section last'; div.innerHTML = html.join(''); followingNode = menuNode.parentNode; followingNode.parentNode.insertBefore(div, followingNode); } </code></pre>
[ { "answer_id": 365044, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "var userName = window.location.href.match(/^http:\\/\\/twitter\\.com\\/(\\w+)/)\nif (userName == null)\n return; // Problem?\nuserName = userName[1];\nvar menuNode = document.getElementById('tabMenu');\nif (menuNode != null)\n{\n var html = '<a href=\"http://search.twitter.com/search?q=to:' +\n userName +\n '\" class=\"section-links\" id=\"replies_search_tab\">@Replies Search</a>';\n\n var li = document.createElement('li');\n li.className = 'section last';\n li.innerHTML = html;\n menuNode.appendChild(li);\n}\n menuNode.insertBefore(li, menuNode.firstChild)" }, { "answer_id": 365186, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 3, "selected": true, "text": "var menuNode = document.getElementById('tabMenu');\nif (menuNode!=null)\n{\n // extract username from URL; matches /ev and /ev/favourites\n var username = document.location.pathname.split(\"/\")[1];\n\n // create the link\n var link = document.createElement('a');\n link.setAttribute('href', 'http://search.twitter.com/search?q=to:'+username);\n link.setAttribute('id', 'replies_search_tab');\n link.appendChild(document.createTextNode('@Replies Search'));\n\n // create the list element\n var li = document.createElement('li');\n\n // add link to the proper location\n li.appendChild(link);\n menuNode.appendChild(li); \n}\n <ul id=\"tabMenu\">\n <li>\n <a href=\"/ev\" id=\"updates_tab\">Updates</a> </li>\n <li>\n <a href=\"/ev/favourites\" id=\"favorites_tab\">Favorites</a> </li>\n <li>\n <a href=\"http://search.twitter.com/search?q=to:ev\" id=\"replies_search_tab\">@Replies Search</a></li>\n </ul>\n insertBefore" }, { "answer_id": 609691, "author": "Daniel X Moore", "author_id": 68210, "author_profile": "https://Stackoverflow.com/users/68210", "pm_score": 1, "selected": false, "text": "// ==UserScript==\n// @name MyScript\n// @namespace http://example.com\n// @description Example\n// @include *\n//\n// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js\n// ==/UserScript==\n\nvar menuNode = $('#tabMenu');\nif (menuNode!=null)\n{\n // extract username from URL; matches /ev and /ev/favourites\n var username = document.location.pathname.split(\"/\")[1];\n\n // create the link\n var link = $('<a id=\"replies_search_tab\">@Replies Search</a>');\n link.href = 'http://search.twitter.com/search?q=to:'+username;\n\n // create the list element\n var li = $('<li />');\n\n // add link to the proper location\n li.append(link);\n menuNode.append(li); \n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26366/" ]
365,029
<p>I was reading a book on templates and found the following piece of code:</p> <pre><code>template &lt;template &lt;class&gt; class CreationPolicy&gt; class WidgetManager : public CreationPolicy&lt;Widget&gt; { ... void DoSomething() { Gadget* pW = CreationPolicy&lt;Gadget&gt;().Create(); ... } }; </code></pre> <p>I didn't get the nested templates specified for the CreationPolicy (which is again a template). What is the meaning of that weird looking syntax?</p>
[ { "answer_id": 365035, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 4, "selected": true, "text": "CreationPolicy CreationPolicy CreationPolicy<SomeType>\n CreationPolicy" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39742/" ]
365,045
<p>I have a database (NexusDB (supposedly SQL-92 compliant)) which contains and Item table, a Category table, and a many-to-many ItemCategory table, which is just a pair of keys. As you might expect, Items are assigned to multiple categories. </p> <p>I am wanting to all the end user to select all items which are </p> <p>ItemID | CategoryID<br> --------------------------------<br> 01 | 01<br> 01 | 02<br> 01 | 12<br></p> <p>02 | 01<br> 02 | 02<br> 02 | 47<br></p> <p>03 | 01<br> 03 | 02<br> 03 | 14<br> etc...<br></p> <p>I want to be able to select all ItemID's that are assigned to Categories X, Y, and Z but NOT assigned to Categories P and Q. </p> <p>For the example data above, for instance, say I'd like to grab all Items assigned to Categories 01 or 02 but NOT 12 (yielding Items 02 and 03). Something along the lines of:</p> <p>SELECT ItemID WHERE (CategoryID IN (01, 02)) </p> <p>...and remove from that set SELECT ItemID WHERE NOT (CategoryID = 12)</p> <p>This is probably a pretty basic SQL question, but it's stumping me at the moment. Any help w/b appreciated.</p>
[ { "answer_id": 365053, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 3, "selected": true, "text": "SELECT ItemID FROM Table\nEXCEPT\nSELECT ItemID FROM Table\nWHERE\nCategoryID <> 12\n" }, { "answer_id": 365059, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 1, "selected": false, "text": "SELECT i.ItemID, ic.CategoryID FROM Item AS i\nINNER JOIN ItemCategory ic\nON i.ItemID = ic.ItemID\nWHERE ic.CategoryId = 1 OR ic.CategoryId = 2\n" }, { "answer_id": 365237, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "SELECT\n ItemID\nFROM\n Items I\nINNER JOIN ItemCategories IC1 ON IC1.ItemID = I.ItemID AND IC1.CategoryID = '01'\nINNER JOIN ItemCategories IC2 ON IC2.ItemID = I.ItemID AND IC2.CategoryID = '02'\nLEFT OUTER JOIN ItemCategories IC3 ON IC3.ItemID = I.ItemID AND IC3.CategoryID = '12'\nWHERE IC3.ItemID IS NULL\n SELECT\n ItemID\nFROM\n Items I\nWHERE\n (\n SELECT COUNT(*)\n FROM ItemCategories IC1\n WHERE IC1.ItemID = I.ItemID\n AND IC.CategoryID IN\n (SELECT CategoryID FROM @MustHaves)\n ) = (SELECT COUNT(*) FROM @MustHaves) AND\n (\n SELECT COUNT(*)\n FROM ItemCategories IC1\n WHERE IC1.ItemID = I.ItemID\n AND IC.CategoryID IN\n (SELECT COUNT(*) FROM @MustNotHaves)\n ) = 0\n" }, { "answer_id": 365491, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "SELECT i1.ItemID\nFROM ItemCategory i1\n LEFT OUTER JOIN ItemCategory i2\n ON (i1.ItemID = i2.ItemID AND i2.CategoryID IN ('P', 'Q'))\nWHERE i1.CategoryID IN ('X', 'Y', 'Z')\n AND i2.ItemID IS NULL\nGROUP BY i1.ItemID\nHAVING COUNT(i1.CategoryID) = 3;\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32303/" ]
365,048
<p>why this is happen ?</p> <p>When u create abstract class in c++ Ex: <strong>Class A</strong> (which has a pure virtual function) after that <strong>class B</strong> is inherited from class <strong>A</strong> </p> <p>And if <strong>class A</strong> has constructor called <strong>A()</strong> suppose i created an <strong>Object</strong> of <strong>class B</strong> then the compiler initializes the base class first i.e.<strong>class A</strong> and then initialize the <strong>class B</strong> Then.......?</p> <p>First thing is we can not access a constructor of any class without an Object then how it is initialize the constructor of abstract class if we can not create an object of abstract class .</p>
[ { "answer_id": 365054, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 2, "selected": false, "text": "class A class B class B class A class A\n{\npublic:\n A() {}\n virtual ~A() {}\n virtual void foo() = 0; // pure virtual\n int i;\n};\n\n\nclass B : public A\n{\npublic:\n B() {}\n virtual ~B() {}\n virtual void foo() {}\n int j;\n};\n" }, { "answer_id": 365073, "author": "Drakosha", "author_id": 19868, "author_profile": "https://Stackoverflow.com/users/19868", "pm_score": 1, "selected": false, "text": "struct A {\n A(int x) {..}\n virtual void do() = 0;\n};\n\nstruct B : public A {\n B() : A(13) {} // <--- there you see how we give params to A c'tor\n virtual void do() {..}\n};\n" }, { "answer_id": 365457, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": " And if class A has constructor called A() suppose i created an\n Object of class B then the compiler initializes the base class\n first i.e.class A and then initialize the class B\n Then.......?\n First thing is we can not access a constructor of any class without an Object\nthen how it is initialize the constructor of abstract class if we can not create\nan object of abstract class .\n" }, { "answer_id": 365486, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 0, "selected": false, "text": "A A A A A A a;\nnew A();\n B A A A A B" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45934/" ]
365,058
<p>How can I detect, or be notified, when windows is logging out in python?</p> <p>Edit: Martin v. Löwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for. <br /><br />Edit: im not using a gui this is running as a service</p>
[ { "answer_id": 365232, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 4, "selected": true, "text": "win32ts WM_WTSSESSION_CHANGE RegisterServiceCtrlHandlerEx RegisterServiceCtrlHandler servicemanager SERVICE_CONTROL_SESSIONCHANGE WM_WTSSESSION_CHANGE" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
365,071
<p>I have a form in Axapta/Dynamics Ax (EmplTable) which has two data sources (EmplTable and HRMVirtualNetworkTable) where the second data source (HRMVirtualNetworkTable) is linked to the first on with "Delayed" link type.</p> <p>Is there a way to set an filter on the records, based on the second data source, without having to change the link type to "InnerJoin"?</p>
[ { "answer_id": 1097783, "author": "Jan B. Kjeldsen", "author_id": 4509, "author_profile": "https://Stackoverflow.com/users/4509", "pm_score": 4, "selected": true, "text": "static void updateJoinMode(QueryBuildDataSource qds)\n{\n Counter r;\n if (qds)\n {\n qds.joinMode(JoinMode::OuterJoin);\n for (r = 1; r <= qds.rangeCount(); r++)\n {\n if (qds.range(r).value() && qds.range(r).status() == RangeStatus::Open)\n {\n qds.joinMode(JoinMode::InnerJoin);\n break;\n }\n }\n }\n}\n public void executeQuery()\n{;\n SysQuery::updateJoinMode(this.queryRun() ? this.queryRun().query().dataSourceTable(tableNum(HRMVirtualNetworkTable)) : this.query().dataSourceTable(tableNum(HRMVirtualNetworkTable))); \n super();\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19808/" ]
365,082
<p>As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information?</p>
[ { "answer_id": 14743532, "author": "Seperman", "author_id": 1497443, "author_profile": "https://Stackoverflow.com/users/1497443", "pm_score": 5, "selected": false, "text": "class Person(models.Model):\n ...\n\n def address_report(self, instance):\n ...\n # short_description functions like a model field's verbose_name\n address_report.short_description = \"Address\"\n" }, { "answer_id": 24121475, "author": "Naggappan Ramukannan", "author_id": 2134767, "author_profile": "https://Stackoverflow.com/users/2134767", "pm_score": 5, "selected": false, "text": "class Employee(models.Model):\n name = models.CharField(max_length = 100)\n dob = models.DateField('Date Of Birth')\n doj = models.DateField(verbose_name='Date Of Joining')\n mobile=models.IntegerField(max_length = 12)\n email = models.EmailField(max_length=50)\n bill = models.BooleanField(db_index=True,default=False)\n proj = models.ForeignKey(Project, verbose_name='Project')\n" }, { "answer_id": 40016382, "author": "Majid Zandi", "author_id": 4085584, "author_profile": "https://Stackoverflow.com/users/4085584", "pm_score": 3, "selected": false, "text": "from django.db import models\n\nclass MyClassName(models.Model): \n field_name = models.IntegerField(verbose_name='Field Caption')\n" }, { "answer_id": 71623876, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "from django.db import models\n\nclass MyModel(models.Model): # Here\n name = models.CharField(max_length=255, verbose_name=\"My Name\")\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
365,086
<p>How can I project the row number onto the linq query result set.</p> <p>Instead of say:</p> <p>field1, field2, field3</p> <p>field1, field2, field3</p> <p>I would like:</p> <p>1, field1, field2, field3</p> <p>2, field1, field2, field3</p> <p>Here is my attempt at this:</p> <pre><code>public List&lt;ScoreWithRank&gt; GetHighScoresWithRank(string gameId, int count) { Guid guid = new Guid(gameId); using (PPGEntities entities = new PPGEntities()) { int i = 1; var query = from s in entities.Scores where s.Game.Id == guid orderby s.PlayerScore descending select new ScoreWithRank() { Rank=i++, PlayerName = s.PlayerName, PlayerScore = s.PlayerScore }; return query.ToList&lt;ScoreWithRank&gt;(); } } </code></pre> <p>Unfortunately, the "Rank=i++" line throws the following compile-time exception:</p> <p>"An expression tree may not contain an assignment operator"</p>
[ { "answer_id": 365127, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)\n{\n Guid guid = new Guid(gameId);\n using (PPGEntities entities = new PPGEntities())\n {\n var query = from s in entities.Scores\n where s.Game.Id == guid\n orderby s.PlayerScore descending\n select new\n {\n PlayerName = s.PlayerName,\n PlayerScore = s.PlayerScore\n };\n\n return query.AsEnumerable() // Client-side from here on\n .Select((player, index) => new ScoreWithRank()\n {\n PlayerName = player.PlayerName,\n PlayerScore = player.PlayerScore,\n Rank = index + 1;\n })\n .ToList();\n\n }\n}\n" }, { "answer_id": 365150, "author": "Jeff Weber", "author_id": 42818, "author_profile": "https://Stackoverflow.com/users/42818", "pm_score": 1, "selected": false, "text": "public List<Score> GetHighScores(string gameId, int count)\n{\n Guid guid = new Guid(gameId);\n using (PPGEntities entities = new PPGEntities())\n {\n var query = from s in entities.Scores\n where s.Game.Id == guid\n orderby s.PlayerScore descending\n select s;\n return query.ToList<Score>();\n } \n}\n void hsc_LoadHighScoreCompleted(object sender, GetHighScoreCompletedEventArgs e)\n{\n ObservableCollection<Score> list = e.Result;\n\n _listBox.ItemsSource = list.Select((player, index) => new ScoreWithRank()\n {\n PlayerName = player.PlayerName,\n PlayerScore = player.PlayerScore,\n Rank = index+=1\n }).ToList();\n}\n" }, { "answer_id": 9133776, "author": "shannonlh", "author_id": 1188210, "author_profile": "https://Stackoverflow.com/users/1188210", "pm_score": 0, "selected": false, "text": "let Rank = i++\n Rank.ToString()\n public List<ScoreWithRank> GetHighScoresWithRank(string gameId, int count)\n{\nGuid guid = new Guid(gameId);\nusing (PPGEntities entities = new PPGEntities())\n{\n int i = 1;\n var query = from s in entities.Scores\n let Rank = i++\n where s.Game.Id == guid\n orderby s.PlayerScore descending\n select new ScoreWithRank()\n {\n Rank.ToString(),\n PlayerName = s.PlayerName,\n PlayerScore = s.PlayerScore\n };\n return query.ToList<ScoreWithRank>();\n}\n" }, { "answer_id": 14672679, "author": "Onur Bıyık", "author_id": 43506, "author_profile": "https://Stackoverflow.com/users/43506", "pm_score": 0, "selected": false, "text": ".Select((x, index) => new\n{\n SequentialNumber = index + 1\n ,FieldFoo = x.FieldFoo \n}).ToList();\n" }, { "answer_id": 54160675, "author": "Rohit Dodiya", "author_id": 5882380, "author_profile": "https://Stackoverflow.com/users/5882380", "pm_score": 0, "selected": false, "text": "List<Emp> Lstemp = GetEmpList(); \nint Srno = 0; \nvar columns = from t in Lstemp \n orderby t.Name \n select new { \n Row_number=++Srno, \n EmpID = t.ID, \n Name = t.Name, \n City = t.City \n };\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42818/" ]
365,087
<p>I m using a dropdown to display "Location" field of a table. I want to set first item of dropdowm as "-Select Location-". I can't set tables first record as "Select" because table is stroed in xml format. And table file is generated dynamicaly. I am currentaly using as</p> <pre><code> ddlLocationName.Dispose(); ddlLocationName.AppendDataBoundItems = true; ddlLocationName.Items.Add("Select Location"); ddlLocationName.DataSource = _section.GetLocations(); ddlLocationName.DataBind(); ddlLocationName.AppendDataBoundItems = false; </code></pre> <p>but data is binded repeatedly. What will be the solution for this problem? Thaks in advance.</p>
[ { "answer_id": 365092, "author": "Samiksha", "author_id": 29515, "author_profile": "https://Stackoverflow.com/users/29515", "pm_score": 0, "selected": false, "text": "ListItem li = new ListItem(\"Select Location\",\"-1\");\nddlLocationName.Items.Add(li);\n ddlLocationName.SelectedValue = \"-1\";\n" }, { "answer_id": 365093, "author": "Tom Jelen", "author_id": 28399, "author_profile": "https://Stackoverflow.com/users/28399", "pm_score": 2, "selected": true, "text": "ddlLocationName.Items.Clear();\nddlLocationName.DataSource = _section.GetLocations();\nddlLocationName.DataBind();\nddlLocationName.Items.Insert(0, \"Select Location\"); // Adds the item in the first position\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43886/" ]
365,094
<p>I've been using <a href="http://www.rainlendar.net" rel="noreferrer">Rainlendar</a> for some time and I noticed that it has an option to put the window "on desktop". It's like a bottomMost window (as against topmost).</p> <p>How could I do this on a WPF app?</p> <p>Thanks</p>
[ { "answer_id": 365270, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 3, "selected": false, "text": " using System;\n using System.Runtime.InteropServices;\n using System.Windows;\n using System.Windows.Interop;\n [DllImport(\"user32.dll\")]\nstatic extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,\n int Y, int cx, int cy, uint uFlags);\n\nconst UInt32 SWP_NOSIZE = 0x0001;\nconst UInt32 SWP_NOMOVE = 0x0002;\nconst UInt32 SWP_NOACTIVATE = 0x0010;\n\nstatic readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\npublic static void SetBottom(Window window)\n{\n IntPtr hWnd = new WindowInteropHelper(window).Handle;\n SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n}\n" }, { "answer_id": 395495, "author": "Artur Carvalho", "author_id": 1013, "author_profile": "https://Stackoverflow.com/users/1013", "pm_score": 2, "selected": false, "text": "[DllImport(\"user32.dll\")]\nstatic extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);\n[DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\npublic static void SetOnDesktop(Window window)\n{\n IntPtr hWnd = new WindowInteropHelper(window).Handle; \n IntPtr hWndProgMan = FindWindow(\"Progman\", \"Program Manager\");\n SetParent(hWnd, hWndProgMan);\n}\n" }, { "answer_id": 15499185, "author": "HrejWaltz", "author_id": 2186451, "author_profile": "https://Stackoverflow.com/users/2186451", "pm_score": 3, "selected": false, "text": " const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n const UInt32 SWP_NOACTIVATE = 0x0010;\n const UInt32 SWP_NOZORDER = 0x0004;\n const int WM_ACTIVATEAPP = 0x001C;\n const int WM_ACTIVATE = 0x0006;\n const int WM_SETFOCUS = 0x0007;\n static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n const int WM_WINDOWPOSCHANGING = 0x0046;\n\n [DllImport(\"user32.dll\")]\n static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,\n int Y, int cx, int cy, uint uFlags);\n [DllImport(\"user32.dll\")]\n static extern IntPtr DeferWindowPos(IntPtr hWinPosInfo, IntPtr hWnd,\n IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);\n [DllImport(\"user32.dll\")]\n static extern IntPtr BeginDeferWindowPos(int nNumWindows);\n [DllImport(\"user32.dll\")]\n static extern bool EndDeferWindowPos(IntPtr hWinPosInfo);\n\n private void Window_Loaded(object sender, RoutedEventArgs e)\n {\n IntPtr hWnd = new WindowInteropHelper(this).Handle;\n SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n\n IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;\n HwndSource src = HwndSource.FromHwnd(windowHandle);\n src.AddHook(new HwndSourceHook(WndProc));\n }\n\n private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SETFOCUS)\n {\n IntPtr hWnd = new WindowInteropHelper(this).Handle;\n SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n handled = true;\n }\n return IntPtr.Zero;\n }\n\n private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;\n HwndSource src = HwndSource.FromHwnd(windowHandle);\n src.RemoveHook(new HwndSourceHook(this.WndProc));\n }\n" }, { "answer_id": 39150799, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class WindowSinker\n{\n #region Properties\n\n const UInt32 SWP_NOSIZE = 0x0001;\n const UInt32 SWP_NOMOVE = 0x0002;\n const UInt32 SWP_NOACTIVATE = 0x0010;\n const UInt32 SWP_NOZORDER = 0x0004;\n const int WM_ACTIVATEAPP = 0x001C;\n const int WM_ACTIVATE = 0x0006;\n const int WM_SETFOCUS = 0x0007;\n const int WM_WINDOWPOSCHANGING = 0x0046;\n\n static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\n Window Window = null;\n\n #endregion\n\n #region WindowSinker\n\n public WindowSinker(Window Window)\n {\n this.Window = Window;\n }\n\n #endregion\n\n #region Methods\n\n [DllImport(\"user32.dll\")]\n static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr DeferWindowPos(IntPtr hWinPosInfo, IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr BeginDeferWindowPos(int nNumWindows);\n\n [DllImport(\"user32.dll\")]\n static extern bool EndDeferWindowPos(IntPtr hWinPosInfo);\n\n void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)\n {\n var Handle = (new WindowInteropHelper(Window)).Handle;\n\n var Source = HwndSource.FromHwnd(Handle);\n Source.RemoveHook(new HwndSourceHook(WndProc));\n }\n\n void OnLoaded(object sender, RoutedEventArgs e)\n {\n var Hwnd = new WindowInteropHelper(Window).Handle;\n SetWindowPos(Hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n\n var Handle = (new WindowInteropHelper(Window)).Handle;\n\n var Source = HwndSource.FromHwnd(Handle);\n Source.AddHook(new HwndSourceHook(WndProc));\n }\n\n IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SETFOCUS)\n {\n hWnd = new WindowInteropHelper(Window).Handle;\n SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n handled = true;\n }\n return IntPtr.Zero;\n }\n\n public void Sink()\n {\n Window.Loaded += OnLoaded;\n Window.Closing += OnClosing;\n }\n\n public void Unsink()\n {\n Window.Loaded -= OnLoaded;\n Window.Closing -= OnClosing;\n }\n\n #endregion\n}\n\npublic static class WindowExtensions\n{\n #region Always On Bottom\n\n public static readonly DependencyProperty SinkerProperty = DependencyProperty.RegisterAttached(\"Sinker\", typeof(WindowSinker), typeof(WindowExtensions), new UIPropertyMetadata(null));\n public static WindowSinker GetSinker(DependencyObject obj)\n {\n return (WindowSinker)obj.GetValue(SinkerProperty);\n }\n public static void SetSinker(DependencyObject obj, WindowSinker value)\n {\n obj.SetValue(SinkerProperty, value);\n }\n\n public static readonly DependencyProperty AlwaysOnBottomProperty = DependencyProperty.RegisterAttached(\"AlwaysOnBottom\", typeof(bool), typeof(WindowExtensions), new UIPropertyMetadata(false, OnAlwaysOnBottomChanged));\n public static bool GetAlwaysOnBottom(DependencyObject obj)\n {\n return (bool)obj.GetValue(AlwaysOnBottomProperty);\n }\n public static void SetAlwaysOnBottom(DependencyObject obj, bool value)\n {\n obj.SetValue(AlwaysOnBottomProperty, value);\n }\n static void OnAlwaysOnBottomChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n var Window = sender as Window;\n if (Window != null)\n {\n if ((bool)e.NewValue)\n {\n var Sinker = new WindowSinker(Window);\n Sinker.Sink();\n SetSinker(Window, Sinker);\n }\n else\n {\n var Sinker = GetSinker(Window);\n Sinker.Unsink();\n SetSinker(Window, null);\n }\n }\n }\n\n #endregion\n}\n" }, { "answer_id": 56906138, "author": "kroimon", "author_id": 291823, "author_profile": "https://Stackoverflow.com/users/291823", "pm_score": 2, "selected": false, "text": "WM_WINDOWPOSCHANGING SWP_NOZORDER SetWindowPos WM_SETFOCUS WindowSinker.AlwaysOnBottom=\"True\" using System;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Windows;\nusing System.Windows.Interop;\n\npublic class WindowSinker\n{\n #region Windows API\n\n // ReSharper disable InconsistentNaming\n\n private const int WM_WINDOWPOSCHANGING = 0x0046;\n\n private const uint SWP_NOSIZE = 0x0001;\n private const uint SWP_NOMOVE = 0x0002;\n private const uint SWP_NOZORDER = 0x0004;\n private const uint SWP_NOACTIVATE = 0x0010;\n\n [StructLayout(LayoutKind.Sequential)]\n public struct WINDOWPOS\n {\n public IntPtr hwnd;\n public IntPtr hwndInsertAfter;\n public int x;\n public int y;\n public int cx;\n public int cy;\n public uint flags;\n }\n\n private static readonly IntPtr HWND_BOTTOM = new IntPtr(1);\n\n // ReSharper restore InconsistentNaming\n\n #endregion\n\n #region WindowSinker\n\n private readonly Window window;\n private bool disposed;\n\n public WindowSinker(Window window)\n {\n this.window = window;\n\n if (window.IsLoaded)\n {\n OnWindowLoaded(window, null);\n }\n else\n {\n window.Loaded += OnWindowLoaded;\n }\n\n window.Closing += OnWindowClosing;\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (disposed) return;\n\n window.Loaded -= OnWindowLoaded;\n window.Closing -= OnWindowClosing;\n\n disposed = true;\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ~WindowSinker()\n {\n Dispose(false);\n }\n\n #endregion\n\n #region Event Handlers\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy,\n uint uFlags);\n\n private void OnWindowLoaded(object sender, RoutedEventArgs e)\n {\n SetWindowPos(new WindowInteropHelper(window).Handle, HWND_BOTTOM, 0, 0, 0, 0,\n SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);\n\n var source = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle);\n source?.AddHook(WndProc);\n }\n\n private void OnWindowClosing(object sender, CancelEventArgs e)\n {\n var source = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle);\n source?.RemoveHook(WndProc);\n }\n\n private IntPtr WndProc(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_WINDOWPOSCHANGING)\n {\n var windowPos = Marshal.PtrToStructure<WINDOWPOS>(lParam);\n windowPos.flags |= SWP_NOZORDER;\n Marshal.StructureToPtr(windowPos, lParam, false);\n }\n\n return IntPtr.Zero;\n }\n\n #endregion\n\n #region Attached Properties\n\n private static readonly DependencyProperty SinkerProperty = DependencyProperty.RegisterAttached(\n \"Sinker\",\n typeof(WindowSinker),\n typeof(WindowSinker),\n null);\n\n public static readonly DependencyProperty AlwaysOnBottomProperty = DependencyProperty.RegisterAttached(\n \"AlwaysOnBottom\",\n typeof(bool),\n typeof(WindowSinker),\n new UIPropertyMetadata(false, OnAlwaysOnBottomChanged));\n\n public static WindowSinker GetSinker(DependencyObject d)\n {\n return (WindowSinker) d.GetValue(SinkerProperty);\n }\n\n private static void SetSinker(DependencyObject d, WindowSinker value)\n {\n d.SetValue(SinkerProperty, value);\n }\n\n public static bool GetAlwaysOnBottom(DependencyObject d)\n {\n return (bool) d.GetValue(AlwaysOnBottomProperty);\n }\n\n public static void SetAlwaysOnBottom(DependencyObject d, bool value)\n {\n d.SetValue(AlwaysOnBottomProperty, value);\n }\n\n private static void OnAlwaysOnBottomChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n if (sender is Window window)\n {\n if ((bool) e.NewValue)\n {\n SetSinker(window, new WindowSinker(window));\n }\n else\n {\n GetSinker(window)?.Dispose();\n SetSinker(window, null);\n }\n }\n }\n\n #endregion\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
365,095
<p>How do you make the authentication for a browser-based application dependent on the client machine? Say the admin can login only from <b>this</b> machine.</p> <p>Assumptions: There is complete control over the network and all machines (client and server) involved.</p> <p>I am looking for an apache/linux solution.</p>
[ { "answer_id": 365102, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 3, "selected": true, "text": " <Directory \"/www/hidden/docs\">\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17404/" ]
365,100
<p>I keep on hearing this words '<strong>callback</strong>' and '<strong>postback</strong>' tossed around.<br> What is the difference between two ? </p> <p>Is postback very specific to the ASP.NET pages ?</p>
[ { "answer_id": 365106, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 9, "selected": true, "text": "<form> Console Request Response" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41968/" ]
365,103
<p>I want to profile (keep an Eye on) all the activities that goes on in a Database which is in PostgreSQL.</p> <p>Is there any such utility which will help me do this?</p>
[ { "answer_id": 365112, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 3, "selected": false, "text": "pg_catalog pg_stat_user_tables pg_stat_user_indexes pg_stat* pg_stat_activity" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45951/" ]
365,125
<p>As part of a VBA program, I have to set the background colors of certain cells to green, yellow or red, based on their values (basically a health monitor where green is okay, yellow is borderline and red is dangerous).</p> <p>I know how to set the values of those cells, but how do I set the background color.</p>
[ { "answer_id": 365131, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "ActiveCell.Interior.ColorIndex = 28\n ActiveCell.Interior.Color = RGB(255,0,0)\n" }, { "answer_id": 60529043, "author": "Matt G", "author_id": 8120930, "author_profile": "https://Stackoverflow.com/users/8120930", "pm_score": 1, "selected": false, "text": "Sub Name()\nSelection.Interior.Color = 65535 '(your number may be different depending on the above)\nEnd Sub\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14860/" ]
365,155
<p>I want a simple tutorial to show me how to load a yaml file and parse the data. Expat style would be great but any solution that actually shows me the data in some form would be useful.</p> <p>So far I ran multiple tests in the <code>yaml-0.1.1</code> source code for C and I either get an error, no output whatsoever, or in the <code>run-emitter.c</code> case. It reads in the yaml file and prints it to <code>STDOUT</code>, it does not produce the text via <code>libyaml</code> functions/structs. In the cases with an error I don't know if it was because the file was bad or my build is incorrect (I didn't modify anything...) The file was copied from yaml.org</p> <p>Can anyone point me to a tutorial? (I googled for at least 30 minutes reading anything that looked relevant) or a name of a lib that has a good tutorial or example. Maybe you can tell me which <code>libyaml</code> test loads in files and does something with it or why I got errors. This document does not explain how to <em>use</em> the file--only how to load it:</p> <p><a href="http://pyyaml.org/wiki/LibYAML#Documentation" rel="nofollow noreferrer">http://pyyaml.org/wiki/LibYAML#Documentation</a></p>
[ { "answer_id": 365230, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "#include <iyaml++.hh>\n#include <tr1/memory>\n#include <iostream>\n#include <stdexcept>\n\nusing namespace std;\n\n// What should libyaml++ do when a YAML entity is parsed?\n// NOTE: if any of the event handlers is not defined, a respective default\n// no-op handler will be used. For example, not defining on_eos() is\n// equivalent to defining void on_eos() { }.\nclass my_handler : public yaml::event_handler {\n void on_string(const std::string& s) { cout << \"parsed string: \" << s << endl; }\n void on_integer(const std::string& s) { cout << \"parsed integer: \" << s << endl; }\n void on_sequence_begin() { cout << \"parsed sequence-begin.\" << endl; }\n void on_mapping_begin() { cout << \"parsed mapping-begin.\" << endl; }\n void on_sequence_end() { cout << \"parsed sequence-end.\" << endl; }\n void on_mapping_end() { cout << \"parsed mapping-end.\" << endl; }\n void on_document() { cout << \"parsed document.\" << endl; }\n void on_pair() { cout << \"parsed pair.\" << endl; }\n void on_eos() { cout << \"parsed eos.\" << endl; }\n};\n\n// ok then, now that i know how to behave on each YAML entity encountered, just\n// give me a stream to parse!\nint main(int argc, char* argv[])\n{\n tr1::shared_ptr<my_handler> handler(new my_handler());\n while( cin ) {\n try { yaml::load(cin, handler); } // throws on syntax error\n\n catch( const runtime_error& e ) {\n cerr << e.what() << endl;\n }\n }\n return 0;\n}\n" }, { "answer_id": 621451, "author": "mk-fg", "author_id": 1646435, "author_profile": "https://Stackoverflow.com/users/1646435", "pm_score": 4, "selected": false, "text": "#include <yaml.h>\n#include <stdio.h>\n#include <glib.h>\n\nvoid process_layer(yaml_parser_t *parser, GNode *data);\ngboolean dump(GNode *n, gpointer data);\n\n\n\nint main (int argc, char **argv) {\n char *file_path = \"test.yaml\";\n GNode *cfg = g_node_new(file_path);\n yaml_parser_t parser;\n\n FILE *source = fopen(file_path, \"rb\");\n yaml_parser_initialize(&parser);\n yaml_parser_set_input_file(&parser, source);\n process_layer(&parser, cfg); // Recursive parsing\n yaml_parser_delete(&parser);\n fclose(source);\n\n printf(\"Results iteration:\\n\");\n g_node_traverse(cfg, G_PRE_ORDER, G_TRAVERSE_ALL, -1, dump, NULL);\n g_node_destroy(cfg);\n\n return(0);\n}\n\n\n\nenum storage_flags { VAR, VAL, SEQ }; // \"Store as\" switch\n\nvoid process_layer(yaml_parser_t *parser, GNode *data) {\n GNode *last_leaf = data;\n yaml_event_t event;\n int storage = VAR; // mapping cannot start with VAL definition w/o VAR key\n\n while (1) {\n yaml_parser_parse(parser, &event);\n\n // Parse value either as a new leaf in the mapping\n // or as a leaf value (one of them, in case it's a sequence)\n if (event.type == YAML_SCALAR_EVENT) {\n if (storage) g_node_append_data(last_leaf, g_strdup((gchar*) event.data.scalar.value));\n else last_leaf = g_node_append(data, g_node_new(g_strdup((gchar*) event.data.scalar.value)));\n storage ^= VAL; // Flip VAR/VAL switch for the next event\n }\n\n // Sequence - all the following scalars will be appended to the last_leaf\n else if (event.type == YAML_SEQUENCE_START_EVENT) storage = SEQ;\n else if (event.type == YAML_SEQUENCE_END_EVENT) storage = VAR;\n\n // depth += 1\n else if (event.type == YAML_MAPPING_START_EVENT) {\n process_layer(parser, last_leaf);\n storage ^= VAL; // Flip VAR/VAL, w/o touching SEQ\n }\n\n // depth -= 1\n else if (\n event.type == YAML_MAPPING_END_EVENT\n || event.type == YAML_STREAM_END_EVENT\n ) break;\n\n yaml_event_delete(&event);\n }\n}\n\n\ngboolean dump(GNode *node, gpointer data) {\n int i = g_node_depth(node);\n while (--i) printf(\" \");\n printf(\"%s\\n\", (char*) node->data);\n return(FALSE);\n}\n" }, { "answer_id": 838428, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 6, "selected": false, "text": "YAML::Node config = YAML::LoadFile(\"config.yaml\");\n\nif (config[\"lastLogin\"]) {\n std::cout << \"Last logged in: \" << config[\"lastLogin\"].as<DateTime>() << \"\\n\";\n}\n\nconst std::string username = config[\"username\"].as<std::string>();\nconst std::string password = config[\"password\"].as<std::string>();\nlogin(username, password);\nconfig[\"lastLogin\"] = getCurrentDateTime();\n\nstd::ofstream fout(\"config.yaml\");\nfout << config;\n" }, { "answer_id": 69552155, "author": "Mikolasan", "author_id": 1104612, "author_profile": "https://Stackoverflow.com/users/1104612", "pm_score": 3, "selected": false, "text": "yaml-cpp libyaml #include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <ryml_std.hpp>\n#include <ryml.hpp>\n\nstd::string get_file_contents(const char *filename)\n{\n std::ifstream in(filename, std::ios::in | std::ios::binary);\n if (!in) {\n std::cerr << \"could not open \" << filename << std::endl;\n exit(1);\n }\n std::ostringstream contents;\n contents << in.rdbuf();\n return contents.str();\n}\n\nint main(int argc, char const *argv[]) \n{\n std::string contents = get_file_contents(\"config.yaml\");\n ryml::Tree tree = ryml::parse_in_place(ryml::to_substr(contents));\n ryml::NodeRef foo = tree[\"foo\"];\n for (ryml::NodeRef const& child : foo.children()) {\n std::cout << \"key: \" << child.key() << \" val: \" << child.val() << std::endl;\n }\n \n ryml::NodeRef array = tree[\"matrix\"][\"array\"];\n for (ryml::NodeRef const& child : array.children()) {\n double val;\n child >> val;\n std::cout << \"float val: \" << std::setprecision (18) << val << std::endl;\n }\n return 0;\n}\n foo:\n bar: a\n barbar: b\n barbarbar: c\n\nmatrix:\n array:\n - 0.045533736417839546\n - 0.16564066086021373\n - 0.028658520327566304\n - 0.009133486414620372\n - -0.5801749091384203\n git clone --recurse-submodules -j8 https://github.com/biojppm/rapidyaml.git\n rapidyaml cmake_minimum_required(VERSION 3.14)\n\nproject(so_answer VERSION 0.0.1 LANGUAGES CXX)\n\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\n\nadd_subdirectory(thirdparty/rapidyaml)\n\nadd_executable(example example.cpp)\ntarget_include_directories(example PRIVATE thirdparty/rapidyaml/src)\ntarget_link_libraries(example ryml)\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,168
<p>Since I kicked off the process of inserting 7M rows from one table into two others, I'm wondering now if there's a faster way to do this. The process is expected to finish in an hour, that's 24h of processing.</p> <p>Here's how it goes:</p> <p>The data from this table</p> <pre><code>RAW (word VARCHAR2(4000), doc VARCHAR2(4000), count NUMBER); </code></pre> <p>should find a new home in two other cluster tables T1 and T2</p> <pre><code>CREATE CLUSTER C1 (word VARCHAR2(4000)) SIZE 200 HASHKEYS 10000000; CREATE CLUSTER C2 (doc VARCHAR2(4000)) SIZE 200 HASHKEYS 10000000; T1 (word VARCHAR2(4000), doc VARCHAR2(4000), count NUMBER) CLUSTER C1(word); T2 (doc VARCHAR2(4000), word VARCHAR2(4000), count NUMBER) CLUSTER C2(doc); </code></pre> <p>through Java inserts with manual commit like this</p> <pre><code>stmtT1 = conn.prepareStatement("insert into T1 values(?,?,?)"); stmtT2 = conn.prepareStatement("insert into T2 values(?,?,?)"); rs = stmt.executeQuery("select word, doc, count from RAW"); conn.setAutoCommit(false); while (rs.next()) { word = rs.getString(1); doc = rs.getString(2); count = rs.getInt(3); if (commitCount++==10000) { conn.commit(); commitCount=0; } stmtT1.setString(1, word); stmtT1.setString(2, doc); stmtT1.setInt(3, count); stmtT2.setString(1, doc); stmtT2.setString(2, word); stmtT2.setInt(3,count); stmtT1.execute(); stmtT2.execute(); } conn.commit(); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 368455, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "insert all\ninto t1\ninto t2\nselect * from RAW\n/\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36942/" ]
365,191
<p>How to calculate minute difference between two date-times in PHP?</p>
[ { "answer_id": 365214, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 8, "selected": true, "text": "January 1, 1970, 00:00:00 GMT" }, { "answer_id": 365220, "author": "user38526", "author_id": 38526, "author_profile": "https://Stackoverflow.com/users/38526", "pm_score": 9, "selected": false, "text": "$to_time = strtotime(\"2008-12-13 10:42:00\");\n$from_time = strtotime(\"2008-12-13 10:21:00\");\necho round(abs($to_time - $from_time) / 60,2). \" minute\";\n" }, { "answer_id": 365350, "author": "Tom", "author_id": 45974, "author_profile": "https://Stackoverflow.com/users/45974", "pm_score": 5, "selected": false, "text": "<?php\n$date1 = time();\nsleep(2000);\n$date2 = time();\n$mins = ($date2 - $date1) / 60;\necho $mins;\n?>\n" }, { "answer_id": 12382882, "author": "mike", "author_id": 782804, "author_profile": "https://Stackoverflow.com/users/782804", "pm_score": 9, "selected": false, "text": "$start_date = new DateTime('2007-09-01 04:10:58');\n$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));\necho $since_start->days.' days total<br>';\necho $since_start->y.' years<br>';\necho $since_start->m.' months<br>';\necho $since_start->d.' days<br>';\necho $since_start->h.' hours<br>';\necho $since_start->i.' minutes<br>';\necho $since_start->s.' seconds<br>';\n $minutes = $since_start->days * 24 * 60;\n$minutes += $since_start->h * 60;\n$minutes += $since_start->i;\necho $minutes.' minutes';\n" }, { "answer_id": 20761655, "author": "Muhammad", "author_id": 487289, "author_profile": "https://Stackoverflow.com/users/487289", "pm_score": 4, "selected": false, "text": "$start_date = new DateTime(\"2013-12-24 06:00:00\",new DateTimeZone('Pacific/Nauru'));\n$end_date = new DateTime(\"2013-12-24 06:45:00\", new DateTimeZone('Pacific/Nauru'));\n$interval = $start_date->diff($end_date);\n$hours = $interval->format('%h'); \n$minutes = $interval->format('%i');\necho 'Diff. in minutes is: '.($hours * 60 + $minutes);\n" }, { "answer_id": 22678132, "author": "hriziya", "author_id": 1005741, "author_profile": "https://Stackoverflow.com/users/1005741", "pm_score": 4, "selected": false, "text": "//Usage:\n$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'\n$diff = ago($pubDate); // output: 23 hrs ago\n\n// Return the value of time different in \"xx times ago\" format\nfunction ago($timestamp)\n{\n\n $today = new DateTime(date('y-m-d h:i:s')); // [2]\n //$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');\n $thatDay = new DateTime($timestamp);\n $dt = $today->diff($thatDay);\n\n if ($dt->y > 0){\n $number = $dt->y;\n $unit = \"year\";\n } else if ($dt->m > 0) {\n $number = $dt->m;\n $unit = \"month\";\n } else if ($dt->d > 0) {\n $number = $dt->d;\n $unit = \"day\";\n } else if ($dt->h > 0) {\n $number = $dt->h;\n $unit = \"hour\";\n } else if ($dt->i > 0) {\n $number = $dt->i;\n $unit = \"minute\";\n } else if ($dt->s > 0) {\n $number = $dt->s;\n $unit = \"second\";\n }\n \n $unit .= $number > 1 ? \"s\" : \"\";\n \n $ret = $number.\" \".$unit.\" \".\"ago\";\n return $ret;\n}\n" }, { "answer_id": 24100772, "author": "Raj Nandan Sharma", "author_id": 3090583, "author_profile": "https://Stackoverflow.com/users/3090583", "pm_score": 4, "selected": false, "text": "<?php\n\n//Code written by purpledesign.in Jan 2014\nfunction dateDiff($date)\n{\n $mydate= date(\"Y-m-d H:i:s\");\n $theDiff=\"\";\n //echo $mydate;//2014-06-06 21:35:55\n $datetime1 = date_create($date);\n $datetime2 = date_create($mydate);\n $interval = date_diff($datetime1, $datetime2);\n //echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago').\"<br>\";\n $min=$interval->format('%i');\n $sec=$interval->format('%s');\n $hour=$interval->format('%h');\n $mon=$interval->format('%m');\n $day=$interval->format('%d');\n $year=$interval->format('%y');\n if($interval->format('%i%h%d%m%y')==\"00000\") {\n //echo $interval->format('%i%h%d%m%y').\"<br>\";\n return $sec.\" Seconds\";\n } else if($interval->format('%h%d%m%y')==\"0000\"){\n return $min.\" Minutes\";\n } else if($interval->format('%d%m%y')==\"000\"){\n return $hour.\" Hours\";\n } else if($interval->format('%m%y')==\"00\"){\n return $day.\" Days\";\n } else if($interval->format('%y')==\"0\"){\n return $mon.\" Months\";\n } else{\n return $year.\" Years\";\n } \n}\n?>\n <?php\n require('date.php');\n $mydate='2014-11-14 21:35:55';\n echo \"The Difference between the server's date and $mydate is:<br> \";\n echo dateDiff($mydate);\n?>\n" }, { "answer_id": 26668053, "author": "Yubraj Pokharel", "author_id": 2404780, "author_profile": "https://Stackoverflow.com/users/2404780", "pm_score": 4, "selected": false, "text": "function calculate_time_span($date){\n $seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);\n\n $months = floor($seconds / (3600*24*30));\n $day = floor($seconds / (3600*24));\n $hours = floor($seconds / 3600);\n $mins = floor(($seconds - ($hours*3600)) / 60);\n $secs = floor($seconds % 60);\n\n if($seconds < 60)\n $time = $secs.\" seconds ago\";\n else if($seconds < 60*60 )\n $time = $mins.\" min ago\";\n else if($seconds < 24*60*60)\n $time = $hours.\" hours ago\";\n else if($seconds < 24*60*60)\n $time = $day.\" day ago\";\n else\n $time = $months.\" month ago\";\n\n return $time;\n}\n" }, { "answer_id": 28186490, "author": "Veerendra", "author_id": 2982676, "author_profile": "https://Stackoverflow.com/users/2982676", "pm_score": 3, "selected": false, "text": "function date_getFullTimeDifference( $start, $end )\n{\n$uts['start'] = strtotime( $start );\n $uts['end'] = strtotime( $end );\n if( $uts['start']!==-1 && $uts['end']!==-1 )\n {\n if( $uts['end'] >= $uts['start'] )\n {\n $diff = $uts['end'] - $uts['start'];\n if( $years=intval((floor($diff/31104000))) )\n $diff = $diff % 31104000;\n if( $months=intval((floor($diff/2592000))) )\n $diff = $diff % 2592000;\n if( $days=intval((floor($diff/86400))) )\n $diff = $diff % 86400;\n if( $hours=intval((floor($diff/3600))) )\n $diff = $diff % 3600;\n if( $minutes=intval((floor($diff/60))) )\n $diff = $diff % 60;\n $diff = intval( $diff );\n return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );\n }\n else\n {\n echo \"Ending date/time is earlier than the start date/time\";\n }\n }\n else\n {\n echo \"Invalid date/time data detected\";\n }\n}\n" }, { "answer_id": 31322272, "author": "yussan", "author_id": 2780875, "author_profile": "https://Stackoverflow.com/users/2780875", "pm_score": 4, "selected": false, "text": "date_diff date_diff $start = date_create('2015-01-26 12:01:00');\n$end = date_create('2015-01-26 13:15:00');\n$diff=date_diff($end,$start);\nprint_r($diff);\n" }, { "answer_id": 44317968, "author": "besimple", "author_id": 2423284, "author_profile": "https://Stackoverflow.com/users/2423284", "pm_score": 3, "selected": false, "text": "function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {\n//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)\n $nInterval = strtotime($sDate2) - strtotime($sDate1);\n if ($sUnit=='D') { // days\n $nInterval = $nInterval/60/60/24;\n } else if ($sUnit=='H') { // hours\n $nInterval = $nInterval/60/60;\n } else if ($sUnit=='M') { // minutes\n $nInterval = $nInterval/60;\n } else if ($sUnit=='S') { // seconds\n }\n return $nInterval;\n} //DateDiffInterval\n" }, { "answer_id": 48274342, "author": "GYaN", "author_id": 4057622, "author_profile": "https://Stackoverflow.com/users/4057622", "pm_score": 0, "selected": false, "text": "function get_time($date,$nosuffix=''){\n $datetime = new DateTime($date);\n $interval = date_create('now')->diff( $datetime );\n if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );\n else $suffix='';\n //return $interval->y;\n if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}\n elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}\n elseif($interval->d >=1) {$count = $interval->d; $text = 'day';} \n elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}\n elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}\n elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}\n else {$count = $interval->s; $text = 'second';}\n if(empty($text)) return '<i class=\"fa fa-clock-o\"></i> '.$count;\n return '<i class=\"fa fa-clock-o\"></i> '.$count.(($count ==1)?(\" $text\"):(\" ${text}s\")).' '.$suffix; \n}\n" }, { "answer_id": 55320337, "author": "Ali Han", "author_id": 585626, "author_profile": "https://Stackoverflow.com/users/585626", "pm_score": 2, "selected": false, "text": "function alihan_diff_dates($date = null, $diff = \"minutes\") {\n $start_date = new DateTime($date);\n $since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now\n print_r($since_start);\n switch ($diff) {\n case 'seconds':\n return $since_start->s;\n break;\n case 'minutes':\n return $since_start->i;\n break;\n case 'hours':\n return $since_start->h;\n break;\n case 'days':\n return $since_start->d;\n break; \n default:\n # code...\n break;\n }\n}\n /*\nDateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) \n*/\n $diff_mins = alihan_diff_dates(\"2019-03-24 13:24:19\", \"minutes\");\n" }, { "answer_id": 56458038, "author": "Sumit Kumar Gupta", "author_id": 8484740, "author_profile": "https://Stackoverflow.com/users/8484740", "pm_score": 0, "selected": false, "text": "<?php\n\n $time1 = \"23:58\";\n $time2 = \"01:00\";\n $time1 = explode(':',$time1);\n $time2 = explode(':',$time2);\n $hours1 = $time1[0];\n $hours2 = $time2[0];\n $mins1 = $time1[1];\n $mins2 = $time2[1];\n $hours = $hours2 - $hours1;\n $mins = 0;\n if($hours < 0)\n {\n $hours = 24 + $hours;\n }\n if($mins2 >= $mins1) {\n $mins = $mins2 - $mins1;\n }\n else {\n $mins = ($mins2 + 60) - $mins1;\n $hours--;\n }\n if($mins < 9)\n {\n $mins = str_pad($mins, 2, '0', STR_PAD_LEFT);\n }\n if($hours < 9)\n {\n $hours =str_pad($hours, 2, '0', STR_PAD_LEFT);\n }\necho $hours.':'.$mins;\n?>\n" }, { "answer_id": 57908603, "author": "Rahilkhan Pathan", "author_id": 9393184, "author_profile": "https://Stackoverflow.com/users/9393184", "pm_score": 5, "selected": false, "text": "<?php\n$start = strtotime('12:01:00');\n$end = strtotime('13:16:00');\n$mins = ($end - $start) / 60;\necho $mins;\n?>\n 75\n" }, { "answer_id": 58628125, "author": "Mustafa Bazghandi", "author_id": 7826774, "author_profile": "https://Stackoverflow.com/users/7826774", "pm_score": 3, "selected": false, "text": "2019/02/01 10:23:45 $diff_time=(strtotime(date(\"Y/m/d H:i:s\"))-strtotime(\"2019/02/01 10:23:45\"))/60;\n" }, { "answer_id": 64631486, "author": "Soner from The Ottoman Empire", "author_id": 4990642, "author_profile": "https://Stackoverflow.com/users/4990642", "pm_score": 1, "selected": false, "text": "$date1=date_create(\"2020-03-15\");\n$date2=date_create(\"2020-12-12\");\n$diff=date_diff($date1,$date2);\necho $diff->format(\"%R%a days\");\n" }, { "answer_id": 66189503, "author": "Udith Chandrarathna", "author_id": 7967496, "author_profile": "https://Stackoverflow.com/users/7967496", "pm_score": 1, "selected": false, "text": "$origin = new DateTime('2021-02-10 09:46:32');\n$target = new DateTime('2021-02-11 09:46:32');\n$interval = $origin->diff($target);\necho (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)\n" }, { "answer_id": 67445652, "author": "Hamza Qureshi", "author_id": 14913109, "author_profile": "https://Stackoverflow.com/users/14913109", "pm_score": -1, "selected": false, "text": "$now = \\Carbon\\Carbon::now()->toDateString(); // get current time \n $a = strtotime(\"2012-09-21 12:12:22\"); \n $b = strtotime($now);\n $minutes = ceil(($a - $b) / 3600); it will get ceiling value \n" }, { "answer_id": 67691063, "author": "Şafak Gezer", "author_id": 274393, "author_profile": "https://Stackoverflow.com/users/274393", "pm_score": 4, "selected": false, "text": "DateTime::diff $date1 = new DateTime('2020-09-01 01:00:00');\n$date2 = new DateTime('2021-09-01 14:00:00');\n$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;\n" }, { "answer_id": 70173394, "author": "nimrod", "author_id": 569077, "author_profile": "https://Stackoverflow.com/users/569077", "pm_score": 0, "selected": false, "text": "$start = new DateTime('yesterday');\n$end = new DateTime('now');\n$diffInMinutes = iterator_count(new \\DatePeriod($start, new \\DateInterval('PT1M'), $end));\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38940/" ]
365,204
<p>I am new to UserControls, and while developing my own control I found a problem with showing events of my control in the property grid at design time. If I have some events in my control I want to see them in Property grid and if I double-click that I want to have a handler, in the same way Microsoft does for its controls.</p>
[ { "answer_id": 365216, "author": "lc.", "author_id": 44853, "author_profile": "https://Stackoverflow.com/users/44853", "pm_score": 3, "selected": true, "text": "public [Description(\"This event is raised when the user presses the enter key while the control has focus.\"),\n Category(\"Key\")]\n public event EventHandler EnterPressed;\n" }, { "answer_id": 1079021, "author": "Filini", "author_id": 21162, "author_profile": "https://Stackoverflow.com/users/21162", "pm_score": 1, "selected": false, "text": " #region MyEvent CUSTOM EVENT\n\n protected virtual void OnMyEvent(MyEventEventArgs e)\n {\n if (MyEvent != null)\n MyEvent(this, e);\n }\n\n public delegate void MyEventHandler(object sender, MyEventEventArgs e);\n public event MyEventHandler MyEvent;\n\n public class MyEventEventArgs : EventArgs\n {\n\n }\n\n #endregion MyEvent CUSTOM EVENT\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45648/" ]
365,208
<p>Do you have any experience with <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" rel="nofollow noreferrer">T4</a> and <a href="http://www.t4editor.net/" rel="nofollow noreferrer">T4 Editor</a>? Can you compare it to <a href="http://www.codesmithtools.com/" rel="nofollow noreferrer">CodeSmith</a> or <a href="http://www.mygenerationsoftware.com/" rel="nofollow noreferrer">MyGeneration</a>?</p> <p>What code generators do you use? What do you recommend?</p> <p>I want to use it for generatig of SPs. Is there anything else you find code generation useful?</p>
[ { "answer_id": 365211, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 1, "selected": false, "text": "tab tab if try" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19712/" ]
365,219
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/12249056/executing-sql-server-agent-job-from-a-stored-procedure-and-returning-job-result">Executing SQL Server Agent Job from a stored procedure and returning job result</a> </p> </blockquote> <p>Is there a way to determine when a sql agent job as finished once it has been started with sp_start_job?</p>
[ { "answer_id": 365250, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 2, "selected": false, "text": "XP_SQLAGENT_ENUM_JOBS sp_help_jobs" }, { "answer_id": 3104804, "author": "Maashu", "author_id": 222489, "author_profile": "https://Stackoverflow.com/users/222489", "pm_score": 1, "selected": false, "text": "CREATE PROCEDURE spWorkaround_checkJobExists\n\n@job_id UNIQUEIDENTIFIER \n, @thisIteration tinyint \n, @maxRecurse tinyint\n\nAS\n\nIF (@thisIteration <= @maxRecurse)\nBEGIN\n IF EXISTS(\n select * FROM msdb.dbo.sysjobs where job_id = @job_id\n ) \n BEGIN\n WAITFOR DELAY '00:00:01'\n DECLARE @nextIteration int\n SET @nextIteration = @thisIteration + 1\n EXEC dbo.spWorkaround_checkJobExists @job_id, @nextIteration, @maxRecurse\n END\nEND\n" }, { "answer_id": 10498078, "author": "raghumithra", "author_id": 1099663, "author_profile": "https://Stackoverflow.com/users/1099663", "pm_score": 1, "selected": false, "text": " sp_help_job @job_name @execution_status = 0\n" }, { "answer_id": 10760585, "author": "topwik", "author_id": 62068, "author_profile": "https://Stackoverflow.com/users/62068", "pm_score": 3, "selected": false, "text": "-- output from stored procedure xp_sqlagent_enum_jobs is captured in the following table\n declare @xp_results TABLE ( job_id UNIQUEIDENTIFIER NOT NULL,\n last_run_date INT NOT NULL,\n last_run_time INT NOT NULL,\n next_run_date INT NOT NULL,\n next_run_time INT NOT NULL,\n next_run_schedule_id INT NOT NULL,\n requested_to_run INT NOT NULL, -- BOOL\n request_source INT NOT NULL,\n request_source_id sysname COLLATE database_default NULL,\n running INT NOT NULL, -- BOOL\n current_step INT NOT NULL,\n current_retry_attempt INT NOT NULL,\n job_state INT NOT NULL)\n\n -- start the job\n declare @r as int\n exec @r = msdb..sp_start_job @job\n\n -- quit if unable to start\n if @r<>0\n RAISERROR (N'Could not start job: %s.', 16, 2, @job)\n\n -- start with an initial delay to allow the job to appear in the job list (maybe I am missing something ?)\n WAITFOR DELAY '0:0:01';\n set @seccount = 1\n\n -- check job run state\n insert into @xp_results\n execute master.dbo.xp_sqlagent_enum_jobs 1, @job_owner, @job_id\n\n set @running= (SELECT top 1 running from @xp_results)\n\n while @running<>0\n begin\n WAITFOR DELAY '0:0:01';\n set @seccount = @seccount + 1\n\n delete from @xp_results\n\n insert into @xp_results\n execute master.dbo.xp_sqlagent_enum_jobs 1, @job_owner, @job_id\n\n set @running= (SELECT top 1 running from @xp_results)\n end\n\n -- result: not ok (=1) if still running\n\n if @running <> 0 begin\n -- still running\n return 0\n end\n else begin\n\n -- did it finish ok ?\n set @run_status = 0\n\n select @run_status=run_status\n from msdb.dbo.sysjobhistory\n where job_id=@job_id\n and cast(run_date as bigint) * 1000000 + run_time >= @start_job\n\n if @run_status=1\n return 1 --finished ok\n else --error\n RAISERROR (N'job %s did not finish successfully.', 16, 2, @job)\n\n end\n\n END TRY\n" }, { "answer_id": 10760776, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "SELECT TOP 1 1 AS FinishedRunning\nFROM msdb..sysjobactivity aj\nJOIN msdb..sysjobs sj on sj.job_id = aj.job_id\nWHERE aj.stop_execution_date IS NOT NULL\nAND aj.start_execution_date IS NOT NULL\nAND sj.name = 'YourJobNameHere'\nAND NOT EXISTS\n(\n SELECT TOP 1 1\n FROM msdb..sysjobactivity New\n WHERE New.job_id = aj.job_id\n AND new.start_execution_date > aj.start_execution_date\n)\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1200558/" ]
365,222
<p>I have a base recipe class and I am using a datacontext. I overrode the insert method for the recipe in the datacontext and am trying to insert into its children. Nomatter what I do I cannot get the child to insert.Currently, just the recipe inserts and nothing happens with the child.</p> <pre><code> partial void InsertRecipe(Recipe instance) { // set up the arrays for (int x = 0; x &lt; instance.PlainIngredients.Count; ++x) { instance.TextIngredients.Add(new TextIngredient() { StepNumber = x + 1, Text = instance.PlainIngredients[x] }); } this.ExecuteDynamicInsert(instance); } </code></pre> <p>I have tried everything I can think of. I even instantiated another datacontext in the method and after the instance came back from ExecuteDynamicInsert with the id, tried to add it, and I get timeout errors.</p>
[ { "answer_id": 367299, "author": "Matthew Kruskamp", "author_id": 22521, "author_profile": "https://Stackoverflow.com/users/22521", "pm_score": 3, "selected": true, "text": " public override void SubmitChanges(\n System.Data.Linq.ConflictMode failureMode)\n {\n ChangeSet changes = this.GetChangeSet();\n\n var recipeInserts = (from r in changes.Inserts\n where (r as Recipe) != null\n select r as Recipe).ToList<Recipe>();\n\n var recipeUpdates = (from r in changes.Updates\n where (r as Recipe) != null\n select r as Recipe).ToList<Recipe>();\n\n ConvertTextData(recipeInserts);\n ConvertTextData(recipeUpdates);\n\n base.SubmitChanges(failureMode);\n }\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22521/" ]
365,223
<p>Is there a way to programmatically disable usb storage devices from working while still keeping usb ports functional for other types of devices like keyboards and mice?</p>
[ { "answer_id": 365245, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 4, "selected": true, "text": "Directions for Use:\n\n1.) Take the following blue text, copy it, and paste it into a text document. Then, save it as USBSTOR.ADM.\nCLASS MACHINE\nCATEGORY \"Custom Policies\"\nKEYNAME \"SYSTEM\\CurrentControlSet\\Services\\UsbStor\"\n POLICY \"USB Mass Storage Installation\"\n EXPLAIN \"When this policy is enabled, USB mass storage device permissions can be changed by using the drop down box.\n\nSelecting 'Grant Permission' will allow USB mass storage devices to be installed. Selecting 'Deny Permission' will prohibit\nthe installation of USB mass storage devices.\n\nIF REMOVING THIS POLICY: Reset to original setting and let policy propegate before deleting policy.\"\n PART \"Change Settings:\" DROPDOWNLIST REQUIRED\n VALUENAME \"Start\"\n ITEMLIST\n NAME \"Grant Permission\" VALUE NUMERIC 3 DEFAULT\n NAME \"Deny Permission\" VALUE NUMERIC 4\n END ITEMLIST\n END PART\n END POLICY\nEND CATEGORY\n\n2.) Open a group policy management console (gpedit.msc), and right click on \"administrative templates\" under \"Computer Configuration\". Select \"Add/Remove Templates\".\n\n3.) Browse to the text document you just saved and click OK. You'll now see \"Custom Policies\" under \"Administrative Templates\". Right click on it, select \"View\", then select \"Filtering\". Uncheck the bottom box, labeled \"Only show policy settings that can be fully managed\".\n\n4.) Click ok. Now you'll see the USB policy available for use under the custom policy heading. From there, you can enable or disable it just like any other policy.\n REG ADD \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR\" /v Start /t REG_DWORD /d 4 /f\n REG ADD \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR\" /v Start /t REG_DWORD /d 3 /f\n" }, { "answer_id": 2570151, "author": "user308111", "author_id": 308111, "author_profile": "https://Stackoverflow.com/users/308111", "pm_score": 2, "selected": false, "text": "@echo off\n\n:: Disable USBstor driver\nreg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR /v Start /t REG_DWORD /d 4 /f\n\n:: USB Read Only Mode\nreg add HKLM\\SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies /v WriteProtect /t REG_DWORD /d 1 /f\n\n:: USB Disable startup\n\nreg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR /v Boot /t REG_DWORD /d 0 /f\n\nrem reg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR /v System /t REG_DWORD /d 1 /f\n\nreg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR /v Auto Load /t REG_DWORD /d 0 /f\n\n:: Disable read permissions on USBstor driver\n\n:: Remove Access for Users from files\n\ncacls %SystemRoot%\\inf\\usbstor.inf /E /R users\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /R users\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /R users\ncacls %SystemRoot%\\inf\\usbstor.inf /E /D users\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /D users\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D users\n\n:: Remove Access for System\ncacls %SystemRoot%\\inf\\usbstor.inf /E /R system\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /R system\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /R system\ncacls %SystemRoot%\\inf\\usbstor.inf /E /D system\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /D system\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D system\n\n:: Remove Access for ower Users\ncacls %SystemRoot%\\inf\\usbstor.inf /E /R \"Power Users\"\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /R \"Power Users\"\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /R \"Power Users\"\ncacls %SystemRoot%\\inf\\usbstor.inf /E /D \"Power Users\"\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /D \"Power Users\"\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D \"Power Users\"\n\n:: Remove Access for Administrators\ncacls %SystemRoot%\\inf\\usbstor.inf /E /R Administrators\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /R Administrators\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /R Administrators\ncacls %SystemRoot%\\inf\\usbstor.inf /E /D Administrators\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /D Administrators\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D Administrators\n\n:: Remove Access for EveryOne\ncacls %SystemRoot%\\inf\\usbstor.inf /E /R Everyone\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /R Everyone\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /R Everyone\ncacls %SystemRoot%\\inf\\usbstor.inf /E /D Everyone\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /D Everyone\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D Everyone\n\n\nREM ::USB_REG_PERMISSION_changes\n\n:: If parameter recover then undo all this\nIF [%1]==[enable] GOTO Enable\n:: Create a temporary .REG file - DISABLE USB\n> \"%Temp%.\\u1.ini\" ECHO HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR [0 0 0 0]\nregini \"%Temp%.\\u1.ini\"\nDEL \"%Temp%.\\u1.ini\"\n\n:Exit\n\n:: Leave state \n-----------------------------------------------------------------\n\n\n\n========================================\n\n\n\n\nEnable_usb_storage.bat\n----------------------------------------------\n\n\n@echo off\n\n:: Enable USBstor driver from registry \nreg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR /v Start /t REG_DWORD /d 3 /f\n\n:: Enable USBstor READ / Write mode\nreg add HKLM\\SYSTEM\\CurrentControlSet\\Control\\StorageDevicePolicies /v WriteProtect /t REG_DWORD /d 0 /f\n\n\nREM :: Remove permissions of actual USBSTORAGE Files\n\n\n:: Provide Access for Users from files\ncacls %SystemRoot%\\inf\\usbstor.inf /E /G users:F\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /G users:F\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /G users:F\nrem cacls %SystemRoot%\\inf\\usbstor.inf /E /D users\nrem cacls %SystemRoot%\\inf\\usbstor.PNF /E /D users\n\n:: Provide Access for System\ncacls %SystemRoot%\\inf\\usbstor.inf /E /G system:F\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /G system:F\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /G system:F\nrem cacls %SystemRoot%\\inf\\usbstor.inf /E /D system\nrem cacls %SystemRoot%\\inf\\usbstor.PNF /E /D system\n\n:: Provide Access for ower Users\ncacls %SystemRoot%\\inf\\usbstor.inf /E /G \"Power Users\":F\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /G \"Power Users\":F\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /G \"Power Users\":F\nrem cacls %SystemRoot%\\inf\\usbstor.inf /E /D \"Power Users\"\nrem cacls %SystemRoot%\\inf\\usbstor.PNF /E /D \"Power Users\"\n\n:: Provide Access for Administrators\ncacls %SystemRoot%\\inf\\usbstor.inf /E /G Administrators:F\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /G Administrators:F\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /G Administrators:F\nrem cacls %SystemRoot%\\inf\\usbstor.inf /E /D Administrators\nrem cacls %SystemRoot%\\inf\\usbstor.PNF /E /D Administrators\n\n\n\n:: Provide Access for EveryOne\ncacls %SystemRoot%\\inf\\usbstor.inf /E /G Everyone:F\ncacls %SystemRoot%\\inf\\usbstor.PNF /E /G Everyone:F\ncacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /F Everyone:F\nrem cacls %SystemRoot%\\inf\\usbstor.inf /E /D Everyone\nrem cacls %SystemRoot%\\inf\\usbstor.PNF /E /D Everyone\nrem cacls %SystemRoot%\\system32\\drivers\\USBSTOR.SYS /E /D Everyone\n\n\n\nREM ::USB_REG_PERMISSION_changes\n\n:: If parameter recover then undo all this\nIF [%1]==[enable] GOTO Enable\n:: Create a temporary .REG file - DISABLE USB\n> \"%Temp%.\\u1.ini\" ECHO HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR [1 5 8 11 17]\nregini \"%Temp%.\\u1.ini\"\nDEL \"%Temp%.\\u1.ini\"\n\n:Exit\n\n\n:: Leave state \n" }, { "answer_id": 3369392, "author": "ankit moradiya", "author_id": 406485, "author_profile": "https://Stackoverflow.com/users/406485", "pm_score": 0, "selected": false, "text": "HKEY_LOCAL_MACHINE 4 3" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41630/" ]
365,224
<p>Pour in your posts. I'll start with a couple, let us see how much we can collect.</p> <p>To provide inline event handlers like</p> <pre><code>button.Click += (sender,args) =&gt; { }; </code></pre> <p>To find items in a collection</p> <pre><code> var dogs= animals.Where(animal =&gt; animal.Type == "dog"); </code></pre> <p>For iterating a collection, like</p> <pre><code> animals.ForEach(animal=&gt;Console.WriteLine(animal.Name)); </code></pre> <p>Let them come!!</p>
[ { "answer_id": 365228, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 3, "selected": true, "text": "var dude = mySource.Select(x => new {Name = x.name, Surname = x.surname});\n" }, { "answer_id": 365256, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 0, "selected": false, "text": " static Func<int, int> Foo(int n)\n {\n return a => n += a;\n }\n" }, { "answer_id": 365666, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 2, "selected": false, "text": "Func<int, int> multiply = x => x * 2;\nint y = multiply(4);\n" }, { "answer_id": 366504, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "public Double GetLengthOfElements(string[] wordArr) {\n\n double count = wordArr.Sum(word => word.Length);\n return count;\n}\n" }, { "answer_id": 1021375, "author": "Priyan R", "author_id": 57024, "author_profile": "https://Stackoverflow.com/users/57024", "pm_score": 1, "selected": false, "text": "void Task_Progress(object sender,TaskProgressArgs e)\n{\n BeginInvoke(new MethodInvoker(() => UpdateProgress(e)));\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45956/" ]
365,249
<p>when a System.Web.HttpResponse.End() is called a System.Thread.Abort is being fired, which i'm guessing is (or fires) an exception? I've got some logging and this is being listed in the log file...</p> <p>A first chance </p> <pre><code>exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll 12/14/2008 01:09:31:: Error in Path :/authenticate Raw Url :/authenticate Message :Thread was being aborted. Source :mscorlib Stack Trace : at System.Threading.Thread.AbortInternal() at System.Threading.Thread.Abort(Object stateInfo) at System.Web.HttpResponse.End() at DotNetOpenId.Response.Send() at DotNetOpenId.RelyingParty.AuthenticationRequest.RedirectToProvider() at MyProject.Services.Authentication.OpenIdAuthenticationService.GetOpenIdPersonaDetails(Uri serviceUri) in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\Services\Authentication\OpenIdAuthenticationService.cs:line 108 at MyProject.Mvc.Controllers.AuthenticationController.Authenticate() in C:\Users\Pure Krome\Documents\Visual Studio 2008\Projects\MyProject\Projects\MVC Application\Controllers\AuthenticationController.cs:line 69 TargetSite :Void AbortInternal() A first chance exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL An exception of type 'System.Threading.ThreadAbortException' occurred in Ackbar.Mvc.DLL but was not handled in user code </code></pre> <p>Is this normal behavior and is it possible to gracefully abort instead of (what looks like) a sudden abrupt abort?</p> <h2>Update</h2> <p>So far it the common census that it's <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx" rel="noreferrer">by design</a>. So i'm wondering if it's possible we could take this question and see if we could tweak the code to make it not feel like we're ending the thread <em>prematurely</em> and gracefully exit ... Possible? Code examples?</p>
[ { "answer_id": 365552, "author": "Peter Oehlert", "author_id": 44656, "author_profile": "https://Stackoverflow.com/users/44656", "pm_score": 2, "selected": false, "text": "catch(Exception e) { // log exception and then do not throw again }" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
365,259
<p>I want to search for a line in a file, using regex, inside a Perl script.</p> <p>Assuming it is in a system with grep installed, is it better to:</p> <ul> <li>call the external <code>grep</code> through an <code>open()</code> command</li> <li><code>open()</code> the file directly and use a <code>while</code> loop and an <code>if ($line =~ m/regex/)</code>?</li> </ul>
[ { "answer_id": 365403, "author": "Adrian Pronk", "author_id": 41861, "author_profile": "https://Stackoverflow.com/users/41861", "pm_score": 3, "selected": false, "text": "LANG= LANGUAGE= /bin/grep\n" }, { "answer_id": 365410, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 3, "selected": false, "text": "open my $regex = qr/blah/;\nwhile (<>) {\n if (/$regex/) {\n print;\n exit;\n }\n}\nprint \"Not found\\n\";\n print $_ <> while (my $line = <>) {\n if ($line =~ /$regex/) {\n print $line;\n exit;\n }\n}\n" }, { "answer_id": 366244, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "$line = `grep '$regex' file | head -n 1`;\n" }, { "answer_id": 2562213, "author": "SergioAraujo", "author_id": 2571881, "author_profile": "https://Stackoverflow.com/users/2571881", "pm_score": 2, "selected": false, "text": "sed '/pattern/q' file\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
365,261
<p>For desktop application that is. This is just a general question that maybe only need general answers.</p>
[ { "answer_id": 365613, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 4, "selected": false, "text": "typedef struct Pnmrdr_T *Pnmrdr_T;\n\nstruct Pnmrdr_T *Pnmrdr_new(FILE *);\npixel Pnmrdr_get(Pnmrdr_T);\nvoid Pnmrdr_close(Pnmrdr_T);\nvoid Pnmrdr_free(Pnmrdr_T *rp); // frees memory and sets *rp = NULL\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38515/" ]
365,284
<p>When you rotate an image using canvas, it'll get cut off - how do I avoid this? I already made the canvas element bigger then the image, but it's still cutting off the edges.</p> <p>Example:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script type="text/javascript"&gt; function startup() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'player.gif'; img.onload = function() { ctx.rotate(5 * Math.PI / 180); ctx.drawImage(img, 0, 0, 64, 120); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload='startup();'&gt; &lt;canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 365292, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": true, "text": "ctx.translate(85, 85);\nctx.rotate(5 * Math.PI / 180);\n" }, { "answer_id": 1015486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "ctx.translate(85, 85);\nctx.rotate(5 * Math.PI / 180); // for 5 degrees like the example from Vincent\n ctx.translate(-85, -85);\n" }, { "answer_id": 1025021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "ctx.save();\nctx.translate(85,85);\nctx.rotate(5 * Math.PI / 180);\nctx.fillRect(10,10,10,10);\nctx.restore();\n Square = {\n x:10,\n y:10,\n width:10,\n height:10,\n angle:5\n}\nctx.save();\nctx.translate(Square.x,Square.y);\nctx.rotate(Square.angle * Math.PI / 180);\nctx.fillRect(-Square.width/2,-Square.height/2,Square.width,Square.height);\nctx.restore();\n" }, { "answer_id": 8226296, "author": "luhuiya", "author_id": 932672, "author_profile": "https://Stackoverflow.com/users/932672", "pm_score": 0, "selected": false, "text": "function drawImage(myContext,imgSrc, x, y, size, rotate) {<br/>\n var halfS = size / 2;<br/>\n var imageCursor = new Image();<br/>\n imageCursor.src = imgSrc;<br/>\n myContext.save();<br/>\n var tX = x - halfS;<br/>\n var tY = y - halfS;<br/>\n myContext.translate(tX, tY);<br/>\n myContext.rotate(Math.PI / 180 * rotate);<br/>\n var dX = 0, dY = 0;<br/>\n if (rotate == 0) { dX = 0; dY = 0; }<br/>\n else if (rotate > 0 && rotate < 90) { dX = 0; dY = -(size / (90 / rotate)); }<br/>\n else if (rotate == 90) { dX = 0; dY = -size; }<br/>\n else if (rotate > 90 && rotate < 180) { dX = -(size / (90 / (rotate - 90))); dY = -size; }<br/>\n else if (rotate == 180) { dX = dY = -size; }<br/>\n else if (rotate > 180 && rotate < 270) { dX = -size; dY = -size + (size / (90 / (rotate - 180))); }<br/>\n else if (rotate == 270) { dX = -size; dY = 0; }<br/>\n else if (rotate > 270 && rotate < 360) { dX = -size + (size / (90 / (rotate - 270))); dY = 0; }<br/>\n else if (rotate == 360) { dX = 0; dY = 0; }<br/>\n myContext.drawImage(imageCursor, dX, dY, size, size);<br/>\n myContext.restore();<br/>\n }\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45974/" ]
365,312
<p>I have the following XML document:</p> <pre><code>&lt;projects&gt; &lt;project&gt; &lt;name&gt;Shockwave&lt;/name&gt; &lt;language&gt;Ruby&lt;/language&gt; &lt;owner&gt;Brian May&lt;/owner&gt; &lt;state&gt;New&lt;/state&gt; &lt;startDate&gt;31/10/2008 0:00:00&lt;/startDate&gt; &lt;/project&gt; &lt;project&gt; &lt;name&gt;Other&lt;/name&gt; &lt;language&gt;Erlang&lt;/language&gt; &lt;owner&gt;Takashi Miike&lt;/owner&gt; &lt;state&gt; Canceled &lt;/state&gt; &lt;startDate&gt;07/11/2008 0:00:00&lt;/startDate&gt; &lt;/project&gt; ... </code></pre> <p>And I'd like to get this from the transformation (XSLT) result:</p> <pre><code>Shockwave,Ruby,Brian May,New,31/10/2008 0:00:00 Other,Erlang,Takashi Miike,Cancelled,07/11/2008 0:00:00 </code></pre> <p>Does anyone know the XSLT to achieve this? I'm using .net in case that matters.</p>
[ { "answer_id": 365338, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 7, "selected": true, "text": "<xsl:stylesheet version=\"1.0\"\nxmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n<xsl:output method=\"text\" encoding=\"iso-8859-1\"/>\n\n<xsl:strip-space elements=\"*\" />\n\n<xsl:template match=\"/*/child::*\">\n<xsl:for-each select=\"child::*\">\n<xsl:if test=\"position() != last()\">\"<xsl:value-of select=\"normalize-space(.)\"/>\", </xsl:if>\n<xsl:if test=\"position() = last()\">\"<xsl:value-of select=\"normalize-space(.)\"/>\"<xsl:text>&#xD;</xsl:text>\n</xsl:if>\n</xsl:for-each>\n</xsl:template>\n\n</xsl:stylesheet>\n" }, { "answer_id": 365372, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\" encoding=\"utf-8\" />\n\n <xsl:param name=\"delim\" select=\"','\" />\n <xsl:param name=\"quote\" select=\"'&quot;'\" />\n <xsl:param name=\"break\" select=\"'&#xA;'\" />\n\n <xsl:template match=\"/\">\n <xsl:apply-templates select=\"projects/project\" />\n </xsl:template>\n\n <xsl:template match=\"project\">\n <xsl:apply-templates />\n <xsl:if test=\"following-sibling::*\">\n <xsl:value-of select=\"$break\" />\n </xsl:if>\n </xsl:template>\n\n <xsl:template match=\"*\">\n <!-- remove normalize-space() if you want keep white-space at it is --> \n <xsl:value-of select=\"concat($quote, normalize-space(), $quote)\" />\n <xsl:if test=\"following-sibling::*\">\n <xsl:value-of select=\"$delim\" />\n </xsl:if>\n </xsl:template>\n\n <xsl:template match=\"text()\" />\n</xsl:stylesheet>\n" }, { "answer_id": 9394064, "author": "ioquatix", "author_id": 293815, "author_profile": "https://Stackoverflow.com/users/293815", "pm_score": 4, "selected": false, "text": "xsl:stylesheet <?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:csv=\"csv:csv\">\n <xsl:output method=\"text\" encoding=\"utf-8\"/>\n <xsl:strip-space elements=\"*\"/>\n\n <xsl:variable name=\"delimiter\" select=\"','\"/>\n\n <csv:columns>\n <column>name</column>\n <column>sublease</column>\n <column>addressBookID</column>\n <column>boundAmount</column>\n <column>rentalAmount</column>\n <column>rentalPeriod</column>\n <column>rentalBillingCycle</column>\n <column>tenureIncome</column>\n <column>tenureBalance</column>\n <column>totalIncome</column>\n <column>balance</column>\n <column>available</column>\n </csv:columns>\n\n <xsl:template match=\"/property-manager/properties\">\n <!-- Output the CSV header -->\n <xsl:for-each select=\"document('')/*/csv:columns/*\">\n <xsl:value-of select=\".\"/>\n <xsl:if test=\"position() != last()\">\n <xsl:value-of select=\"$delimiter\"/>\n </xsl:if>\n </xsl:for-each>\n <xsl:text>&#xa;</xsl:text>\n \n <!-- Output rows for each matched property -->\n <xsl:apply-templates select=\"property\"/>\n </xsl:template>\n\n <xsl:template match=\"property\">\n <xsl:variable name=\"property\" select=\".\"/>\n \n <!-- Loop through the columns in order -->\n <xsl:for-each select=\"document('')/*/csv:columns/*\">\n <!-- Extract the column name and value -->\n <xsl:variable name=\"column\" select=\".\"/>\n <xsl:variable name=\"value\" select=\"$property/*[name() = $column]\"/>\n \n <!-- Quote the value if required -->\n <xsl:choose>\n <xsl:when test=\"contains($value, '&quot;')\">\n <xsl:variable name=\"x\" select=\"replace($value, '&quot;', '&quot;&quot;')\"/>\n <xsl:value-of select=\"concat('&quot;', $x, '&quot;')\"/>\n </xsl:when>\n <xsl:when test=\"contains($value, $delimiter)\">\n <xsl:value-of select=\"concat('&quot;', $value, '&quot;')\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$value\"/>\n </xsl:otherwise>\n </xsl:choose>\n \n <!-- Add the delimiter unless we are the last expression -->\n <xsl:if test=\"position() != last()\">\n <xsl:value-of select=\"$delimiter\"/>\n </xsl:if>\n </xsl:for-each>\n \n <!-- Add a newline at the end of the record -->\n <xsl:text>&#xa;</xsl:text>\n </xsl:template>\n\n</xsl:stylesheet>\n" }, { "answer_id": 61820507, "author": "jmiserez", "author_id": 202504, "author_profile": "https://Stackoverflow.com/users/202504", "pm_score": 3, "selected": false, "text": "CsvEscape , \" EscapeQuotes CsvEscape EscapeQuotes xsltproc xmltocsv.xslt file.xml > file.csv <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\" encoding=\"UTF-8\"/>\n\n <xsl:template name=\"EscapeQuotes\">\n <xsl:param name=\"value\"/>\n <xsl:choose>\n <xsl:when test=\"contains($value,'&quot;')\">\n <xsl:value-of select=\"substring-before($value,'&quot;')\"/>\n <xsl:text>&quot;&quot;</xsl:text>\n <xsl:call-template name=\"EscapeQuotes\">\n <xsl:with-param name=\"value\" select=\"substring-after($value,'&quot;')\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$value\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n\n <xsl:template name=\"CsvEscape\">\n <xsl:param name=\"value\"/>\n <xsl:choose>\n <xsl:when test=\"contains($value,',')\">\n <xsl:text>&quot;</xsl:text>\n <xsl:call-template name=\"EscapeQuotes\">\n <xsl:with-param name=\"value\" select=\"$value\"/>\n </xsl:call-template>\n <xsl:text>&quot;</xsl:text>\n </xsl:when>\n <xsl:when test=\"contains($value,'&#xA;')\">\n <xsl:text>&quot;</xsl:text>\n <xsl:call-template name=\"EscapeQuotes\">\n <xsl:with-param name=\"value\" select=\"$value\"/>\n </xsl:call-template>\n <xsl:text>&quot;</xsl:text>\n </xsl:when>\n <xsl:when test=\"contains($value,'&quot;')\">\n <xsl:text>&quot;</xsl:text>\n <xsl:call-template name=\"EscapeQuotes\">\n <xsl:with-param name=\"value\" select=\"$value\"/>\n </xsl:call-template>\n <xsl:text>&quot;</xsl:text>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$value\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <xsl:template match=\"/\">\n <xsl:text>project,name,language,owner,state,startDate</xsl:text>\n <xsl:text>&#xA;</xsl:text>\n <xsl:for-each select=\"projects/project\">\n <xsl:call-template name=\"CsvEscape\"><xsl:with-param name=\"value\" select=\"normalize-space(name)\"/></xsl:call-template>\n <xsl:text>,</xsl:text>\n <xsl:call-template name=\"CsvEscape\"><xsl:with-param name=\"value\" select=\"normalize-space(language)\"/></xsl:call-template>\n <xsl:text>,</xsl:text>\n <xsl:call-template name=\"CsvEscape\"><xsl:with-param name=\"value\" select=\"normalize-space(owner)\"/></xsl:call-template>\n <xsl:text>,</xsl:text>\n <xsl:call-template name=\"CsvEscape\"><xsl:with-param name=\"value\" select=\"normalize-space(state)\"/></xsl:call-template>\n <xsl:text>,</xsl:text>\n <xsl:call-template name=\"CsvEscape\"><xsl:with-param name=\"value\" select=\"normalize-space(startDate)\"/></xsl:call-template>\n <xsl:text>&#xA;</xsl:text>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ]
365,339
<p>We currently send an email notification in plain text or html format. Our environment is C#/.NET/SQL Server.</p> <p>I'd like to know if anyone recommends a particular solution. I see two ways of doing this:</p> <ul> <li>dynamically convert current email to pdf using a third party library and sending the pdf as an attachment</li> </ul> <p>or </p> <ul> <li>use SSRS to allow users to export pdf report (could eventually have SSRS push reports)</li> </ul> <p>I'm open to third party libraries (especially if they are open source and free). It seems that SSRS is the simplest and easiest way to go. Anyone have any tips?</p>
[ { "answer_id": 365398, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 3, "selected": true, "text": "class Program\n{\n static void Main(string[] args)\n {\n string html = \n@\"<html>\n<head>\n <meta http-equiv=\"\"Content-Type\"\" content=\"\"text/html; charset=utf-8\"\" />\n</head>\n<body>\n <p style=\"\"color: red;\"\">Hello World</p>\n</body>\n</html>\";\n\n Document document = new Document(PageSize.A4);\n using (Stream output = new FileStream(\"out.pdf\", FileMode.Create, FileAccess.Write, FileShare.None))\n using (StringReader htmlReader = new StringReader(html))\n using (XmlTextReader reader = new XmlTextReader(htmlReader))\n {\n PdfWriter.GetInstance(document, output);\n HtmlParser.Parse(document, reader);\n }\n\n }\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36902/" ]
365,352
<p>It is not uncommon for me (or likely anyone else) to have a list of objects I need to iterate through and then interact with a list of properties. I use a nested loop, like this:</p> <pre><code>IList&lt;T&gt; listOfObjects; IList&lt;TProperty&gt; listOfProperties; foreach (T dataObject in listOfObjects) { foreach (TProperty property in listOfProperties) { //do something clever and extremely useful here } } </code></pre> <p>Is this the time and performance tested pattern for this problem? Or is there something more performant, more elegant, or just plain fun (while still being readable and maintainable of course)?</p> <p>The code above doesn't make me smile. Can someone please help bring some joy to my loop?</p> <p>Thank you!</p> <p>Update: I use the term "nerd" in a most positive sense. As part of the wikipedia definition puts it "that refers to a person who passionately pursues intellectual activities". By "code nerd" I mean someone who is concerned about continually improving oneself as a programmer, finding new, novel, and elegant ways of coding that are fast, maintainable, and beautiful! They rejoice to move out of VB6 and want smart people to critique their code and help them smartify themselves. (Note: they also like to make new words that end in -ify).</p> <p>Final note:</p> <p>Thank you to Dave R, Earwicker, and TheSoftwareJedi for sending me down the Linq path. It is just the sort of happy code I was looking for!</p>
[ { "answer_id": 365360, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 0, "selected": false, "text": "foreach (T dataObject in listOfObjects)\n{ \n foreach (TProperty property in listOfProperties) \n {\n if (property.something == \"blah\") \n { // OK, we found the piece we're interested in...\n\n // do something clever...\n\n }\n }\n}\n" }, { "answer_id": 365437, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 3, "selected": false, "text": "foreach (var pair in from obj in listOfObjects\n from prop in listOfProperties \n select new {obj, prop})\n{\n Console.WriteLine(pair.obj + \", \" + pair.prop);\n}\n" }, { "answer_id": 365443, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 4, "selected": true, "text": " var list1 = Enumerable.Range(1, 100);\n var list2 = Enumerable.Range(1, 100);\n\n foreach (var item in from a in list1\n from b in list2\n where a % b == 0\n select new { a, b })\n {\n Console.WriteLine(item);\n };\n" }, { "answer_id": 369108, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "Action<T, TProp> somethingClever = //your clever method\n\nlistOfObjects\n .SelectMany(\n o => listOfProperties,\n (o, p) => new {o, p})\n .ToList()\n .ForEach(x => somethingClever(x.o, x.p));\n" }, { "answer_id": 369146, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 2, "selected": false, "text": "foreach(dataObject in listOfObjects)\n DoSomethingCleverWithProperties(dataObject, listOfProperties);\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/620435/" ]
365,353
<ol> <li>In WordPress, how do I hide a Page?</li> <li>How do I then reimplement it as a DIV, let's say, on another Page?</li> </ol> <p><strong>Context</strong></p> <p>I'm trying to get some year-end tax write-offs here for my freelance business, and so I'm donating WordPress sites to churches. Now, unfortunately I'm finding that several pastors don't understand computers that well, and even though WordPress is fairly easy to tech guys like you and me, they get a bit confused. Therefore, I commented out Posts, Comments, Plugins, Widgets, Users, Design, and left nothing but Pages (New, Edit, Delete) and Media Gallery. I then took a theme that showed the Pages as tabs at the top like a normal website.</p> <p>My hope is to call a particular page like Sidebar1 as its title. However, instead of this being displayed as a tab, it will be hidden. Then, it will be reimplemented as a DIV inside the page titled Home. If the pastor accidentally deletes Sidebar1, all he has to do is recreate it again and poof it reappears.</p> <p>This doesn't deal with the Wordpress website, but the Wordpress installation.</p> <p>I've changed the admin -- I just need to change the front-end.</p> <p>I could figure this out on my own, but in the interest of time I wondered if someone had already done this?</p> <p>Your help could help me get this done just in time for Christmas for some area churches here. Thank you.</p>
[ { "answer_id": 366756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "wp_list_pages('sort_column=menu_order&exclude=3&title_li=');\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,370
<p>I am currently using TcpListener to address incoming connections, each of which are given a thread for handling the communication and then shutdown that single connection. Code looks as follows:</p> <pre><code>TcpListener listener = new TcpListener(IPAddress.Any, Port); System.Console.WriteLine("Server Initialized, listening for incoming connections"); listener.Start(); while (listen) { // Step 0: Client connection TcpClient client = listener.AcceptTcpClient(); Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection)); clientThread.Start(client.GetStream()); client.Close(); } </code></pre> <p>The <code>listen</code> variable is a boolean that is a field on the class. Now, when the program shuts down I want it to stop listening for clients. Setting listen to <code>false</code> will prevent it from taking on more connections, but since <code>AcceptTcpClient</code> is a blocking call, it will at minimum take the next client and THEN exit. Is there any way to force it to simply break out and stop, right then and there? What effect does calling listener.Stop() have while the other blocking call is running?</p>
[ { "answer_id": 365533, "author": "Peter Oehlert", "author_id": 44656, "author_profile": "https://Stackoverflow.com/users/44656", "pm_score": 7, "selected": true, "text": "TcpListener Abort() ThreadAbortException listener.Pending() Thread.Sleep() AcceptTcpClient() while (listen) {\n // Step 0: Client connection\n if (!listener.Pending()) {\n Thread.Sleep(500); // choose a number (in milliseconds) that makes sense\n continue; // skip to next iteration of loop\n }\n TcpClient client = listener.AcceptTcpClient();\n Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));\n clientThread.Start(client.GetStream());\n client.Close();\n}\n BeginAcceptTcpClient() IAsyncResult TcpClient ThreadPool.QueueUserWorkerItem TcpClient ThreadPool BeginAcceptTcpClient() EndAcceptTcpClient() TcpClient TcpClient using(){} TcpClient.Dispose() TcpClient.Close() finally try {} finally {}" }, { "answer_id": 365664, "author": "Dzmitry Huba", "author_id": 45943, "author_profile": "https://Stackoverflow.com/users/45943", "pm_score": 2, "selected": false, "text": " clientThread.Start(client.GetStream());\n client.Close();\n" }, { "answer_id": 986359, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": " while (listen) \n {\n // Step 0: Client connection \n if (!listener.Pending()) \n {\n Thread.Sleep(500); // choose a number (in milliseconds) that makes sense\n continue; // skip to next iteration of loop\n }\n else // Enter here only if have pending clients\n {\n TcpClient client = listener.AcceptTcpClient();\n Thread clientThread = new Thread(new ParameterizedThreadStart(HandleConnection));\n clientThread.Start(client.GetStream());\n client.Close();\n }\n }\n" }, { "answer_id": 1632722, "author": "zproxy", "author_id": 94411, "author_profile": "https://Stackoverflow.com/users/94411", "pm_score": 6, "selected": false, "text": "listener.Server.Close() A blocking operation was interrupted by a call to WSACancelBlockingCall\n" }, { "answer_id": 17817176, "author": "Andriy Vandych", "author_id": 2548170, "author_profile": "https://Stackoverflow.com/users/2548170", "pm_score": 2, "selected": false, "text": "TcpListener.Pending()" }, { "answer_id": 52879008, "author": "Peter Suwara", "author_id": 7270813, "author_profile": "https://Stackoverflow.com/users/7270813", "pm_score": 0, "selected": false, "text": " ServerSocket = new TcpListener(endpoint);\n try\n {\n ServerSocket.Start();\n ServerSocket.BeginAcceptTcpClient(OnClientConnect, null);\n ServerStarted = true;\n\n Console.WriteLine(\"Server has successfully started.\");\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Server was unable to start : {ex.Message}\");\n return false;\n }\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9479/" ]
365,371
<p>I can't figure out how to achieve the following layout with CSS (probably because I don't actually know CSS).</p> <p>I have a bunch of divs like this:</p> <pre><code>&lt;div class="right"&gt; &lt;p&gt;1&lt;/p&gt; &lt;/div&gt; &lt;div class="left"&gt; &lt;p&gt;2&lt;/p&gt; &lt;/div&gt; &lt;div class="left"&gt; &lt;p&gt;3&lt;/p&gt; &lt;/div&gt; &lt;div class="left"&gt; &lt;p&gt;4&lt;/p&gt; &lt;/div&gt; &lt;div class="right"&gt; &lt;p&gt;5&lt;/p&gt; &lt;/div&gt; &lt;div class="right"&gt; &lt;p&gt;6&lt;/p&gt; &lt;/div&gt; </code></pre> <p>(not the real contents)</p> <p>Now I want the layout to look like two equal columns of divs, with the "right" ones on the right, and the "left" ones on the left, thus:</p> <pre><code>2 1 3 5 4 6 </code></pre> <p>[<strong>Edit: In a previous version of this question I had textareas inside the divs, and the divs all had different names like "one" and "xyz".</strong>] I tried something like</p> <pre><code>div.right { width:50%; float:right; clear:right; } div.left { width:50%; float:left; clear:left;} </code></pre> <p>but it doesn't quite work: It produces something like:</p> <pre><code>2 1 3 4 5 6 </code></pre> <p>(without the "clear"s, it blithely produces </p> <pre><code>2 1 3 4 6 5 </code></pre> <p>which is not what is wanted).</p> <p>It is apparent that it can be made to work if the divs are ordered differently, but I'd like not to do that (because these divs are generated dynamically if the browser has Javascript, and I don't want to change the actual order that is displayed in the absence of Javascript, for semantic reasons). Is it still possible to achieve the layout I want?</p> <p>[For what it's worth, I'm willing to have it not work on IE or older versions of other browsers, so if there is a solution that works only on standards-compliant browsers, that's okay :-)]</p>
[ { "answer_id": 365407, "author": "dave mankoff", "author_id": 10093, "author_profile": "https://Stackoverflow.com/users/10093", "pm_score": 2, "selected": false, "text": "div {\n width: 198px;\n border: 1px solid black;\n}\ndiv.onediv, div.tendiv, div.xyzdiv { float: right; }\ndiv.twodiv, div.abcdiv, div.pqrdiv { float: left; } <div style=\"width: 400px;\">\n <div class=\"onediv\"><p>One name</p> <textarea id=\"one\"></textarea></div>\n <div class=\"twodiv\"><p>Two name</p> <textarea id=\"two\"></textarea></div>\n <div class=\"tendiv\"><p>Ten name</p> <textarea id=\"ten\"></textarea></div>\n <div class=\"abcdiv\"><p>Abc name</p> <textarea id=\"abc\"></textarea></div>\n <div class=\"xyzdiv\"><p>Xyz name</p> <textarea id=\"xyz\"></textarea></div>\n <div class=\"pqrdiv\"><p>Pqr name</p> <textarea id=\"pqr\"></textarea></div>\n</div> div div {\n width: 198px;\n border: 1px solid black;\n}\ndiv.col1 { float: right; }\ndiv.col2 { float: left; } <div style=\"width: 400px;\">\n <div class=\"col1\"><p>One name</p> <textarea id=\"one\"></textarea></div>\n <div class=\"col2\"><p>Two name</p> <textarea id=\"two\"></textarea></div>\n <div class=\"col1\"><p>Ten name</p> <textarea id=\"ten\"></textarea></div>\n <div class=\"col2\"><p>Abc name</p> <textarea id=\"abc\"></textarea></div>\n <div class=\"col1\"><p>Xyz name</p> <textarea id=\"xyz\"></textarea></div>\n <div class=\"col2\"><p>Pqr name</p> <textarea id=\"pqr\"></textarea></div>\n</div>" }, { "answer_id": 365465, "author": "LeJeune", "author_id": 37955, "author_profile": "https://Stackoverflow.com/users/37955", "pm_score": 1, "selected": false, "text": "<table>\n <tr>\n <td>\n <p>One name</p> <textarea id=\"one\"></textarea>\n </td>\n <td>\n <p>XYZ name</p> <textarea id=\"xyz\"></textarea>\n </td>\n </tr>\n ....\n </table>\n" }, { "answer_id": 369644, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 1, "selected": false, "text": "<div> $(\"div:eq(3)\").remove().insertAfter(\"div:eq(4)\");\n" }, { "answer_id": 369976, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 2, "selected": false, "text": ".left { width: 51%; float: left; }\n.right { width: 49%; }\n <style>\n div div { text-align: center; padding: 20px 0; overflow: hidden; }\n .left { width: 251px; float: left; background: red; }\n .right { width: 249px; background: green; }\n</style>\n<div style=\"width: 500px;\" >\n <div class=\"left\"> <p>1</p> </div>\n <div class=\"right\"> <p>2</p> </div>\n <div class=\"left\"> <p>3</p> </div>\n <div class=\"left\"> <p>4</p> </div>\n <div class=\"right\"> <p>5</p> </div>\n <div class=\"right\"> <p>6</p> </div>\n</div>\n" }, { "answer_id": 376358, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<style>\n #container { width: 500px; border: 1px grey solid; overflow: hidden; }\n #container .rightSide { width: 250px; float: right; }\n #container .left { width: 250px; background: red; padding: 20px 0; overflow: hidden; text-align: center; }\n #container .right { width: 250px; background: green; padding: 20px 0; overflow: hidden; text-align: center; }\n</style>\n<script type=\"text/javascript\">\n$(document).ready(function() {\n $('#container').prepend('<div class=\"rightSide\"></div>');\n $('#container div.right').each(function() {\n var $rightContent = $(this).remove().html();\n $('.rightSide').append('<div class=\"right\">' + $rightContent + '</div>');\n });\n});\n</script>\n<div id=\"container\" >\n <div class=\"right\"> <p>1</p> </div>\n <div class=\"left\"> <p>2</p> </div>\n <div class=\"left\"> <p>3</p> </div>\n <div class=\"left\"> <p>4</p> </div>\n <div class=\"right\"> <p>5</p> </div>\n <div class=\"right\"> <p>6</p> </div>\n</div>\n" }, { "answer_id": 977358, "author": "ilya n.", "author_id": 115200, "author_profile": "https://Stackoverflow.com/users/115200", "pm_score": 2, "selected": false, "text": ".left-column .right, .right-column .left {\n display: none;\n}\n .right {\n position: flow(side); \n}\n .container {\n position: relative;\n}\n\n.left, .right {\n position: absolute;\n top : 0;\n width: 50%;\n} \n\n.left {\n left: 0;\n}\n\n.right {\n left: 50%;\n}\n\n.left ~ .left, .right ~ .right {\n top : 100px;\n}\n\n.left ~ .left ~ .left, .right ~ .right ~ .right {\n top : 200px;\n}\n\n.left ~ .left ~ .left ~ .left, .right ~ .right ~ .right ~ .right {\n top : 300px;\n}\n\n... /* you need to include as many rules as the maximum possible height */\n" }, { "answer_id": 977398, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 0, "selected": false, "text": "<html>\n <head>\n <link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"css/reset.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"css/text.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"css/960.css\" />\n </head>\n <body>\n <div class=\"container_16\">\n <div class=\"grid_1 alpha\" style=\"text-align:center;\">\n 2\n </div>\n <div class=\"grid_1 omega\" style=\"text-align:center;\">\n 1\n </div>\n <div class=\"clear\"></div>\n <div class=\"grid_1 alpha\" style=\"text-align:center;\">\n 4\n </div>\n <div class=\"grid_1 omega\" style=\"text-align:center;\">\n 3\n </div>\n <div class=\"clear\"></div>\n <div class=\"grid_1 alpha\" style=\"text-align:center;\">\n 5\n </div>\n <div class=\"grid_1 omega\" style=\"text-align:center;\">\n 4\n </div>\n </div>\n</body>\n</html>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4958/" ]
365,376
<p>I use a basic Post to send data to a Django server.</p> <p>The data consists of a base64 encoded 640*380 PNG image dynamically created by the flex component.</p> <pre><code>&lt;mx:HTTPService id="formSend" showBusyCursor="true" useProxy="false" url="http://127.0.0.1/form/" method="POST" result="formSentConfirmation(event)" fault="formSendingFailed(event)"/&gt; private function sendForm(url:String, message:String, meteo:Number):void { formSend.url = url; var params:Object = { message: message, image_data: getEncodedImage() }; snapButton.label = "sending ..."; formSend.send(params); } </code></pre> <p>On the server side i can see that the data is in the request.POST not in request.FILES. That means the image is not send as a File with multiencode HTTP.</p> <ol> <li><p>Will i get into trouble on a real server ? since the limit is 200k for urlencoded POST var.</p></li> <li><p>How to make HTTPservice send the data as a file?</p></li> <li><p>Any other solutions?</p></li> </ol> <p>Thanks</p>
[ { "answer_id": 1471859, "author": "franckyfranck", "author_id": 177787, "author_profile": "https://Stackoverflow.com/users/177787", "pm_score": 2, "selected": false, "text": "var urlLoader:URLLoader = new URLLoader();\n urlLoader.dataFormat = URLLoaderDataFormat.BINARY;\n urlLoader.data = _img.data;\n urlLoader.addEventListener(Event.COMPLETE,LoadedComplete);\n\n var request:URLRequest = new URLRequest(\"www.url.com?toto=toto\");\n request.method = URLRequestMethod.POST\n request.contentType = \"multipart/form-data\";\n request.data = _img.data;\n request.requestHeaders = new Array(new URLRequestHeader(\"toto\", \"toto\"));\n\n urlLoader.load(request);\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32032/" ]
365,380
<p>I was wondering if InnoDB would be the best way to format the table? The table contains one field, primary key, and the table will get 816k rows a day (est.). This will get very large very quick! I'm working on a file storage way (would this be faster)? The table is going to store ID numbers of Twitter Ids that have already been processed?</p> <p>Also, any estimated memory usage on a <code>SELECT min('id')</code> statement? Any other ideas are greatly appreciated!</p>
[ { "answer_id": 365405, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SELECT min('id')" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45530/" ]
365,382
<p>How do you rotate an image with the canvas html5 element from the bottom center angle?</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script type="text/javascript"&gt; function startup() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = 'player.gif'; img.onload = function() { ctx.translate(185, 185); ctx.rotate(90 * Math.PI / 180); ctx.drawImage(img, 0, 0, 64, 120); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload='startup();'&gt; &lt;canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Unfortunately this seems to rotate it from the top left angle of the image. Any idea?</p> <p>Edit: in the end the object (space ship) has to rotate like a clock pointer, as if it is turning right/left.</p>
[ { "answer_id": 365418, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 6, "selected": true, "text": "ctx.translate(32, 120);\n ctx.rotate(90 * Math.PI/180);\n ctx.drawImage(img, -32, -120, 64, 120);\n" }, { "answer_id": 366362, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<html>\n <head>\n <title>test</title>\n <script type=\"text/javascript\">\n canvasW = canvasH = 800;\n imgW = imgH = 128;\n function startup() {\n var canvas = document.getElementById('canvas');\n var ctx = canvas.getContext('2d');\n // Just to see what I do...\n ctx.strokeRect(0, 0, canvasW, canvasH);\n var img = new Image();\n img.src = 'player.png';\n img.onload = function() {\n // Just for reference\n ctx.drawImage(img, 0, 0, 128, 128);\n ctx.drawImage(img, canvasW/2 - imgW/2, canvasH/2 - imgH/2, 128, 128);\n mark(ctx, \"red\");\n // Keep current context (transformations)\n ctx.save();\n // Put bottom center at origin\n ctx.translate(imgW/2, imgH);\n // Rotate\n // Beware the next translations/positions are done along the rotated axis\n ctx.rotate(45 * Math.PI / 180);\n // Mark new origin\n mark(ctx, \"red\");\n // Restore position\n ctx.translate(-imgW/2, -imgH);\n ctx.drawImage(img, 0, 0, imgW, imgH);\n mark(ctx, \"green\");\n // Draw it an wanted position\n ctx.drawImage(img, canvasW/2, canvasH/3, imgW, imgH);\n // Move elsewhere:\n ctx.translate(canvasW/2, canvasH/2);\n ctx.drawImage(img, 0, 0, imgW, imgH);\n mark(ctx, \"blue\");\n ctx.restore();\n }\n }\n function mark(ctx, color) {\n ctx.save();\n//~ ctx.fillStyle = color;\n//~ ctx.fillRect(-2, -2, 4, 4);\n ctx.strokeStyle = color;\n ctx.strokeRect(0, 0, imgW, imgH);\n ctx.restore();\n }\n </script>\n </head>\n <body onload='startup();'>\n <canvas id=\"canvas\" style=\"position: absolute; left: 300px; top: 300px;\" width=\"800\" height=\"800\"></canvas>\n </body>\n</html>\n" }, { "answer_id": 422552, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<html>\n <head>\n <title>Canvas Pinball flippers by stirfry</title>\n <script type=\"application/x-javascript\">\n /*THIS SCRIPT ADAPTED BY STIRFRY. SOURCE TEETHGRINDER no warranty or liability implied or otherwise. use at your own risk. No credit required. Enjoy.stirfry.thank(you)*/\n var img = new Image();\n //img.src = \"flipper.gif\";//right\n img.src=\"http://i39.tinypic.com/k1vq0x.gif\"\n var img2 = new Image();\n //img2.src = \"flipper2.gif\";//left\n img2.src =\"http://i42.tinypic.com/14c8wht.gif\"\n var gAngle = 0;\n gAngle = 60;\n stop = false;\n inertia = .8;\n vel = 10;\n k = 0.1;\n\n function drawagain(){\n gAngle = 60;\n stop = false;\n inertia = .8;\n vel = 10;\n k = 0.1;\n draw()\n }\n\n function draw(){\n var ctx = document.getElementById('canvas').getContext('2d');\n ctx.save();\n\n vel = ( vel * inertia ) + ( -gAngle * k );\n\n gAngle += vel;\n\n ctx.fillStyle = 'rgb(255,255,255)';\n ctx.fillRect (0, 0, 600, 600);\n\n ctx.translate(380, 480); //location of the system\n ctx.rotate( gAngle * Math.PI / 180 );//rotate first then draw the flipper\n ctx.drawImage(img, -105, -16); \nctx.restore();\nctx.save();\n ctx.translate(120, 480); //location of the system\n ctx.rotate( -1*gAngle * Math.PI / 180 );//rotate first then draw the flipper\n ctx.drawImage(img2, -18, -16); \n\nctx.restore();\n\n if( !stop )\n setTimeout(draw, 30);\n }\n\n </script>\n <style type=\"text/css\">\n body { margin: 20px; font-family: arial,verdana,helvetica; background: #fff;}\n h1 { font-size: 140%; font-weight:normal; color: #036; border-bottom: 1px solid #ccc; }\n canvas { border: 2px solid #000; float: left; margin-right: 20px; margin-bottom: 20px; }\n pre { float:left; display:block; background: rgb(238,238,238); border: 1px dashed #666; padding: 15px 20px; margin: 0 0 10px 0; }\n .gameLayer {position: absolute; top: 0px; left: 0px;}\n #scoreLayer {font-family: arial; color: #FF0000; left: 10px; font-size: 70%; }\n #windowcontainer {position:relative; height:300px;}\n </style>\n </head>\n\n <body onload=\"draw()\">\n <div id=\"windowcontainer\">\n <canvas id=\"canvas\" width=\"500\" height=\"500\"></canvas>\n <INPUT VALUE=\"flip\" TYPE=BUTTON onClick=\"drawagain();\"><br/>\n </div>\n\n </body>\n</html>\n" }, { "answer_id": 15819128, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "ctx.save(); \nctx.translate(x,y);\nctx.rotate(degree*Math.PI/180);\nctx.translate(-x,-y); \nctx.fillText(text,x,y); \nctx.stroke(); \nctx.restore();\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45974/" ]
365,391
<p>I'm trying to use an excel VB macro to download excel files from a membership password-protected site. I am using the "InternetExplorer" object to open a browser window, log-in and browse to the correct page, then scanning for the links I want in the page. Using the Workbooks.Open(URLstring) doesn't work because Excel isn't logged. Instead of the actual file, it opens the html page asking for the log-in.</p> <p>My preference would be to use the VB macro to automate the right-click "save target as" event in internet explorer on the correct link, but I don't know exactly how to do this.</p>
[ { "answer_id": 365644, "author": "Tmdean", "author_id": 45084, "author_profile": "https://Stackoverflow.com/users/45084", "pm_score": 1, "selected": false, "text": "Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n...\nSub YourMacro()\n ... Navigate IE to the correct document, and get it to pop \n up the \"Save As\" dialog ...\n\n Set sh = CreateObject(\"WScript.Shell\")\n sh.AppActivate \"File Download\"\n sh.SendKeys \"S\"\n Sleep 100\n sh.SendKeys \"C:\\Path\\filename.ext{ENTER}\"\nEnd Sub\n" }, { "answer_id": 369210, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 0, "selected": false, "text": "Sub HTTPDownloadFile(ByVal URL As String, ByVal LocalFileName As String)\n Dim http As Object ' Inet\n Dim Contents() As Byte\n\n Set http = New Inet\n Set http = CreateObject(\"InetCtls.Inet\")\n With http\n .protocol = icHTTP\n .URL = URL\n Contents() = .OpenURL(.URL, icByteArray)\n End With\n Set http = Nothing\n\n Open LocalFileName For Binary Access Write As #1\n Put #1, , Contents()\n Close #1\nEnd Sub\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,395
<p>just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns).</p> <p>Thanks in advance</p>
[ { "answer_id": 365399, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 5, "selected": true, "text": "a[1:-1, 1:-1]\n" }, { "answer_id": 365983, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "a[[slice(1, -1) for _ in a.shape]]\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44354/" ]
365,424
<p>I've written an Apache module in C. Under certain conditions, I can get it to segfault, but I have no idea as to why. At this point, it could be my code, it could be the way I'm compiling the program, or it could be a bug in the OS library (the segfault happens during a call to dlopen()).</p> <p>I've tried running through GDB and Valgrind with no success. GDB gives me a backtrace into the dlopen() system call that appears meaningless. In Valgrind, the bug actually seems to disappear or at least become non-reproducible. On the other hand, I'm a total novice when it comes to these tools.</p> <p>I'm a little new to production quality C programming (I started on C many years ago, but have never worked professionally with it.) What is the best way for me to go about learning the ropes of debugging programs? What other tools should I be investigating? In summary, how do you figure out how to tackle new bug challenges?</p> <p>EDIT: Just to clarify, I want to thank Sydius's and dmckee's input. I had taken a look at Apache's guide and am fairly familiar with dlopen (and dlsym and dlclose). My module works for the most part (it's at about 3k lines of code and, as long as I don't activate this one section, things seem to work just fine.)</p> <p>I guess this is where my original question comes from - I don't know what to do next. I know I haven't used GDB and Valgrind to their full potential. I know that I may not be compiling with the exact right flags. But I'm having trouble figuring out more. I can find beginner's guides that tell me what I already know, and man pages that tell me more than I need to know but with no guidance.</p>
[ { "answer_id": 365539, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "dlopen() Apache" }, { "answer_id": 365599, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 3, "selected": false, "text": "-g -O0 gcc -g -O -O" }, { "answer_id": 365616, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 1, "selected": false, "text": "valgrind --trace-children=yes ....\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10093/" ]
365,427
<p>I have problems with Boost.Spirit parsing a string. </p> <p>The string looks like </p> <pre><code>name1 has this and that.\n name 2 has this and that.\n na me has this and that.\n </code></pre> <p>and I have to extract the names. The text "has this and that" is always the same but the name can consist of spaces therefore I can't use graph_p. </p> <p>1) How do I parse such a string?</p> <p>Since the string has several lines of that format I have to store the names in a vector. </p> <p>I used something like </p> <pre><code>std::string name; rule&lt;&gt; r = *graph_p[append(name)]; </code></pre> <p>for saving one name but </p> <p>2) what's the best way to save several names in a vector?</p> <p>Thanks in advance</p> <p>Konrad</p>
[ { "answer_id": 365742, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 0, "selected": false, "text": "string s = \"na me has this and that.\\n\";\nmyVector . push_back( s.substr( 0, s.find( \"has this and that\" ) ) );\n" }, { "answer_id": 365845, "author": "hvintus", "author_id": 46037, "author_profile": "https://Stackoverflow.com/users/46037", "pm_score": 2, "selected": false, "text": "vector<string> names;\nstring name;\nparse(str,\n *( \n (*(anychar_p - \"has this and that.\")) [assign_a(name)]\n >> \"has this and that.\\n\") [push_back_a(names, name)]\n ))\n" }, { "answer_id": 4471713, "author": "hkaiser", "author_id": 269943, "author_profile": "https://Stackoverflow.com/users/269943", "pm_score": 2, "selected": false, "text": "#include <boost/spirit/include/qi.hpp>\n\nnamespace qi = boost::spirit::qi;\n\nstd::vector<std::string> names;\nstd::string input = \"name1 has this and that.\\n\"\n \"name 2 has this and that.\\n\"\n \"na me has this and that.\\n\";\nbool result = qi::parse(\n input.begin(), input.end(),\n *(*(qi::char_ - \" has this and that.\\n\") >> \" has this and that.\\n\"),\n names\n);\n result true names" }, { "answer_id": 5163029, "author": "Danilo", "author_id": 640479, "author_profile": "https://Stackoverflow.com/users/640479", "pm_score": 0, "selected": false, "text": "qi::lit(\"has this and that\")\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,453
<p>Greetings!</p> <p>I'd like to investigate Django but I'm running Windows XP. I've installed XMPP and I currently have Python 2.6 installed (is it true that 2.5 is the only version that will work with XMPP?). What else do I need to get up and running? Any tips, recommended IDEs, etc? </p>
[ { "answer_id": 365464, "author": "Sam", "author_id": 428, "author_profile": "https://Stackoverflow.com/users/428", "pm_score": 2, "selected": false, "text": "@echo off\npython manage.py runserver\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
365,458
<p>Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects <code>std::vector::reserve</code> to throw <code>std::bad_alloc</code>. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) and behavior (expecting the exception to be thrown).</p> <p>Here's a minimal example that reproduces it:</p> <pre><code>#include &lt;vector&gt; int main() { size_t uint_max = static_cast&lt;size_t&gt;(-1); std::vector&lt;char&gt; v; v.reserve(uint_max); } </code></pre> <p>Running valgrind, I get this output:</p> <pre><code>Warning: silly arg (-1) to __builtin_new() new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry. at 0x40192BC: VALGRIND_PRINTF_BACKTRACE (valgrind.h:319) by 0x401C823: operator new(unsigned) (vg_replace_malloc.c:164) by 0x80487BF: std::vector&lt;char, std::allocator&lt;char&gt; &gt;::reserve(unsigned) new_allocator.h:92) by 0x804874D: main (vg.cxx:6) </code></pre> <p>I'd like to modify my unit test to simply skip the offending code when it's being run from within valgrind. Is this possible?</p>
[ { "answer_id": 365624, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 1, "selected": false, "text": "MYAPP_UNIT_TESTS_DISABLED=\"NEW_MINUS_ONE,FLY_TO_MOON,DEREF_NULL\" valgrind myapp\n bool unit_test_enabled(const char *testname);\n" }, { "answer_id": 365796, "author": "Hasturkun", "author_id": 20270, "author_profile": "https://Stackoverflow.com/users/20270", "pm_score": 6, "selected": true, "text": "RUNNING_ON_VALGRIND" }, { "answer_id": 62364698, "author": "vinc17", "author_id": 3782797, "author_profile": "https://Stackoverflow.com/users/3782797", "pm_score": 3, "selected": false, "text": "valgrind.h LD_PRELOAD LD_PRELOAD \"/valgrind/\" \"/vgpreload\" int tests_run_within_valgrind (void)\n{\n char *p = getenv (\"LD_PRELOAD\");\n if (p == NULL)\n return 0;\n return (strstr (p, \"/valgrind/\") != NULL ||\n strstr (p, \"/vgpreload\") != NULL);\n}\n valgrind env | grep -i valgrind\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40620/" ]
365,460
<p>I want to select an option in select tag through the value. - javascript</p> <pre><code>var selectbox=document.getElementById("Lstrtemplate"); var TemplateName=selectbox.options[selectbox.selectedIndex].text; </code></pre> <p>Now i am having the option text in TemplateName, using this i want to update an another select tag, which is having the same text.. </p> <p>But dont want to use index or id.. </p> <p>Want to achieve only by the value</p> <p>Please help me</p>
[ { "answer_id": 365463, "author": "Andreas Grech", "author_id": 44084, "author_profile": "https://Stackoverflow.com/users/44084", "pm_score": 1, "selected": false, "text": "var TemplateName = selectbox.options[selectbox.selectedIndex].value;\n" }, { "answer_id": 365468, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "var selectbox=document.getElementById(\"temp1\");\nvar selectbox2=document.getElementById(\"temp2\");\nselectbox2.value = selectbox.value;\n" }, { "answer_id": 365474, "author": "Peter Oehlert", "author_id": 44656, "author_profile": "https://Stackoverflow.com/users/44656", "pm_score": 0, "selected": false, "text": "var selectbox=document.getElementById(\"Lstrtemplate\");\nvar TemplateName=selectbox.options[selectbox.selectedIndex].text;\n\nvar select2 = document.getElementById(\"SecondSelect\");\nfor (optionElem in select2.options)\n if (optionElem.text == TemplateName)\n {\n select2.value = optionElem.value;\n break;\n }\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38172/" ]
365,472
<p>I get the above error whenever I try and use ActionLink ? I've only just started playing around with MVC and don't really understand what it's problem is with the code (below):</p> <pre><code>&lt;%= Html.ActionLink("Lists", "Index", "Lists"); %&gt; </code></pre> <p>This just seems to be a parsing issue but it only happens when I run the page. The application builds perfectly fine, so I really don't get it because the error is a compilation error? If I take line 25 out it will happen on the next line instead...</p> <pre><code> Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1026: ) expected Source Error: Line 23: &lt;/div&gt; Line 24: Line 25: &lt;%= Html.ActionLink("Lists", "Index", "Lists"); %&gt; Line 26: &lt;a href="&lt;%= Url.Action("/", "Lists"); %&gt;"&gt;Click here to view your lists&lt;/a&gt; Line 27: Source File: d:\Coding\Playground\HowDidYouKnowMVCSoln\HowDidYouKnowMVC\Views\Home\Index.aspx Line: 25 </code></pre>
[ { "answer_id": 365478, "author": "maxnk", "author_id": 45862, "author_profile": "https://Stackoverflow.com/users/45862", "pm_score": 3, "selected": false, "text": "<%= Html.ActionLink(\"Lists\", \"Index\", \"Lists\") %>\n" }, { "answer_id": 365480, "author": "Mike Scott", "author_id": 43649, "author_profile": "https://Stackoverflow.com/users/43649", "pm_score": 6, "selected": true, "text": "<%= ... %> <% ...; %>" }, { "answer_id": 5262357, "author": "Amel Music", "author_id": 254836, "author_profile": "https://Stackoverflow.com/users/254836", "pm_score": 2, "selected": false, "text": "<%= Url.Action(\"SearchPatientSchedules\", \"PatientSchedules\" **)** %>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26081/" ]
365,482
<p>What is the difference between ArrayList and List in VB.NET</p>
[ { "answer_id": 365494, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 4, "selected": false, "text": "List<string> strList; // can store only strings\nList<int> intList; // can store only ints\nArrayList someList; // can store anything\n" }, { "answer_id": 366197, "author": "ggf31416", "author_id": 38561, "author_profile": "https://Stackoverflow.com/users/38561", "pm_score": 2, "selected": false, "text": "Dim customers as new ArrayList\nDim c as new Customer\nDim m as new Manager\ncustomers.Add(c)\ncustomers.Add(m)\n\n'This will cause an exception ' \nFor each c as Customer in customers\nconsole.writeline(c.Name)\nNext\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38997/" ]
365,487
<p>Everyday I receive thousands of emails and I want to parse the content/body of these emails to load them into a database.</p> <p>My problem is that nowadays I am parsing the email body manually and I would like to change the logic to a <strong>Regular Expression in C#.</strong></p> <p>Here is the body of the emails:</p> <hr> <p>Gentilissima Agenzia Nexity Residenziale</p> <p>il nostro utente:</p> <p>Sig./Sig.ra :<strong>Pablo Azorin</strong></p> <p>Email: <strong>pabloazorin@gmail.com</strong></p> <p>Tel.: <strong>02322-498900</strong></p> <p>sta cercando un immobile con le seguenti caratteristiche:</p> <p>Categoria: <strong>Residenziale</strong></p> <p>Tipologia: <strong>Villa</strong></p> <p>Tipo di contratto: <strong>Vendita</strong></p> <p>Comune: Assago Prov. <strong>Milano</strong></p> <p>Zona: <strong>non specificata</strong></p> <p>Fascia di prezzo: <strong>non specificata</strong></p> <hr> <p>I need to extract the text in bold and I thought a RegEx is what I need for this...</p> <p>Looking forward to get your suggestion about how to make it works.</p> <p>Thanks!</p> <p><strong>--Pablo</strong></p>
[ { "answer_id": 366545, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 2, "selected": false, "text": "Sig\\./Sig\\.ra :(.*)\n\nEmail: (.*)\n\nTel\\.: (.*)\n\nsta cercando un immobile con le seguenti caratteristiche:\n\nCategoria: (.*)\n\nTipologia: (.*)\n\nTipo di contratto: (.*)\n\nComune: (.*)\n\nZona: (.*)\n\nFascia di prezzo: (.*)\n Regex regexObj = new Regex(@\"Sig\\./Sig\\.ra :(.*)\n\nEmail: (.*)\n\nTel\\.: (.*)\n\nsta cercando un immobile con le seguenti caratteristiche:\n\nCategoria: (.*)\n\nTipologia: (.*)\n\nTipo di contratto: (.*)\n\nComune: (.*)\n\nZona: (.*)\n\nFascia di prezzo: (.*)\");\nMatch matchObj = regexObj.Match(subjectString);\nstring Sig = matchObj.Groups[1].Value;\nstring Email = matchObj.Groups[2].Value;\n// and so on to get all the other parts\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,489
<p>My company is about to hire <strong>.NET developers</strong>. We work on a variety of .NET platforms: ASP.NET, Compact Framework, Windowsforms, Web Services. I'd like to compile a list/catalog of good questions, a kind of minimum standard to see if the applicants are experienced. So, my question is:</p> <p><strong>What questions</strong> do you think should a good <strong>.NET programmer be able to respond</strong>?</p> <p>I'd also see it as a <strong>checklist</strong> for myself, in order to see where my own deficits are <em>(there are many...)</em>.</p> <p><img src="https://i.imgur.com/Xo2yI.png" alt="alt text"></p> <p>*UPDATE: It want to make clear that we're not testing only for .NET knowledge, and that problem solving capabilities and general programming skills are even more important to us. </p>
[ { "answer_id": 366377, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 7, "selected": false, "text": "a.Equals(b) a == b Assembly.LoadFrom Assembly.LoadFile Finalize() Dispose() Debug.Write Trace.Write catch (Exception e) {throw e;} (Exception e) {throw;} typeof(foo) myFoo.GetType() q= q=5 http://localhost/page.aspx?q=5" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
365,495
<p>I have been a .net developer for the past three yrs. Just curious to know about the network security field. What kind of work does the developers working in these area do? I really have not much idea about network security but what my understanding is these people are involved in securing network, preventing attacks on network as obvious. Could any one please give me some details about this field and also what does it take to move to this field.</p>
[ { "answer_id": 366377, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 7, "selected": false, "text": "a.Equals(b) a == b Assembly.LoadFrom Assembly.LoadFile Finalize() Dispose() Debug.Write Trace.Write catch (Exception e) {throw e;} (Exception e) {throw;} typeof(foo) myFoo.GetType() q= q=5 http://localhost/page.aspx?q=5" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45280/" ]
365,496
<p>I have an update query being run by a cron task that's timing out. The query takes, on average, five minutes to execute when executed in navicat.</p> <p>The code looks roughly like this. It's quite simple:</p> <pre><code>// $db is a mysqli link set_time_limit (0); // should keep the script from timing out $query = "SLOW QUERY"; $result = $db-&gt;query($query); if (!$result) echo "error"; </code></pre> <p>Even though the script shouldn't timeout, the time spent waiting on the sql call still seems to be subject to a timeout.</p> <p>Is there an asynchronous call that can be used? Or adjust the timeout?</p> <p>Is the timeout different because it's being called from the command line rather than through Apache?</p> <p>Thanks</p>
[ { "answer_id": 365549, "author": "Karsten", "author_id": 28144, "author_profile": "https://Stackoverflow.com/users/28144", "pm_score": 6, "selected": true, "text": "set_time_limit(0);\nignore_user_abort(1);\n" }, { "answer_id": 65779637, "author": "Jambu Atchison", "author_id": 11115559, "author_profile": "https://Stackoverflow.com/users/11115559", "pm_score": 0, "selected": false, "text": "$timeout_seconds = 3153600; // 1 year... \n\n// Make sure the PHP script doesn't time out\nset_time_limit(0);\nignore_user_abort(1);\n\n// Make sure the PHP socket doesn't time out\nini_set('default_socket_timeout', $timeout_seconds);\nini_set('mysqlnd.net_read_timeout', $timeout_seconds);\n\n// Make sure the MySQL server doesn't time out\n// Assuming your $link is a MySQLi object:\n$link->query(\"SET SESSION connect_timeout=\" . $timeout_seconds);\n$link->query(\"SET SESSION delayed_insert_timeout=\" . $timeout_seconds);\n$link->query(\"SET SESSION have_statement_timeout='NO'\");\n$link->query(\"SET SESSION net_read_timeout=\" . $timeout_seconds);\n$link->query(\"SET SESSION net_write_timeout=\" . $timeout_seconds);\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430/" ]
365,522
<p>A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it's possible with some bitwise operators, but not sure.</p>
[ { "answer_id": 365544, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 7, "selected": true, "text": "#include<stdio.h>\n\nint add(int x, int y) {\n int a, b;\n do {\n a = x & y;\n b = x ^ y;\n x = a << 1;\n y = b;\n } while (a);\n return b;\n}\n\n\nint main( void ){\n printf( \"2 + 3 = %d\", add(2,3));\n return 0;\n}\n x ^ y (x & y) (x & y) << 1" }, { "answer_id": 365561, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 3, "selected": false, "text": "len(range(x)+range(y))\n +" }, { "answer_id": 365573, "author": "Lara Dougan", "author_id": 4081, "author_profile": "https://Stackoverflow.com/users/4081", "pm_score": 2, "selected": false, "text": "#define BIT_LEN 32\n#define ADD_OK 0\n#define ADD_UNDERFLOW 1\n#define ADD_OVERFLOW 2\n\nint ripple_add(int a, int b, char carry_in, char* flags) {\n int result = 0;\n int current_bit_position = 0;\n char a_bit = 0, b_bit = 0, result_bit = 0;\n\n while ((a || b) && current_bit_position < BIT_LEN) {\n a_bit = a & 1;\n b_bit = b & 1;\n result_bit = (a_bit ^ b_bit ^ carry_in);\n result |= result_bit << current_bit_position++;\n carry_in = (a_bit & b_bit) | (a_bit & carry_in) | (b_bit & carry_in);\n a >>= 1;\n b >>= 1;\n }\n\n if (current_bit_position < BIT_LEN) {\n *flags = ADD_OK;\n }\n else if (a_bit & b_bit & ~result_bit) {\n *flags = ADD_UNDERFLOW;\n }\n else if (~a_bit & ~b_bit & result_bit) {\n *flags = ADD_OVERFLOW;\n }\n else {\n *flags = ADD_OK;\n }\n\n return result;\n}\n" }, { "answer_id": 365584, "author": "davidfowl", "author_id": 45091, "author_profile": "https://Stackoverflow.com/users/45091", "pm_score": 4, "selected": false, "text": "int add(int a, int b) \n{\n return -(-a) - (-b);\n}\n" }, { "answer_id": 366247, "author": "ackb", "author_id": 45215, "author_profile": "https://Stackoverflow.com/users/45215", "pm_score": 5, "selected": false, "text": "int add(int a, int b) {\n const char *c=0;\n return &(&c[a])[b];\n}\n" }, { "answer_id": 2310745, "author": "Deadcode", "author_id": 161468, "author_profile": "https://Stackoverflow.com/users/161468", "pm_score": 3, "selected": false, "text": "int sub(int x, int y) {\n unsigned a, b;\n do {\n a = ~x & y;\n b = x ^ y;\n x = b;\n y = a << 1;\n } while (a);\n return b;\n}\n" }, { "answer_id": 19392987, "author": "kyle k", "author_id": 2300216, "author_profile": "https://Stackoverflow.com/users/2300216", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n unsigned int x = 3, y = 1, sum, carry;\n sum = x ^ y; // Ex - OR x and y\n carry = x & y; // AND x and y\n while (carry != 0) {\n carry = carry << 1; // left shift the carry\n x = sum; // initialize x as sum\n y = carry; // initialize y as carry\n sum = x ^ y; // sum is calculated\n carry = x & y; /* carry is calculated, the loop condition is\n evaluated and the process is repeated until\n carry is equal to 0.\n */\n }\n printf(\"%d\\n\", sum); // the program will print 4\n return 0;\n}\n" }, { "answer_id": 25219150, "author": "user3922199", "author_id": 3922199, "author_profile": "https://Stackoverflow.com/users/3922199", "pm_score": 0, "selected": false, "text": "int add(int x, int y)\n{\n int t1_set, t2_set;\n int carry = 0;\n int result = 0;\n int mask = 0x1;\n\n while (mask != 0) {\n t1_set = x & mask;\n t2_set = y & mask;\n if (carry) {\n if (!t1_set && !t2_set) {\n carry = 0;\n result |= mask;\n } else if (t1_set && t2_set) {\n result |= mask;\n }\n } else {\n if ((t1_set && !t2_set) || (!t1_set && t2_set)) {\n result |= mask;\n } else if (t1_set && t2_set) {\n carry = 1;\n }\n }\n mask <<= 1;\n }\n return (result);\n}\n int add_better (int x, int y)\n{\n int b1_set, b2_set;\n int mask = 0x1;\n int result = 0;\n int carry = 0;\n\n while (mask != 0) {\n b1_set = x & mask ? 1 : 0;\n b2_set = y & mask ? 1 : 0;\n if ( (b1_set ^ b2_set) ^ carry)\n result |= mask;\n carry = (b1_set & b2_set) | (b1_set & carry) | (b2_set & carry);\n mask <<= 1;\n }\n return (result);\n}\n" }, { "answer_id": 31770377, "author": "James", "author_id": 4485034, "author_profile": "https://Stackoverflow.com/users/4485034", "pm_score": 1, "selected": false, "text": "def foo(a, b):\n\"\"\"iterate through a and b, count iteration via a list, check len\"\"\"\n x = []\n for i in range(a):\n x.append(a)\n for i in range(b):\n x.append(b)\n print len(x)\n" }, { "answer_id": 32164253, "author": "nk911", "author_id": 2933964, "author_profile": "https://Stackoverflow.com/users/2933964", "pm_score": -1, "selected": false, "text": "add = lambda a,b : -(-a)-(-b)\n add= lambda a,b : len(list(map(lambda x:x,(i for i in range(-a,b)))))\n" }, { "answer_id": 38166888, "author": "Jake Smith", "author_id": 1480946, "author_profile": "https://Stackoverflow.com/users/1480946", "pm_score": 0, "selected": false, "text": "public int Sum(int a, int b) => b != 0 ? Sum(a ^ b, (a & b) << 1) : a;\n" }, { "answer_id": 39192714, "author": "Konstantin Purtov", "author_id": 1502891, "author_profile": "https://Stackoverflow.com/users/1502891", "pm_score": 0, "selected": false, "text": "def summ(a, b):\n #for 4 bytes(or 4*8 bits)\n max_num = 0xFFFFFFFF\n while a != 0:\n a, b = ((a & b) << 1), (a ^ b)\n if a > max_num:\n b = (b&max_num) \n break\n return b\n" }, { "answer_id": 42465956, "author": "realPK", "author_id": 853001, "author_profile": "https://Stackoverflow.com/users/853001", "pm_score": 2, "selected": false, "text": "// Recursive solution\npublic static int addR(int x, int y) {\n\n if (y == 0) return x;\n int sum = x ^ y; //SUM of two integer is X XOR Y\n int carry = (x & y) << 1; //CARRY of two integer is X AND Y\n return addR(sum, carry);\n}\n\n//Iterative solution\npublic static int addI(int x, int y) {\n\n while (y != 0) {\n int carry = (x & y); //CARRY is AND of two bits\n x = x ^ y; //SUM of two bits is X XOR Y\n y = carry << 1; //shifts carry to 1 bit to calculate sum\n }\n return x;\n}\n" }, { "answer_id": 43152244, "author": "lalatnayak", "author_id": 2626610, "author_profile": "https://Stackoverflow.com/users/2626610", "pm_score": 0, "selected": false, "text": "def add(x, y):\nif (x >= 0 and y >= 0) or (x < 0 and y < 0):\n return _add(x, y)\nelse:\n return __add(x, y)\n\n\ndef _add(x, y):\nif y == 0:\n return x\nelse:\n return _add((x ^ y), ((x & y) << 1))\n\n\ndef __add(x, y):\nif x < 0 < y:\n x = _add(~x, 1)\n if x > y:\n diff = -sub(x, y)\n else:\n diff = sub(y, x)\n return diff\nelif y < 0 < x:\n y = _add(~y, 1)\n if y > x:\n diff = -sub(y, x)\n else:\n diff = sub(y, x)\n return diff\nelse:\n raise ValueError(\"Invalid Input\")\n\n\ndef sub(x, y):\nif y > x:\n raise ValueError('y must be less than x')\nwhile y > 0:\n b = ~x & y\n x ^= y\n y = b << 1\nreturn x\n" }, { "answer_id": 52396130, "author": "guribe94", "author_id": 2848402, "author_profile": "https://Stackoverflow.com/users/2848402", "pm_score": 1, "selected": false, "text": "def sum_no_arithmetic_operators(x,y):\n while True:\n carry = x & y\n x = x ^ y\n y = carry << 1\n if y == 0:\n break\n return x\n" }, { "answer_id": 52798240, "author": "Edward J Beckett", "author_id": 538921, "author_profile": "https://Stackoverflow.com/users/538921", "pm_score": 2, "selected": false, "text": "int add(int x, int y) {\n return y == 0 ? x : add(x ^ y, (x & y) << 1);\n}\n" }, { "answer_id": 58365510, "author": "Prajilesh", "author_id": 3346515, "author_profile": "https://Stackoverflow.com/users/3346515", "pm_score": 2, "selected": false, "text": "func add(a int, b int) int {\n\nfor {\n carry := (a & b) << 1\n a = a ^ b\n b = carry \n if b == 0 {\n break\n }\n}\n\nreturn a \n\n}\n def add(a,b): \n mask = 0xffffffff\n\n while b & mask:\n carry = a & b\n a = a ^ b\n b = carry << 1\n\n return (a & mask)\n" }, { "answer_id": 62070829, "author": "crispengari", "author_id": 12925831, "author_profile": "https://Stackoverflow.com/users/12925831", "pm_score": 0, "selected": false, "text": "int add(int a, int b){\n while(b!=0){\n int sum = a^b; // add without carrying\n int carry = (a&b)<<1; // carrying without adding\n a= sum;\n b= carry;\n }\n return a;\n }\n // the function can be writen as follows :\n int add(int a, int b){\n if(b==0){\n return a; // any number plus 0 = that number simple!\n }\n int sum = a ^ b;// adding without carrying;\n int carry = (a & b)<<1; // carry, without adding\n return add(sum, carry);\n }\n" }, { "answer_id": 69210827, "author": "Hareesh", "author_id": 16377851, "author_profile": "https://Stackoverflow.com/users/16377851", "pm_score": 0, "selected": false, "text": "This can be done using Half Adder.\nHalf Adder is method to find sum of numbers with single bit.\nA B SUM CARRY A & B A ^ B\n0 0 0 0 0 0\n0 1 1 0 0 1\n1 0 1 0 0 1\n1 1 0 1 0 0\n\nWe can observe here that SUM = A ^ B and CARRY = A & B\nWe know CARRY is always added at 1 left position from where it was \ngenerated.\nso now add ( CARRY << 1 ) in SUM, and repeat this process until we get \nCarry 0.\n\nint Addition( int a, int b)\n{\n if(B==0)\n return A;\n Addition( A ^ B, (A & B) <<1 )\n}\n\nlet's add 7 (0111) and 3 (0011) answer will be 10 (1010)\n" }, { "answer_id": 70937803, "author": "Criss Gibran", "author_id": 8781656, "author_profile": "https://Stackoverflow.com/users/8781656", "pm_score": 0, "selected": false, "text": " var a = 3\n var b = 5\n var sum = 0\n var carry = 0\n\n while (b != 0) {\n sum = a ^ b\n carry = a & b\n a = sum\n b = carry << 1\n }\n\n print (sum)\n" }, { "answer_id": 73628699, "author": "Wimukthi Rajapaksha", "author_id": 10505343, "author_profile": "https://Stackoverflow.com/users/10505343", "pm_score": 0, "selected": false, "text": "public int getSum(int a, int b) {\n return (b==0) ? a : getSum(a^b, (a&b)<<1);\n}\n public int getSum(int a, int b) {\n int c=0;\n while(b!=0) {\n c=a&b;\n a=a^b;\n b=c<<1;\n }\n return a;\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23126/" ]
365,559
<p>i am trying to produce clouds effect in my flash animation using as3</p> <p>i am able to generate clouds through action script but the real problem is how to make them be generated at one end of the screen and travel diagonally to the other end... </p> <p>any thoughts?</p>
[ { "answer_id": 367080, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "package {\n\n import flash.display.Sprite;\n import flash.events.Event;\n\n public class Cloud extends Sprite{\n\n public var xSpeed:Number = 1;\n public var ySpeed:Number = 1;\n\n public function Cloud() {\n addEventListener(Event.ENTER_FRAME, handleEnterFrame);\n }\n\n public function handleEnterFrame(e:Event):void {\n x += xSpeed;\n y += ySpeed;\n }\n\n }\n\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
365,591
<p>I thought 2048 security violation error were mean to happen when trying to access other domains. </p> <p>I got:</p> <p><strong>"Security sandbox violation: <a href="http://127.0.0.1/site_media/main.swf" rel="nofollow noreferrer">http://127.0.0.1/site_media/main.swf</a> cannot load data from 127.0.0.1:80"</strong>, isn it the same domain? what is the solution ?</p> <p>on doing</p> <pre><code>var loader:MultipartLoader = new MultipartLoader("http://127.0.0.1/create/"); </code></pre> <p>Did i miss something ?</p>
[ { "answer_id": 367492, "author": "Moss Collum", "author_id": 13210, "author_profile": "https://Stackoverflow.com/users/13210", "pm_score": 1, "selected": false, "text": "var loader:MultipartLoader = new MultipartLoader(\"/create/\");\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32032/" ]
365,602
<p>If I were looking to create my own language are there any tools that would help me along? I have heard of yacc but I'm wondering how I would implement features that I want in the language.</p>
[ { "answer_id": 365636, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 4, "selected": false, "text": "[compiler]" }, { "answer_id": 70345715, "author": "Yuchang Ke", "author_id": 6623366, "author_profile": "https://Stackoverflow.com/users/6623366", "pm_score": 0, "selected": false, "text": "rply llvmlite goyacc" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265473/" ]
365,603
<p>When viewing a webpage, I would like to copy a selection of text with its html formatting in one piece. Meaning if some text is in bold and blue, I want the tool to create a style or class in the html which makes the text blue. Everything is contained in the produced html.</p> <p>I have downloaded a similar plugin but the classes definitions are still external which means I have to get them separately. A non technical user would be at a loss here. I want the user to be able to copy and paste to a new webpage and that page just just works properly because the html copied contains everything.</p> <p>This doesn't have to be a FF plugin. It could be IE or a Windows app.</p>
[ { "answer_id": 365680, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 0, "selected": false, "text": "<h2><a href=\"http://stackoverflow.com/questions/365603/firefox-plugin-to-copy-text-with-its-formatting-intelligently\">Firefox plugin to copy text with its formatting Intelligently?</a></h2>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232/" ]
365,615
<p>In C#/VB.NET/.NET, which loop runs faster, <code>for</code> or <code>foreach</code>?</p> <p>Ever since I read that a <code>for</code> loop works faster than a <code>foreach</code> loop a <a href="https://learn.microsoft.com/previous-versions/dotnet/articles/ms973839(v=msdn.10)" rel="noreferrer">long time ago</a> I assumed it stood true for all collections, generic collections, all arrays, etc.</p> <p>I scoured Google and found a few articles, but most of them are inconclusive (read comments on the articles) and open ended.</p> <p>What would be ideal is to have each scenario listed and the best solution for the same.</p> <p>For example (just an example of how it should be):</p> <ol> <li>for iterating an array of 1000+ strings - <code>for</code> is better than <code>foreach</code></li> <li>for iterating over <code>IList</code> (non generic) strings - <code>foreach</code> is better than <code>for</code></li> </ol> <p>A few references found on the web for the same: </p> <ol> <li><a href="https://learn.microsoft.com/previous-versions/dotnet/articles/ms973839(v=msdn.10)" rel="noreferrer">Original grand old article by Emmanuel Schanzer</a></li> <li><a href="https://www.codeproject.com/KB/cs/foreach.aspx" rel="noreferrer">CodeProject FOREACH Vs. FOR</a></li> <li><a href="https://learn.microsoft.com/archive/blogs/kevin_ransom/to-foreach-or-not-to-foreach-that-is-the-question" rel="noreferrer">Blog - To <code>foreach</code> or not to <code>foreach</code>, that is the question</a></li> <li><a href="https://web.archive.org/web/20100123104946/http://weblogs.asp.net/mdavey/archive/2004/02/25/79504.aspx" rel="noreferrer">ASP.NET forum - NET 1.1 C# <code>for</code> vs <code>foreach</code></a></li> </ol> <p> </p> <p>[Edit]</p> <p>Apart from the readability aspect of it, I am really interested in facts and figures. There are applications where the last mile of performance optimization squeezed do matter. </p>
[ { "answer_id": 365627, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": false, "text": "for foreach foreach foreach foreach LinkedList<T>" }, { "answer_id": 365630, "author": "Oliver Friedrich", "author_id": 44532, "author_profile": "https://Stackoverflow.com/users/44532", "pm_score": 2, "selected": false, "text": "for foreach foreach IEnumerator" }, { "answer_id": 365692, "author": "Alex York", "author_id": 35064, "author_profile": "https://Stackoverflow.com/users/35064", "pm_score": 3, "selected": false, "text": "for foreach LINQ foreach foreach foreach array List<int> foreach foreach (int i in myCollection)\n for myCollection array List for (int i = 0; i < myCollection.Length, i++)\n" }, { "answer_id": 472194, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 3, "selected": false, "text": "foreach IEnumerable" }, { "answer_id": 472258, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "foreach for using System;\nusing System.Diagnostics;\nusing System.Linq;\n\nclass Test\n{\n const int Size = 1000000;\n const int Iterations = 10000;\n\n static void Main()\n {\n double[] data = new double[Size];\n Random rng = new Random();\n for (int i=0; i < data.Length; i++)\n {\n data[i] = rng.NextDouble();\n }\n\n double correctSum = data.Sum();\n\n Stopwatch sw = Stopwatch.StartNew();\n for (int i=0; i < Iterations; i++)\n {\n double sum = 0;\n for (int j=0; j < data.Length; j++)\n {\n sum += data[j];\n }\n if (Math.Abs(sum-correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"For loop: {0}\", sw.ElapsedMilliseconds);\n\n sw = Stopwatch.StartNew();\n for (int i=0; i < Iterations; i++)\n {\n double sum = 0;\n foreach (double d in data)\n {\n sum += d;\n }\n if (Math.Abs(sum-correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"Foreach loop: {0}\", sw.ElapsedMilliseconds);\n }\n}\n For loop: 16638\nForeach loop: 16529\n List<double>" }, { "answer_id": 1946941, "author": "ctford", "author_id": 111495, "author_profile": "https://Stackoverflow.com/users/111495", "pm_score": 7, "selected": false, "text": "foreach for foreach foreach IEnumerable for IList for foreach" }, { "answer_id": 1946942, "author": "Meta-Knight", "author_id": 48910, "author_profile": "https://Stackoverflow.com/users/48910", "pm_score": 4, "selected": false, "text": "foreach for foreach (int i in Enumerable.Range(1, 10))...\n for" }, { "answer_id": 1946947, "author": "Rob Fonseca-Ensor", "author_id": 21433, "author_profile": "https://Stackoverflow.com/users/21433", "pm_score": 6, "selected": false, "text": "using System.Diagnostics;\n//...\nStopwatch sw = new Stopwatch()\nsw.Start()\nfor(int i = 0; i < 1000000;i ++)\n{\n //do whatever it is you need to time\n}\nsw.Stop();\n//print out sw.ElapsedMilliseconds\n" }, { "answer_id": 1946967, "author": "Mahesh Velaga", "author_id": 175421, "author_profile": "https://Stackoverflow.com/users/175421", "pm_score": 0, "selected": false, "text": "for foreach" }, { "answer_id": 1946975, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 5, "selected": false, "text": "foreach for foreach" }, { "answer_id": 1947108, "author": "Brian Rasmussen", "author_id": 38206, "author_profile": "https://Stackoverflow.com/users/38206", "pm_score": 3, "selected": false, "text": "for foreach" }, { "answer_id": 1947193, "author": "Tad Donaghe", "author_id": 1572436, "author_profile": "https://Stackoverflow.com/users/1572436", "pm_score": 2, "selected": false, "text": "myList.ForEach(c => Console.WriteLine(c.ToString());\n" }, { "answer_id": 1948168, "author": "Reed Copsey", "author_id": 65358, "author_profile": "https://Stackoverflow.com/users/65358", "pm_score": 3, "selected": false, "text": "for for foreach" }, { "answer_id": 1948314, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 3, "selected": false, "text": "public IEnumerator<int> For(int start, int end, int step) {\n int n = start;\n while (n <= end) {\n yield n;\n n += step;\n }\n}\n foreach (int n in For(1, 200, 4)) {\n Console.WriteLine(n);\n}\n" }, { "answer_id": 7004586, "author": "GorillaApe", "author_id": 294022, "author_profile": "https://Stackoverflow.com/users/294022", "pm_score": 1, "selected": false, "text": "for foreach" }, { "answer_id": 24177105, "author": "Diganta Kumar", "author_id": 798727, "author_profile": "https://Stackoverflow.com/users/798727", "pm_score": 2, "selected": false, "text": "foreach List array for foreach private static void MeasureTime()\n {\n var array = new int[10000];\n var list = array.ToList();\n Console.WriteLine(\"Array size: {0}\", array.Length);\n\n Console.WriteLine(\"Array For loop ......\");\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < array.Length; i++)\n {\n Thread.Sleep(1);\n }\n stopWatch.Stop();\n Console.WriteLine(\"Time take to run the for loop is {0} millisecond\", stopWatch.ElapsedMilliseconds);\n\n Console.WriteLine(\" \");\n Console.WriteLine(\"Array Foreach loop ......\");\n var stopWatch1 = Stopwatch.StartNew();\n foreach (var item in array)\n {\n Thread.Sleep(1);\n }\n stopWatch1.Stop();\n Console.WriteLine(\"Time take to run the foreach loop is {0} millisecond\", stopWatch1.ElapsedMilliseconds);\n\n Console.WriteLine(\" \");\n Console.WriteLine(\"List For loop ......\");\n var stopWatch2 = Stopwatch.StartNew();\n for (int i = 0; i < list.Count; i++)\n {\n Thread.Sleep(1);\n }\n stopWatch2.Stop();\n Console.WriteLine(\"Time take to run the for loop is {0} millisecond\", stopWatch2.ElapsedMilliseconds);\n\n Console.WriteLine(\" \");\n Console.WriteLine(\"List Foreach loop ......\");\n var stopWatch3 = Stopwatch.StartNew();\n foreach (var item in list)\n {\n Thread.Sleep(1);\n }\n stopWatch3.Stop();\n Console.WriteLine(\"Time take to run the foreach loop is {0} millisecond\", stopWatch3.ElapsedMilliseconds);\n }\n for array private static void MeasureNewTime()\n {\n var data = new double[Size];\n var rng = new Random();\n for (int i = 0; i < data.Length; i++)\n {\n data[i] = rng.NextDouble();\n }\n Console.WriteLine(\"Lenght of array: {0}\", data.Length);\n Console.WriteLine(\"No. of iteration: {0}\", Iterations);\n Console.WriteLine(\" \");\n double correctSum = data.Sum();\n\n Stopwatch sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n double sum = 0;\n for (int j = 0; j < data.Length; j++)\n {\n sum += data[j];\n }\n if (Math.Abs(sum - correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"For loop with Array: {0}\", sw.ElapsedMilliseconds);\n\n sw = Stopwatch.StartNew();\n for (var i = 0; i < Iterations; i++)\n {\n double sum = 0;\n foreach (double d in data)\n {\n sum += d;\n }\n if (Math.Abs(sum - correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"Foreach loop with Array: {0}\", sw.ElapsedMilliseconds);\n Console.WriteLine(\" \");\n\n var dataList = data.ToList();\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n double sum = 0;\n for (int j = 0; j < dataList.Count; j++)\n {\n sum += data[j];\n }\n if (Math.Abs(sum - correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"For loop with List: {0}\", sw.ElapsedMilliseconds);\n\n sw = Stopwatch.StartNew();\n for (int i = 0; i < Iterations; i++)\n {\n double sum = 0;\n foreach (double d in dataList)\n {\n sum += d;\n }\n if (Math.Abs(sum - correctSum) > 0.1)\n {\n Console.WriteLine(\"Summation failed\");\n return;\n }\n }\n sw.Stop();\n Console.WriteLine(\"Foreach loop with List: {0}\", sw.ElapsedMilliseconds);\n }\n" }, { "answer_id": 24455055, "author": "shadowf", "author_id": 1004665, "author_profile": "https://Stackoverflow.com/users/1004665", "pm_score": 0, "selected": false, "text": "List<MyCustomType>" }, { "answer_id": 39653573, "author": "barlop", "author_id": 385907, "author_profile": "https://Stackoverflow.com/users/385907", "pm_score": 1, "selected": false, "text": "for(int i=0;i<textBox1.lines.length;i++) str=textBox1.Lines[i] for (int i = 0; i < richTextBox.Lines.Length; i++)\n{\n s = richTextBox.Lines[i];\n}\n String s=String.Empty;\n foreach(string str in txtText.Lines)\n {\n s=str;\n }\n" }, { "answer_id": 66349595, "author": "mohamad tolou", "author_id": 11371716, "author_profile": "https://Stackoverflow.com/users/11371716", "pm_score": 1, "selected": false, "text": " internal static void Test()\n {\n int LOOP_LENGTH = 10000000;\n Random random = new Random((int)DateTime.Now.ToFileTime());\n\n {\n Dictionary<int, int> dict = new Dictionary<int, int>();\n long first_memory = GC.GetTotalMemory(true);\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < 64; i++)\n {\n dict.Add(i, i);\n }\n\n for (int i = 0; i < LOOP_LENGTH; i++)\n {\n for (int k = 0; k < dict.Count; k++)\n {\n if (dict[k] > 1000000) Console.WriteLine(\"Test\");\n }\n }\n stopWatch.Stop();\n var last_memory = GC.GetTotalMemory(true);\n Console.WriteLine($\"Dictionary for T:{stopWatch.Elapsed.TotalSeconds}s\\t M:{last_memory - first_memory}\");\n\n GC.Collect();\n }\n\n\n {\n Dictionary<int, int> dict = new Dictionary<int, int>();\n long first_memory = GC.GetTotalMemory(true);\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < 64; i++)\n {\n dict.Add(i, i);\n }\n\n for (int i = 0; i < LOOP_LENGTH; i++)\n {\n foreach (var item in dict)\n {\n if (item.Value > 1000000) Console.WriteLine(\"Test\");\n }\n }\n stopWatch.Stop();\n var last_memory = GC.GetTotalMemory(true);\n Console.WriteLine($\"Dictionary foreach T:{stopWatch.Elapsed.TotalSeconds}s\\t M:{last_memory - first_memory}\");\n\n GC.Collect();\n }\n\n {\n Dictionary<int, int> dict = new Dictionary<int, int>();\n long first_memory = GC.GetTotalMemory(true);\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < 64; i++)\n {\n dict.Add(i, i);\n }\n\n for (int i = 0; i < LOOP_LENGTH; i++)\n {\n foreach (var item in dict.Values)\n {\n if (item > 1000000) Console.WriteLine(\"Test\");\n }\n }\n stopWatch.Stop();\n var last_memory = GC.GetTotalMemory(true);\n Console.WriteLine($\"Dictionary foreach values T:{stopWatch.Elapsed.TotalSeconds}s\\t M:{last_memory - first_memory}\");\n\n GC.Collect();\n }\n\n\n {\n List<int> dict = new List<int>();\n long first_memory = GC.GetTotalMemory(true);\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < 64; i++)\n {\n dict.Add(i);\n }\n\n for (int i = 0; i < LOOP_LENGTH; i++)\n {\n for (int k = 0; k < dict.Count; k++)\n {\n if (dict[k] > 1000000) Console.WriteLine(\"Test\");\n }\n }\n stopWatch.Stop();\n var last_memory = GC.GetTotalMemory(true);\n Console.WriteLine($\"list for T:{stopWatch.Elapsed.TotalSeconds}s\\t M:{last_memory - first_memory}\");\n\n GC.Collect();\n }\n\n\n {\n List<int> dict = new List<int>();\n long first_memory = GC.GetTotalMemory(true);\n var stopWatch = Stopwatch.StartNew();\n for (int i = 0; i < 64; i++)\n {\n dict.Add(i);\n }\n\n for (int i = 0; i < LOOP_LENGTH; i++)\n {\n foreach (var item in dict)\n {\n if (item > 1000000) Console.WriteLine(\"Test\");\n }\n }\n stopWatch.Stop();\n var last_memory = GC.GetTotalMemory(true);\n Console.WriteLine($\"list foreach T:{stopWatch.Elapsed.TotalSeconds}s\\t M:{last_memory - first_memory}\");\n\n GC.Collect();\n }\n }\n" }, { "answer_id": 74021843, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 1, "selected": false, "text": "for foreach using BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Running;\n\npublic class Program\n{\n public static void Main()\n {\n BenchmarkRunner.Run<LoopsBenchmarks>();\n }\n}\n\n[MemoryDiagnoser]\npublic class LoopsBenchmarks\n{\n private List<int> arr = Enumerable.Range(1, 1_000_000_000).ToList();\n\n [Benchmark]\n public void For()\n {\n for (int i = 0; i < arr.Count; i++)\n {\n int item = arr[i];\n }\n }\n\n [Benchmark]\n public void Foreach()\n {\n foreach (int item in arr)\n {\n }\n }\n}\n for foreach" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33015/" ]
365,649
<p>I was looking through Mozilla's <a href="http://mxr.mozilla.org/mozilla/source/js/narcissus/jsexec.js" rel="nofollow noreferrer">JS in JS</a> code and came across the <a href="http://mxr.mozilla.org/mozilla/source/js/narcissus/jsexec.js#137" rel="nofollow noreferrer">snarf function</a>. It's not defined in the javascript, it seems, just in the C version <a href="http://mxr.mozilla.org/mozilla/source/js/src/js.c#3712" rel="nofollow noreferrer">here</a>. It isn't very well-commented, though. I Google searched this to no avail. </p> <p>Is this a standard part of JavaScript? (My guess is no.) Is it some kind of extension? What is it supposed to do? </p>
[ { "answer_id": 365716, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 4, "selected": true, "text": "snarf(filename)" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
365,650
<p>When I try to build my project I get the following message in the build window :</p> <p><strong>========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========</strong></p> <p>I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info on what's wrong . I am using Visual Studio 2005 Professional Edition .</p>
[ { "answer_id": 12840704, "author": "ulidtko", "author_id": 531179, "author_profile": "https://Stackoverflow.com/users/531179", "pm_score": 2, "selected": false, "text": "appwiz.cpl" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
365,657
<p>On my main form, there is another (floatable) window. This floatable window works sort of like a popupwindow in that it will close when the user clicks somewhere else outside of this window. This is handled by the Deactivate event. But what I want to do is, if the user clicks on a different control (say a button), I want to both close this float window and then activate that button with just one click. Currently, the user has to click twice (one to deactivate the window and once more to activate the desired button). Is there a way to do this with just one click?</p>
[ { "answer_id": 365691, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "foreach(Control c in parentForm.Controls)\n{\n c.Click += delegate(object sender, EventArgs e)\n {\n if(floatyWindow != null && floatyWindow.IsFloating)\n {\n floatyWindow.Close();\n }\n };\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36258/" ]
365,661
<p>Is it possible for an Subversion client to break a repository in any way? This could be any sort of destructive disruption, but it must be such that it cannot be recovered from without restoring the repository from a backup.</p> <p>Obviously, deleting everything and then checking that it is easy to fix simply with a rollback, so I am looking for something more than that.</p>
[ { "answer_id": 365672, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "file://" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20770/" ]
365,669
<p>I typically use the .markdown or .md extension for markdown documents. Unfortunately spotlight refuses to index them unless they have the .txt file extension.</p> <p>I've seen a possible solution involving <a href="http://blog.macromates.com/2007/leopard-issues/" rel="noreferrer">editing Info.plist files</a> on the textmate blog. Is there a better way?</p> <p>Update: I just discovered <a href="http://github.com/mdk/qlmarkdown/" rel="noreferrer">QuickLook generator for Markdown files</a> which adds spotlight support and nice HTML quicklook previews. It works a treat!</p>
[ { "answer_id": 365675, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 2, "selected": false, "text": "UTExportedTypeDeclarations" }, { "answer_id": 33404681, "author": "Pwdr", "author_id": 1052107, "author_profile": "https://Stackoverflow.com/users/1052107", "pm_score": 2, "selected": false, "text": "command + R Utilities Terminal csrutil disable /System/Library/Spotlight/RichText.mdimporter/Contents/Info.plist sudo open -a TextEdit /System/Library/Spotlight/RichText.mdimporter/Contents/Info.plist <string>net.daringfireball.markdown</string> LSItemContentTypes csrutil enable" }, { "answer_id": 33873422, "author": "Brian Reiter", "author_id": 110045, "author_profile": "https://Stackoverflow.com/users/110045", "pm_score": 3, "selected": false, "text": "cp -r /System/Library/Spotlight/RichText.mdimporter .\npatch -p2 RichText.mdimporter/Contents/Info.plist < Markdown.patch\nmv RichText.mdimporter Markdown.mdimporter\nsudo cp -R Markdown.mdimporter /Library/Spotlight\nmdimport -r /Library/Spotlight/Markdown.mdimporter\n diff -ru RichText.mdimporter/Contents/Info.plist Markdown.mdimporter/Contents/Info.plist\n--- RichText.mdimporter/Contents/Info.plist 2015-11-23 16:14:12.000000000 +0200\n+++ Markdown.mdimporter/Contents/Info.plist 2015-11-23 16:10:03.000000000 +0200\n@@ -13,15 +13,7 @@\n <string>MDImporter</string>\n <key>LSItemContentTypes</key>\n <array>\n- <string>public.rtf</string>\n- <string>public.html</string>\n- <string>public.xml</string>\n- <string>public.plain-text</string>\n- <string>com.apple.traditional-mac-plain-text</string>\n- <string>com.apple.rtfd</string>\n- <string>com.apple.webarchive</string>\n- <string>org.oasis-open.opendocument.text</string>\n- <string>org.openxmlformats.wordprocessingml.document</string>\n+ <string>net.daringfireball.markdown</string>\n </array>\n </dict>\n </array>\n@@ -30,11 +22,11 @@\n <key>CFBundleGetInfoString</key>\n <string>1.0, Copyright (c) 2004-2010 Apple Inc.</string>\n <key>CFBundleIdentifier</key>\n- <string>com.apple.MDImporter.RichText</string>\n+ <string>com.apple.MDImporter.Markdown</string>\n <key>CFBundleInfoDictionaryVersion</key>\n <string>6.0</string>\n <key>CFBundleName</key>\n- <string>Rich Text Sniffer</string>\n+ <string>Markdown Sniffer</string>\n <key>CFBundleShortVersionString</key>\n <string>6.9</string>\n <key>CFBundleSupportedPlatforms</key>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18751/" ]
365,699
<p>I find myself doing 2 things quite often in JS, at the moment using jQuery:</p> <p>The first is the populating of an HTML element, which might look like:</p> <pre><code>$.get('http://www.example.com/get_result.php', { id: 1 }, function (data) { $('#elementId').html(data); }); </code></pre> <p>The second is populating a select element with a JSON result, such as:</p> <pre><code>$.getJSON('http://www.example.com/get_result.php', { id: 1 }, function(data) { $.each(data, function(value, name) { $('#selectField').append('&lt;option value="' + value + '"&gt;' + name + '&lt;/option&gt;'); } )}; </code></pre> <p>What I'm looking for is either a better what of doing either of these or an extension (either library or a chunk of code) to jQuery that will do these without having to recreate the code all the time. Or is there already something in jQuery that makes this faster?</p> <p><strong>Edit:</strong> As mentioned by <a href="https://stackoverflow.com/questions/365699/better-way-or-reusable-code-to-populate-an-html-element-or-create-a-select-afte#365790">Kevin Gorski</a>, populating the HTML element could be done as:</p> <pre><code>$('#elementId').load('http://www.example.com/get_result.php', { id: 1 }); </code></pre> <p>This is perfect. Although, if you wanted to do a POST, it wouldn't work. Then doing <a href="https://stackoverflow.com/questions/365699/better-way-or-reusable-code-to-populate-an-html-element-or-create-a-select-afte#365797">Collin Allen's</a> method is better.</p>
[ { "answer_id": 365797, "author": "Collin Allen", "author_id": 41728, "author_profile": "https://Stackoverflow.com/users/41728", "pm_score": 2, "selected": false, "text": "(function ($) {\n $.fn.populateWith = function(sUrl, oData, fCallback) {\n if (!oData) oData = false;\n if (!fCallback) fCallback = false;\n $(this).load(sUrl, oData, fCallback);\n };\n})(jQuery);\n <select> $(\"#firstSelect\").populateWith(\"backend.html\");\n $(\"#secondSelect\").populateWith(\"backend.html\", false, function() {\n alert('Callback fired!');\n});\n $(\"#thirdSelect\").populateWith(\"backend.html\", {id: 1}, function() {\n alert('Callback fired with data!');\n});\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
365,719
<p>I got a little stuck and I'm hoping someone can point me in the right direction. I have an NSMutableArray that stores a sequence. I created an enumerator so that a while loop can get the content of the array one by one.</p> <p>Everything works fine however I want the methods to be called with a 10 second gap in between each call. Right now it plays all at once (or in very quick order). What should I look at to create a delay in between method calls?</p> <p>Below is what I got so far. Thanks!</p> <pre><code>NSEnumerator * enumerator = [gameSequenceArray objectEnumerator]; id element; while(element = [enumerator nextObject]) { NSLog(element); int elementInt = [element intValue]; [self.view showButton:elementInt]; } </code></pre>
[ { "answer_id": 365798, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 3, "selected": true, "text": "[NSObject performSelector:@selector(some:selector:name:) withObject:objInstance afterDelay: 10]\n" }, { "answer_id": 367067, "author": "acreek", "author_id": 46022, "author_profile": "https://Stackoverflow.com/users/46022", "pm_score": 0, "selected": false, "text": "NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];\n\nNSTimeInterval time = 5;\n\nfor (NSString *element in enumerator) {\n id elementId = element;\n\n time++;\n\n [self.view performSelector:@selector(showButton:) withObject:elementId afterDelay:time];\n}\n" }, { "answer_id": 368055, "author": "Abizern", "author_id": 41116, "author_profile": "https://Stackoverflow.com/users/41116", "pm_score": 2, "selected": false, "text": "NSTimeInterval time = 10;\n\nfor (id elementId in gameSequenceArray) {\n\n [self.view performSelector:@selector(showButton:) withObject:elementID afterDelay:time];\n}\n - (void)showButton:(id)anElement {\n ...\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46022/" ]
365,743
<p>I have a small app that has a Render thread. All this thread does is draw my objects at their current location.</p> <p>I have some code like:</p> <pre><code>public void render() { // ... rendering various objects if (mouseBall != null) mouseBall.draw() } </code></pre> <p>Then I also have some mouse handler that creates and sets mouseBall to a new ball when the user clicks the mouse. The user can then drag the mouse around and the ball will follow where the mouse goes. When the user releases the ball I have another mouse event that sets mouseBall = null. </p> <p>The problem is, my render loop is running fast enough that at random times the conditional (mouseBall != null) will return true, but in that split second after that point the user will let go of the mouse and I'll get a nullpointer exception for attempting .draw() on a null object.</p> <p>What is the solution to a problem like this?</p>
[ { "answer_id": 365748, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "mouseBall null public void render()\n{\n // ... rendering various objects\n tmpBall = mouseBall;\n if (tmpBall != null) tmpBall.draw();\n}\n" }, { "answer_id": 365762, "author": "Nathaniel Flath", "author_id": 41241, "author_profile": "https://Stackoverflow.com/users/41241", "pm_score": 3, "selected": false, "text": " \npublic void render()\n{\n // ... rendering various objects\n synchronized(this) {\n if (mouseBall != null) mouseBall .draw();\n }\n}\n" }, { "answer_id": 429095, "author": "Andrzej Doyle", "author_id": 45664, "author_profile": "https://Stackoverflow.com/users/45664", "pm_score": 2, "selected": false, "text": "public void render()\n{\n AtomicReference<MouseBallClass> mouseBall = ...;\n\n // ... rendering various objects\n MouseBall tmpBall = mouseBall.get();\n if (tmpBall != null) tmpBall.draw();\n} mouseBall.compareAndSet(null, possibleNewBall); MouseBall oldBall = mouseBall.getAndSet(newMouseBall);\n // Cleanup code using oldBall" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,750
<p>I'm using VB.net (2003), and calling the SelectNodes method on an xml document.<br> If I have a document:</p> <pre><code>&lt;InqRs&gt; &lt;DetRs&gt; &lt;RefInfo&gt; &lt;RefType&gt;StopNum&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;RefInfo&gt; &lt;RefType&gt;Id&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;/DetRs&gt; &lt;DetRs&gt; &lt;RefInfo&gt; &lt;RefType&gt;StopNum&lt;/RefType&gt; &lt;RefId&gt;0&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;RefInfo&gt; &lt;RefType&gt;Id&lt;/RefType&gt; &lt;RefId&gt;1&lt;/RefId&gt; &lt;/RefInfo&gt; &lt;/DetRs&gt; &lt;/InqRs&gt; </code></pre> <p>How can I select just for the <code>DetRs</code> that has <code>RefType=Id</code> and <code>RefId=0</code>, ie, the 'first' one above?</p> <p>I've tried several different attempts, among others: </p> <pre><code>InqRs/DetRs[RefInfo/RefType='Id' and RefInfo/RefId='0'] InqRs/DetRs[RefInfo/RefType='Id'][RefInfo/RefId='0'] </code></pre> <p>But these select both of the DetRs sections (because of the StopNum RefId of 0, I presume). </p>
[ { "answer_id": 365957, "author": "Toby White", "author_id": 45891, "author_profile": "https://Stackoverflow.com/users/45891", "pm_score": 1, "selected": false, "text": "DetRs/Refinfo[RefType='Id' and RefId='0']/..\n" }, { "answer_id": 366835, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 2, "selected": false, "text": "DetRs /*/DetRs RefInfo /*/DetRs [RefInfo] RefType Id /*/DetRs [RefInfo RefType Id RefId /*/DetRs [RefInfo RefType Id and RefId DetRs /*/DetRs[RefInfo[RefType='Id' and RefId=0]]" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,768
<p>I have an intel assembly assignment. I need to write a calculator which uses 2 stacks. For example, i have an expression like 23+4/2^4$ .So that $ indicates the end of expression. What I will do is to have two stacks, one for numbers, one for operators and push and pop them according to the operator precedence.</p> <p>What I need is how can I use 2 stacks for two different purpose at the same time. As long as I know esp register indicates the place for variables in the stack to pop the last or to push a new one. But if I only have one esp register, how can I have two stacks?</p> <p>Thanks in advance... </p>
[ { "answer_id": 365883, "author": "israkir", "author_id": 26379, "author_profile": "https://Stackoverflow.com/users/26379", "pm_score": -1, "selected": false, "text": "mov ecx,256\nL1: call ReadInt\n push eax ;push the integer to where esp=1 points\n add esp,ecx ;esp=1+256=257, now esp points to 257.\n\n call ReadChar ;read operand\n cmp al,endChar ;compare with end sign=$\n je next \n push al ;push operand to where esp=257 points\n sub esp,ecx ;esp=257-256=1, now esp is in the original position\n loop L1\nnext:\n...\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26379/" ]
365,773
<p>How do I detect when my Compact Framework application is being smart-minimized (smart minimize is what happens when the user clicks the "X" button in the top-right corner on a Pocket PC)?</p> <p>The Deactivate event isn't the right way because it occurs in circumstances other than minimization, such as when a message box or another form is shown on top of the main form. And the form's WindowState doesn't help because there is no "Minimized" WindowState on .NET CF.</p> <p>I heard that by setting MinimizeBox = false, my app will be closed instead of minimized. But I actually don't want my app to close, I just want to know when it has been minimized.</p>
[ { "answer_id": 410216, "author": "Geries Handal", "author_id": 37328, "author_profile": "https://Stackoverflow.com/users/37328", "pm_score": 4, "selected": true, "text": "using System.Runtime.InteropServices;\n [DllImport(\"coredll.dll\")]\nstatic extern IntPtr DefWindowProc(IntPtr hWnd, uint uMsg, UIntPtr wParam,\n IntPtr lParam);\n using System.Runtime.InteropServices;\n...\n\npublic partial class Main : Form\n{\n public Main()\n {\n\n\n InitializeComponent();\n }\n\n [DllImport(\"coredll.dll\")]\n static extern int ShowWindow(IntPtr hWnd, int nCmdShow);\n\n const int SW_MINIMIZED = 6;\n\n ...\n ...\n\n public void HideForm()\n {\n ShowWindow(this.Handle, SW_MINIMIZED);\n }\n} \n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ]
365,777
<p><em>Let's say I have download links for files on my site.</em> </p> <p>When clicked these links send an AJAX request to the server which returns the URL with the location of the file. </p> <p>What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?</p>
[ { "answer_id": 365855, "author": "Vilx-", "author_id": 41360, "author_profile": "https://Stackoverflow.com/users/41360", "pm_score": 1, "selected": false, "text": "window.open()" }, { "answer_id": 365910, "author": "fasih.rana", "author_id": 46024, "author_profile": "https://Stackoverflow.com/users/46024", "pm_score": 3, "selected": false, "text": "Content-disposition: attachment; filename=fname.ext\n" }, { "answer_id": 365919, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 4, "selected": false, "text": "window.location.href = new_url" }, { "answer_id": 4646947, "author": "roulio", "author_id": 569844, "author_profile": "https://Stackoverflow.com/users/569844", "pm_score": 5, "selected": false, "text": "<script type=\"text/javascript\">\nfunction populateIframe(id,path) \n{\n var ifrm = document.getElementById(id);\n ifrm.src = \"download.php?path=\"+path;\n}\n</script>\n <iframe id=\"frame1\" style=\"display:none\"></iframe>\n<a href=\"javascript:populateIframe('frame1','<?php echo $path; ?>')\">download</a>\n <?php \n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Disposition: attachment; filename=\".$_GET['path']);\n readfile($_GET['path']);\n?>\n" }, { "answer_id": 13671107, "author": "DanielKhan", "author_id": 1870584, "author_profile": "https://Stackoverflow.com/users/1870584", "pm_score": 4, "selected": false, "text": "<?php \n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Disposition: attachment; filename=\".$_GET['path']);\n readfile($_GET['path']);\n?>\n" }, { "answer_id": 15236354, "author": "nikib3ro", "author_id": 237858, "author_profile": "https://Stackoverflow.com/users/237858", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\n var urlParams;\n (window.onpopstate = function () {\n var match,\n pl = /\\+/g, // Regex for replacing addition symbol with a space\n search = /([^&=]+)=?([^&]*)/g,\n decode = function (s) { return decodeURIComponent(s.replace(pl, \" \")); },\n query = window.location.search.substring(1);\n\n urlParams = {};\n while (match = search.exec(query))\n urlParams[decode(match[1])] = decode(match[2]);\n })();\n\n (window.onload = function() {\n var path = urlParams[\"file\"];\n setTimeout(function() { document.location.href = path; }, 1000);\n });\n</script>\n" }, { "answer_id": 22412962, "author": "Matt K", "author_id": 798634, "author_profile": "https://Stackoverflow.com/users/798634", "pm_score": 2, "selected": false, "text": "<Files *.apk>\n ForceType application/force-download\n Header set Content-Disposition attachment\n Header set Content-Type application/vnd.android.package-archive\n Header set Content-Transfer-Encoding binary\n</Files>\n" }, { "answer_id": 32128075, "author": "James Bordine II", "author_id": 2495433, "author_profile": "https://Stackoverflow.com/users/2495433", "pm_score": 2, "selected": false, "text": "<?php\n if(isset($_GET['path'])){\n if(in_array($_GET['path'], glob(\"*/*.*\"))){\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Disposition: attachment; filename=\".$_GET['path']);\n readfile($_GET['path']);\n }\n }\n?>\n <iframe id=\"download\" style=\"display:none\"></iframe>\n <input type=\"submit\" value=\"Download\" onclick=\"ChangeSource('document_path');return false;\">\n <script type=\"text/javascript\">\n <!--\n function ChangeSource(path){\n document.getElementByID('download').src = 'path_to_php?path=' + document_path;\n }\n -->\n</script>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
365,780
<p>As you can see in the image below I have a tree datamodel consisting of groups that can contain other groups plus an arbitary number of items wich again can hold Parameters. The Parameters itself are defined globally and just reoccur in the items. Only the parameter's actual value may differ from parameter usage to parameter usage in the different items.</p> <p>The image below is an ordinary WPF treeview control with a custom control template and datatemplates for the items.</p> <p>Now my goal is to remove the parameter names above the textboxes and stack them vertically in a separate column at the very left of the treeview and just leave the textboxes there but also stacked vertically so they the correspond with their parameter names in the first column.</p> <p>Is there a way I can solve this with control templates and data templates and databinding to the view model ? (Yes I use MVVM)</p> <p><a href="http://img242.imageshack.us/img242/5377/treebh8.th.png" rel="nofollow noreferrer">treeview image http://img242.imageshack.us/img242/5377/treebh8.th.png</a> <a href="http://img242.imageshack.us/img242/5377/treebh8.png" rel="nofollow noreferrer">image link</a></p> <p>The problem is a general layout problem that must work well with databinding. generally I want to bind the object graph to a view that somewhat looks like this (cutout mockup):</p> <p><a href="http://img75.imageshack.us/img75/5763/treelayoutjh5.jpg" rel="nofollow noreferrer">treelayout http://img75.imageshack.us/img75/5763/treelayoutjh5.jpg</a></p> <p>Note that the ParamX headers are not really part of the treelayout anymore. But the values still are. Now the values must keep a connection (i.e. the are on the same row) with them. Also if none of the items in the tree contain for example Param1 the Param1 header and the corresponding row must completely dissappear.</p>
[ { "answer_id": 366486, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\nnamespace WpfTreeGridWhatever\n{\n public class ItemBase\n {\n }\n public class Group : ItemBase\n {\n public string Name { get; set; }\n public IList<ItemBase> Items { get; set; }\n }\n public class Item : ItemBase\n {\n public string Name { get; set; }\n public IList<Parameter> Parameters { get; set; }\n }\n public class Parameter\n {\n public string Name { get; set; }\n public string Value { get; set; }\n }\n}\n public Window1()\n {\n DataContext = new Group[]\n {\n new Group()\n {\n Name=\"Group A\",\n Items = new List<ItemBase>()\n {\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n new Parameter(){Name=\"Param 3\",Value=\"0.0\"},\n new Parameter(){Name=\"Param 4\",Value=\"off\"},\n }\n },\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"}\n }\n },\n new Group()\n {\n Name=\"Group B\",\n Items = new List<ItemBase>()\n {\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n new Parameter(){Name=\"Param 3\",Value=\"0.0\"},\n new Parameter(){Name=\"Param 4\",Value=\"off\"},\n }\n },\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n new Parameter(){Name=\"Param 3\",Value=\"0.0\"},\n new Parameter(){Name=\"Param 4\",Value=\"off\"},\n new Parameter(){Name=\"Param 5\",Value=\"2000\"},\n }\n },\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n }\n },\n new Group()\n {\n Name=\"Group C\",\n Items = new List<ItemBase>()\n {\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n new Parameter(){Name=\"Param 3\",Value=\"0.0\"},\n new Parameter(){Name=\"Param 4\",Value=\"off\"},\n }\n },\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n new Parameter(){Name=\"Param 3\",Value=\"0.0\"},\n new Parameter(){Name=\"Param 4\",Value=\"off\"},\n new Parameter(){Name=\"Param 5\",Value=\"2000\"},\n }\n },\n new Item()\n {\n Name=\"Item\",\n Parameters=new List<Parameter>()\n {\n new Parameter(){Name=\"Param 1\",Value=\"12\"},\n new Parameter(){Name=\"Param 2\",Value=\"true\"},\n }\n },\n }\n }\n }\n }\n }\n }\n };\n\n InitializeComponent();\n }\n <Window x:Class=\"WpfTreeGridWhatever.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:l=\"clr-namespace:WpfTreeGridWhatever\"\n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Window.Resources>\n <LinearGradientBrush x:Key=\"Bk\" StartPoint=\"0,0\" EndPoint=\"0,1\" >\n <GradientStop Offset=\"0\" Color=\"DarkGray\"/>\n <GradientStop Offset=\"1\" Color=\"White\"/>\n </LinearGradientBrush>\n <DataTemplate DataType=\"{x:Type l:Parameter}\">\n <Border CornerRadius=\"5\" Background=\"{StaticResource Bk}\"\n BorderThickness=\"1\" BorderBrush=\"Gray\" Margin=\"2\" >\n <StackPanel Margin=\"5\">\n <TextBlock Height=\"12\" Text=\"{Binding Name}\"/>\n <TextBox Height=\"22\" Text=\"{Binding Value}\"/>\n </StackPanel>\n </Border>\n </DataTemplate>\n <DataTemplate DataType=\"{x:Type l:Item}\" >\n <StackPanel>\n <Border CornerRadius=\"5\" Background=\"{StaticResource Bk}\"\n BorderThickness=\"1\" BorderBrush=\"Gray\" Height=\"25\" Margin=\"3\">\n <TextBlock Height=\"12\" Text=\"{Binding Name}\" VerticalAlignment=\"Center\" Margin=\"3,0\"/>\n </Border>\n <ItemsControl ItemsSource=\"{Binding Parameters}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Horizontal\"/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n </ItemsControl>\n </StackPanel>\n </DataTemplate>\n <DataTemplate DataType=\"{x:Type l:Group}\">\n <StackPanel>\n <Border CornerRadius=\"5\" Background=\"{StaticResource Bk}\"\n BorderThickness=\"1\" BorderBrush=\"Gray\" Height=\"25\" Margin=\"3\">\n <TextBlock Height=\"12\" Text=\"{Binding Name}\" VerticalAlignment=\"Center\" Margin=\"3,0\"/>\n </Border>\n <ItemsControl ItemsSource=\"{Binding Items}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Horizontal\"/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n </ItemsControl>\n </StackPanel>\n </DataTemplate>\n\n </Window.Resources>\n <Grid>\n <ItemsControl ItemsSource=\"{Binding}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Horizontal\"/>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n </ItemsControl>\n </Grid>\n</Window>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4227/" ]
365,782
<p>What is the accepted/most commonly used way to manipulate dynamic (with all dimensions not known until runtime) multi-dimensional arrays in C and/or C++.</p> <p>I'm trying to find the cleanest way to accomplish what this Java code does:</p> <pre><code>public static void main(String[] args){ Scanner sc=new Scanner(System.in); int rows=sc.nextInt(); int cols=sc.nextInt(); int[][] data=new int[rows][cols]; manipulate(data); } public static void manipulate(int[][] data){ for(int i=0;i&lt;data.length;i++) for(int j=0;j&lt;data[0].length.j++){ System.out.print(data[i][j]); } } </code></pre> <p>(reads from std_in just to clarify that dimensions aren't known until runtime).</p> <p>Edit:I noticed that this question is pretty popular even though it's pretty old. I don't actually agree with the top voted answer. I think the best choice for C is to use a single-dimensional array as Guge said below "You can alloc rows<em>cols</em>sizeof(int) and access it by table[row*cols+col].".</p> <p>There is a number of choices with C++, if you really like boost or stl then the answers below might be preferable, but the simplest and probably fastest choice is to use a single dimensional array as in C.</p> <p>Another viable choice in C and C++ if you want the [][] syntax is lillq's answer down at the bottom is manually building the array with lots of malloc's.</p>
[ { "answer_id": 365800, "author": "Klaim", "author_id": 2368, "author_profile": "https://Stackoverflow.com/users/2368", "pm_score": 4, "selected": false, "text": "#include \"boost/multi_array.hpp\"\n#include <cassert>\n\nint \nmain () {\n // Create a 3D array that is 3 x 4 x 2\n typedef boost::multi_array<double, 3> array_type;\n typedef array_type::index index;\n array_type A(boost::extents[3][4][2]);\n\n // Assign values to the elements\n int values = 0;\n for(index i = 0; i != 3; ++i) \n for(index j = 0; j != 4; ++j)\n for(index k = 0; k != 2; ++k)\n A[i][j][k] = values++;\n\n // Verify values\n int verify = 0;\n for(index i = 0; i != 3; ++i) \n for(index j = 0; j != 4; ++j)\n for(index k = 0; k != 2; ++k)\n assert(A[i][j][k] == verify++);\n\n return 0;\n}\n Multi-Array test!\nPlease enter the size of the dimension 0 : 4\n\nPlease enter the size of the dimension 1 : 6\n\nPlease enter the size of the dimension 2 : 2\n\nText matrix with 3 dimensions of size (4,6,2) have been created.\n\nReady!\nType 'help' for the command list.\n\n>read 0.0.0\nText at (0,0,0) :\n \"\"\n\n>write 0.0.0 \"This is a nice test!\"\nText \"This is a nice test!\" written at position (0,0,0)\n\n>read 0.0.0\nText at (0,0,0) :\n \"This is a nice test!\"\n\n>write 0,0,1 \"What a nice day!\"\nText \"What a nice day!\" written at position (0,0,1)\n\n>read 0.0.0\nText at (0,0,0) :\n \"This is a nice test!\"\n\n>read 0.0.1\nText at (0,0,1) :\n \"What a nice day!\"\n\n>write 3,5,1 \"This is the last text!\"\nText \"This is the last text!\" written at position (3,5,1)\n\n>read 3,5,1\nText at (3,5,1) :\n \"This is the last text!\"\n\n>exit\n const unsigned int DIMENSION_COUNT = 3; // dimension count for this test application, change it at will :)\n\n// here is the type of the multi-dimensional (DIMENSION_COUNT dimensions here) array we want to use\n// for this example, it own texts\ntypedef boost::multi_array< std::string , DIMENSION_COUNT > TextMatrix;\n\n// this provide size/index based position for a TextMatrix entry.\ntypedef std::tr1::array<TextMatrix::index, DIMENSION_COUNT> Position; // note that it can be a boost::array or a simple array\n\n/* This function will allow the user to manipulate the created array\n by managing it's commands.\n Returns true if the exit command have been called.\n*/\nbool process_command( const std::string& entry, TextMatrix& text_matrix );\n\n/* Print the position values in the standard output. */\nvoid display_position( const Position& position );\n\nint main()\n{\n std::cout << \"Multi-Array test!\" << std::endl;\n\n // get the dimension informations from the user\n Position dimensions; // this array will hold the size of each dimension \n\n for( int dimension_idx = 0; dimension_idx < DIMENSION_COUNT; ++dimension_idx )\n {\n std::cout << \"Please enter the size of the dimension \"<< dimension_idx <<\" : \";\n // note that here we should check the type of the entry, but it's a simple example so lets assume we take good numbers\n std::cin >> dimensions[dimension_idx]; \n std::cout << std::endl;\n\n }\n\n // now create the multi-dimensional array with the previously collected informations\n TextMatrix text_matrix( dimensions );\n\n std::cout << \"Text matrix with \" << DIMENSION_COUNT << \" dimensions of size \";\n display_position( dimensions );\n std::cout << \" have been created.\"<< std::endl;\n std::cout << std::endl;\n std::cout << \"Ready!\" << std::endl;\n std::cout << \"Type 'help' for the command list.\" << std::endl;\n std::cin.sync();\n\n\n // we can now play with it as long as we want\n bool wants_to_exit = false;\n while( !wants_to_exit )\n {\n std::cout << std::endl << \">\" ;\n std::tr1::array< char, 256 > entry_buffer; \n std::cin.getline(entry_buffer.data(), entry_buffer.size());\n\n const std::string entry( entry_buffer.data() );\n wants_to_exit = process_command( entry, text_matrix );\n }\n\n return 0;\n}\n void write_in_text_matrix( TextMatrix& text_matrix, const Position& position, const std::string& text )\n{\n text_matrix( position ) = text;\n std::cout << \"Text \\\"\" << text << \"\\\" written at position \";\n display_position( position );\n std::cout << std::endl;\n}\n\nvoid read_from_text_matrix( const TextMatrix& text_matrix, const Position& position )\n{\n const std::string& text = text_matrix( position );\n std::cout << \"Text at \";\n display_position(position);\n std::cout << \" : \"<< std::endl;\n std::cout << \" \\\"\" << text << \"\\\"\" << std::endl;\n}\n" }, { "answer_id": 365829, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 2, "selected": false, "text": "void *Array_get_2d(Array_T a, int width, int height, int i, int j) {\n return Array_get(a, j * width, i, j);\n}\n" }, { "answer_id": 365843, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::vector< std::vector<int> > v;\nv.resize(rows, std::vector<int>(cols, 42)); // init value is 42\nv[row][col] = ...;\n std::vector std::vector col_count * row + col std::vector<int> v(col_count * row_count, 42);\nv[col_count * row + col) = ...;\n [x][y] v.size() v[0].size() boost::multi_array int ** rows = new int*[row_count];\nfor(std::size_t i = 0; i < row_count; i++) {\n rows[i] = new int[cols_count];\n std::fill(rows[i], rows[i] + cols_count, 42);\n}\n\n// use it... rows[row][col] then free it...\n\nfor(std::size_t i = 0; i < row_count; i++) {\n delete[] rows[i];\n}\n\ndelete[] rows;\n" }, { "answer_id": 365990, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 2, "selected": false, "text": "rows * columns * sizeof(datatype) int array [ rows ] [ columns ];\n int array [ rows * columns ]\n int * array = malloc ( rows * columns * sizeof(int) );\n int main( int argc, char ** argv )\n{\n assert( argc > 2 );\n\n int rows = atoi( argv[1] );\n int columns = atoi( argv[2] );\n\n assert(rows > 0 && columns > 0);\n int data [ rows ] [ columns ]; // Yes, legal!\n\n memset( &data, 0, sizeof(data) );\n\n print( rows, columns, data );\n manipulate( rows, columns, data );\n print( rows, columns, data );\n}\n void manipulate( int theRows, int theColumns, int theData[theRows][theColumns] )\n{\n for ( int r = 0; r < theRows; r ++ )\n for ( int c = 0; c < theColumns; c ++ )\n theData[r][c] = r*10 + c;\n}\n int *array = new int[rows * cols]();\n std::vector<int> array(rows * cols);\n void manipulate( int theRows, int theColumns, int *theData )\n{\n for ( int r = 0; r < theRows; r ++ )\n for ( int c = 0; c < theColumns; c ++ )\n theData[r * theColumns + c] = r*10 + c;\n}\n" }, { "answer_id": 366066, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "// First dimension\nint** array = new int*[3];\nfor( int i = 0; i < 3; ++i )\n{\n // Second dimension\n array[i] = new int[4];\n}\n\n// You can then access your array data with\nfor( int i = 0; i < 3; ++i )\n{\n for( int j = 0; j < 4; ++j )\n {\n std::cout << array[i][j];\n }\n}\n int* buffer = new int[3*4]; \nint** array = new int*[3];\n\nfor( int i = 0; i < 3; ++i )\n{\n array[i] = array + i * 4;\n}\n // You can then access your array data with\nfor( int i = 0; i < 3; ++i )\n{\n for( int j = 0; j < 4; ++j )\n {\n const int index = i * 4 + j;\n std::cout << buffer[index];\n }\n}\n" }, { "answer_id": 366749, "author": "lillq", "author_id": 2064, "author_profile": "https://Stackoverflow.com/users/2064", "pm_score": 0, "selected": false, "text": "main()\n{\n int i;\n int rows;\n int cols;\n int **array = NULL;\n\n array = malloc(sizeof(int*) * rows);\n if (array == NULL)\n return 0; // check for malloc fail\n\n for (i = 0; i < rows; i++)\n {\n array[i] = malloc(sizeof(int) * cols)\n if (array[i] == NULL)\n return 0; // check for malloc fail\n }\n\n // and now you have a dynamically sized array\n}\n" }, { "answer_id": 27978290, "author": "user2880576", "author_id": 2880576, "author_profile": "https://Stackoverflow.com/users/2880576", "pm_score": 1, "selected": false, "text": "template <typename T> \nclass Array2D {\nprivate:\n std::unique_ptr<T> managed_array_;\n T* array_;\n size_t x_, y_;\n\npublic:\n Array2D(size_t x, size_t y) {\n managed_array_.reset(new T[x * y]);\n array_ = managed_array_.get();\n y_ = y;\n }\n T* operator[](size_t x) const {\n return &array_[x * y_];\n }\n};\n auto a = Array2D<int>(x, y);\na[xi][yi] = 42;\n" }, { "answer_id": 27978475, "author": "cmaster - reinstate monica", "author_id": 2445184, "author_profile": "https://Stackoverflow.com/users/2445184", "pm_score": 3, "selected": false, "text": "void manipulate(int rows, int cols, int (*data)[cols]) {\n for(int i=0; i < rows; i++) {\n for(int j=0; j < cols; j++) {\n printf(\"%d \", data[i][j]); \n }\n printf(\"\\n\");\n }\n}\n\nint main() {\n int rows = ...;\n int cols = ...;\n int (*data)[cols] = malloc(rows*sizeof(*data));\n manipulate(rows, cols, data);\n free(data);\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34957/" ]
365,805
<p>W3c validator didn't ding me on this, but I was curious if anyone else had an opinion on placing html comments outside of the html tags?</p> <pre> ... &lt;/body&gt; &lt;/html&gt; &lt;!-- byee --&gt; </pre> <p>I have an application and am outputting some data and want it to be the absolute last thing that is done, which unfortunately means I've already attached my last &lt;/html&gt;. </p>
[ { "answer_id": 33569915, "author": "BernardF", "author_id": 1517981, "author_profile": "https://Stackoverflow.com/users/1517981", "pm_score": 1, "selected": false, "text": ".directive replace Template for directive 'yourDirective' must have exactly one root element." } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
365,817
<p>A programmer I know has a website that is fully Standards Compliant. It uses Unicode-encoded fully-validated XHTML 1.1 with CSS. The pages are frames-free, table-free and JavaScript-free.</p> <p>He would like to be directed to a blogging tool that does not demand any particular database system or web server, but does create static pages that comply with the above standards and best practices and is itself a professionally finished native Windows application.</p> <p>...and it should be able to produce an RSS feed as well.</p> <p>Is there anything out there that comes close to this?</p>
[ { "answer_id": 33569915, "author": "BernardF", "author_id": 1517981, "author_profile": "https://Stackoverflow.com/users/1517981", "pm_score": 1, "selected": false, "text": ".directive replace Template for directive 'yourDirective' must have exactly one root element." } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30176/" ]
365,820
<p>How do you rotate an image using <a href="http://code.google.com/p/jquery-rotate/" rel="nofollow noreferrer">jQuery-rotate</a> plugin?</p> <p>I have tried the following and it doesn't seem to work:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=windows-1252"&gt; &lt;title&gt;View Photo&lt;/title&gt; &lt;script type="text/javascript" src="scripts/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/jquery.rotate.1-1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var angle = 0; setInterval ( function (e) { rotate(); }, 100 ); function rotate() { angle = angle + 1; $('#pic').rotate(angle); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;img border="0" src="player.gif" name="pic" id="pic"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Other methods that are supported by most browsers are wanted too, thanks!</p>
[ { "answer_id": 1710976, "author": "jvan", "author_id": 208144, "author_profile": "https://Stackoverflow.com/users/208144", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\n//<![CDATA[\n var angle = 1;\n\n $(document).ready(function() {\n setInterval(function() {\n $(\"#pic\").rotate(angle);\n /* angle += 1; Increases the rotating speed */\n }, 100);\n });\n//]]>\n</script>\n" }, { "answer_id": 3380355, "author": "Spencer", "author_id": 407733, "author_profile": "https://Stackoverflow.com/users/407733", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n//<![CDATA[\n var angle = 1;\n\n $(document).ready(function(angle) {\n setInterval(function(angle) {\n $(\"#pic\").rotate(angle);\n /* angle += 1; Increases the rotating speed */\n }, 100);\n });\n//]]>\n</script>\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45974/" ]
365,823
<p>Curious to get people's thoughts. I conduct frequent interviews, and have had enough in my career to reflect on them, and I've noticed a broad array of questions. I made this c++ specific, but it's worth noting that I have had people ask me algorithmic complexity questions over the phone, and I don't even mean what is the complexity of a hash lookup vs. a binary tree, I mean more like analytical problems, such as "imagine there are 4 bumble bees, each buzzing bla bla bla."</p> <p>Now personally I prefer to keep phone screens a little more concrete, and leave the abstract questions for the white board. So when conducting c++ phone interviews, what kind of topics do you cover, especially for Sr. developers?</p> <p>I know there is another thread similar to this, but frankly it seems to completely have missed the point that this is about phone screens, not interviews that are face to face. Plus this is more c++ specific.</p>
[ { "answer_id": 365862, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 5, "selected": true, "text": "a = b++ + b++? a = b++ + b++" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44996/" ]
365,826
<p>How do I calculate distance between two GPS coordinates (using latitude and longitude)?</p>
[ { "answer_id": 365853, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 10, "selected": true, "text": "radians = degrees * PI / 180 function degreesToRadians(degrees) {\n return degrees * Math.PI / 180;\n}\n\nfunction distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {\n var earthRadiusKm = 6371;\n\n var dLat = degreesToRadians(lat2-lat1);\n var dLon = degreesToRadians(lon2-lon1);\n\n lat1 = degreesToRadians(lat1);\n lat2 = degreesToRadians(lat2);\n\n var a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n return earthRadiusKm * c;\n}\n distanceInKmBetweenEarthCoordinates(0,0,0,0) // Distance between same \n // points should be 0\n0\n\ndistanceInKmBetweenEarthCoordinates(51.5, 0, 38.8, -77.1) // From London\n // to Arlington\n5918.185064088764\n" }, { "answer_id": 365857, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 2, "selected": false, "text": "local EARTH_RAD = 6378137.0 \n -- earth's radius in meters (official geoid datum, not 20,000km / pi)\n\nlocal radmiles = EARTH_RAD*100.0/2.54/12.0/5280.0;\n -- earth's radius in miles\n\nlocal multipliers = {\n radians = 1, miles = radmiles, mi = radmiles, feet = radmiles * 5280,\n meters = EARTH_RAD, m = EARTH_RAD, km = EARTH_RAD / 1000, \n degrees = 360 / (2 * math.pi), min = 60 * 360 / (2 * math.pi)\n}\n\nfunction gcdist(pt1, pt2, units) -- return distance in radians or given units\n --- this formula works best for points close together or antipodal\n --- rounding error strikes when distance is one-quarter Earth's circumference\n --- (ref: wikipedia Great-circle distance)\n if not pt1.radians then pt1 = rad(pt1) end\n if not pt2.radians then pt2 = rad(pt2) end\n local sdlat = sin((pt1.lat - pt2.lat) / 2.0);\n local sdlon = sin((pt1.lon - pt2.lon) / 2.0);\n local res = sqrt(sdlat * sdlat + cos(pt1.lat) * cos(pt2.lat) * sdlon * sdlon);\n res = res > 1 and 1 or res < -1 and -1 or res\n res = 2 * asin(res);\n if units then return res * assert(multipliers[units])\n else return res\n end\nend\n" }, { "answer_id": 501224, "author": "Marko Tintor", "author_id": 61003, "author_profile": "https://Stackoverflow.com/users/61003", "pm_score": 5, "selected": false, "text": "SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))\n-- computes distance in meters using eliptical model, accurate to the mm\n" }, { "answer_id": 1416950, "author": "Peter Greis", "author_id": 172680, "author_profile": "https://Stackoverflow.com/users/172680", "pm_score": 6, "selected": false, "text": "#include <math.h>\n#include \"haversine.h\"\n\n#define d2r (M_PI / 180.0)\n\n//calculate haversine distance for linear distance\ndouble haversine_km(double lat1, double long1, double lat2, double long2)\n{\n double dlong = (long2 - long1) * d2r;\n double dlat = (lat2 - lat1) * d2r;\n double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);\n double c = 2 * atan2(sqrt(a), sqrt(1-a));\n double d = 6367 * c;\n\n return d;\n}\n\ndouble haversine_mi(double lat1, double long1, double lat2, double long2)\n{\n double dlong = (long2 - long1) * d2r;\n double dlat = (lat2 - lat1) * d2r;\n double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2);\n double c = 2 * atan2(sqrt(a), sqrt(1-a));\n double d = 3956 * c; \n\n return d;\n}\n" }, { "answer_id": 2922582, "author": "Mike Chamberlain", "author_id": 289319, "author_profile": "https://Stackoverflow.com/users/289319", "pm_score": 4, "selected": false, "text": "double CalculateGreatCircleDistance(double lat1, double long1, double lat2, double long2, double radius)\n{\n return radius * Math.Acos(\n Math.Sin(lat1) * Math.Sin(lat2)\n + Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(long2 - long1));\n}\n" }, { "answer_id": 6679079, "author": "Henry Vilinskiy", "author_id": 842683, "author_profile": "https://Stackoverflow.com/users/842683", "pm_score": 3, "selected": false, "text": "Create Function [dbo].[DistanceInMiles] \n ( @fromLatitude float ,\n @fromLongitude float ,\n @toLatitude float, \n @toLongitude float\n )\n returns float\nAS \nBEGIN\ndeclare @distance float\n\nselect @distance = cast((3963 * ACOS(round(COS(RADIANS(90-@fromLatitude))*COS(RADIANS(90-@toLatitude))+ \nSIN(RADIANS(90-@fromLatitude))*SIN(RADIANS(90-@toLatitude))*COS(RADIANS(@fromLongitude-@toLongitude)),15)) \n)as float) \n return round(@distance,1)\nEND\n" }, { "answer_id": 6789596, "author": "Elanchezhian Babu P", "author_id": 857851, "author_profile": "https://Stackoverflow.com/users/857851", "pm_score": 2, "selected": false, "text": " private double deg2rad(double deg)\n {\n return (deg * Math.PI / 180.0);\n }\n\n private double rad2deg(double rad)\n {\n return (rad / Math.PI * 180.0);\n }\n\n private double GetDistance(double lat1, double lon1, double lat2, double lon2)\n {\n //code for Distance in Kilo Meter\n double theta = lon1 - lon2;\n double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));\n dist = Math.Abs(Math.Round(rad2deg(Math.Acos(dist)) * 60 * 1.1515 * 1.609344 * 1000, 0));\n return (dist);\n }\n\n private double GetDirection(double lat1, double lon1, double lat2, double lon2)\n {\n //code for Direction in Degrees\n double dlat = deg2rad(lat1) - deg2rad(lat2);\n double dlon = deg2rad(lon1) - deg2rad(lon2);\n double y = Math.Sin(dlon) * Math.Cos(lat2);\n double x = Math.Cos(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) - Math.Sin(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(dlon);\n double direct = Math.Round(rad2deg(Math.Atan2(y, x)), 0);\n if (direct < 0)\n direct = direct + 360;\n return (direct);\n }\n\n private double GetSpeed(double lat1, double lon1, double lat2, double lon2, DateTime CurTime, DateTime PrevTime)\n {\n //code for speed in Kilo Meter/Hour\n TimeSpan TimeDifference = CurTime.Subtract(PrevTime);\n double TimeDifferenceInSeconds = Math.Round(TimeDifference.TotalSeconds, 0);\n double theta = lon1 - lon2;\n double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));\n dist = rad2deg(Math.Acos(dist)) * 60 * 1.1515 * 1.609344;\n double Speed = Math.Abs(Math.Round((dist / Math.Abs(TimeDifferenceInSeconds)) * 60 * 60, 0));\n return (Speed);\n }\n\n private double GetDuration(DateTime CurTime, DateTime PrevTime)\n {\n //code for speed in Kilo Meter/Hour\n TimeSpan TimeDifference = CurTime.Subtract(PrevTime);\n double TimeDifferenceInSeconds = Math.Abs(Math.Round(TimeDifference.TotalSeconds, 0));\n return (TimeDifferenceInSeconds);\n }\n" }, { "answer_id": 7149950, "author": "Random Dev", "author_id": 76051, "author_profile": "https://Stackoverflow.com/users/76051", "pm_score": 2, "selected": false, "text": "\nlet GreatCircleDistance<[<Measure>] 'u> (R : float<'u>) (p1 : Location) (p2 : Location) =\n let degToRad (x : float<deg>) = System.Math.PI * x / 180.0<deg/rad>\n\n let sq x = x * x\n // take the sin of the half and square the result\n let sinSqHf (a : float<rad>) = (System.Math.Sin >> sq) (a / 2.0<rad>)\n let cos (a : float<deg>) = System.Math.Cos (degToRad a / 1.0<rad>)\n\n let dLat = (p2.Latitude - p1.Latitude) |> degToRad\n let dLon = (p2.Longitude - p1.Longitude) |> degToRad\n\n let a = sinSqHf dLat + cos p1.Latitude * cos p2.Latitude * sinSqHf dLon\n let c = 2.0 * System.Math.Atan2(System.Math.Sqrt(a), System.Math.Sqrt(1.0-a))\n\n R * c\n" }, { "answer_id": 7595937, "author": "Roman Makarov", "author_id": 970916, "author_profile": "https://Stackoverflow.com/users/970916", "pm_score": 6, "selected": false, "text": "double _eQuatorialEarthRadius = 6378.1370D;\ndouble _d2r = (Math.PI / 180D);\n\nprivate int HaversineInM(double lat1, double long1, double lat2, double long2)\n{\n return (int)(1000D * HaversineInKM(lat1, long1, lat2, long2));\n}\n\nprivate double HaversineInKM(double lat1, double long1, double lat2, double long2)\n{\n double dlong = (long2 - long1) * _d2r;\n double dlat = (lat2 - lat1) * _d2r;\n double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D);\n double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a));\n double d = _eQuatorialEarthRadius * c;\n\n return d;\n}\n" }, { "answer_id": 11429615, "author": "Maxs", "author_id": 82063, "author_profile": "https://Stackoverflow.com/users/82063", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION `CalculateDistanceInKm`(\n fromLatitude float,\n fromLongitude float,\n toLatitude float, \n toLongitude float\n) RETURNS float\nBEGIN\n declare distance float;\n\n select \n 6367 * ACOS(\n round(\n COS(RADIANS(90-fromLatitude)) *\n COS(RADIANS(90-toLatitude)) +\n SIN(RADIANS(90-fromLatitude)) *\n SIN(RADIANS(90-toLatitude)) *\n COS(RADIANS(fromLongitude-toLongitude))\n ,15)\n )\n into distance;\n\n return round(distance,3);\nEND;\n" }, { "answer_id": 13069278, "author": "TheLukeMcCarthy", "author_id": 409119, "author_profile": "https://Stackoverflow.com/users/409119", "pm_score": 2, "selected": false, "text": "Function MetresDistanceBetweenTwoGPSCoordinates($latitude1, $longitude1, $latitude2, $longitude2) \n{ \n $Rad = ([math]::PI / 180); \n\n $earthsRadius = 6378.1370 # Earth's Radius in KM \n $dLat = ($latitude2 - $latitude1) * $Rad \n $dLon = ($longitude2 - $longitude1) * $Rad \n $latitude1 = $latitude1 * $Rad \n $latitude2 = $latitude2 * $Rad \n\n $a = [math]::Sin($dLat / 2) * [math]::Sin($dLat / 2) + [math]::Sin($dLon / 2) * [math]::Sin($dLon / 2) * [math]::Cos($latitude1) * [math]::Cos($latitude2) \n $c = 2 * [math]::ATan2([math]::Sqrt($a), [math]::Sqrt(1-$a)) \n\n $distance = [math]::Round($earthsRadius * $c * 1000, 0) #Multiple by 1000 to get metres \n\n Return $distance \n}\n" }, { "answer_id": 14459730, "author": "Paulo Miguel Almeida", "author_id": 832748, "author_profile": "https://Stackoverflow.com/users/832748", "pm_score": 5, "selected": false, "text": "public class HaversineAlgorithm {\n\n static final double _eQuatorialEarthRadius = 6378.1370D;\n static final double _d2r = (Math.PI / 180D);\n\n public static int HaversineInM(double lat1, double long1, double lat2, double long2) {\n return (int) (1000D * HaversineInKM(lat1, long1, lat2, long2));\n }\n\n public static double HaversineInKM(double lat1, double long1, double lat2, double long2) {\n double dlong = (long2 - long1) * _d2r;\n double dlat = (lat2 - lat1) * _d2r;\n double a = Math.pow(Math.sin(dlat / 2D), 2D) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r)\n * Math.pow(Math.sin(dlong / 2D), 2D);\n double c = 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));\n double d = _eQuatorialEarthRadius * c;\n\n return d;\n }\n\n}\n" }, { "answer_id": 18144531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "from math import pi,sqrt,sin,cos,atan2\n\ndef haversine(pos1, pos2):\n lat1 = float(pos1['lat'])\n long1 = float(pos1['long'])\n lat2 = float(pos2['lat'])\n long2 = float(pos2['long'])\n\n degree_to_rad = float(pi / 180.0)\n\n d_lat = (lat2 - lat1) * degree_to_rad\n d_long = (long2 - long1) * degree_to_rad\n\n a = pow(sin(d_lat / 2), 2) + cos(lat1 * degree_to_rad) * cos(lat2 * degree_to_rad) * pow(sin(d_long / 2), 2)\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n km = 6367 * c\n mi = 3956 * c\n\n return {\"km\":km, \"miles\":mi}\n" }, { "answer_id": 21262510, "author": "Tod Samay", "author_id": 3116023, "author_profile": "https://Stackoverflow.com/users/3116023", "pm_score": 3, "selected": false, "text": "double calcDistanceByHaversine(double rLat1, double rLon1, double rHeading1,\n double rLat2, double rLon2, double rHeading2){\n double rDLatRad = 0.0;\n double rDLonRad = 0.0;\n double rLat1Rad = 0.0;\n double rLat2Rad = 0.0;\n double a = 0.0;\n double c = 0.0;\n double rResult = 0.0;\n double rEarthRadius = 0.0;\n double rDHeading = 0.0;\n double rDHeadingRad = 0.0;\n\n if ((rLat1 < -90.0) || (rLat1 > 90.0) || (rLat2 < -90.0) || (rLat2 > 90.0)\n || (rLon1 < -180.0) || (rLon1 > 180.0) || (rLon2 < -180.0)\n || (rLon2 > 180.0)) {\n return -1;\n };\n\n rDLatRad = (rLat2 - rLat1) * DEGREE_TO_RADIANS;\n rDLonRad = (rLon2 - rLon1) * DEGREE_TO_RADIANS;\n rLat1Rad = rLat1 * DEGREE_TO_RADIANS;\n rLat2Rad = rLat2 * DEGREE_TO_RADIANS;\n\n a = sin(rDLatRad / 2) * sin(rDLatRad / 2) + sin(rDLonRad / 2) * sin(\n rDLonRad / 2) * cos(rLat1Rad) * cos(rLat2Rad);\n\n if (a == 0.0) {\n return 0.0;\n }\n\n c = 2 * atan2(sqrt(a), sqrt(1 - a));\n rEarthRadius = 6378.1370 - (21.3847 * 90.0 / ((fabs(rLat1) + fabs(rLat2))\n / 2.0));\n rResult = rEarthRadius * c;\n\n // Chord to Arc Correction based on Heading changes. Important for routes with many turns and U-turns\n\n if ((rHeading1 >= 0.0) && (rHeading1 < 360.0) && (rHeading2 >= 0.0)\n && (rHeading2 < 360.0)) {\n rDHeading = fabs(rHeading1 - rHeading2);\n if (rDHeading > 180.0) {\n rDHeading -= 180.0;\n }\n rDHeadingRad = rDHeading * DEGREE_TO_RADIANS;\n if (rDHeading > 5.0) {\n rResult = rResult * (rDHeadingRad / (2.0 * sin(rDHeadingRad / 2)));\n } else {\n rResult = rResult / cos(rDHeadingRad);\n }\n }\n return rResult;\n}\n" }, { "answer_id": 27590190, "author": "Przemek", "author_id": 1981559, "author_profile": "https://Stackoverflow.com/users/1981559", "pm_score": 2, "selected": false, "text": " def deg2rad(deg: Double) = deg * Math.PI / 180.0\n\n def rad2deg(rad: Double) = rad / Math.PI * 180.0\n\n def getDistanceMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double) = {\n val theta = lon1 - lon2\n val dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) *\n Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta))\n Math.abs(\n Math.round(\n rad2deg(Math.acos(dist)) * 60 * 1.1515 * 1.609344 * 1000)\n )\n }\n" }, { "answer_id": 28212561, "author": "quape", "author_id": 1776334, "author_profile": "https://Stackoverflow.com/users/1776334", "pm_score": 4, "selected": false, "text": "deg2rad() $R = 6371; // km\n$dLat = deg2rad($lat2-$lat1);\n$dLon = deg2rad($lon2-$lon1);\n$lat1 = deg2rad($lat1);\n$lat2 = deg2rad($lat2);\n\n$a = sin($dLat/2) * sin($dLat/2) +\n sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2); \n\n$c = 2 * atan2(sqrt($a), sqrt(1-$a)); \n$d = $R * $c;\n" }, { "answer_id": 34486089, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 4, "selected": false, "text": "function distance(lat1, lon1, lat2, lon2) {\n var p = 0.017453292519943295; // Math.PI / 180\n var c = Math.cos;\n var a = 0.5 - c((lat2 - lat1) * p)/2 + \n c(lat1 * p) * c(lat2 * p) * \n (1 - c((lon2 - lon1) * p))/2;\n\n return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km\n}\n from math import cos, asin, sqrt\ndef distance(lat1, lon1, lat2, lon2):\n p = 0.017453292519943295\n a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2\n return 12742 * asin(sqrt(a))\n" }, { "answer_id": 41748819, "author": "Tim Partridge", "author_id": 224976, "author_profile": "https://Stackoverflow.com/users/224976", "pm_score": 3, "selected": false, "text": "using System.Device.Location;\n\ndouble lat1 = 45.421527862548828D;\ndouble long1 = -75.697189331054688D;\ndouble lat2 = 53.64135D;\ndouble long2 = -113.59273D;\n\nGeoCoordinate geo1 = new GeoCoordinate(lat1, long1);\nGeoCoordinate geo2 = new GeoCoordinate(lat2, long2);\n\ndouble distance = geo1.GetDistanceTo(geo2);\n" }, { "answer_id": 45670322, "author": "Sai Li", "author_id": 5793247, "author_profile": "https://Stackoverflow.com/users/5793247", "pm_score": 3, "selected": false, "text": "func degreesToRadians(degrees: Double) -> Double {\n return degrees * Double.pi / 180\n}\n\nfunc distanceInKmBetweenEarthCoordinates(lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> Double {\n\n let earthRadiusKm: Double = 6371\n\n let dLat = degreesToRadians(degrees: lat2 - lat1)\n let dLon = degreesToRadians(degrees: lon2 - lon1)\n\n let lat1 = degreesToRadians(degrees: lat1)\n let lat2 = degreesToRadians(degrees: lat2)\n\n let a = sin(dLat/2) * sin(dLat/2) +\n sin(dLon/2) * sin(dLon/2) * cos(lat1) * cos(lat2)\n let c = 2 * atan2(sqrt(a), sqrt(1 - a))\n return earthRadiusKm * c\n}\n" }, { "answer_id": 48244460, "author": "Peter Perháč", "author_id": 81520, "author_profile": "https://Stackoverflow.com/users/81520", "pm_score": 2, "selected": false, "text": "import java.lang.Math.{atan2, cos, sin, sqrt}\n\ndef latLonDistance(lat1: Double, lon1: Double)(lat2: Double, lon2: Double): Double = {\n val earthRadiusKm = 6371\n val dLat = (lat2 - lat1).toRadians\n val dLon = (lon2 - lon1).toRadians\n val latRad1 = lat1.toRadians\n val latRad2 = lat2.toRadians\n\n val a = sin(dLat / 2) * sin(dLat / 2) + sin(dLon / 2) * sin(dLon / 2) * cos(latRad1) * cos(latRad2)\n val c = 2 * atan2(sqrt(a), sqrt(1 - a))\n earthRadiusKm * c\n}\n" }, { "answer_id": 53114943, "author": "mroach", "author_id": 642978, "author_profile": "https://Stackoverflow.com/users/642978", "pm_score": 2, "selected": false, "text": "defmodule Geo do\n @earth_radius_km 6371\n @earth_radius_sm 3958.748\n @earth_radius_nm 3440.065\n @feet_per_sm 5280\n\n @d2r :math.pi / 180\n\n def deg_to_rad(deg), do: deg * @d2r\n\n def great_circle_distance(p1, p2, :km), do: haversine(p1, p2) * @earth_radius_km\n def great_circle_distance(p1, p2, :sm), do: haversine(p1, p2) * @earth_radius_sm\n def great_circle_distance(p1, p2, :nm), do: haversine(p1, p2) * @earth_radius_nm\n def great_circle_distance(p1, p2, :m), do: great_circle_distance(p1, p2, :km) * 1000\n def great_circle_distance(p1, p2, :ft), do: great_circle_distance(p1, p2, :sm) * @feet_per_sm\n\n @doc \"\"\"\n Calculate the [Haversine](https://en.wikipedia.org/wiki/Haversine_formula)\n distance between two coordinates. Result is in radians. This result can be\n multiplied by the sphere's radius in any unit to get the distance in that unit.\n For example, multiple the result of this function by the Earth's radius in\n kilometres and you get the distance between the two given points in kilometres.\n \"\"\"\n def haversine({lat1, lon1}, {lat2, lon2}) do\n dlat = deg_to_rad(lat2 - lat1)\n dlon = deg_to_rad(lon2 - lon1)\n\n radlat1 = deg_to_rad(lat1)\n radlat2 = deg_to_rad(lat2)\n\n a = :math.pow(:math.sin(dlat / 2), 2) +\n :math.pow(:math.sin(dlon / 2), 2) *\n :math.cos(radlat1) * :math.cos(radlat2)\n\n 2 * :math.atan2(:math.sqrt(a), :math.sqrt(1 - a))\n end\nend\n" }, { "answer_id": 56499934, "author": "abd3llatif", "author_id": 7316824, "author_profile": "https://Stackoverflow.com/users/7316824", "pm_score": 1, "selected": false, "text": "import 'dart:math';\n\nclass GeoUtils {\n\n static double _degreesToRadians(degrees) {\n return degrees * pi / 180;\n }\n\n static double distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {\n var earthRadiusKm = 6371;\n\n var dLat = _degreesToRadians(lat2-lat1);\n var dLon = _degreesToRadians(lon2-lon1);\n\n lat1 = _degreesToRadians(lat1);\n lat2 = _degreesToRadians(lat2);\n\n var a = sin(dLat/2) * sin(dLat/2) +\n sin(dLon/2) * sin(dLon/2) * cos(lat1) * cos(lat2);\n var c = 2 * atan2(sqrt(a), sqrt(1-a));\n return earthRadiusKm * c;\n }\n}\n" }, { "answer_id": 61058800, "author": "shghm", "author_id": 12552884, "author_profile": "https://Stackoverflow.com/users/12552884", "pm_score": 0, "selected": false, "text": "gpsdistance<-function(lat1,lon1,lat2,lon2){\n\n# internal function to change deg to rad\n\ndegreesToRadians<- function (degrees) {\nreturn (degrees * pi / 180)\n}\n\nR<-6371e3 #radius of Earth in meters\n\nphi1<-degreesToRadians(lat1) # latitude 1\nphi2<-degreesToRadians(lat2) # latitude 2\nlambda1<-degreesToRadians(lon1) # longitude 1\nlambda2<-degreesToRadians(lon2) # longitude 2\n\ndelta_phi<-phi1-phi2 # latitude-distance\ndelta_lambda<-lambda1-lambda2 # longitude-distance\n\na<-sin(delta_phi/2)*sin(delta_phi/2)+\ncos(phi1)*cos(phi2)*sin(delta_lambda/2)*\nsin(delta_lambda/2)\n\ncc<-2*atan2(sqrt(a),sqrt(1-a))\n\ndistance<- R * cc\n\nreturn(distance) # in meters\n}\n" }, { "answer_id": 61990886, "author": "Csaba Toth", "author_id": 292502, "author_profile": "https://Stackoverflow.com/users/292502", "pm_score": 2, "selected": false, "text": "import kotlin.math.*\n\nclass HaversineAlgorithm {\n\n companion object {\n private const val MEAN_EARTH_RADIUS = 6371.008\n private const val D2R = Math.PI / 180.0\n }\n\n private fun haversineInKm(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {\n val lonDiff = (lon2 - lon1) * D2R\n val latDiff = (lat2 - lat1) * D2R\n val latSin = sin(latDiff / 2.0)\n val lonSin = sin(lonDiff / 2.0)\n val a = latSin * latSin + (cos(lat1 * D2R) * cos(lat2 * D2R) * lonSin * lonSin)\n val c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))\n return MEAN_EARTH_RADIUS * c\n }\n}\n" }, { "answer_id": 66463472, "author": "Lakpriya Senevirathna", "author_id": 9708440, "author_profile": "https://Stackoverflow.com/users/9708440", "pm_score": 0, "selected": false, "text": "public static double degreesToRadians(double degrees) {\n return degrees * Math.PI / 180;\n}\n\npublic static double distanceInKmBetweenEarthCoordinates(Location location1, Location location2) {\n double earthRadiusKm = 6371;\n\n double dLat = degreesToRadians(location2.getLatitude()-location1.getLatitude());\n double dLon = degreesToRadians(location2.getLongitude()-location1.getLongitude());\n\n double lat1 = degreesToRadians(location1.getLatitude());\n double lat2 = degreesToRadians(location2.getLatitude());\n\n double a = Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n return earthRadiusKm * c;\n}\n" }, { "answer_id": 67004536, "author": "bLight", "author_id": 6809916, "author_profile": "https://Stackoverflow.com/users/6809916", "pm_score": 0, "selected": false, "text": "function GreatCircleDistance(const Lat1, Long1, Lat2, Long2: Double): Double;\nvar\n Lat1Rad, Long1Rad, Lat2Rad, Long2Rad: Double;\nconst\n EARTH_RADIUS_KM = 6378;\nbegin\n Lat1Rad := DegToRad(Lat1);\n Long1Rad := DegToRad(Long1);\n Lat2Rad := DegToRad(Lat2);\n Long2Rad := DegToRad(Long2);\n Result := EARTH_RADIUS_KM * ArcCos(Cos(Lat1Rad) * Cos(Lat2Rad) * Cos(Long1Rad - Long2Rad) + Sin(Lat1Rad) * Sin(Lat2Rad));\nend;\n" }, { "answer_id": 68195808, "author": "Dean Mark", "author_id": 6374637, "author_profile": "https://Stackoverflow.com/users/6374637", "pm_score": 2, "selected": false, "text": "from geopy.distance import geodesic\nnewport_ri = (41.49008, -71.312796)\ncleveland_oh = (41.499498, -81.695391)\nprint(geodesic(newport_ri, cleveland_oh).km)\n" }, { "answer_id": 69945125, "author": "Jonattan Velásquez", "author_id": 3308761, "author_profile": "https://Stackoverflow.com/users/3308761", "pm_score": 0, "selected": false, "text": "public float Distance(float lat1, float lon1, float lat2, float lon2)\n{\n var earthRadiusKm = 6371;\n\n var dLat = (lat2 - lat1) * Mathf.Rad2Deg;\n var dLon = (lon2 - lon1) * Mathf.Rad2Deg;\n\n var a = Mathf.Sin(dLat / 2) * Mathf.Sin(dLat / 2) +\n Mathf.Sin(dLon / 2) * Mathf.Sin(dLon / 2) * \n Mathf.Cos(lat1 * Mathf.Rad2Deg) * Mathf.Cos(lat2 * Mathf.Rad2Deg);\n\n var c = 2 * Mathf.Atan2(Mathf.Sqrt(a), Mathf.Sqrt(1 - a));\n return earthRadiusKm * c;\n}\n\n" }, { "answer_id": 72209854, "author": "ramzan ali", "author_id": 7181473, "author_profile": "https://Stackoverflow.com/users/7181473", "pm_score": 1, "selected": false, "text": "export const degreeToRadian = (degree: number) => {\n return degree * Math.PI / 180;\n}\n\nexport const distanceBetweenEarthCoordinatesInKm = (lat1: number, lon1: number, lat2: number, lon2: number) => {\n const earthRadiusInKm = 6371;\n\n const dLat = degreeToRadian(lat2 - lat1);\n const dLon = degreeToRadian(lon2 - lon1);\n\n lat1 = degreeToRadian(lat1);\n lat2 = degreeToRadian(lat2);\n\n const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n return earthRadiusInKm * c;\n}\n" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14635/" ]
365,841
<p>My Windows application runs under Wine, but the installation is a bit of a headache for laymen, and the wrappers I've seen online (PlayOnLinux, Wine Doors) require even more packages to be installed. Is there a way to make a package that will install Wine if the user needs it to be installed, install the application and shortcuts, all with minimal user hassle?</p>
[ { "answer_id": 365993, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 3, "selected": false, "text": "msiexec /i /q msiexec" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39702/" ]
365,866
<p><b>Background</b><br /> I'm researching the efficiency of messaging within contemporary web applications, examining the use of alternatives to XML. This is a university project whose results will be released publicly - the greater the participation of the community, the greater the value of the results that are given back.</p> <p>I need as many real-life examples of XML in use as possible so as to:</p> <ul> <li>fully understand to what uses XML is put when host A talks to host B<br /> I can certainly imagine how XML should/may be used. The reality may be quite different.<br />&nbsp;</li> <li>perform tests on actual not hypothetical data<br />How XML performs compared to Technology X on sets of <em>real-life</em> data is of equal importance to how XML compares to Technology X on an <em>arbitrary</em> set of data<br />&nbsp;</li> <li>identify and measure any patterns of use of XML<br />&nbsp;e.g. elements-only, elements plus some attributes or minimal elements and heavy attribute usage</li> </ul> <p><b>The Question</b><br /></p> <p><b>How do <em>you</em> use XML within the world of web applications?</b></p> <p>When Host B returns XML-structured data to Host A over HTTP, what comes back? This may be a server returning data in an AJAX environment or one server collating data from one or more other servers.</p> <p>Ideal answers would include:</p> <ul> <li>A real-life example of XML within an HTTP response</li> <li>The URL, where relevant, to request the above</li> <li>An explanation, if needed, of what the data represents</li> <li>An explanation, if not obvious, of why such messages are being exchanged (e.g. to fulfil a user request; host X returning a health status report to host Y)</li> </ul> <p>I'd prefer examples from applications/services that <i>you've</i> made, developed or worked on, although any examples are welcome. Anything from a 5-line XML document to a 10,000 line monster would be great.</p> <p>Your own opinions on the use of XML in your example would also be wonderful (e.g. we implemented XML-structured responses because of Requirement X/Person Y even though I thought JSON would have been better because ...; or, we use XML to do this because [really good reason] and it's just the best choice for the job).</p> <p><strong>Update</strong><br /> I very much appreciate all answers on the topic of XML in general, however what I'm really looking for is <em>real-life examples of HTTP response bodies containing XML</em>.</p> <p>I'm currently fairly aware of the history of XML, of what common alternatives may exist and how they may compare in features and suitability to given scenarios.</p> <p>What would be of greater benefit would be a impression of how XML is currently used in the exchange of data between HTTP hosts regardless of whether any current usage is correct or suitable. Examples of cases where XML is misapplied are just as valuable as cases where XML is correctly-applied.</p>
[ { "answer_id": 365997, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 0, "selected": false, "text": "~ eval" } ]
2008/12/13
[ "https://Stackoverflow.com/questions/365866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5343/" ]