qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
118,534
<p>Is there a way to manipulate the speed of the video playback? I'm especially interested in a way to slow down with frame blending, exactly like the function in Final Cut Pro. </p>
[ { "answer_id": 535155, "author": "smokris", "author_id": 64860, "author_profile": "https://Stackoverflow.com/users/64860", "pm_score": 3, "selected": false, "text": "Movie Loader Movie Loader Movie Location Billboard Timebase External Movie Loader Patch Time Patch Time Movie Loader Patch Time Movie Loader Patch Time Mathematical Expression t/2 Patch Time Mathematical Expression Mathematical Expression Patch Time Movie Loader t/3 t*2 Integrator Integrator Value 1 Integrator Movie Loader Patch Time Integrator Value 0.5" }, { "answer_id": 6329636, "author": "forresto", "author_id": 592125, "author_profile": "https://Stackoverflow.com/users/592125", "pm_score": 0, "selected": false, "text": "Rate Playhead Seconds" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20824/" ]
118,540
<p>First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.</p> <p>Here's the situation</p> <p>I have an abstract concept of a grid, with Y steps exactly Y_STEP apart (the x steps are working fine so ignore them for now)</p> <p>The grid is in an abstract coordinate space, and to get things to line up I've got a magic offset in there, let's call it Y_OFFSET</p> <p>to snap to the grid I've got the following code (python)</p> <pre><code>def snapToGrid(originalPos, offset, step): index = int((originalPos - offset) / step) #truncates the remainder away return index * gap + offset </code></pre> <p>so I pass the cursor position, Y_OFFSET and Y_STEP into that function and it returns me the nearest floored y position on the grid</p> <p>That appears to work fine in the original scenario, however when I take into account the fact that the view is scrollable things get a little weird.</p> <p>Scrolling is made as basic as I can get it, I've got a viewPort that keeps count of the distance scrolled along the Y Axis and just offsets everything that goes through it.</p> <p>Here's a snippet of the cursor's mouseMotion code:</p> <pre><code>def mouseMotion(self, event): pixelPos = event.pos[Y] odePos = Scroll.pixelPosToOdePos(pixelPos) self.tool.positionChanged(odePos) </code></pre> <p>So there's two things to look at there, first the Scroll module's translation from pixel position to the abstract coordinate space, then the tool's positionChanged function which takes the abstract coordinate space value and snaps to the nearest Y step.</p> <p>Here's the relevant Scroll code</p> <pre><code>def pixelPosToOdePos(pixelPos): offsetPixelPos = pixelPos - self.viewPortOffset return pixelsToOde(offsetPixelPos) def pixelsToOde(pixels): return float(pixels) / float(pixels_in_an_ode_unit) </code></pre> <p>And the tools update code</p> <pre><code>def positionChanged(self, newPos): self.snappedPos = snapToGrid(originalPos, Y_OFFSET, Y_STEP) </code></pre> <p>The last relevant chunk is when the tool goes to render itself. It goes through the Scroll object, which transforms the tool's snapped coordinate space position into an onscreen pixel position, here's the code:</p> <pre><code>#in Tool def render(self, screen): Scroll.render(screen, self.image, self.snappedPos) #in Scroll def render(self, screen, image, odePos): pixelPos = self.odePosToPixelPos(odePos) screen.blit(image, pixelPos) # screen is a surface from pygame for the curious def odePosToPixelPos(self.odePos): offsetPos = odePos + self.viewPortOffset return odeToPixels(offsetPos) def odeToPixels(odeUnits): return int(odeUnits * pixels_in_an_ode_unit) </code></pre> <p>Whew, that was a long explanation. Hope you're still with me... </p> <p>The problem I'm now getting is that when I scroll up the drawn image loses alignment with the cursor.<br> It starts snapping to the Y step exactly 1 step below the cursor. Additionally it appears to phase in and out of allignment.<br> At some scrolls it is out by 1 and other scrolls it is spot on.<br> It's never out by more than 1 and it's always snapping to a valid grid location.</p> <p>Best guess I can come up with is that somewhere I'm truncating some data in the wrong spot, but no idea where or how it ends up with this behavior.</p> <p>Anyone familiar with coordinate spaces, scrolling and snapping?</p>
[ { "answer_id": 118645, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 0, "selected": false, "text": "def positionChanged(self, newPos):\n self.snappedPos = snapToGrid(newPos, Y_OFFSET, Y_STEP)\n def snapToGrid(originalPos, offset, step):\n EPS = 1e-6\n index = int((originalPos - offset) / step + EPS) #truncates the remainder away\n return index * gap + offset\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
118,547
<p>I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).</p> <p>I'd be really grateful if anyone can share some sample C code that can successfully create a zip file on Windows XP/2003. Failing that, if someone can find solid docs or a tutorial that would be great, since MSDN searches don't turn up much. I'm really hoping to avoid having to ship a third-party lib for this, because the functionality is obviously there, I just can't figure out how to access it. Google searches turn up nothing useful, just tantalizing bits and pieces of information. Here's hoping someone in the community has sorted this out and can share it for posterity!</p>
[ { "answer_id": 118606, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 4, "selected": true, "text": "FILE* f = fopen(\"path\", \"wb\");\nfwrite(\"\\x50\\x4B\\x05\\x06\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\", 22, 1, f);\nfclose(f);\n" }, { "answer_id": 121720, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "#include <windows.h>\n#include <shldisp.h>\n#include <tlhelp32.h>\n#include <stdio.h>\n\nint main(int argc, TCHAR* argv[])\n{\n DWORD strlen = 0;\n char szFrom[] = \"C:\\\\Temp\",\n szTo[] = \"C:\\\\Sample.zip\";\n HRESULT hResult;\n IShellDispatch *pISD;\n Folder *pToFolder = NULL;\n VARIANT vDir, vFile, vOpt;\n BSTR strptr1, strptr2;\n\n CoInitialize(NULL);\n\n hResult = CoCreateInstance(CLSID_Shell, NULL, CLSCTX_INPROC_SERVER, IID_IShellDispatch, (void **)&pISD);\n\n if (SUCCEEDED(hResult) && pISD != NULL)\n {\n strlen = MultiByteToWideChar(CP_ACP, 0, szTo, -1, 0, 0);\n strptr1 = SysAllocStringLen(0, strlen);\n MultiByteToWideChar(CP_ACP, 0, szTo, -1, strptr1, strlen);\n\n VariantInit(&vDir);\n vDir.vt = VT_BSTR;\n vDir.bstrVal = strptr1;\n hResult = pISD->NameSpace(vDir, &pToFolder);\n\n if (SUCCEEDED(hResult))\n {\n strlen = MultiByteToWideChar(CP_ACP, 0, szFrom, -1, 0, 0);\n strptr2 = SysAllocStringLen(0, strlen);\n MultiByteToWideChar(CP_ACP, 0, szFrom, -1, strptr2, strlen);\n\n VariantInit(&vFile);\n vFile.vt = VT_BSTR;\n vFile.bstrVal = strptr2;\n\n VariantInit(&vOpt);\n vOpt.vt = VT_I4;\n vOpt.lVal = 4; // Do not display a progress dialog box\n\n hResult = NULL;\n printf(\"Copying %s to %s ...\\n\", szFrom, szTo);\n hResult = pToFolder->CopyHere(vFile, vOpt); //NOTE: this appears to always return S_OK even on error\n /*\n * 1) Enumerate current threads in the process using Thread32First/Thread32Next\n * 2) Start the operation\n * 3) Enumerate the threads again\n * 4) Wait for any new threads using WaitForMultipleObjects\n *\n * Of course, if the operation creates any new threads that don't exit, then you have a problem. \n */\n if (hResult == S_OK) {\n //NOTE: hard-coded for testing - be sure not to overflow the array if > 5 threads exist\n HANDLE hThrd[5]; \n HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPALL ,0); //TH32CS_SNAPMODULE, 0);\n DWORD NUM_THREADS = 0;\n if (h != INVALID_HANDLE_VALUE) {\n THREADENTRY32 te;\n te.dwSize = sizeof(te);\n if (Thread32First(h, &te)) {\n do {\n if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) ) {\n //only enumerate threads that are called by this process and not the main thread\n if((te.th32OwnerProcessID == GetCurrentProcessId()) && (te.th32ThreadID != GetCurrentThreadId()) ){\n //printf(\"Process 0x%04x Thread 0x%04x\\n\", te.th32OwnerProcessID, te.th32ThreadID);\n hThrd[NUM_THREADS] = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);\n NUM_THREADS++;\n }\n }\n te.dwSize = sizeof(te);\n } while (Thread32Next(h, &te));\n }\n CloseHandle(h);\n\n printf(\"waiting for all threads to exit...\\n\");\n //Wait for all threads to exit\n WaitForMultipleObjects(NUM_THREADS, hThrd , TRUE , INFINITE);\n\n //Close All handles\n for ( DWORD i = 0; i < NUM_THREADS ; i++ ){\n CloseHandle( hThrd[i] );\n }\n } //if invalid handle\n } //if CopyHere() hResult is S_OK\n\n SysFreeString(strptr2);\n pToFolder->Release();\n }\n\n SysFreeString(strptr1);\n pISD->Release();\n }\n\n CoUninitialize();\n\n printf (\"Press ENTER to exit\\n\");\n getchar();\n return 0;\n\n}\n HZIP newZip = CreateZip(\"C:\\\\Sample.zip\", NULL, ZIP_FILENAME);\nBOOL retval = AddFolderContent(newZip, \"C:\", \"temp\");\n if (ZipAdd(hZip, RelativePathNewFileFound, RelativePathNewFileFound, 0, ZIP_FILENAME) != ZR_OK)\n ZRESULT ret;\nTCHAR real_path[MAX_PATH] = {0};\n_tcscat(real_path, AbsolutePath);\n_tcscat(real_path, RelativePathNewFileFound);\nif (ZipAdd(hZip, RelativePathNewFileFound, real_path, 0, ZIP_FILENAME) != ZR_OK)\n" }, { "answer_id": 230762, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "FILE* f = fopen(\"path\", \"wb\"); \nfwrite(\"\\x50\\x4B\\x05\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\", 22, 1, f);\nfclose(f);\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20840/" ]
118,565
<p>Say I have a web service <a href="http://www.example.com/webservice.pl?q=google" rel="noreferrer">http://www.example.com/webservice.pl?q=google</a> which returns text "google.com". I need to call this web service (<a href="http://www.example.com/webservice.pl" rel="noreferrer">http://www.example.com/webservice.pl</a>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.</p> <p>What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.</p>
[ { "answer_id": 118574, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "$.get(\n \"http://xyz.com/webservice.pl\",\n { q : \"google\" },\n function(data) {\n alert(data); // \"google.com\"\n }\n);\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ]
118,591
<p>I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:</p> <pre><code>find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \; </code></pre> <p>I am familiar with the os.name and getpass.getuser for the most general cross-platform elements. I also have this function to generate a list of the full names of all the files in the equivalent of ~/podcasts/current:</p> <pre><code>def AllFiles(filepath, depth=1, flist=[]): fpath=os.walk(filepath) fpath=[item for item in fpath] while depth &lt; len(fpath): for item in fpath[depth][-1]: flist.append(fpath[depth][0]+os.sep+item) depth+=1 return flist </code></pre> <p>First off, there must be a better way to do that, any suggestion welcome. Either way, for example, "AllFiles('/users/me/music/itunes/itunes music/podcasts')" gives the relevant list, on Windows. Presumably I should be able to go over this list and call os.stat(list_member).st_mtime and move all the stuff older than a certain number in days to the archive; I am a little stuck on that bit.</p> <p>Of course, anything with the concision of the bash command would also be illuminating.</p>
[ { "answer_id": 118647, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "find find" }, { "answer_id": 118658, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "import os, stat\nos.stat(\"test\")[stat.ST_MTIME]\n walk_results[2] walk_results[1]" }, { "answer_id": 118817, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 4, "selected": true, "text": "import os\nimport shutil\nfrom os import path\nfrom os.path import join, getmtime\nfrom time import time\n\narchive = \"bak\"\ncurrent = \"cur\"\n\ndef archive_old_versions(days = 3):\n for root, dirs, files in os.walk(current):\n for name in files:\n fullname = join(root, name)\n if (getmtime(fullname) < time() - days * 60 * 60 * 24):\n shutil.move(fullname, join(archive, name))\n" }, { "answer_id": 118879, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 2, "selected": false, "text": "import subprocess\nsubprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',\n '-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11596/" ]
118,624
<p>Like it says.</p>
[ { "answer_id": 118637, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "<h2> class=\"employee-name\" <p> <ul>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16398/" ]
118,630
<p>I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:</p> <pre><code>const T operator+(const T&amp; lhs, const T&amp; rhs) { return T(lhs) +=rhs; } </code></pre> <p>But it was pointed out to me that this would also work:</p> <pre><code>const T operator+ (T lhs, const T&amp; rhs) { return lhs+=rhs; } </code></pre> <p>In essence, this form transfers creation of the temporary from the body of the implementation to the function call.</p> <p>It seems a little awkward to have different types for the two parameters, but is there anything wrong with the second form? Is there a reason to prefer one over the other?</p>
[ { "answer_id": 119049, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "const T operator+(const T& lhs, const T& rhs)\n{\n return T(lhs)+=rhs;\n}\n" }, { "answer_id": 256351, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "const T operator+(const T& lhs, const T& rhs)\n{\n T temp(lhs);\n temp +=rhs;\n return temp;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1674/" ]
118,632
<p>I need to layout a html datatable with CSS. </p> <p>The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.</p> <p>How can I do this using a simple semantically valid html table and css only?</p> <p>For example:</p> <pre> | Main column | Col 2 | Column 3 | &lt;------------------ fixed width in px -------------------&gt; &lt;------- as wide as possible ---------&gt; Thin as possible depending on contents: &lt;-----&gt; &lt;--------&gt; </pre>
[ { "answer_id": 118655, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 4, "selected": true, "text": "td.zero_width {\n width: 1%;\n}\n <td class=\"zero_width\">...</td>\n" }, { "answer_id": 118749, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<table>\n <tr>\n <td>foo</td>\n <td class=\"importantColumn\">bar</td>\n <td>woo</td>\n <td>pah</td>\n </tr>\n</table>\n\n.importantColumn{\n width: 100%;\n}\n white-space:nowrap" }, { "answer_id": 16863688, "author": "daveomcd", "author_id": 394241, "author_profile": "https://Stackoverflow.com/users/394241", "pm_score": 1, "selected": false, "text": "width: 100%; .column-fill { min-width: 325px; }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
118,633
<p>Although I do understand the serious implications of playing with this function (or at least that's what I think), I fail to see why it's becoming one of these things that respectable programmers wouldn't ever use, even those who don't even know what it is for.</p> <p>Let's say I'm developing an application where memory usage varies extremely depending on what the user is doing. The application life cycle can be divided into two main stages: editing and real-time processing. During the editing stage, suppose that billions or even trillions of objects are created; some of them small and some of them not, some may have finalizers and some may not, and suppose their lifetimes vary from a very few milliseconds to long hours. Next, the user decides to switch to the real-time stage. At this point, suppose that performance plays a fundamental role and the slightest alteration in the program's flow could bring catastrophic consequences. Object creation is then reduced to the minimum possible by using object pools and the such but then, the GC chimes in unexpectedly and throws it all away, and someone dies.</p> <p>The question: In this case, wouldn't it be wise to call GC.Collect() before entering the second stage?</p> <p>After all, these two stages never overlap in time with each other and all the optimization and statistics the GC could have gathered would be of little use here...</p> <p>Note: As some of you have pointed out, .NET might not be the best platform for an application like this, but that's beyond the scope of this question. The intent is to clarify whether a GC.Collect() call can improve an application's overall behaviour/performance or not. We all agree that the circumstances under which you would do such a thing are extremely rare but then again, the GC tries to guess and does it perfectly well most of the time, but it's still about guessing.</p> <p>Thanks.</p>
[ { "answer_id": 118891, "author": "Jason Short", "author_id": 19974, "author_profile": "https://Stackoverflow.com/users/19974", "pm_score": 4, "selected": false, "text": "Collect GC.Collect IDisposable" }, { "answer_id": 8837636, "author": "Dib", "author_id": 254215, "author_profile": "https://Stackoverflow.com/users/254215", "pm_score": 5, "selected": false, "text": "GC.Collect Utils.ReleaseCOMObject(objExcel)\n\n' Call the Garbage Collector twice. The GC needs to be called twice in order to get the\n' Finalizers called - the first time in, it simply makes a list of what is to be finalized,\n' the second time in, it actually does the finalizing. Only then will the object do its \n' automatic ReleaseComObject. Note: Calling the GC is a time-consuming process, \n' but one that may be necessary when automating Excel because it is the only way to \n' release all the Excel COM objects referenced indirectly.\n' Ref: http://www.informit.com/articles/article.aspx?p=1346865&seqNum=5\n' Ref: http://support.microsoft.com/default.aspx?scid=KB;EN-US;q317109\nGC.Collect()\nGC.WaitForPendingFinalizers()\nGC.Collect()\nGC.WaitForPendingFinalizers()\n GC Collect Public" }, { "answer_id": 10573348, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "Finalize WeakReference GC.Collect GC.Collect GC.Collect GC.Collect GC.Collect" }, { "answer_id": 15527609, "author": "Venugopal M", "author_id": 2132005, "author_profile": "https://Stackoverflow.com/users/2132005", "pm_score": 3, "selected": false, "text": "var obj = /* object utilizing the memory, in my case Form itself */\nGC.Collect(GC.GetGeneration(obj ,GCCollectionMode.Optimized).\n" }, { "answer_id": 21581452, "author": "Paul Smith", "author_id": 2026713, "author_profile": "https://Stackoverflow.com/users/2026713", "pm_score": 2, "selected": false, "text": "For Each Sheet in Spreadsheets\n ProcessSheet(FileName,sheet)\nNext\n\nPrivate Sub ProcessSheet(ByVal Filename as string, ByVal Sheet as string)\n ' open the spreadsheet \n Using SLDoc as SLDocument = New SLDocument(Filename, Sheet)\n ' do some work....\n SLDoc.Save\n End Using\n GC.Collect()\n GC.WaitForPendingFinalizers()\n GC.Collect()\n GC.WaitForPendingFinalizers()\nEnd Sub\n For Each Sheet in Spreadsheets\n ProcessSheet(FileName,sheet)\n GC.Collect()\n GC.WaitForPendingFinalizers()\n GC.Collect()\n GC.WaitForPendingFinalizers()\nNext\n\nPrivate Sub ProcessSheet(ByVal Filename as string, ByVal Sheet as string)\n ' open the spreadsheet \n Using SLDoc as SLDocument = New SLDocument(Filename, Sheet)\n ' do some work....\n SLDoc.Save\n End Using\nEnd Sub\n GC.Collect()" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
118,643
<p>I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?</p>
[ { "answer_id": 118744, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 7, "selected": true, "text": "pindent.py pindent.py -c myfile.py def foobar(a, b):\n if a == b:\n a = a+1\n elif a < b:\n b = b-1\n if b > a: a = a-1\n # end if\n else:\n print 'oops!'\n # end if\n# end def foobar\n myfile.py def foobar(a, b):\n if a == b:\n a = a+1\n elif a < b:\n b = b-1\n if b > a: a = a-1\n else:\n print 'oops!'\n pindent.py -r pindent.py -r myfile.py myfile.py pindent.py -c def foobar(a, b):\nif a == b:\na = a+1\nelif a < b:\nb = b-1\nif b > a: a = a-1\n# end if\nelse:\nprint 'oops!'\n# end if\n# end def foobar\n" }, { "answer_id": 1479855, "author": "NevilleDNZ", "author_id": 77431, "author_profile": "https://Stackoverflow.com/users/77431", "pm_score": 1, "selected": false, "text": "fi = od = yrt = end = lambda object: None;\nclass MyClass(object):\n def myfunction(self, arg1, arg2):\n for i in range(arg1) :# do\n if i > 5 :# then\n print i\n fi\n od # or end(i) #\n end(myfunction)\nend(MyClass)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
118,654
<p>Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)? </p>
[ { "answer_id": 119713, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": -1, "selected": false, "text": "re html5lib" }, { "answer_id": 170856, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 6, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing HtmlAgilityPack;\n\nnamespace GovParsingTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n HtmlWeb hw = new HtmlWeb();\n string url = @\"http://www.house.gov/house/House_Calendar.shtml\";\n HtmlDocument doc = hw.Load(url);\n\n HtmlNode docNode = doc.DocumentNode;\n HtmlNode div = docNode.SelectSingleNode(\"//div[@id='primary']\");\n HtmlNodeCollection tableRows = div.SelectNodes(\".//tr\");\n\n foreach (HtmlNode row in tableRows)\n {\n HtmlNodeCollection cells = row.SelectNodes(\".//td\");\n HtmlNode dateNode = cells[0];\n HtmlNode eventNode = cells[1];\n\n while (eventNode.HasChildNodes)\n {\n eventNode = eventNode.FirstChild;\n }\n\n Console.WriteLine(dateNode.InnerText);\n Console.WriteLine(eventNode.InnerText);\n Console.WriteLine();\n }\n\n //Console.WriteLine(div.InnerHtml);\n Console.ReadKey();\n }\n }\n}\n" }, { "answer_id": 6549240, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 1, "selected": false, "text": "D:\\Code>ipy\nIronPython 2.7 (2.7.0.40) on .NET 4.0.30319.235\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.path.append(\"D:\\Code\\IronPython\\BeautifulSoup-3.2.0\")\n>>> import urllib2\n>>> from BeautifulSoup import BeautifulSoup\n>>> page = urllib2.urlopen(\"http://www.example.com\")\n>>> soup = BeautifulSoup(page)\n<string>:1: DeprecationWarning: object.__new__() takes no parameters\n>>> i = soup('img')[0]\n>>> i['src']\n'http://example.com/blah.png'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7883/" ]
118,659
<p>I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL.</p> <p>My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also like to be able to run the simulation inside the editor. <strong>This means I also have to share the simulation code which uses SDL threads.</strong></p> <p>So, my question is this: Is there a way to have an the render OpenGL to a Qt window by using SDL?</p> <p>I have read on the web that it might be possible to supply SDL with a window handle in which to render. Anybody has experience dong that?</p> <p>Also, the threaded part of the simulator might pose a problem since it uses SDL threads.</p>
[ { "answer_id": 144953, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 5, "selected": false, "text": "#include \"SDL.h\"\n#include <QWidget>\n\nclass SDLVideo : public QWidget {\n Q_OBJECT\n\npublic:\n SDLVideo(QWidget *parent = 0, Qt::WindowFlags f = 0) : QWidget(parent, f), m_Screen(0){\n setAttribute(Qt::WA_PaintOnScreen);\n setUpdatesEnabled(false);\n\n // Set the new video mode with the new window size\n char variable[64];\n snprintf(variable, sizeof(variable), \"SDL_WINDOWID=0x%lx\", winId());\n putenv(variable);\n\n SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);\n\n // initialize default Video\n if((SDL_Init(SDL_INIT_VIDEO) == -1)) {\n std:cerr << \"Could not initialize SDL: \" << SDL_GetError() << std::endl;\n }\n\n m_Screen = SDL_SetVideoMode(640, 480, 8, SDL_HWSURFACE | SDL_DOUBLEBUF);\n if (m_Screen == 0) {\n std::cerr << \"Couldn't set video mode: \" << SDL_GetError() << std::endl;\n }\n }\n\n virtual ~SDLVideo() {\n if(SDL_WasInit(SDL_INIT_VIDEO) != 0) {\n SDL_QuitSubSystem(SDL_INIT_VIDEO);\n m_Screen = 0;\n }\n }\nprivate:\n SDL_Surface *m_Screen;\n};\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17087/" ]
118,678
<p>I have an Events list in sharepoint and need to disallow users from having the ability to create meeting workspaces in the new event form. Shy of customizing the new event form (which breaks attachment support), how can this be done?</p>
[ { "answer_id": 119919, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 0, "selected": false, "text": " <!-- <Template Name=\"MPS\" ID=\"2\">\n ... \n </Template> -->\n" }, { "answer_id": 137309, "author": "andrew", "author_id": 17767, "author_profile": "https://Stackoverflow.com/users/17767", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\"> \n var anchors = document.getElementsByTagName('input');\n for(var i=0;i<anchors.length;i++)\n {\n var anchorName = anchors[i].name.match('CrossProjectLinkField');\n if(anchorName != null)\n {\n anchors[i].disabled = true;\n break;\n }\n }\n</script>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17767/" ]
118,685
<p>On my blog I use some CSS classes which are defined in my stylesheet, but in RSS readers those styles don't show up. I had been searching for <code>class="whatever"</code> and replacing with <code>style="something: something;"</code>. But this means whenever I modify my CSS I need to modify my RSS-generating code too, and it doesn't work for a tag which belongs to multiple classes (i.e. <code>class="snapshot accent"</code>). Is there any way to point to my stylesheet from my feed?</p>
[ { "answer_id": 382960, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 6, "selected": true, "text": "<?xml-stylesheet?> style style" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
118,686
<p>I'm using GDI+ in C++. (This issue might exist in C# too). </p> <p>I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.</p> <p>For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".</p> <p>My question is: is this intended or documented behaviour, and how do I disable this? </p> <pre><code>RectF Rect(0,0,32767,32767); RectF Bounds1, Bounds2; graphics-&gt;MeasureString(L"PP", 1, font, Rect, &amp;Bounds1); graphics-&gt;MeasureString(L"PP", 2, font, Rect, &amp;Bounds2); margin = Bounds1.Width * 2 - Bounds2.Width; </code></pre>
[ { "answer_id": 8515930, "author": "vscpp", "author_id": 245582, "author_profile": "https://Stackoverflow.com/users/245582", "pm_score": 3, "selected": false, "text": "StringFormat.GenericTypographic graphics->MeasureString(L\"PP\", 1, font, width, StringFormat.GenericTypographic);\n DrawString" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10592/" ]
118,693
<p>Dynamically creating a radio button using eg </p> <pre><code>var radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', name); </code></pre> <p>works in Firefox but not in IE. Why not?</p>
[ { "answer_id": 118702, "author": "Patrick Wilkes", "author_id": 6370, "author_profile": "https://Stackoverflow.com/users/6370", "pm_score": 3, "selected": false, "text": "function createRadioElement( name, checked ) {\n var radioInput;\n try {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n radioInput = document.createElement(radioHtml);\n } catch( err ) {\n radioInput = document.createElement('input');\n radioInput.setAttribute('type', 'radio');\n radioInput.setAttribute('name', name);\n if ( checked ) {\n radioInput.setAttribute('checked', 'checked');\n }\n }\n\n return radioInput;\n}\n" }, { "answer_id": 119079, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 5, "selected": false, "text": "function createRadioElement(name, checked) {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n\n var radioFragment = document.createElement('div');\n radioFragment.innerHTML = radioHtml;\n\n return radioFragment.firstChild;\n}\n" }, { "answer_id": 120372, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": false, "text": "var createElement = (function()\n{\n // Detect IE using conditional compilation\n if (/*@cc_on @*//*@if (@_win32)!/*@end @*/false)\n {\n // Translations for attribute names which IE would otherwise choke on\n var attrTranslations =\n {\n \"class\": \"className\",\n \"for\": \"htmlFor\"\n };\n\n var setAttribute = function(element, attr, value)\n {\n if (attrTranslations.hasOwnProperty(attr))\n {\n element[attrTranslations[attr]] = value;\n }\n else if (attr == \"style\")\n {\n element.style.cssText = value;\n }\n else\n {\n element.setAttribute(attr, value);\n }\n };\n\n return function(tagName, attributes)\n {\n attributes = attributes || {};\n\n // See http://channel9.msdn.com/Wiki/InternetExplorerProgrammingBugs\n if (attributes.hasOwnProperty(\"name\") ||\n attributes.hasOwnProperty(\"checked\") ||\n attributes.hasOwnProperty(\"multiple\"))\n {\n var tagParts = [\"<\" + tagName];\n if (attributes.hasOwnProperty(\"name\"))\n {\n tagParts[tagParts.length] =\n ' name=\"' + attributes.name + '\"';\n delete attributes.name;\n }\n if (attributes.hasOwnProperty(\"checked\") &&\n \"\" + attributes.checked == \"true\")\n {\n tagParts[tagParts.length] = \" checked\";\n delete attributes.checked;\n }\n if (attributes.hasOwnProperty(\"multiple\") &&\n \"\" + attributes.multiple == \"true\")\n {\n tagParts[tagParts.length] = \" multiple\";\n delete attributes.multiple;\n }\n tagParts[tagParts.length] = \">\";\n\n var element =\n document.createElement(tagParts.join(\"\"));\n }\n else\n {\n var element = document.createElement(tagName);\n }\n\n for (var attr in attributes)\n {\n if (attributes.hasOwnProperty(attr))\n {\n setAttribute(element, attr, attributes[attr]);\n }\n }\n\n return element;\n };\n }\n // All other browsers\n else\n {\n return function(tagName, attributes)\n {\n attributes = attributes || {};\n var element = document.createElement(tagName);\n for (var attr in attributes)\n {\n if (attributes.hasOwnProperty(attr))\n {\n element.setAttribute(attr, attributes[attr]);\n }\n }\n return element;\n };\n }\n})();\n\n// Usage\nvar rb = createElement(\"input\", {type: \"radio\", checked: true});\n" }, { "answer_id": 120433, "author": "ujh", "author_id": 4936, "author_profile": "https://Stackoverflow.com/users/4936", "pm_score": 2, "selected": false, "text": "Builder.node('input', {type: 'radio', name: name})\n" }, { "answer_id": 1936533, "author": "Cypher", "author_id": 235584, "author_profile": "https://Stackoverflow.com/users/235584", "pm_score": 1, "selected": false, "text": "function createRadioElement( name, checked ) {\n var radioInput;\n try {\n var radioHtml = '<input type=\"radio\" name=\"' + name + '\"';\n if ( checked ) {\n radioHtml += ' checked=\"checked\"';\n }\n radioHtml += '/>';\n radioInput = document.createElement(radioHtml);\n } catch( err ) {\n radioInput = document.createElement('input');\n radioInput.setAttribute('type', 'radio');\n radioInput.setAttribute('name', name);\n if ( checked ) {\n radioInput.setAttribute('checked', 'checked');\n }\n }\n return radioInput;}\n" }, { "answer_id": 8503100, "author": "Dheeraj", "author_id": 1097598, "author_profile": "https://Stackoverflow.com/users/1097598", "pm_score": 2, "selected": false, "text": "html\n head\n script(type='text/javascript')\n function createRadioButton()\n {\n var newRadioButton\n = document.createElement(input(type='radio',name='radio',value='1st'));\n document.body.insertBefore(newRadioButton);\n }\n body\n input(type='button',onclick='createRadioButton();',value='Create Radio Button')\n" }, { "answer_id": 12387980, "author": "Sandeep Shekhawat", "author_id": 1390850, "author_profile": "https://Stackoverflow.com/users/1390850", "pm_score": 2, "selected": false, "text": "<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”RadioDemo.aspx.cs” Inherits=”JavascriptTutorial.RadioDemo” %>\n\n<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>\n\n<html xmlns=”http://www.w3.org/1999/xhtml”>\n<head runat=”server”>\n<title></title>\n<script type=”text/javascript”>\n\n/* Getting Id of Div in which radio button will be add*/\nvar containerDivClientId = “<%= containerDiv.ClientID %>”;\n\n/*variable count uses for define unique Ids of radio buttons and group name*/\nvar count = 100;\n\n/*This function call by button OnClientClick event and uses for create radio buttons*/\nfunction dynamicRadioButton()\n{\n/* create a radio button */\nvar radioYes = document.createElement(“input”);\nradioYes.setAttribute(“type”, “radio”);\n\n/*Set id of new created radio button*/\nradioYes.setAttribute(“id”, “radioYes” + count);\n\n/*set unique group name for pair of Yes / No */\nradioYes.setAttribute(“name”, “Boolean” + count);\n\n/*creating label for Text to Radio button*/\nvar lblYes = document.createElement(“lable”);\n\n/*create text node for label Text which display for Radio button*/\nvar textYes = document.createTextNode(“Yes”);\n\n/*add text to new create lable*/\nlblYes.appendChild(textYes);\n\n/*add radio button to Div*/\ncontainerDiv.appendChild(radioYes);\n\n/*add label text for radio button to Div*/\ncontainerDiv.appendChild(lblYes);\n\n/*add space between two radio buttons*/\nvar space = document.createElement(“span”);\nspace.setAttribute(“innerHTML”, “&nbsp;&nbsp”);\ncontainerDiv.appendChild(space);\n\nvar radioNo = document.createElement(“input”);\nradioNo.setAttribute(“type”, “radio”);\nradioNo.setAttribute(“id”, “radioNo” + count);\nradioNo.setAttribute(“name”, “Boolean” + count);\n\nvar lblNo = document.createElement(“label”);\nlblNo.innerHTML = “No”;\ncontainerDiv.appendChild(radioNo);\ncontainerDiv.appendChild(lblNo);\n\n/*add new line for new pair of radio buttons*/\nvar spaceBr= document.createElement(“br”);\ncontainerDiv.appendChild(spaceBr);\n\ncount++;\nreturn false;\n}\n</script>\n</head>\n<body>\n<form id=”form1″ runat=”server”>\n<div>\n<asp:Button ID=”btnCreate” runat=”server” Text=”Click Me” OnClientClick=”return dynamicRadioButton();” />\n<div id=”containerDiv” runat=”server”></div>\n</div>\n</form>\n</body>\n</html>\n" }, { "answer_id": 33281875, "author": "Saravana Kumar", "author_id": 1599942, "author_profile": "https://Stackoverflow.com/users/1599942", "pm_score": 2, "selected": false, "text": "for(i=0;i<=10;i++){\n var selecttag1=document.createElement(\"input\");\n selecttag1.setAttribute(\"type\", \"radio\");\n selecttag1.setAttribute(\"name\", \"irrSelectNo\"+i);\n selecttag1.setAttribute(\"value\", \"N\");\n selecttag1.setAttribute(\"id\",\"irrSelectNo\"+i);\n\n var lbl1 = document.createElement(\"label\");\n lbl1.innerHTML = \"YES\";\n cell3Div.appendChild(lbl);\n cell3Div.appendChild(selecttag1);\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6370/" ]
118,698
<p>In JavaScript, you can use <a href="http://peter.michaux.ca/article/3556" rel="noreferrer">Lazy Function Definitions</a> to optimize the 2nd - Nth call to a function by performing the <strong>expensive</strong> one-time operations only on the first call to the function.</p> <p>I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function.</p> <p>Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call.</p> <pre><code>$called = false; function foo($param_1){ global $called; if($called == false){ doExpensiveStuff($param_1); $called = true; } echo '&lt;b&gt;'.$param_1.'&lt;/b&gt;'; } </code></pre> <p>PS I've thought about using an include_once() or require_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive.</p> <p>Any Ideas? or is there a better way to tackle this?</p>
[ { "answer_id": 118718, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "if( !function_exists('baz') )\n{ \n function baz( $args ){ \n echo $args; \n }\n}\n create_function if( !isset( $baz ) ) \n { \n $baz = function( $args )\n { \n echo $args;\n }\n}\n\n$baz('hello');\n\n$baz = function( $args )\n{ \n echo $args + \"world\"; \n}\n$baz('hello');\n $fname = 'f_first'; \nfunction f_first( $even ) \n{ \n global $fname; \n doExpensiveStuff(); \n $fname = 'f_others';\n $fname( $even );\n /* code */ \n}\nfunction f_others( $odd ) \n{\n print \"<b>\".$odd.\"</b>\";\n}\n\nforeach( $blah as $i=>$v ) \n{\n $fname($v);\n}\n $func = function( $x ) use ( $func ) \n{ \n doexpensive(); \n $func = function( $y )\n { \n print \"<b>\".$y.\"</b>\";\n }\n $func($x);\n}\nforeach( range(1..200) as $i=>$v ) \n{ \n $func( $v ); \n}\n $data = // some array structure\ndoslowthing(); \nforeach( $data as $i => $v ) \n{\n // code here \n}\n" }, { "answer_id": 118752, "author": "Jurassic_C", "author_id": 20572, "author_profile": "https://Stackoverflow.com/users/20572", "pm_score": 0, "selected": false, "text": "$func = \"foo\"; \n\nfunction foo()\n{\n global $func;\n $func = \"bar\";\n echo \"expensive stuff\";\n};\n\n\nfunction bar()\n{\n echo \"do nothing, i guess\";\n};\n\nfor($i=0; $i<5; $i++)\n{\n $func();\n}\n" }, { "answer_id": 118767, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 0, "selected": false, "text": "Class SomeClass{\n protected $whatever_called;\n function __construct(){\n $this->called = false;\n }\n public function whatever(){\n if(!$this->whatever_called){\n //expensive stuff\n $this->whatever_called = true;\n }\n //rest of the function\n }\n} \n" }, { "answer_id": 118792, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "include() include_once() include() require_once()" }, { "answer_id": 119235, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 5, "selected": true, "text": "function foo() {\n static $called = false;\n if ($called == false) {\n $called = true;\n expensive_stuff();\n }\n}\n" }, { "answer_id": 119913, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "var cache = null;\nfunction doStuff() {\n if (cache == null) {\n cache = doExpensiveStuff();\n }\n return cache;\n}\n class StuffDoer {\n function doStuff() {\n if ($this->cache == null) {\n $this->cache = $this->doExpensiveStuff();\n }\n return $this->cache;\n }\n}\n" }, { "answer_id": 120044, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 0, "selected": false, "text": "function doStuff($param1) {\n static $called = false;\n if (!$called) {\n doExpensiveStuff($param1);\n $called = true;\n }\n // do the rest\n}\n function doStuff($param1) {\n static $buffer = array();\n if (!array_key_exists($param1, $buffer)) {\n doExpensiveStuff($param1);\n $buffer[$param1] = true;\n }\n // do the rest\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6144/" ]
118,719
<p>Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.</p> <p>Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option? </p>
[ { "answer_id": 118754, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "Font font = new Font(\"Arial\", 12, GraphicsUnit.Pixel);\n\nTypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));\n\nstring fontStr = converter.ConvertToInvariantString(font);\n\nFont font2 = (Font) converter.ConvertFromString(fontStr);\n\nConsole.WriteLine(font.Name == font2.Name); // prints True\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
118,724
<p>I have done some searches looking for information about how to do logging with the Spring Framework.</p> <p>We currently have an application that has no logging in it except for system.out statements (very bad way).</p> <p>What I would like to do, is add logging, but also want to be able to control the logging at run time, with say JMX.</p> <p>We are using Rad 7.0 / WebSphere 6.1</p> <p>I am interesting to find out what is the best way(s) to accomplish this (I figure there may be several).</p> <p>Update: Thoughts on the following <a href="http://www.devx.com/Java/Article/30799/0/page/1" rel="nofollow noreferrer">Spring AOP Logging</a> Good ideal or not. This is in reference to a question posted here on logging: <a href="https://stackoverflow.com/questions/105852/how-do-you-deal-with-conditional-logging-when-trying-to-respect-a-limited-cyclo">Conditional Logging</a>. Does this improve things or just makes it more difficult in the area of logging?</p>
[ { "answer_id": 119095, "author": "Matt", "author_id": 20630, "author_profile": "https://Stackoverflow.com/users/20630", "pm_score": 1, "selected": false, "text": "# Set root logger level to WARN and appenders to A1 & F1.\nlog4j.rootLogger=WARN, A1, F1\n\n# A1 is set to be a ConsoleAppender.\nlog4j.appender.A1=org.apache.log4j.ConsoleAppender\n# logging to console only INFO\nlog4j.appender.A1.Threshold=INFO\n# F1 is a file appender\nlog4j.appender.F1=org.apache.log4j.RollingFileAppender\n\n# Tell Spring to be quiet\nlog4j.logger.org.springframework=WARN\n# debug logging for my classes\nlog4j.logger.com.yourcorp=DEBUG\nlog4j.logger.org.hibernate=INFO\n\n# A1 uses PatternLayout.\nlog4j.appender.A1.layout=org.apache.log4j.PatternLayout\nlog4j.appender.A1.layout.ConversionPattern=%-4r : %d{HH:mm:ss,SSS} [%t] %-5p %c{1} %x - %m%n\n\nlog4j.appender.F1.File=./log/mylogfile.log\nlog4j.appender.F1.MaxFileSize=10MB\nlog4j.appender.F1.MaxBackupIndex=5\nlog4j.appender.F1.layout=org.apache.log4j.PatternLayout\nlog4j.appender.F1.layout.ConversionPattern=%-4r : %d{HH:mm:ss,SSS} [%t] %-5p %c{1} %x - %m%n\n" }, { "answer_id": 119775, "author": "trunkc", "author_id": 1961117, "author_profile": "https://Stackoverflow.com/users/1961117", "pm_score": 2, "selected": false, "text": " <bean id=\"performanceMonitor\" class=\"org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptor\">\n <property name=\"useDynamicLogger\" value=\"false\"/>\n <property name=\"trackAllInvocations\" value=\"true\"/>\n </bean>\n\n <bean id=\"txRequired\" class=\"org.springframework.transaction.interceptor.TransactionProxyFactoryBean\" abstract=\"true\">\n <property name=\"transactionManager\" ref=\"transactionManager\"/>\n <property name=\"transactionAttributes\" >\n <props> <prop key=\"*\">PROPAGATION_REQUIRED</prop> </props>\n </property>\n <property name=\"preInterceptors\">\n <list>\n <ref bean=\"performanceMonitor\"/> \n </list>\n </property>\n </bean>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8981/" ]
118,727
<p>I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:</p> <pre><code>1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5275) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2143: syntax error : missing ';' before '}' 1&gt;c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(28523) : error C2059: syntax error : '}' </code></pre> <p>Following the first error statement drops into this part of the mshtml.h code, pointing at the "True = 1" line:</p> <pre><code>EXTERN_C const GUID CLSID_CDocument; EXTERN_C const GUID CLSID_CScriptlet; typedef enum _BoolValue { True = 1, False = 0, BoolValue_Max = 2147483647L } BoolValue; EXTERN_C const GUID CLSID_CPluginSite; </code></pre> <p>It looks like someone on expert-sexchange also came across this error but I'd rather not dignify that site with a "7 day free trial".</p> <p>Any suggestions would be most welcome.</p>
[ { "answer_id": 118739, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "True 1" }, { "answer_id": 118745, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "#undef True \n#undef False \n" }, { "answer_id": 119020, "author": "Lou", "author_id": 4341, "author_profile": "https://Stackoverflow.com/users/4341", "pm_score": 1, "selected": false, "text": "#include <atlctl.h>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341/" ]
118,728
<p>I find the autoindent style of Notepad++ a little weird: when I am typing on an indented line, I <em>do</em> want it to indent the next line after I press Enter (this it does properly). However, when I am on an empty line (no indentation, no characters) and I press Enter, it indents the next line, using the same indentation as the last non-empty line. I find this extremely annoying; have you ever encountered this problem and do you know how to fix it?</p> <p>(Note: I'm editing HTML/PHP files.)</p>
[ { "answer_id": 118903, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "<Macro name=\"Trim and save\" Ctrl=\"no\" Alt=\"yes\" Shift=\"yes\" Key=\"83\">\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"1\" message=\"2170\" wParam=\"0\" lParam=\"0\" sParam=\" \" />\n <Action type=\"0\" message=\"2327\" wParam=\"0\" lParam=\"0\" sParam=\"\" />\n <Action type=\"0\" message=\"2327\" wParam=\"0\" lParam=\"0\" sParam=\"\" />\n <Action type=\"2\" message=\"0\" wParam=\"42024\" lParam=\"0\" sParam=\"\" />\n <Action type=\"2\" message=\"0\" wParam=\"41006\" lParam=\"0\" sParam=\"\" />\n</Macro>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
118,730
<p>Does anyone know how I can get rid of the following assembler warning?</p> <p>Code is x86, 32 bit:</p> <pre><code>int test (int x) { int y; // do a bit-rotate by 8 on the lower word. leave upper word intact. asm ("rorw $8, %0\n\t": "=q"(y) :"0"(x)); return y; } </code></pre> <p>If I compile it I get the following (very valid) warning:</p> <pre><code>Warning: using `%ax' instead of `%eax' due to `w' suffix </code></pre> <p>What I'm looking for is a way to tell the compiler/assembler that I want to access the lower 16 bit sub-register of %0. Accessing the byte sub-registers (in this case AL and AH) would be nice to know as well. </p> <p>I've already chosen the "q" modifier, so the compiler is forced to use EAX, EBX, ECX or EDX. I've made sure the compiler has to pick a register that has sub-registers.</p> <p>I know that I can force the asm-code to use a specific register (and its sub-registers), but I want to leave the register-allocation job up to the compiler.</p>
[ { "answer_id": 118737, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "%w0 int\ntest(int x)\n{\n int y;\n asm (\"rorw $8, %w0\" : \"=q\" (y) : \"0\" (x));\n return y;\n}\n int\ntest(int x)\n{\n int y;\n asm (\"xchg %b0, %h0\" : \"=Q\" (y) : \"0\" (x));\n return y;\n}\n .md gcc/config/i386/i386.md" }, { "answer_id": 119365, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 0, "selected": false, "text": "uint32_t y, hi=(x&~0xffff), lo=(x&0xffff);\ny = hi + (((lo >> 8) + (lo << 8))&0xffff);\n" }, { "answer_id": 122375, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "int\ntest(int x)\n{\n int y;\n asm (\"xchg %b0, %h0\" : \"=Q\" (y) : \"0\" (x));\n return y;\n}\n" }, { "answer_id": 17825185, "author": "Nathan Kurz", "author_id": 49301, "author_profile": "https://Stackoverflow.com/users/49301", "pm_score": 3, "selected": false, "text": "\"MOV %1, %0\" \"MOV %q1, %w0\" print_reg() /* Print the name of register X to FILE based on its machine mode and number.\n If CODE is 'w', pretend the mode is HImode.\n If CODE is 'b', pretend the mode is QImode.\n If CODE is 'k', pretend the mode is SImode.\n If CODE is 'q', pretend the mode is DImode.\n If CODE is 'x', pretend the mode is V4SFmode.\n If CODE is 't', pretend the mode is V8SFmode.\n If CODE is 'h', pretend the reg is the 'high' byte register.\n If CODE is 'y', print \"st(0)\" instead of \"st\", if the reg is stack op.\n If CODE is 'd', duplicate the operand for AVX instruction.\n */\n ix86_print_operand() %c2 #define ASM_LEA_ADD_BYTES(ptr, bytes) \\\n __asm volatile(\"lea %c1(%0), %0\" : \\\n /* reads/writes %0 */ \"+r\" (ptr) : \\\n /* reads */ \"i\" (bytes));\n %c1 ptr = (char *)ptr + bytes\n %P0 #define ASM_CALL_FUNC(func) \\\n __asm volatile(\"call %P0\") : \\\n /* no writes */ : \\\n /* reads %0 */ \"i\" (func)) \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
118,748
<p>How do I open multiple pages in Internet Explorer 7 with a single DOS command? Is a batch file the only way to do this?</p> <p>Thanks!</p>
[ { "answer_id": 118796, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 4, "selected": true, "text": "@echo off\n@setlocal\n\n:openurl\nset url=%~1\n\nif \"%url:~0,4%\" == \"http\" (\n start \"%ProgramFiles%\\Internet Explorer\\iexplore.exe\" \"%url%\"\n)\nif NOT \"%url:~0,4%\" == \"http\" (\n start \"%ProgramFiles%\\Internet Explorer\\iexplore.exe\" \"http://%url%\"\n)\n\nshift\nif \"%~1\" == \"\" goto :end\ngoto :openurl\n\n:end\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
118,774
<p>Deep down in WinDef.h there's this relic from the segmented memory era:</p> <pre><code>#define far #define near </code></pre> <p>This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?</p>
[ { "answer_id": 118779, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "#undef near\n#undef far\n" }, { "answer_id": 118782, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "windows.h #include <windows.h>\n#undef near\n#undef far\n" }, { "answer_id": 118873, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "#pragma push_macro(\"near\")\n#undef near\n//your code here.\n#pragma pop_macro (\"near\")\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841/" ]
118,813
<p>I want to use the macports version of python instead of the one that comes with Leopard.</p>
[ { "answer_id": 118820, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "$ which python\n/usr/bin/python\n$ which python2.5\n/opt/local/bin/python2.5\n .profile export PATH=/opt/local/bin:/opt/local/sbin:$PATH\n" }, { "answer_id": 118821, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "$PATH /usr/local/bin/python .bashrc PATH=/usr/local/bin:$PATH" }, { "answer_id": 118823, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 2, "selected": false, "text": "#!/usr/bin/env python .profile .bash_profile .profile export PATH=/opt/local/bin:/opt/local/sbin:$PATH\n bin/" }, { "answer_id": 118824, "author": "jacobian", "author_id": 18184, "author_profile": "https://Stackoverflow.com/users/18184", "pm_score": 5, "selected": false, "text": "~/.bash_profile /opt/local/bin" }, { "answer_id": 604946, "author": "bryan", "author_id": 73049, "author_profile": "https://Stackoverflow.com/users/73049", "pm_score": 4, "selected": false, "text": "sudo port install python25\nsudo port install python_select\nsudo python_select python25\n /opt/local/bin/python PATH" }, { "answer_id": 6166416, "author": "chipiik", "author_id": 774930, "author_profile": "https://Stackoverflow.com/users/774930", "pm_score": 4, "selected": false, "text": "python_select sudo port select python python26\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013/" ]
118,839
<p>I would like to replace only the group in parenthesis in this expression :</p> <pre><code>my_string.gsub(/&lt;--MARKER_START--&gt;(.)*&lt;--MARKER_END--&gt;/, 'replace_text') </code></pre> <p>so that I get : <code>&lt;--MARKER_START--&gt;replace_text&lt;--MARKER_END--&gt;</code></p> <p>I know I could repeat the whole <code>MARKER_START</code> and <code>MARKER_END</code> blocks in the substitution expression but I thought there should be a more simple way to do this.</p>
[ { "answer_id": 118852, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "my_string.gsub(/(<--MARKER_START-->)(.*)(<--MARKER_END-->)/, '\\1replace_text\\3')\n" }, { "answer_id": 118958, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": false, "text": " s.gsub( /(?<=<--MARKER START-->).*?(?=<--MARKER END-->)/, 'replacement text' )\n ?<= s.gsub( /(<--MARKER START-->).*?(?=<--MARKER END-->)/, '\\1replacement text' )\n (.)* .*? \"<b>One</b> Two <b>Three</b>\".gsub( /<b>.*<\\/b>/, 'BOLD' )\n=> \"BOLD\"\n \"<b>One</b> Two <b>Three</b>\".gsub( /<b>.*?<\\/b>/, 'BOLD' )\n=> \"BOLD Two BOLD\"\n \"123F\" =~ /\\d(?=F)/ # will match the 3, but not the 1 or the 2\n \"123F\" =~ /\\dF/ # will match 3F, because F is considered part of the match\n <--MARKER END--> <--MARKER START--> <--MARKER-->" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20871/" ]
118,851
<p>Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.</p> <p>A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?</p> <pre><code>routes.MapRoute("UserItems", "User/{UserID}/Items", new {controller = "User", action = "Items"}); </code></pre> <p>And on my aspx page</p> <pre><code>Html.ActionLink("Items", "UserItems", new { UserID = 1 }) </code></pre>
[ { "answer_id": 119040, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 2, "selected": false, "text": "public string ActionLink(string linkText, string actionName, object values);\n Html.ActionLink(\"Items\", \"Items\", new { UserID = 1 })\n <a href=\"<%=Url.RouteUrl(\"UserItems\", new { UserId = 1 })%>\">Items</a>\n" }, { "answer_id": 712857, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "<% string action = Url.RouteUrl(\"NamedRoute\", new \n { controller=\"User\",\n action=\"Items\",\n UserID=1});%>\n <a href=\"<%=action%>\">link</a>\n" }, { "answer_id": 4840673, "author": "Dayi Chen", "author_id": 595443, "author_profile": "https://Stackoverflow.com/users/595443", "pm_score": 0, "selected": false, "text": "Html.ActionLink(\"Items\", \"User\", new { UserID = 1 })\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
118,863
<p>When is it appropriate to use a class in Visual Basic for Applications (VBA)?</p> <p>I'm assuming the <a href="http://en.wikipedia.org/wiki/Class_(computer_science)#Reasons_for_using_classes" rel="noreferrer">accelerated development and reduction of introducing bugs</a> is a common benefit for most languages that support OOP. But with VBA, is there a specific criterion? </p>
[ { "answer_id": 126502, "author": "JonnyGold", "author_id": 2665, "author_profile": "https://Stackoverflow.com/users/2665", "pm_score": 1, "selected": false, "text": "VBCode.mysub(param1, param2)\n" }, { "answer_id": 143395, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 7, "selected": true, "text": "Total = 0\nFor i = 0 To NumRows-1\n Total = Total + (OrderArray(i,1) * OrderArray(i,3))\nNext i\n Total = 0\nFor Each objOrder in colOrders\n Total = Total + objOrder.Quantity * objOrder.Price\nNext i\n --- WorksheetProtector class module ---\n\nPrivate m_objWorksheet As Worksheet\nPrivate m_sPassword As String\n\nPublic Sub Unprotect(Worksheet As Worksheet, Password As String)\n ' Nothing to do if we didn't define a password for the worksheet\n If Len(Password) = 0 Then Exit Sub\n\n ' If the worksheet is already unprotected, nothing to do\n If Not Worksheet.ProtectContents Then Exit Sub\n\n ' Unprotect the worksheet\n Worksheet.Unprotect Password\n\n ' Remember the worksheet and password so we can protect again\n Set m_objWorksheet = Worksheet\n m_sPassword = Password\nEnd Sub\n\nPublic Sub Protect()\n ' Protects the worksheet with the same password used to unprotect it\n If m_objWorksheet Is Nothing Then Exit Sub\n If Len(m_sPassword) = 0 Then Exit Sub\n\n ' If the worksheet is already protected, nothing to do\n If m_objWorksheet.ProtectContents Then Exit Sub\n\n m_objWorksheet.Protect m_sPassword\n Set m_objWorksheet = Nothing\n m_sPassword = \"\"\nEnd Sub\n\nPrivate Sub Class_Terminate()\n ' Reprotect the worksheet when this object goes out of scope\n On Error Resume Next\n Protect\nEnd Sub\n Public Sub DoSomething()\n Dim objWorksheetProtector as WorksheetProtector\n Set objWorksheetProtector = New WorksheetProtector\n objWorksheetProtector.Unprotect myWorksheet, myPassword\n\n ... manipulate myWorksheet - may raise an error\n\nEnd Sub \n" }, { "answer_id": 9264988, "author": "Mike", "author_id": 1207363, "author_profile": "https://Stackoverflow.com/users/1207363", "pm_score": 3, "selected": false, "text": "Dim strFileName As String\nDim dlgXLS As New CFileDialog\n\nWith dlgXLS\n .Title = \"Choose a Spreadsheet\"\n .Filter = \"Excel (*.xls)|*.xls|All Files (*.*)|*.*\"\n .Flags = ofnFileMustExist OR ofnExplorer\n\n If OpenFileDialog() Then\n strFileName = .FileName\n End If\nEnd With\nSet dlgXLS = Nothing\n" }, { "answer_id": 64596272, "author": "Gener4tor", "author_id": 9930052, "author_profile": "https://Stackoverflow.com/users/9930052", "pm_score": 1, "selected": false, "text": "\nPublic Function MyClass(ByVal someInit As Boolean) As MyClassClass\n Set MyClass = New MyClassClass\n Call MyClass.Init(someInit)\nEnd Function\n Set varName = new ClassName \n'content of class-module: MyClass\nimplements IMyInterface\nprivate sub IMyInterface_SomeFunction()\n 'This can only be called if you got an object of type \"IMyInterface\"\nend function\nprivate sub IMyInterface_SomeFunction()\n 'You need this to call the function when having an object of the type \"MyClass\"\n Call IMyInterface_SomeFunction()\nend function" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
118,884
<p>I have noticed that some browsers (in particular, Firefox and <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="noreferrer">Opera</a>) are very zealous in using cached copies of <strong>.css</strong> and <strong>.js</strong> files, even between browser sessions. This leads to a problem when you update one of these files, but the user's browser keeps on using the cached copy.</p> <p>What is the most elegant way of forcing the user's browser to reload the file when it has changed?</p> <p>Ideally, the solution would not force the browser to reload the file on every visit to the page.</p> <hr/> <p>I have found <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118921#118921">John Millikin's</a> and <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/118901#118901">da5id's</a> suggestion to be useful. It turns out there is a term for this: <strong>auto-versioning</strong>.</p> <p>I have posted a new answer below which is a combination of my original solution and John's suggestion.</p> <p>Another idea that was suggested by <strong>SCdF</strong> would be to append a bogus query string to the file. (Some Python code, to automatically use the timestamp as a bogus query string, was <a href="https://stackoverflow.com/questions/118884/how-to-force-the-browser-to-reload-cached-css-and-javascript-files/121143#121143">submitted by <em>pi.</em></a>.)</p> <p>However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.)</p>
[ { "answer_id": 118886, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 9, "selected": false, "text": ".htaccess json-1.3.js RewriteEngine on\nRewriteRule ^(.*)\\.[\\d]{10}\\.(css|js)$ $1.$2 [L]\n /**\n * Given a file, i.e. /css/base.css, replaces it with a string containing the\n * file's mtime, i.e. /css/base.1221534296.css.\n *\n * @param $file The file to be loaded. Must be an absolute path (i.e.\n * starting with slash).\n */\nfunction auto_version($file)\n{\n if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))\n return $file;\n\n $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);\n return preg_replace('{\\\\.([^./]+)$}', \".$mtime.\\$1\", $file);\n}\n <link rel=\"stylesheet\" href=\"/css/base.css\" type=\"text/css\" />\n <link rel=\"stylesheet\" href=\"<?php echo auto_version('/css/base.css'); ?>\" type=\"text/css\" />\n" }, { "answer_id": 118902, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 6, "selected": false, "text": "?foo=1234 ?" }, { "answer_id": 118930, "author": "helios", "author_id": 9686, "author_profile": "https://Stackoverflow.com/users/9686", "pm_score": 3, "selected": false, "text": "<link rel=\"stylesheet\" src=\"myStyles.css?ABCDEF12345sessionID\" />\n<script language=\"javascript\" src=\"myCode.js?ABCDEF12345sessionID\"></script>\n <link rel=\"stylesheet\" src=\"myStyles.css?20080922_1020\" />\n<script language=\"javascript\" src=\"myCode.js?20080922_1120\"></script>\n" }, { "answer_id": 119056, "author": "keparo", "author_id": 19468, "author_profile": "https://Stackoverflow.com/users/19468", "pm_score": 8, "selected": false, "text": "<script src=\"/myJavascript.js?version=4\"></script>\n <!-- Development version: -->\n<script>document.write('<script src=\"/myJavascript.js?dev=' + Math.floor(Math.random() * 100) + '\"\\><\\/script>');</script>\n" }, { "answer_id": 119319, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": -1, "selected": false, "text": "Cache-Control: no-cache, no-store, must-revalidate\n" }, { "answer_id": 119326, "author": "airrob", "author_id": 1513, "author_profile": "https://Stackoverflow.com/users/1513", "pm_score": 4, "selected": false, "text": "foo.css?version=1" }, { "answer_id": 120960, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 7, "selected": false, "text": "http://mysite.com/css/[md5_hash_here]/style.css\n" }, { "answer_id": 121143, "author": "pi.", "author_id": 15274, "author_profile": "https://Stackoverflow.com/users/15274", "pm_score": 3, "selected": false, "text": "def import_tag(pattern, name, **kw):\n if name[0] == \"/\":\n name = name[1:]\n # Additional HTML attributes\n attrs = ' '.join(['%s=\"%s\"' % item for item in kw.items()])\n try:\n # Get the files modification time\n mtime = os.stat(os.path.join('/documentroot', name)).st_mtime\n include = \"%s?%d\" % (name, mtime)\n # This is the same as sprintf(pattern, attrs, include) in other\n # languages\n return pattern % (attrs, include)\n except:\n # In case of error return the include without the added query\n # parameter.\n return pattern % (attrs, name)\n\ndef script(name, **kw):\n return import_tag('<script %s src=\"/%s\"></script>', name, **kw)\n\ndef stylesheet(name, **kw):\n return import_tag('<link rel=\"stylesheet\" type=\"text/css\" %s href=\"/%s\">', name, **kw)\n script(\"/main.css\")\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/main.css?1221842734\">\n" }, { "answer_id": 126086, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 3, "selected": false, "text": "/styles/screen.css\n /styles/screen.css?v=1234\n /v/1234/styles/screen.css\n background-image body {\n background-image: url('images/happy.gif');\n}\n /v/1234/styles/images/happy.gif\n images/happy.gif /styles/screen.css?v=1235 /styles/images/happy.gif /v/* /styles/screen.css DefaultServlet .css .js" }, { "answer_id": 131037, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 0, "selected": false, "text": "<!--#include virtual=\"/includes/css-element.txt\"-->\n <link rel=\"stylesheet\" href=\"mycss.css\"/>\n" }, { "answer_id": 1041463, "author": "Michiel", "author_id": 125699, "author_profile": "https://Stackoverflow.com/users/125699", "pm_score": 4, "selected": false, "text": "<link rel=\"stylesheet\" href=\"/css/base.css?[hash-here]\" type=\"text/css\" />\n" }, { "answer_id": 3417141, "author": "Nick Johnson", "author_id": 227569, "author_profile": "https://Stackoverflow.com/users/227569", "pm_score": 4, "selected": false, "text": "RewriteRule ^(.*)\\.[^.][\\d]+\\.(css|js)$ $1.$2 [L]\n" }, { "answer_id": 4622905, "author": "lony", "author_id": 227821, "author_profile": "https://Stackoverflow.com/users/227821", "pm_score": 3, "selected": false, "text": "/**\n * Extend filepath with timestamp to force browser to\n * automatically refresh them if they are updated\n *\n * This is based on Kip's version, but now\n * also works on virtual hosts\n * @link http://stackoverflow.com/questions/118884/what-is-an-elegant-way-to-force-browsers-to-reload-cached-css-js-files\n *\n * Usage:\n * - extend your .htaccess file with\n * # Route for My_View_Helper_AutoRefreshRewriter\n * # which extends files with there timestamp so if these\n * # are updated a automatic refresh should occur\n * # RewriteRule ^(.*)\\.[^.][\\d]+\\.(css|js)$ $1.$2 [L]\n * - then use it in your view script like\n * $this->headLink()->appendStylesheet( $this->autoRefreshRewriter($this->cssPath . 'default.css'));\n *\n */\nclass My_View_Helper_AutoRefreshRewriter extends Zend_View_Helper_Abstract {\n\n public function autoRefreshRewriter($filePath) {\n\n if (strpos($filePath, '/') !== 0) {\n\n // Path has no leading '/'\n return $filePath;\n } elseif (file_exists($_SERVER['DOCUMENT_ROOT'] . $filePath)) {\n\n // File exists under normal path\n // so build path based on this\n $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $filePath);\n return preg_replace('{\\\\.([^./]+)$}', \".$mtime.\\$1\", $filePath);\n } else {\n\n // Fetch directory of index.php file (file from all others are included)\n // and get only the directory\n $indexFilePath = dirname(current(get_included_files()));\n\n // Check if file exist relativ to index file\n if (file_exists($indexFilePath . $filePath)) {\n\n // Get timestamp based on this relativ path\n $mtime = filemtime($indexFilePath . $filePath);\n\n // Write generated timestamp to path\n // but use old path not the relativ one\n return preg_replace('{\\\\.([^./]+)$}', \".$mtime.\\$1\", $filePath);\n } else {\n return $filePath;\n }\n }\n }\n}\n" }, { "answer_id": 7999354, "author": "A Programmer", "author_id": 1028240, "author_profile": "https://Stackoverflow.com/users/1028240", "pm_score": -1, "selected": false, "text": "<?php\n//Replace the 'style.css' with the link to the stylesheet.\necho \"<style type='text/css'>\".file_get_contents('style.css').\"</style>\";\n?>\n" }, { "answer_id": 14383167, "author": "ThomasH", "author_id": 127465, "author_profile": "https://Stackoverflow.com/users/127465", "pm_score": 2, "selected": false, "text": "no-cache" }, { "answer_id": 14536240, "author": "Phantom007", "author_id": 468975, "author_profile": "https://Stackoverflow.com/users/468975", "pm_score": 7, "selected": false, "text": "<link href=\"mycss.css?v=<?= filemtime('mycss.css') ?>\" rel=\"stylesheet\">\n" }, { "answer_id": 15704646, "author": "Scott Arciszewski", "author_id": 2224584, "author_profile": "https://Stackoverflow.com/users/2224584", "pm_score": 1, "selected": false, "text": "<link rel=\"stylesheet\" href=\"file.css?<?=hash_hmac('sha1', session_id(), md5_file(\"file.css\")); ?>\" />\n" }, { "answer_id": 17467422, "author": "Ponmudi VN", "author_id": 2186642, "author_profile": "https://Stackoverflow.com/users/2186642", "pm_score": 3, "selected": false, "text": "example.css?randomNo = Math.random()\n" }, { "answer_id": 18033374, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\" src=\"Scripts/exampleScript<%=Global.JsPostfix%>\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"Css/exampleCss<%=Global.CssPostfix%>\" />\n protected void Application_Start(object sender, EventArgs e)\n{\n ...\n string jsVersion = ConfigurationManager.AppSettings[\"JsVersion\"];\n bool updateEveryAppStart = Convert.ToBoolean(ConfigurationManager.AppSettings[\"UpdateJsEveryAppStart\"]);\n int buildNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Revision;\n JsPostfix = \"\";\n#if !DEBUG\n JsPostfix += \".min\";\n#endif\n JsPostfix += \".js?\" + jsVersion + \"_\" + buildNumber;\n if (updateEveryAppStart)\n {\n Random rand = new Random();\n JsPosfix += \"_\" + rand.Next();\n }\n ...\n}\n" }, { "answer_id": 21614688, "author": "Alex White", "author_id": 1721440, "author_profile": "https://Stackoverflow.com/users/1721440", "pm_score": -1, "selected": false, "text": "$.getScript $.ajaxSetup cache: false <script src=\"scripts/app.js\"></script>\n $.ajaxSetup({\n cache: false\n});\n\n$.getScript('scripts/app.js'); // GET scripts/app.js?_1391722802668\n" }, { "answer_id": 25265359, "author": "Amarnath Bakthavathsalam", "author_id": 2008645, "author_profile": "https://Stackoverflow.com/users/2008645", "pm_score": 1, "selected": false, "text": "cache-control:max-age <system.webServer>\n <modules runAllManagedModulesForAllRequests=\"true\"/>\n <staticContent>\n <clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"00.00:01:00\"/>\n </staticContent>\n <httpProtocol>\n <customHeaders>\n <add name=\"ETAG\" value=\"\"/>\n </customHeaders>\n </httpProtocol>\n</system.webServer>\n\n<location path=\"Images\">\n <system.webServer>\n <staticContent>\n <clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"180.00:00:00\" />\n </staticContent>\n </system.webServer>\n</location>\n" }, { "answer_id": 26129241, "author": "user3738893", "author_id": 3738893, "author_profile": "https://Stackoverflow.com/users/3738893", "pm_score": 4, "selected": false, "text": "http://localhost/MvcBM_time/bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81 v" }, { "answer_id": 27451135, "author": "undefined", "author_id": 610585, "author_profile": "https://Stackoverflow.com/users/610585", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n# Create a JSON map from filenames to MD5 hashes\n# Run as hashes.sh < inputfile.list > outputfile.json\n\necho \"{\"\ndelim=\"\"\nwhile read l; do\n echo \"$delim\\\"$l\\\": \\\"`md5 -q $l`\\\"\"\n delim=\",\"\ndone\necho \"}\"\n" }, { "answer_id": 27924764, "author": "Lloyd Banks", "author_id": 1423787, "author_profile": "https://Stackoverflow.com/users/1423787", "pm_score": 4, "selected": false, "text": "(function(){\n\n // Match this timestamp with the release of your code\n var lastVersioning = Date.UTC(2014, 11, 20, 2, 15, 10);\n \n var lastCacheDateTime = localStorage.getItem('lastCacheDatetime');\n\n if(lastCacheDateTime){\n if(lastVersioning > lastCacheDateTime){\n var reload = true;\n }\n }\n\n localStorage.setItem('lastCacheDatetime', Date.now());\n\n if(reload){\n location.reload(true);\n }\n\n})();\n location.reload(true) <head>" }, { "answer_id": 31525382, "author": "pinkp", "author_id": 2409791, "author_profile": "https://Stackoverflow.com/users/2409791", "pm_score": 2, "selected": false, "text": "?$Now.Format(dmYHis)\n" }, { "answer_id": 31795900, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 5, "selected": false, "text": "/some.template /some.template /some.template /v<release_tag_1>/…files… /v<release_tag_2>/…files… <script> <link> <base>" }, { "answer_id": 37181172, "author": "statler", "author_id": 618660, "author_profile": "https://Stackoverflow.com/users/618660", "pm_score": 1, "selected": false, "text": "private void ParseIndex(string inFile, string addPath, string outFile)\n{\n string path = Path.GetDirectoryName(inFile);\n HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();\n document.Load(inFile);\n\n foreach (HtmlNode link in document.DocumentNode.Descendants(\"script\"))\n {\n if (link.Attributes[\"src\"]!=null)\n {\n resetQueryString(path, addPath, link, \"src\");\n }\n }\n\n foreach (HtmlNode link in document.DocumentNode.Descendants(\"link\"))\n {\n if (link.Attributes[\"href\"] != null && link.Attributes[\"type\"] != null)\n {\n if (link.Attributes[\"type\"].Value == \"text/css\" || link.Attributes[\"type\"].Value == \"text/html\")\n {\n resetQueryString(path, addPath, link, \"href\");\n }\n }\n }\n\n document.Save(outFile);\n MessageBox.Show(\"Your file has been processed.\", \"Autoversion complete\");\n}\n\nprivate void resetQueryString(string path, string addPath, HtmlNode link, string attrType)\n{\n string currFileName = link.Attributes[attrType].Value;\n\n string uripath = currFileName;\n if (currFileName.Contains('?'))\n uripath = currFileName.Substring(0, currFileName.IndexOf('?'));\n string baseFile = Path.Combine(path, uripath);\n if (!File.Exists(baseFile))\n baseFile = Path.Combine(addPath, uripath);\n if (!File.Exists(baseFile))\n return;\n DateTime lastModified = System.IO.File.GetLastWriteTime(baseFile);\n link.Attributes[attrType].Value = uripath + \"?v=\" + lastModified.ToString(\"yyyyMMddhhmm\");\n}\n" }, { "answer_id": 37538586, "author": "GreQ", "author_id": 6331590, "author_profile": "https://Stackoverflow.com/users/6331590", "pm_score": 3, "selected": false, "text": "<script>\n var node = document.createElement(\"script\");\n node.type = \"text/javascript\";\n node.src = 'test.js?' + Math.floor(Math.random()*999999999);\n document.getElementsByTagName(\"head\")[0].appendChild(node);\n</script>\n" }, { "answer_id": 39060477, "author": "Mizo Games", "author_id": 1482251, "author_profile": "https://Stackoverflow.com/users/1482251", "pm_score": 0, "selected": false, "text": "// Add it to the top of the page\n<?php\n srand();\n $random_number = rand();\n?>\n <script src=\"file.js?version=<?php echo $random_number;?>\"></script>\n" }, { "answer_id": 41304784, "author": "readikus", "author_id": 1010468, "author_profile": "https://Stackoverflow.com/users/1010468", "pm_score": 3, "selected": false, "text": "exec('git rev-parse --verify HEAD 2> /dev/null', $gitLog);\necho ' <script src=\"/path/to/script.js\"?v='.$gitLog[0].'></script>'.PHP_EOL;\n" }, { "answer_id": 42576123, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 4, "selected": false, "text": "<script src=\"{{ asset('/js/your.js?v='.filemtime('js/your.js')) }}\"></script>\n <link rel=\"stylesheet\" href=\"{{asset('css/your.css?v='.filemtime('css/your.css'))}}\">\n filemtime <link rel=\"stylesheet\" href=\"assets/css/your.css?v=1577772366\">\n" }, { "answer_id": 46169589, "author": "Karan Shaw", "author_id": 6905379, "author_profile": "https://Stackoverflow.com/users/6905379", "pm_score": 3, "selected": false, "text": "$(window).load(function() {\n location.reload(true);\n});\n .load" }, { "answer_id": 48727671, "author": "Pawel", "author_id": 696535, "author_profile": "https://Stackoverflow.com/users/696535", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n if(document.location.href.indexOf('localhost') !== -1) {\n const scr = document.createElement('script');\n document.setAttribute('type', 'text/javascript');\n document.setAttribute('src', 'scripts.js' + '?wizardry=' + Math.random());\n document.head.appendChild(scr);\n document.write('<script type=\"application/x-suppress\">'); // prevent next script(from other SO answer)\n }\n</script>\n\n<script type=\"text/javascript\" src=\"scripts.js\">\n" }, { "answer_id": 51606421, "author": "Luis Cambustón", "author_id": 4023929, "author_profile": "https://Stackoverflow.com/users/4023929", "pm_score": 2, "selected": false, "text": "<link rel=\"stylesheet\" href=\"~/css/custom.css?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath(\"~/css/custom.css\")).ToString(),\"[^0-9]\", \"\"))\" />\n\n<script type=\"text/javascript\" src=\"~/js/custom.js?d=@(System.Text.RegularExpressions.Regex.Replace(File.GetLastWriteTime(Server.MapPath(\"~/js/custom.js\")).ToString(),\"[^0-9]\", \"\"))\"></script>\n <script src=\"<%= Page.ResolveClientUrlUnique(\"~/js/custom.js\") %>\" type=\"text/javascript\"></script>\n public static class Extension_Methods\n{\n public static string ResolveClientUrlUnique(this System.Web.UI.Page oPg, string sRelPath)\n {\n string sFilePath = oPg.Server.MapPath(sRelPath);\n string sLastDate = System.IO.File.GetLastWriteTime(sFilePath).ToString();\n string sDateHashed = System.Text.RegularExpressions.Regex.Replace(sLastDate, \"[^0-9]\", \"\");\n\n return oPg.ResolveClientUrl(sRelPath) + \"?d=\" + sDateHashed;\n }\n}\n" }, { "answer_id": 52229111, "author": "Jajikanth pydimarla", "author_id": 4138684, "author_profile": "https://Stackoverflow.com/users/4138684", "pm_score": 1, "selected": false, "text": "<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\"%>\n<c:set var = \"version\" scope = \"application\" value = \"1.0.0\" />\n <script src='<spring:url value=\"/js/myChangedFile.js?version=${version}\"/>'></script>\n" }, { "answer_id": 52671176, "author": "Bangash", "author_id": 6213405, "author_profile": "https://Stackoverflow.com/users/6213405", "pm_score": 2, "selected": false, "text": "<link rel=\"stylesheet\" href=\"cssfolder/somecssfile-ver-1.css\"/>\n" }, { "answer_id": 56141208, "author": "Jessie Lesbian", "author_id": 10831193, "author_profile": "https://Stackoverflow.com/users/10831193", "pm_score": 2, "selected": false, "text": "<script src=\"https://jessietessie.github.io/google-translate-token-generator/google_translate_token_generator.js\" integrity=\"sha384-muTMBCWlaLhgTXLmflAEQVaaGwxYe1DYIf2fGdRkaAQeb4Usma/kqRWFWErr2BSi\" crossorigin=\"anonymous\"></script>\n" }, { "answer_id": 56636730, "author": "patrick", "author_id": 73804, "author_profile": "https://Stackoverflow.com/users/73804", "pm_score": 3, "selected": false, "text": "Chrome network tab disable cache q?Date.now() // Pure JavaScript unique query parameter generation\n//\n//=== myfile.js\n\nfunction hello() { console.log('hello') };\n\n//=== end of file\n\n<script type=\"text/javascript\">\n document.write('<script type=\"text/javascript\" src=\"myfile.js?q=' + Date.now() + '\">\n // document.write is considered bad practice!\n // We can't use hello() yet\n</script>')\n\n<script type=\"text/javascript\">\n hello();\n</script>\n" }, { "answer_id": 58640532, "author": "AIon", "author_id": 5904566, "author_profile": "https://Stackoverflow.com/users/5904566", "pm_score": 3, "selected": false, "text": "\"keep caching consistent with the file\" localhost:port increase in network traffic" }, { "answer_id": 60337162, "author": "Nicolai VdS", "author_id": 6714566, "author_profile": "https://Stackoverflow.com/users/6714566", "pm_score": 0, "selected": false, "text": "datatables?v=1\n datatables?v=Guid.NewGuid()\n <script src=\"~/scripts/main.js?v=@File.GetLastWriteTime(Server.MapPath(\"/scripts/main.js\")).ToString(\"yyyyMMddHHmmss\")\"></script>\n" }, { "answer_id": 60723671, "author": "loretoparisi", "author_id": 758836, "author_profile": "https://Stackoverflow.com/users/758836", "pm_score": 1, "selected": false, "text": "<script>\n var script = document.createElement('script');\n script.src = \"js/app.js?v=\" + Math.random();\n document.getElementsByTagName('head')[0].appendChild(script);\n</script>\n" }, { "answer_id": 60959675, "author": "Amr Lotfy", "author_id": 1356559, "author_profile": "https://Stackoverflow.com/users/1356559", "pm_score": 0, "selected": false, "text": "<link rel=\"stylesheet\" href=\"bla_bla.css?v=my_timestamp\">\n<script src=\"scripts/bla_bla.js?v=my_timestamp\"></script>\n old_timestamp=$(cat timestamp.txt)\ncurrent_timestamp=$(date +%s)\nsed -i -e \"s/$old_timestamp/$current_timestamp/g\" index.html\necho \"$current_timestamp\" >timestamp.txt\n" }, { "answer_id": 63932033, "author": "Jayee", "author_id": 899742, "author_profile": "https://Stackoverflow.com/users/899742", "pm_score": 1, "selected": false, "text": "<link rel=\"stylesheet\" href=\"~/css/xxx.css\" asp-append-version=\"true\" />\n\n <script src=\"~/js/xxx.js\" asp-append-version=\"true\"></script>\n <link rel=\"stylesheet\" href=\"/css/xxx.css?v=rwgRWCjxemznsx7wgNx5PbMO1EictA4Dd0SjiW0S90g\" />\n" }, { "answer_id": 69619469, "author": "zyrup", "author_id": 1590519, "author_profile": "https://Stackoverflow.com/users/1590519", "pm_score": 0, "selected": false, "text": "time() <script src=\"<?php echo get_template_directory_uri(); ?>/js/main.js?v=<?= time() ?>\"></script>\n" }, { "answer_id": 71968270, "author": "Wervice", "author_id": 18889997, "author_profile": "https://Stackoverflow.com/users/18889997", "pm_score": 0, "selected": false, "text": "location.reload(true)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
118,905
<p>I'm trying to write a parser to get the data out of a typical html table day/time schedule (like <a href="http://kut.org/about/schedule" rel="nofollow noreferrer">this</a>). </p> <p>I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days &amp; times they occur. It should take into account rowspans and colspans, so for the linked example, it would return </p> <pre><code>{:event =&gt; "Music With Paul Ray", :times =&gt; [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc. </code></pre> <p>I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem?</p>
[ { "answer_id": 119460, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "for row in table:\n i = 0\n for cell in row: # skipping row 1\n event = name\n starttime = row[0]\n endtime = table[ i + cell.rowspan + 1 ][0]\n\n print event, starttime, endtime\n i += 1\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
118,935
<p>Know of an OCAML/CAML IDE? Especially one that runs on Linux?</p>
[ { "answer_id": 121134, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": false, "text": "vim hump godi -dtypes" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7888/" ]
118,955
<p>For various reasons, we are writing a new business objects/data storage library. One of the requirements of this layer is to separate the logic of the business rules, and the actual data storage layer. </p> <p>It is possible to have multiple data storage layers that implement access to the same object - for example, a main "database" data storage source that implements most objects, and another "ldap" source that implements a User object. In this scenario, User can optionally come from an LDAP source, perhaps with slightly different functionality (eg, not possible to save/update the User object), but otherwise it is used by the application the same way. Another data storage type might be a web service, or an external database.</p> <p>There are two main ways we are looking at implementing this, and me and a co-worker disagree on a fundamental level which is correct. I'd like some advice on which one is the best to use. I'll try to keep my descriptions of each as neutral as possible, as I'm looking for some objective view points here. </p> <ul> <li><p>Business objects are base classes, and data storage objects inherit business objects. Client code deals with data storage objects.</p> <p>In this case, common business rules are inherited by each data storage object, and it is the data storage objects that are directly used by the client code. </p> <p>This has the implication that client code determines which data storage method to use for a given object, because it has to explicitly declare an instance to that type of object. Client code needs to explicitly know connection information for each data storage type it is using.</p> <p>If a data storage layer implements different functionality for a given object, client code explicitly knows about it at compile time because the object looks different. If the data storage method is changed, client code has to be updated.</p></li> <li><p>Business objects encapsulate data storage objects.</p> <p>In this case, business objects are directly used by client application. Client application passes along base connection information to business layer. Decision about which data storage method a given object uses is made by business object code. Connection information would be a chunk of data taken from a config file (client app does not really know/care about details of it), which may be a single connection string for a database, or several pieces connection strings for various data storage types. Additional data storage connection types could also be read from another spot - eg, a configuration table in a database that specifies URLs to various web services. </p> <p>The benefit here is that if a new data storage method is added to an existing object, a configuration setting can be set at runtime to determine which method to use, and it is completely transparent to the client applications. Client apps do not need to be modified if data storage method for a given object changes. </p></li> <li><p>Business objects are base classes, data source objects inherit from business objects. Client code deals primarily with base classes.</p> <p>This is similar to the first method, but client code declares variables of the base business object types, and Load()/Create()/etc static methods on the business objects return the appropriate data source-typed objects. </p> <p>The architecture of this solution is similar to the first method, but the main difference is the decision about which data storage object to use for a given business object is made by the business layer, not the client code. </p></li> </ul> <p>I know there are already existing ORM libraries that provide some of this functionality, but please discount those for now (there is the possibility that a data storage layer is implemented with one of these ORM libraries) - also note I'm deliberately not telling you what language is being used here, other than that it is strongly typed.</p> <p>I'm looking for some general advice here on which method is better to use (or feel free to suggest something else), and why. </p>
[ { "answer_id": 2886344, "author": "Timex", "author_id": 179333, "author_profile": "https://Stackoverflow.com/users/179333", "pm_score": 1, "selected": false, "text": "using(MyConcreteBusinessContext ctx = new MyConcreteBusinessContext(\"datares://model1?DataSource=myserver;Catalog=mydatabase;Trusted_Connection=True ruleres://someruleresource?type=StaticRules&handler=My.Org.Business.Model.RuleManager\")) {\n\nUser user = ctx.GetUserById(\"SZE543\");\nuser.IsLogonActive = false;\nctx.Save();\n}\n\n//a business object\nclass User : BusinessBase {\n public User(BusinessContext ctx) : base(ctx) {}\n\n public bool Validate() {\n IValidator v = ctx.GetValidator(this);\n return v.Validate();\n }\n}\n\n// a validator\nclass UserValidator : BaseValidator, IValidator {\n User userInstance;\n public UserValidator(User user) {\n userInstance = user;\n }\n\n public bool Validate() {\n // actual validation code here\n return true;\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7913/" ]
118,984
<p>Sight is one of the senses most programmers take for granted. Most programmers would spend hours looking at a computer monitor (especially during times when they are <em>in the zone</em>), but I know there are blind programmers (such as T.V. Raman who currently works for Google).</p> <p>If you were a blind person (or slowly becoming blind), how would you set up your development environment to assist you in programming?</p> <p>(One suggestion per answer please. The purpose of this question is to bring the good ideas to the top. In addition, screen readers can read the good ideas earlier.)</p>
[ { "answer_id": 2149878, "author": "Edward Kmett", "author_id": 34707, "author_profile": "https://Stackoverflow.com/users/34707", "pm_score": 5, "selected": false, "text": "{;}" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/118984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599/" ]
119,006
<p>So I have a problem. I checked in my frozen gems and rails even though you aren't supposed to do that. I figured it was easy and wouldn't be that big of a deal anyway. Well, later I updated rails and in doing so deleted all the .svn files in the vendor/rails directories. I have heard that what I really <em>should</em> do is just do something to do with svn:externals to my vendor directory. What exactly do I need to do and will capistrano still use my frozen gems if they aren't in my repo? If it will not use my frozen gems how can I regenerate those .svn files correctly, because this <em>will</em> happen again.</p> <p>Thanks!</p>
[ { "answer_id": 122928, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 3, "selected": true, "text": ".svn svn update gem unpack <gemname> vendor/gems svn add commit vendor/plugins vendor/rails % piston import http://dev.rubyonrails.org/svn/rails/tags/rel_2-0-2/ vendor/rails gem install piston" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
119,008
<p>I recently installed MySQL 5 on Windows 2003 and tried configuring an instance. Everything worked fine until I got to "Applying Security settings", at which point it gave me the above error (<code>Can't connect to MySQL server on 'localhost' (10061)</code>).</p> <p>I do have a port 3306 exception in my firewall for 'MySQL Server'. </p>
[ { "answer_id": 119033, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 6, "selected": true, "text": "'GRANT'" }, { "answer_id": 18281036, "author": "user2690551", "author_id": 2690551, "author_profile": "https://Stackoverflow.com/users/2690551", "pm_score": 1, "selected": false, "text": "MySql iptables TCP my.cnf MySql" }, { "answer_id": 19137455, "author": "Uday Hiwarale", "author_id": 2790983, "author_profile": "https://Stackoverflow.com/users/2790983", "pm_score": 3, "selected": false, "text": "c://windows/system32/drivers/etc.host 127.0.0.1 localhost\n::1 localhost\n" }, { "answer_id": 25162233, "author": "hmehandi", "author_id": 3256694, "author_profile": "https://Stackoverflow.com/users/3256694", "pm_score": 0, "selected": false, "text": "basedir=D:/D_Drive/mysql-5.6.20-win32\ndatadir=D:/D_Drive/mysql-5.6.20-win32/data\nport=8888\n" }, { "answer_id": 35894222, "author": "Kuzhichamadam Inn", "author_id": 6039866, "author_profile": "https://Stackoverflow.com/users/6039866", "pm_score": 1, "selected": false, "text": "run > services.msc > rightclick MySQL57 > properties >set start type option to automatic\n cd: C:\\\n\nC :\\> cd \"C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin\"\n C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin>\n mysql -u root -p C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin> mysql -u root -p **** mysql>\n" }, { "answer_id": 45854188, "author": "Muhammad Abbas", "author_id": 4029409, "author_profile": "https://Stackoverflow.com/users/4029409", "pm_score": 2, "selected": false, "text": "services.msc. MySQL Show" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1748529/" ]
119,009
<p>In our Java applications we typically use the maven conventions (docs, src/java, test, etc.). For Perl we follow similar conventions only using a top level 'lib' which is easy to add to Perl's @INC.</p> <p>I'm about to embark on creating a service written in Erlang, what's a good source layout for Erlang applications?</p>
[ { "answer_id": 809497, "author": "psyeugenic", "author_id": 99013, "author_profile": "https://Stackoverflow.com/users/99013", "pm_score": 2, "selected": false, "text": "code:priv_dir(Name) -> string() | {error, bad_name}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ]
119,011
<p>Can anyone suggest a good way of detecting if a database is empty from Java (needs to support at least Microsoft SQL Server, Derby and Oracle)?</p> <p>By empty I mean in the state it would be if the database were freshly created with a new create database statement, though the check need not be 100% perfect if covers 99% of cases.</p> <p>My first thought was to do something like this...</p> <pre><code>tables = metadata.getTables(null, null, null, null); Boolean isEmpty = !tables.next(); return isEmpty; </code></pre> <p>...but unfortunately that gives me a bunch of underlying system tables (at least in Microsoft SQL Server).</p>
[ { "answer_id": 119066, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 2, "selected": false, "text": "SELECT COUNT(*) FROM [INFORMATION_SCHEMA].[TABLES] WHERE [TABLE_TYPE] = <tabletype>\n SELECT COUNT(*) FROM [sysobjects] WHERE [type] = 'U'\n" }, { "answer_id": 119086, "author": "user19113", "author_id": 19113, "author_profile": "https://Stackoverflow.com/users/19113", "pm_score": 1, "selected": false, "text": "int nonSystemTableCount = 0;\ntables = metadata.getTables(null, null, null, null);\nwhile( tables.next () ) {\n if( !\"SYSTEM TABLE\".equals( tables.getString( \"table_type\" ) ) ) {\n nonSystemTableCount++;\n }\n}\nboolean isEmpty = nonSystemTableCount == 0;\nreturn isEmpty;\n" }, { "answer_id": 44615862, "author": "Naor Bar", "author_id": 6792588, "author_profile": "https://Stackoverflow.com/users/6792588", "pm_score": 0, "selected": false, "text": "select count(*) from user_tables\nselect count(*) from user_sequences\nselect count(*) from user_indexes\n SELECT * FROM sys.all_objects where type_desc in ('USER_TABLE', 'SQL_STORED_PROCEDURE', 'VIEW')\n <project name=\"run_sql_query\" basedir=\".\" default=\"main\">\n <!-- run_sql_query: --> \n <target name=\"run_sql_query\">\n <echo message=\"=== running sql query from file ${database.src.file}; check the result in ${database.out.file} ===\"/>\n <sql classpath=\"${jdbc.jar.file}\" \n driver=\"${database.driver.class}\" \n url=\"${database.url}\" \n userid=\"${database.user}\" \n password=\"${database.password}\" \n src=\"${database.src.file}\"\n output=\"${database.out.file}\"\n print=\"yes\"/>\n </target>\n\n <!-- Main: --> \n <target name=\"main\" depends=\"run_sql_query\"/> \n</project> \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
119,060
<p>The Image Web Part doesn't seem to have an href attribute that I can set. Is there something I am missing?</p>
[ { "answer_id": 119122, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 3, "selected": false, "text": "<a href=\"http://www.google.com\"><img src=\"urlToImage\" /></a>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,098
<p>In new C++ code, I tend to use the C++ iostream library instead of the C stdio library.</p> <p>I've noticed some programmers seem to stick to stdio, insisting that it's more portable.</p> <p>Is this really the case? What is better to use?</p>
[ { "answer_id": 119149, "author": "Mikael Jansson", "author_id": 18753, "author_profile": "https://Stackoverflow.com/users/18753", "pm_score": 4, "selected": false, "text": "// nonsense output, just to examplify\nfprintf(stderr, \"at %p/%s: mean value %.3f of %4d samples\\n\",\n stats, stats->name, stats->mean, stats->sample_count);\n std::cerr << \"at \" << static_cast<void*>(stats) << \"/\" << stats->name\n << \": mean value \" << std::precision(3) << stats->mean\n << \" of \" << std::width(4) << std::fill(' ') << stats->sample_count\n << \" samples \" << std::endl;\n format iostream" }, { "answer_id": 119194, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": true, "text": "Disadvantages of iostreams: verbose\nAdvantages of iostreams: easy to extend for new non POD types.\n #include <iostream>\n#include <iomanip>\n#include <boost/format.hpp>\n\nstruct X\n{ // this structure reverse engineered from\n // example provided by 'Mikael Jansson' in order to make this a running example\n\n char* name;\n double mean;\n int sample_count;\n};\nint main()\n{\n X stats[] = {{\"Plop\",5.6,2}};\n\n // nonsense output, just to exemplify\n\n // stdio version\n fprintf(stderr, \"at %p/%s: mean value %.3f of %4d samples\\n\",\n stats, stats->name, stats->mean, stats->sample_count);\n\n // iostream\n std::cerr << \"at \" << (void*)stats << \"/\" << stats->name\n << \": mean value \" << std::fixed << std::setprecision(3) << stats->mean\n << \" of \" << std::setw(4) << std::setfill(' ') << stats->sample_count\n << \" samples\\n\";\n\n // iostream with boost::format\n std::cerr << boost::format(\"at %p/%s: mean value %.3f of %4d samples\\n\")\n % stats % stats->name % stats->mean % stats->sample_count;\n}\n" }, { "answer_id": 1781584, "author": "R Samuel Klatchko", "author_id": 29809, "author_profile": "https://Stackoverflow.com/users/29809", "pm_score": 2, "selected": false, "text": "// i18n UNSAFE \nstd::cout << \"Dear \" << name.given << ' ' << name.family << std::endl;\n" }, { "answer_id": 8256127, "author": "Sebastian Mach", "author_id": 76722, "author_profile": "https://Stackoverflow.com/users/76722", "pm_score": 2, "selected": false, "text": "// foo.h\n...\nfloat foo;\n...\n // bar/frob/42/icetea.cpp\n...\nscanf (\"%f\", &foo);\n...\n // foo.h\n...\nFixedPoint foo;\n...\n // bar/frob/42/icetea.cpp\n...\nscanf (\"%f\", &foo);\n...\n printf (\"My Matrix: %f %f %f %f\\n\"\n \" %f %f %f %f\\n\"\n \" %f %f %f %f\\n\"\n \" %f %f %f %f\\n\",\n mat(0,0), mat(0,1), mat(0,2), mat(0,3), \n mat(1,0), mat(1,1), mat(1,2), mat(1,3), \n mat(2,0), mat(2,1), mat(2,2), mat(2,3), \n mat(3,0), mat(3,1), mat(3,2), mat(3,3));\n cout << mat << '\\n';\n FixedPoint printf (\"Guten Morgen, Sie sind %f Meter groß und haben %d Kinder\", \n someFloat, someInt);\n\nprintf (\"Good morning, you have %d children and your height is %f meters\",\n someFloat, someInt); // Note: Position changed.\n\n// ^^ not the best example, but different languages have generally different\n// order of \"variables\"\n cout << format(\"%1% %2% %3% %2% %1% \\n\") % \"11\" % \"22\" % \"333\"; // 'simple' style.\n shared_ptr<float> f(new float);\nfscanf (stdout, \"%u %s %f\", f)\n const char *output = \"in total, the thing is 50%\"\n \"feature complete\";\nprintf (output);\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
119,099
<p>Do you know any libraries similar to java.util.Properties that support more advanced features like grouping properties, storing arrays, etc? I am not looking for some heavy super-advanced solution, just something light and useful for any project.</p> <p>Thanks.</p>
[ { "answer_id": 119113, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "java.util.prefs" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
119,107
<p>This is what I have so far: </p> <pre><code>myArray.map!{ rand(max) } </code></pre> <p>Obviously, however, sometimes the numbers in the list are not unique. How can I make sure my list only contains unique numbers without having to create a bigger list from which I then just pick the n unique numbers?</p> <p><strong>Edit:</strong><br> I'd really like to see this done w/o loop - if at all possible.</p>
[ { "answer_id": 119120, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 1, "selected": false, "text": "seen = {}\nmax = 100\n(1..10).map { |n|\n x = rand(max)\n while (seen[x]) \n x = rand(max)\n end\n x\n}\n" }, { "answer_id": 119159, "author": "Ryan Leavengood", "author_id": 20891, "author_profile": "https://Stackoverflow.com/users/20891", "pm_score": 6, "selected": true, "text": "require 'set'\n\ndef rand_n(n, max)\n randoms = Set.new\n loop do\n randoms << rand(max)\n return randoms.to_a if randoms.size >= n\n end\nend\n" }, { "answer_id": 119174, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 0, "selected": false, "text": "r_min r_max r list[i]=list[i-1]+r r+list[i-1] r r_min list[i-1] r_max r_min r_max" }, { "answer_id": 119250, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 6, "selected": false, "text": "(0..50).to_a.sort{ rand() - 0.5 }[0..x] \n (0..50).to_a (0..5).to_a ==> [0,1,2,3,4,5]\n[0,1,2,3,4,5].sort{ -1 } ==> [0, 1, 2, 4, 3, 5] # constant\n[0,1,2,3,4,5].sort{ 1 } ==> [5, 3, 0, 4, 2, 1] # constant\n[0,1,2,3,4,5].sort{ rand() - 0.5 } ==> [1, 5, 0, 3, 4, 2 ] # random\n[1, 5, 0, 3, 4, 2 ][ 0..2 ] ==> [1, 5, 0 ]\n Array#shuffle Array#sort .sort{ rand() - 0.5 }\n .shuffle\n [0..x]\n Array#take .take(x)\n (0..50).to_a.shuffle.take(x)\n" }, { "answer_id": 119429, "author": "Ryan Leavengood", "author_id": 20891, "author_profile": "https://Stackoverflow.com/users/20891", "pm_score": 1, "selected": false, "text": "require 'set'\n\ndef rand_n(n, max)\n randoms = Set.new\n i = 0\n loop do\n randoms << rand(max)\n break if randoms.size > n\n i += 1\n end\n puts \"Took #{i} iterations for #{n} random numbers to a max of #{max}\"\n return randoms.to_a\nend\n" }, { "answer_id": 120637, "author": "TuxmAL", "author_id": 11594, "author_profile": "https://Stackoverflow.com/users/11594", "pm_score": 0, "selected": false, "text": "class NoLoopRand\n def initialize(max)\n @deck = (0..max).to_a\n end\n\n def getrnd\n return @deck.delete_at(rand(@deck.length - 1))\n end\nend\n aRndNum = NoLoopRand.new(10)\nputs aRndNum.getrnd\n nil" }, { "answer_id": 122440, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 5, "selected": false, "text": "a = (0...1000000).sort_by{rand}\n" }, { "answer_id": 125771, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "x = 0\n(1..100).map{|iter| x += rand(100)}.shuffle\n" }, { "answer_id": 8875944, "author": "Doug English", "author_id": 754936, "author_profile": "https://Stackoverflow.com/users/754936", "pm_score": 1, "selected": false, "text": "def n_unique_rand(number_to_generate, rand_upper_limit)\n return (0..rand_upper_limit - 1).sort_by{rand}[0..number_to_generate - 1]\nend\n" }, { "answer_id": 9882824, "author": "Duncan Beevers", "author_id": 132089, "author_profile": "https://Stackoverflow.com/users/132089", "pm_score": 5, "selected": false, "text": "(1..999).to_a.sample 5 # => [389, 30, 326, 946, 746]\n to_a.sort_by sample sort_by sample require 'benchmark'\nrange = 0...1000000\nhow_many = 5\n\nBenchmark.realtime do\n range.to_a.sample(how_many)\nend\n=> 0.081083\n\nBenchmark.realtime do\n (range).sort_by{rand}[0...how_many]\nend\n=> 2.907445\n" }, { "answer_id": 12975652, "author": "mmdemirbas", "author_id": 471214, "author_profile": "https://Stackoverflow.com/users/471214", "pm_score": 0, "selected": false, "text": "# Generates a random array of length n.\n#\n# @param n length of the desired array\n# @param lower minimum number in the array\n# @param upper maximum number in the array\ndef ary_rand(n, lower, upper)\n values_set = (lower..upper).to_a\n repetition = n/(upper-lower+1) + 1\n (values_set*repetition).sample n\nend\n def ary_rand2(n, lower, upper)\n v = (lower..upper).to_a\n (0...n).map{ v[rand(v.length)] }\nend\n puts (ary_rand 5, 0, 9).to_s # [0, 8, 2, 5, 6] expected\nputs (ary_rand 5, 0, 9).to_s # [7, 8, 2, 4, 3] different result for same params\nputs (ary_rand 5, 0, 1).to_s # [0, 0, 1, 0, 1] repeated values from limited range\nputs (ary_rand 5, 9, 0).to_s # [] no such range :)\n" }, { "answer_id": 32370822, "author": "Andrei Madalin Butnaru", "author_id": 2141840, "author_profile": "https://Stackoverflow.com/users/2141840", "pm_score": 1, "selected": false, "text": "Array.new(size) { rand(max) }\n\nrequire 'benchmark'\nmax = 1000000\nsize = 5\nBenchmark.realtime do\n Array.new(size) { rand(max) }\nend\n\n=> 1.9114e-05 \n" }, { "answer_id": 61862553, "author": "Eric Mathison", "author_id": 1133429, "author_profile": "https://Stackoverflow.com/users/1133429", "pm_score": 2, "selected": false, "text": "[*1..99].sample(4) #=> [64, 99, 29, 49]\n Array#sample SecureRandom require 'securerandom'\n\n[*1..99].sample(4, random: SecureRandom) #=> [2, 75, 95, 37]\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
119,114
<p>I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.</p> <p>Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ?</p> <p>What I am after is a way of defining a symbol, let's call it _ATHOME, automatically so I can do this:</p> <pre><code>#ifdef _ATHOME # define TEST_FILES "E:\\Test" # define TEST_SERVER "192.168.0.1" #else # define TEST_FILE "Z:\\Project\\Blah\\Test" # define TEST_SERVER "212.45.68.43" #endif </code></pre> <p><em>NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.</em></p>
[ { "answer_id": 119148, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "LOCATION #if LOCATION==1\n // home\n#else\n // work\n#endif\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
119,123
<p>Why does the <code>sizeof</code> operator return a size larger for a structure than the total sizes of the structure's members?</p>
[ { "answer_id": 119128, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 11, "selected": true, "text": "SIGBUS struct X\n{\n short s; /* 2 bytes */\n /* 2 padding bytes */\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 3 padding bytes */\n};\n\nstruct Y\n{\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n short s; /* 2 bytes */\n};\n\nstruct Z\n{\n int i; /* 4 bytes */\n short s; /* 2 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n};\n\nconst int sizeX = sizeof(struct X); /* = 12 */\nconst int sizeY = sizeof(struct Y); /* = 8 */\nconst int sizeZ = sizeof(struct Z); /* = 8 */\n Z #pragma" }, { "answer_id": 119134, "author": "EmmEff", "author_id": 9188, "author_profile": "https://Stackoverflow.com/users/9188", "pm_score": 8, "selected": false, "text": "struct {\n char a[3];\n short int b;\n long int c;\n char d[3];\n};\n +-------+-------+-------+-------+\n| a | b |\n+-------+-------+-------+-------+\n| b | c |\n+-------+-------+-------+-------+\n| c | d |\n+-------+-------+-------+-------+\n +-------+-------+-------+\n| a |\n+-------+-------+-------+\n| b |\n+-------+-------+-------+-------+\n| c |\n+-------+-------+-------+-------+\n| d |\n+-------+-------+-------+\n +-------+-------+-------+-------+\n| a | pad1 |\n+-------+-------+-------+-------+\n| b | pad2 |\n+-------+-------+-------+-------+\n| c |\n+-------+-------+-------+-------+\n| d | pad3 |\n+-------+-------+-------+-------+\n" }, { "answer_id": 119144, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 4, "selected": false, "text": "#include \"stdio.h\"\n\n\nstruct oneInt {\n int x;\n};\n\nstruct twoInts {\n int x;\n int y;\n};\n\nstruct someBits {\n int x:2;\n int y:6;\n};\n\n\nint main (int argc, char** argv) {\n printf(\"oneInt=%zu\\n\",sizeof(struct oneInt));\n printf(\"twoInts=%zu\\n\",sizeof(struct twoInts));\n printf(\"someBits=%zu\\n\",sizeof(struct someBits));\n return 0;\n}\n oneInt=4\ntwoInts=8\nsomeBits=4\n" }, { "answer_id": 119491, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 5, "selected": false, "text": "__attribute__((packed))" }, { "answer_id": 30760303, "author": "sid1138", "author_id": 4995406, "author_profile": "https://Stackoverflow.com/users/4995406", "pm_score": 3, "selected": false, "text": "struct myStruct\n{\n int a;\n char b;\n int c;\n} data;\n #pragma pack 1\nstruct MyStruct\n{\n int a;\n char b;\n int c;\n short d;\n} myData;\n\nI = sizeof(myData);\n" }, { "answer_id": 35595109, "author": "DigitalRoss", "author_id": 140740, "author_profile": "https://Stackoverflow.com/users/140740", "pm_score": 3, "selected": false, "text": "struct pixel {\n unsigned char red; // 0\n unsigned char green; // 1\n unsigned int alpha; // 4 (gotta skip to an aligned offset)\n unsigned char blue; // 8 (then skip 9 10 11)\n};\n\n// next offset: 12\n" }, { "answer_id": 37032302, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 3, "selected": false, "text": "struct S {int is[];};" }, { "answer_id": 62640093, "author": "RobertS supports Monica Cellio", "author_id": 12139179, "author_profile": "https://Stackoverflow.com/users/12139179", "pm_score": 2, "selected": false, "text": "sizeof sizeof sizeof sizeof sizeof struct foo {\n int a; \n int b;\n int c; \n} bar;\n sizeof(int) == 4 bar sizeof(bar) == 12 struct foo {\n short int a; \n short int b;\n int c; \n} bar;\n sizeof(short int) == 2 sizeof(int) == 4 a b c sizeof(bar) == 8" }, { "answer_id": 72010091, "author": "Zrn-dev", "author_id": 14265581, "author_profile": "https://Stackoverflow.com/users/14265581", "pm_score": 0, "selected": false, "text": "#pragma pack(push, 1)\n\n// your structure\n\n#pragma pack(pop) \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ]
119,146
<p>I have a legacy VB6 executable that runs on Vista. This executable shells out another legacy MFC C++ executable.</p> <p>In our early Vista testing, this call would display the typical UAC message to get the user's permission before running the second executable. This wasn't perfect, but acceptable. However, it now looks like this call is being completely ignored by the OS.</p> <p>What can I do to make this call work?</p>
[ { "answer_id": 122814, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 0, "selected": false, "text": "Private Declare Function CreateProcess Lib \"kernel32\" Alias \"CreateProcessA\" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long\n\nPrivate Declare Function WaitForSingleObject Lib \"kernel32\" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long\n\nPrivate Type PROCESS_INFORMATION\n hProcess As Long\n hThread As Long\n dwProcessId As Long\n dwThreadId As Long\nEnd Type\n\nPrivate Type STARTUPINFO\n cb As Long\n lpReserved As String\n lpDesktop As String\n lpTitle As String\n dwX As Long\n dwY As Long\n dwXSize As Long\n dwYSize As Long\n dwXCountChars As Long\n dwYCountChars As Long\n dwFillAttribute As Long\n dwFlags As Long\n wShowWindow As Integer\n cbReserved2 As Integer\n lpReserved2 As Long\n hStdInput As Long\n hStdOutput As Long\n hStdError As Long\nEnd Type\n\n Dim ProcessInformation As PROCESS_INFORMATION\n Dim StartupInformation As STARTUPINFO\n Dim ReturnValue As Long\n Dim NullString As String\n Dim AppPathString As String\n\n StartupInformation.cb = Len(StartupInformation)\n\n ReturnValue = CreateProcess(NullString, AppPathString, ByVal 0&, ByVal 0&, 1&, NORMAL_PRIORITY_CLASS, ByVal 0&, NullString, StartupInformation, ProcessInformation)\n '\n 'If you need to wait for the exe to finish\n '\n Do While WaitForSingleObject(ProcessInformation.hProcess, 0) <> 0\n DoEvents\n Loop\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6354/" ]
119,167
<p>I'm taking a look at how the model system in django works and I noticed something that I don't understand.</p> <p>I know that you create an empty <code>__init__.py</code> file to specify that the current directory is a package. And that you can set some variable in <code>__init__.py</code> so that import * works properly.</p> <p>But django adds a bunch of from ... import ... statements and defines a bunch of classes in <code>__init__.py</code>. Why? Doesn't this just make things look messy? Is there a reason that requires this code in <code>__init__.py</code>?</p>
[ { "answer_id": 119178, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 7, "selected": true, "text": "__init__.py ./dir/__init__.py import something\n ./test.py import dir\n# can now use dir.something\n __init__.py __init__.py import something import datetime test.py import dir\nprint dir.datetime.datetime.now()\n import dir.some_module_in_dir\nprint dir.datetime.datetime.now()\n __init__.py" }, { "answer_id": 119346, "author": "dgrant", "author_id": 9484, "author_profile": "https://Stackoverflow.com/users/9484", "pm_score": 5, "selected": false, "text": "erikutils sys.path sys.path __init__.py fileutils procutils parseutils erikutils erikutils\n __init__.py\n fileutils.py\n procutils.py\n parseutils.py\n fileutils procutils parseutils miscutils erikutils.foo()\nerikutils.bar()\n erikutils.miscutils.foo()\nerikutils.miscutils.bar()\n erikutils __init__.py django.db.models.fields __init__.py __init__.py" }, { "answer_id": 126499, "author": "nikow", "author_id": 11992, "author_profile": "https://Stackoverflow.com/users/11992", "pm_score": 5, "selected": false, "text": "__init__.py __init__.py del __init__.py from somemodule import some_function1, some_function2, SomeObject\n\ndel somemodule\n somemodule __init__.py from somemodule1 import some_function1, some_function2\nfrom somemodule2 import SomeObject\n\ndel somemodule1\ndel somemodule2\n" }, { "answer_id": 73379400, "author": "joepitz1", "author_id": 4495533, "author_profile": "https://Stackoverflow.com/users/4495533", "pm_score": 2, "selected": false, "text": "__init__.py from x import * __init__.py" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3935/" ]
119,168
<p>I have a datagridview assigned a datasource to it. now how to add a new row to that grid and remove a row from it?</p>
[ { "answer_id": 119337, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "// the data grid\nDataGridView dataGrid;\n\n// create a new data table\nDataTable table = new DataTable();\n\n// create the data adapter\nSqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strDSN);\n\n// populate the table using the SQL adapter\ndataAdapter.Fill(table);\n\n// bind the table to a data source\nBindingSource dbSource = new BindingSource();\ndbSource.DataSource = table;\n\n// finally bind the data source to the grid\ndataGrid.DataSource = dbSource;\n dataAdapter.DeleteCommand = new SqlCommand(...);\n\ndataAdapter.InsertCommand = new SqlCommand(...);\n\ndataAdapter.UpdateCommand = new SqlCommand(...);\n public int DeleteSelectedItems()\n{\n int itemsDeleted = 0;\n\n int count = dataGrid.RowCount;\n\n for (int i = count - 1; i >=0; --i)\n {\n DataGridViewRow row = dataGrid.Rows[i];\n\n if (row.Selected == true)\n {\n dataGrid.Rows.Remove(row);\n\n // count the item deleted\n ++itemsDeleted;\n }\n }\n\n // commit the deletes made\n if (itemsDeleted > 0) Commit();\n}\n public void Commit()\n{\n SqlConnection cn = new SqlConnection();\n\n cn.ConnectionString = \"Do the connection using a DSN\";\n\n // open the connection\n cn.Open();\n\n // commit any data changes\n dataAdapter.DeleteCommand.Connection = cn;\n dataAdapter.InsertCommand.Connection = cn;\n dataAdapter.UpdateCommand.Connection = cn;\n dataAdapter.Update(table);\n dataAdapter.DeleteCommand.Connection = null;\n dataAdapter.InsertCommand.Connection = null;\n dataAdapter.UpdateCommand.Connection = null;\n\n // clean up\n cn.Close();\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,180
<p>What tools allows me keep track of tags when doing web development? For example, I would like to be able to quickly find whether I missed closing a div tag.</p> <p>At the moment I am using notepad++ to write html. It highlights starting and ending tags, but it can take me time to review almost all tags to find where I went wrong.</p>
[ { "answer_id": 119203, "author": "NGittlen", "author_id": 10047, "author_profile": "https://Stackoverflow.com/users/10047", "pm_score": 2, "selected": false, "text": "<body>\n <div>\n Content here...\n </div>\n</body>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
119,197
<p>I have a question about how to do something "The Rails Way". With an application that has a public facing side and an admin interface what is the general consensus in the Rails community on how to do it?</p> <p>Namespaces, subdomains or forego them altogether?</p>
[ { "answer_id": 120168, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 6, "selected": true, "text": "map.namespace :admin do |admin|\n admin.resources :users\n admin.resources :posts\nend\n class Admin::UsersController < ApplicationController\n before_filter :admin_required\n # ...\nend\n class ApplicationController < ActionController::Base\n # ...\n\n protected\n def admin_required\n authenticate_or_request_with_http_basic do |user_name, password|\n user_name == 'admin' && password == 's3cr3t'\n end if RAILS_ENV == 'production' || params[:admin_http]\n end\nend\n authenticate_or_request_with_http_basic ?admin_http=true" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20899/" ]
119,204
<p>I have a large quantity of clearcase data which needs to be migrated into perforce. The revisions span the better part of a decade and I need to preserve as much branch and tag information as possible. Additionally we make extensive use of symbolic links, supported in clearcase but not in perforce. What advice or tools can you suggest which might make this easier? </p>
[ { "answer_id": 2945241, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "//depot/projecta p4 sync //depot/projecta/...@42\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361/" ]
119,207
<p>I'm new to Ruby, and I'm trying the following: </p> <pre><code>mySet = numOfCuts.times.map{ rand(seqLength) } </code></pre> <p>but I get the 'yield called out of block' error. I'm not sure what his means. BTW, this question is part of a more general question I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby"><strong>here</strong></a>.</p>
[ { "answer_id": 119226, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "5.times.foo \n 5.times{ code here } \n" }, { "answer_id": 119236, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 4, "selected": true, "text": "mySet = (1..numOfCuts).map{ rand(seqLength) }\n mySet = []\nnumOfCuts.times {mySet.push( rand(seqLength) )}\n" }, { "answer_id": 119249, "author": "Kyle Burton", "author_id": 19784, "author_profile": "https://Stackoverflow.com/users/19784", "pm_score": 1, "selected": false, "text": "irb(main):089:0> 2.times {|x| puts x}\n0\n1\n2\n irb(main):092:0> (1..3).map { |x| puts x; x+1 }\n1\n2\n3\n[2, 3, 4]\n" }, { "answer_id": 119255, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 0, "selected": false, "text": "yield times (1..5).map{ do something }\n" }, { "answer_id": 120832, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 1, "selected": false, "text": ">> 3.times.map\n=> [0, 1, 2]\n>> \n irb(main):001:0> 3.times.map\nLocalJumpError: yield called out of block\n from (irb):2:in `times'\n from (irb):2:in `signal_status'\nirb(main):002:0> \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
119,271
<p>Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.</p> <pre><code>{ProjectName} |-----&gt;Source |-----&gt;Tools |-----&gt;Viewer |-----{about 5 sub dirs} </code></pre> <p>What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far.</p> <pre><code>&lt;ItemGroup&gt; &lt;Viewer Include=&quot;..\$(ApplicationDirectory)\Tools\viewer\**\*.*&quot; /&gt; &lt;/ItemGroup&gt; &lt;Target Name=&quot;BeforeBuild&quot;&gt; &lt;Copy SourceFiles=&quot;@(Viewer)&quot; DestinationFolder=&quot;@(Viewer-&gt;'$(OutputPath)\\Tools')&quot; /&gt; &lt;/Target&gt; </code></pre> <p>The build script runs but doesn't copy any of the files or folders.</p> <p>Thanks</p>
[ { "answer_id": 119288, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "DestinationFolder=\"@(Viewer->'$(OutputPath)\\\\Tools')\" ? \n @(Viewer->'$(OutputPath)\\\\Tools') \n $(ApplicationDirectory) $(OutputPath)" }, { "answer_id": 120700, "author": "brock.holum", "author_id": 15860, "author_profile": "https://Stackoverflow.com/users/15860", "pm_score": 6, "selected": false, "text": "<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <PropertyGroup>\n <YourDestinationDirectory>..\\SomeDestinationDirectory</YourDestinationDirectory>\n <YourSourceDirectory>..\\SomeSourceDirectory</YourSourceDirectory>\n </PropertyGroup>\n\n <Target Name=\"BeforeBuild\">\n <CreateItem Include=\"$(YourSourceDirectory)\\**\\*.*\">\n <Output TaskParameter=\"Include\" ItemName=\"YourFilesToCopy\" />\n </CreateItem>\n\n <Copy SourceFiles=\"@(YourFilesToCopy)\"\n DestinationFiles=\"@(YourFilesToCopy->'$(YourDestinationDirectory)\\%(RecursiveDir)%(Filename)%(Extension)')\" />\n </Target>\n</Project>\n" }, { "answer_id": 1993557, "author": "Denzil Brown", "author_id": 242509, "author_profile": "https://Stackoverflow.com/users/242509", "pm_score": 5, "selected": false, "text": "<Target Name=\"CopyToDeployFolder\" DependsOnTargets=\"CompileWebSite\">\n <Exec Command=\"xcopy.exe $(OutputDirectory) $(DeploymentDirectory) /e\" WorkingDirectory=\"C:\\Windows\\\" />\n</Target>\n" }, { "answer_id": 13136116, "author": "amit thakur", "author_id": 1785119, "author_profile": "https://Stackoverflow.com/users/1785119", "pm_score": 4, "selected": false, "text": "<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" ToolsVersion=\"3.5\">\n <PropertyGroup>\n <YourDestinationDirectory>..\\SomeDestinationDirectory</YourDestinationDirectory>\n <YourSourceDirectory>..\\SomeSourceDirectory</YourSourceDirectory>\n </PropertyGroup>\n\n <Target Name=\"BeforeBuild\">\n <CreateItem Include=\"$(YourSourceDirectory)\\**\\*.*\">\n <Output TaskParameter=\"Include\" ItemName=\"YourFilesToCopy\" />\n </CreateItem>\n\n <Copy SourceFiles=\"@(YourFilesToCopy)\"\n DestinationFiles=\"$(YourFilesToCopy)\\%(RecursiveDir)\" />\n </Target>\n</Project>\n \\**\\*.*" }, { "answer_id": 15720600, "author": "Rodolfo Neuber", "author_id": 561894, "author_profile": "https://Stackoverflow.com/users/561894", "pm_score": 7, "selected": false, "text": "<Target Name=\"AfterBuild\">\n <ItemGroup>\n <ANTLR Include=\"..\\Data\\antlrcs\\**\\*.*\" />\n </ItemGroup>\n <Copy SourceFiles=\"@(ANTLR)\" DestinationFolder=\"$(TargetDir)\\%(RecursiveDir)\" SkipUnchangedFiles=\"true\" />\n</Target>\n antlrcs $(TargetDir)" }, { "answer_id": 33407475, "author": "PBo", "author_id": 5262306, "author_profile": "https://Stackoverflow.com/users/5262306", "pm_score": 2, "selected": false, "text": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n\n <ItemGroup>\n <MySourceFiles Include=\"c:\\MySourceTree\\**\\*.*\"/>\n </ItemGroup>\n\n <Target Name=\"CopyFiles\">\n <Copy\n SourceFiles=\"@(MySourceFiles)\"\n DestinationFiles=\"@(MySourceFiles->'c:\\MyDestinationTree\\%(RecursiveDir)%(Filename)%(Extension)')\"\n />\n </Target>\n\n</Project>\n" }, { "answer_id": 40157299, "author": "nzrytmn", "author_id": 3193030, "author_profile": "https://Stackoverflow.com/users/3193030", "pm_score": 2, "selected": false, "text": "<ItemGroup >\n<MyProjectSource Include=\"$(OutputRoot)/MySource/**/*.*\" />\n</ItemGroup>\n\n<Target Name=\"AfterCopy\" AfterTargets=\"WebPublish\">\n<Copy SourceFiles=\"@(MyProjectSource)\" \n OverwriteReadOnlyFiles=\"true\" DestinationFolder=\"$(PublishFolder)api/% (RecursiveDir)\"/>\n" }, { "answer_id": 55887267, "author": "Shivinder Singh", "author_id": 11204896, "author_profile": "https://Stackoverflow.com/users/11204896", "pm_score": 0, "selected": false, "text": "<PropertyGroup>\n<BuildDirectory Condition=\"'$(BuildDirectory)' == ''\">Build</BuildDirectory>\n<BackupDirectory Condition=\"'$(BackupDiretory)' == ''\">Backup</BackupDirectory>\n</PropertyGroup>\n\n<ItemGroup>\n<AllFiles Include=\"$(MSBuildProjectDirectory)/$(BuildDirectory)/**/*.*\" />\n</ItemGroup>\n\n<Target Name=\"Backup\">\n<Exec Command=\"if not exist $(BackupDirectory) md $(BackupDirectory)\" />\n<Copy SourceFiles=\"@(AllFiles)\" DestinationFiles=\"@(AllFiles-> \n'$(MSBuildProjectDirectory)/$(BackupDirectory)/%(RecursiveDir)/%(Filename)% \n(Extension)')\" />\n</Target>\n" }, { "answer_id": 58138939, "author": "Sergei Ozerov", "author_id": 7666352, "author_profile": "https://Stackoverflow.com/users/7666352", "pm_score": 0, "selected": false, "text": "<ItemGroup>\n <CopyFileToFolders Include=\"materials\\**\\*\">\n <DestinationFolders>$(MainOutputDirectory)\\Resources\\materials\\%(RecursiveDir)</DestinationFolders>\n </CopyFileToFolders>\n</ItemGroup>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
119,278
<p>I am using informix database, I want a query which you could also generate a row number along with the query</p> <p>Like</p> <pre><code>select row_number(),firstName,lastName from students; row_number() firstName lastName 1 john mathew 2 ricky pointing 3 sachin tendulkar </code></pre> <p>Here firstName, lastName are from Database, where as row number is generated in a query.</p>
[ { "answer_id": 163014, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 3, "selected": false, "text": "begin work;\ncreate sequence myseq;\nselect myseq.nextval,s.firstName,s.lastName from students s;\ndrop sequence myseq;\ncommit work;\n" }, { "answer_id": 176873, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "colnum name datatype\n======= ===== ===\n1 no text;\n2 seq number;\n3 nm text;\n SELECT table3.no, table3.seq, Table3.nm,\n (SELECT COUNT(*) FROM Table3 AS Temp\n WHERE Temp.seq < Table3.seq) + 1 AS RowNum\n FROM Table3;\n" }, { "answer_id": 51661361, "author": "Jhollman", "author_id": 2000656, "author_profile": "https://Stackoverflow.com/users/2000656", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION fnc_numbers_in_range (pMinNumber INT, pMaxNumber INT)\nRETURNING INT as NUMERO;\nDEFINE numero INT;\nLET numero = 0;\nFOR numero = pMinNumber TO pMaxNumber \n RETURN numero WITH RESUME; \nEND FOR; \nEND FUNCTION; \n SELECT * FROM TABLE (fnc_numbers_in_range(0,10000)), my_table;\n" }, { "answer_id": 67332358, "author": "Guasqueño", "author_id": 1137223, "author_profile": "https://Stackoverflow.com/users/1137223", "pm_score": 0, "selected": false, "text": "SELECT ROW_NUMBER() OVER(ORDER BY lastName, firstName) AS rn, firstName, lastName \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,281
<ol> <li><p>New class is a subclass of the original object</p></li> <li><p>It needs to be php4 compatible</p></li> </ol>
[ { "answer_id": 119293, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 2, "selected": false, "text": "$myvar = $subclass->clone($originalObject)\n" }, { "answer_id": 119344, "author": "Jurassic_C", "author_id": 20572, "author_profile": "https://Stackoverflow.com/users/20572", "pm_score": 4, "selected": true, "text": "class childClass extends parentClass\n{\n function childClass()\n {\n //do nothing\n }\n\n function loadFromParentObj( $parentObj )\n {\n $this->a = $parentObj->a;\n $this->b = $parentObj->b;\n $this->c = $parentObj->c;\n }\n};\n\n$myParent = new parentClass();\n$myChild = new childClass();\n$myChild->loadFromParentObj( $myParent );\n" }, { "answer_id": 120758, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 2, "selected": false, "text": "function clone($object, $class)\n{\n $new = new $class();\n foreach ($object as $key => $value)\n {\n $new->$key = $value;\n }\n return $new;\n}\n$mySubclassObject = clone($myObject, 'mySubclass');\n" }, { "answer_id": 121366, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 3, "selected": false, "text": "function change_class($object, $new_class) {\n preg_match('~^O:[0-9]+:\"[^\"]+\":(.+)$~', serialize($object), $matches);\n return unserialize(sprintf('O:%s:\"%s\":%s', strlen($new_class), $new_class, $matches[1]));\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20907/" ]
119,284
<p>I would like to be able to override the default behaviour for positioning the caret in a masked textbox.</p> <p>The default is to place the caret where the mouse was clicked, the masked textbox already contains characters due to the mask.</p> <p>I know that you can hide the caret as mentioned in this <a href="https://stackoverflow.com/questions/44131/how-do-i-hide-the-input-caret-in-a-systemwindowsformstextbox">post</a>, is there something similar for positioning the caret at the beginning of the textbox when the control gets focus. </p>
[ { "answer_id": 119368, "author": "Abbas", "author_id": 4714, "author_profile": "https://Stackoverflow.com/users/4714", "pm_score": 6, "selected": true, "text": " private void maskedTextBox1_Enter(object sender, EventArgs e)\n {\n this.BeginInvoke((MethodInvoker)delegate()\n {\n maskedTextBox1.Select(0, 0);\n }); \n }\n" }, { "answer_id": 119397, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 2, "selected": false, "text": "MaskedTextBox1.Select(5, 0)\n" }, { "answer_id": 442552, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 3, "selected": false, "text": "private void ueTxtAny_Enter(object sender, EventArgs e)\n{\n //This method will prevent the cursor from being positioned in the middle \n //of a textbox when the user clicks in it.\n MaskedTextBox textBox = sender as MaskedTextBox;\n\n if (textBox != null)\n {\n this.BeginInvoke((MethodInvoker)delegate()\n {\n int pos = textBox.SelectionStart;\n\n if (pos > textBox.Text.Length)\n pos = textBox.Text.Length;\n\n textBox.Select(pos, 0);\n });\n }\n}\n" }, { "answer_id": 2479388, "author": "Mike M", "author_id": 297594, "author_profile": "https://Stackoverflow.com/users/297594", "pm_score": 3, "selected": false, "text": "private void maskedTextBoxGPS_Click( object sender, EventArgs e )\n{\n PositionCursorInMaskedTextBox( maskedTextBoxGPS );\n}\n\n\nprivate void PositionCursorInMaskedTextBox( MaskedTextBox mtb )\n{\n if (mtb == null) return;\n\n int pos = mtb.SelectionStart;\n\n if (pos > mtb.Text.Length)\n this.BeginInvoke( (MethodInvoker)delegate() { mtb.Select( mtb.Text.Length, 0 ); });\n}\n" }, { "answer_id": 6311071, "author": "Brian Pressman", "author_id": 793264, "author_profile": "https://Stackoverflow.com/users/793264", "pm_score": 2, "selected": false, "text": "//not the prettiest, but it gets to the first non-masked area when a user mounse-clicks into the control\nprivate void txtAccount_MouseUp(object sender, MouseEventArgs e)\n{\n if (txtAccount.SelectionStart > txtAccount.Text.Length)\n txtAccount.Select(txtAccount.Text.Length, 0);\n}\n" }, { "answer_id": 46027019, "author": "hmota", "author_id": 2410517, "author_profile": "https://Stackoverflow.com/users/2410517", "pm_score": 0, "selected": false, "text": "private void maskedTextBox1_Click(object sender, EventArgs e)\n{\n\n maskedTextBox1.Select(maskedTextBox1.Text.Length, 0);\n}\n" }, { "answer_id": 47877385, "author": "Gman Cornflake", "author_id": 9111068, "author_profile": "https://Stackoverflow.com/users/9111068", "pm_score": 0, "selected": false, "text": " private void maskedTextBox1_Click(object sender, EventArgs e)\n{\n maskedTextBox1.Select(0, 0); \n}\n" }, { "answer_id": 49435429, "author": "Bill Kamer", "author_id": 9536196, "author_profile": "https://Stackoverflow.com/users/9536196", "pm_score": 0, "selected": false, "text": "Private Sub MaskedTextBox1_Click(sender As Object, e As EventArgs) Handles MaskedTextBox1.Click\n Me.MaskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals\n If Me.MaskedTextBox1.Text.Length = 0 Then\n MaskedTextBox1.Select(0, 0)\n End If\n Me.MaskedTextBox1.TextMaskFormat = MaskFormat.IncludePromptAndLiterals\nEnd Sub\n" }, { "answer_id": 60672918, "author": "Joelius", "author_id": 10883465, "author_profile": "https://Stackoverflow.com/users/10883465", "pm_score": 1, "selected": false, "text": "TextMaskFormat = MaskFormat.ExcludePromptAndLiterals MaskFormat.ExcludePromptAndLiterals private void MaskedTextBox_Enter(object sender, EventArgs e)\n{\n // If attached to a MaskedTextBox' Enter-Event, this method will\n // make the cursor jump to the first prompt when the textbox gets focus.\n if (sender is MaskedTextBox textBox)\n {\n MaskFormat oldFormat = textBox.TextMaskFormat;\n textBox.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;\n string fullText = textBox.Text;\n textBox.TextMaskFormat = oldFormat;\n\n int index = fullText.IndexOf(textBox.PromptChar);\n if (index > -1)\n {\n BeginInvoke(new Action(() => textBox.Select(index, 0)));\n }\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
119,286
<p>Consider the following ruby code</p> <p>test.rb:</p> <pre><code>begin puts thisFunctionDoesNotExist x = 1+1 rescue Exception =&gt; e p e end </code></pre> <p>For debugging purposes, I would like the rescue block to know that the error occurred in line 4 of this file. Is there a clean way of doing that?</p>
[ { "answer_id": 119304, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 7, "selected": true, "text": "p e.backtrace \n => [\"(irb):11:in `foo'\", \n \"(irb):17:in `irb_binding'\", \n \"/usr/lib64/ruby/1.8/irb/workspace.rb:52:in `irb_binding'\", \n \"/usr/lib64/ruby/1.8/irb/workspace.rb:52\"]\n p x.backtrace.map{ |x| \n x.match(/^(.+?):(\\d+)(|:in `(.+)')$/); \n [$1,$2,$4] \n}\n\n[\n [\"(irb)\", \"11\", \"foo\"], \n [\"(irb)\", \"48\", \"irb_binding\"], \n [\"/usr/lib64/ruby/1.8/irb/workspace.rb\", \"52\", \"irb_binding\"], \n [\"/usr/lib64/ruby/1.8/irb/workspace.rb\", \"52\", nil]\n]\n >>def foo\n>> thisFunctionDoesNotExist\n>> rescue Exception => e \n>> return e \n>>end \n>>x = foo \n>>x.backtrace\n" }, { "answer_id": 119307, "author": "dan-manges", "author_id": 20072, "author_profile": "https://Stackoverflow.com/users/20072", "pm_score": 5, "selected": false, "text": "p e.backtrace\n [\"/Users/dan/Desktop/x.rb:4\"]\n p e.backtrace[0].split(\":\").last\n" }, { "answer_id": 3114725, "author": "John Bachir", "author_id": 168143, "author_profile": "https://Stackoverflow.com/users/168143", "pm_score": 3, "selected": false, "text": "print e.backtrace.join(\"\\n\")\n" }, { "answer_id": 28897787, "author": "Sergiy Seletskyy", "author_id": 781048, "author_profile": "https://Stackoverflow.com/users/781048", "pm_score": 3, "selected": false, "text": "puts e.backtrace.select { |x| x.match(/HERE-IS-YOUR-PROJECT-FOLDER-NAME/) }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17674/" ]
119,295
<p>Within our Active Directory domain, we have a MS SQL 2005 server, and a SharePoint (MOSS 3.0 I believe) server. Both authenticate against our LDAP server. Would like to allow these authenticated SharePoint visitors to see some of the data from the MS SQL database. Primary challenge is authentication.</p> <p>Any tips on getting the pass-through authentication to work? I have searched (Google) for a proper connection string to use, but keep finding ones that have embedded credentials or other schemes. I gather that SSPI is what I want to use, but am not sure how to implement.</p> <p>clarification: we don't have a single-sign-on server (e.g. Shibboleth) setup yet</p>
[ { "answer_id": 119348, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 2, "selected": true, "text": "using System.Data.SqlClient; \n... \nSqlConnection oSQLConn = new SqlConnection(); \noSQLConn.ConnectionString = \n \"Data Source=(local);\" + \n \"Initial Catalog=myDatabaseName;\" +\n \"Integrated Security=SSPI\";\n //Or\n // \"Server=(local);\" + \n // \"Database=myDatabaseName;\" + \n // \"Trusted_Connection=Yes\";\noSQLConn.Open(); \n... \noSQLConn.Close(); \n (local)" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18484/" ]
119,308
<p>I have a huge database with some 100 tables and some 250 stored procedures. I want to know the list of tables affected by a subset of stored procedures. For example, I have a list of 50 stored procedures, out of 250, and I want to know the list of tables that will be affected by these 50 stored procedures. Is there any easy way for doing this, other than reading all the stored procedures and finding the list of tables manually? </p> <p>PS: I am using SQL Server 2000 and SQL Server 2005 clients for this.</p>
[ { "answer_id": 119403, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 4, "selected": true, "text": "SELECT\n [NAME]\nFROM\n sysobjects\nWHERE\n xType = 'U' AND --specifies a user table object\n id in\n (\n SELECT \n sd.depid \n FROM \n sysobjects so,\n sysdepends sd\n WHERE\n so.name = 'NameOfStoredProcedure' AND \n sd.id = so.id\n )\n" }, { "answer_id": 119424, "author": "Jason Stangroome", "author_id": 20819, "author_profile": "https://Stackoverflow.com/users/20819", "pm_score": 1, "selected": false, "text": "SELECT \n [Proc] = SCHEMA_NAME(p.schema_id) + '.' + p.name,\n [Table] = SCHEMA_NAME(t.schema_id) + '.' + t.name,\n [Column] = c.name,\n d.is_selected,\n d.is_updated\nFROM sys.procedures p\n INNER JOIN sys.sql_dependencies d\n ON d.object_id = p.object_id\n AND d.class IN (0,1)\n INNER JOIN sys.tables t\n ON t.object_id = d.referenced_major_id\n INNER JOIN sys.columns c\n ON c.object_id = t.object_id\n AND c.column_id = d.referenced_minor_id\nWHERE p.type IN ('P')\n-- AND p.object_id = OBJECT_ID('MyProc')\nORDER BY \n 1, 2, 3\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,312
<p>Is it better convention to use hyphens or underscores in your URLs?</p> <p>Should it be <code>/about_us</code> or <code>/about-us</code>?</p> <p>From usability point of view, I personally think <strong>/about-us</strong> is much better for end-user yet Google and most other websites (and javascript frameworks) use underscore naming pattern. Is it just matter of style? Are there any compatibility issues with dashes?</p>
[ { "answer_id": 119339, "author": "Devin Jeanpierre", "author_id": 18515, "author_profile": "https://Stackoverflow.com/users/18515", "pm_score": 3, "selected": false, "text": "variable_names_are_not-subtraction http://example.com/nation-state-country/ http://example.com/nation-state_country/" }, { "answer_id": 119350, "author": "Jason Peacock", "author_id": 18381, "author_profile": "https://Stackoverflow.com/users/18381", "pm_score": 3, "selected": false, "text": "/low-budget-movies\n /low-budget_movies\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275/" ]
119,324
<p>Ok, I'm a newbie to ASP.NET web apps... and web apps in general. I'm just doing a bit of a play app for an internal tool at work.</p> <p>given this tutorial... </p> <p><a href="http://www.asp.net/learn/mvc-videos/video-395.aspx" rel="nofollow noreferrer">http://www.asp.net/learn/mvc-videos/video-395.aspx</a></p> <p>The example basically has a global tasklist. </p> <p>So if I wanted to do the same thing, but now I want to maintain tasks for projects. So I now select a project and I get the task list for that project. How do I keep the context of what project I have selected as I interact with the tasks? Do I encode it into the link somehow? or do you keep it in some kind of session data? or some other way?</p>
[ { "answer_id": 127046, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 3, "selected": false, "text": "\"/projects/{project}/tasks\"" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10431/" ]
119,328
<p>How do I truncate a java <code>String</code> so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?</p>
[ { "answer_id": 119343, "author": "mitchnull", "author_id": 18645, "author_profile": "https://Stackoverflow.com/users/18645", "pm_score": 5, "selected": false, "text": "getBytes() public static int truncateUtf8(String input, byte[] output) {\n \n ByteBuffer outBuf = ByteBuffer.wrap(output);\n CharBuffer inBuf = CharBuffer.wrap(input.toCharArray());\n\n CharsetEncoder utf8Enc = StandardCharsets.UTF_8.newEncoder();\n utf8Enc.encode(inBuf, outBuf, true);\n System.out.println(\"encoded \" + inBuf.position() + \" chars of \" + input.length() + \", result: \" + outBuf.position() + \" bytes\");\n return outBuf.position();\n}\n" }, { "answer_id": 119586, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 6, "selected": true, "text": "public static String truncateWhenUTF8(String s, int maxBytes) {\n int b = 0;\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n\n // ranges from http://en.wikipedia.org/wiki/UTF-8\n int skip = 0;\n int more;\n if (c <= 0x007f) {\n more = 1;\n }\n else if (c <= 0x07FF) {\n more = 2;\n } else if (c <= 0xd7ff) {\n more = 3;\n } else if (c <= 0xDFFF) {\n // surrogate area, consume next char as well\n more = 4;\n skip = 1;\n } else {\n more = 3;\n }\n\n if (b + more > maxBytes) {\n return s.substring(0, i);\n }\n b += more;\n i += skip;\n }\n return s;\n}\n truncateWhenUTF8() private static void test(String s, int maxBytes, int expectedBytes) {\n String result = truncateWhenUTF8(s, maxBytes);\n byte[] utf8 = result.getBytes(Charset.forName(\"UTF-8\"));\n if (utf8.length > maxBytes) {\n System.out.println(\"BAD: our truncation of \" + s + \" was too big\");\n }\n if (utf8.length != expectedBytes) {\n System.out.println(\"BAD: expected \" + expectedBytes + \" got \" + utf8.length);\n }\n System.out.println(s + \" truncated to \" + result);\n}\n\npublic static void main(String[] args) {\n test(\"abcd\", 0, 0);\n test(\"abcd\", 1, 1);\n test(\"abcd\", 2, 2);\n test(\"abcd\", 3, 3);\n test(\"abcd\", 4, 4);\n test(\"abcd\", 5, 4);\n\n test(\"a\\u0080b\", 0, 0);\n test(\"a\\u0080b\", 1, 1);\n test(\"a\\u0080b\", 2, 1);\n test(\"a\\u0080b\", 3, 3);\n test(\"a\\u0080b\", 4, 4);\n test(\"a\\u0080b\", 5, 4);\n\n test(\"a\\u0800b\", 0, 0);\n test(\"a\\u0800b\", 1, 1);\n test(\"a\\u0800b\", 2, 1);\n test(\"a\\u0800b\", 3, 1);\n test(\"a\\u0800b\", 4, 4);\n test(\"a\\u0800b\", 5, 5);\n test(\"a\\u0800b\", 6, 5);\n\n // surrogate pairs\n test(\"\\uD834\\uDD1E\", 0, 0);\n test(\"\\uD834\\uDD1E\", 1, 0);\n test(\"\\uD834\\uDD1E\", 2, 0);\n test(\"\\uD834\\uDD1E\", 3, 0);\n test(\"\\uD834\\uDD1E\", 4, 4);\n test(\"\\uD834\\uDD1E\", 5, 4);\n\n}\n" }, { "answer_id": 119660, "author": "user19050", "author_id": 19050, "author_profile": "https://Stackoverflow.com/users/19050", "pm_score": 2, "selected": false, "text": "foreach character in the Java string\n if 0 <= character <= 0x7f\n count += 1\n else if 0x80 <= character <= 0x7ff\n count += 2\n else if 0x800 <= character <= 0xd7ff // excluding the surrogate area\n count += 3\n else if 0xdc00 <= character <= 0xffff\n count += 3\n else { // surrogate, a bit more complicated\n count += 4\n skip one extra character in the input stream\n }\n" }, { "answer_id": 35148974, "author": "sigget", "author_id": 150333, "author_profile": "https://Stackoverflow.com/users/150333", "pm_score": 4, "selected": false, "text": "/**\n * Truncates a string to the number of characters that fit in X bytes avoiding multi byte characters being cut in\n * half at the cut off point. Also handles surrogate pairs where 2 characters in the string is actually one literal\n * character.\n *\n * Based on: http://www.jroller.com/holy/entry/truncating_utf_string_to_the\n */\npublic static String truncateToFitUtf8ByteLength(String s, int maxBytes) {\n if (s == null) {\n return null;\n }\n Charset charset = Charset.forName(\"UTF-8\");\n CharsetDecoder decoder = charset.newDecoder();\n byte[] sba = s.getBytes(charset);\n if (sba.length <= maxBytes) {\n return s;\n }\n // Ensure truncation by having byte buffer = maxBytes\n ByteBuffer bb = ByteBuffer.wrap(sba, 0, maxBytes);\n CharBuffer cb = CharBuffer.allocate(maxBytes);\n // Ignore an incomplete character\n decoder.onMalformedInput(CodingErrorAction.IGNORE)\n decoder.decode(bb, cb, true);\n decoder.flush(cb);\n return new String(cb.array(), 0, cb.position());\n}\n" }, { "answer_id": 70338834, "author": "walen", "author_id": 6404321, "author_profile": "https://Stackoverflow.com/users/6404321", "pm_score": -1, "selected": false, "text": "public static String utf8ByteTrim(String s, int trimSize) {\n final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);\n if ((bytes[trimSize-1] & 0x80) != 0) { // inside a multibyte sequence\n while ((bytes[trimSize-1] & 0x40) == 0) { // 2nd, 3rd, 4th bytes\n trimSize--;\n }\n trimSize--;\n }\n return new String(bytes, 0, trimSize, StandardCharsets.UTF_8);\n}\n String test = \"Aæ尝试\";\nIntStream.range(1, 16).forEachOrdered(i ->\n System.out.println(\"Size \" + i + \": \" + utf8ByteTrim(test, i))\n);\n\n---\n\nSize 1: A\nSize 2: A\nSize 3: A\nSize 4: Aæ\nSize 5: Aæ\nSize 6: Aæ\nSize 7: Aæ\nSize 8: Aæ\nSize 9: Aæ\nSize 10: Aæ\nSize 11: Aæ尝\nSize 12: Aæ尝\nSize 13: Aæ尝试\nSize 14: Aæ尝试\nSize 15: Aæ尝试\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4220/" ]
119,336
<p>I've got a customer trying to access one of my sites, and they keep getting this error > ssl_error_rx_record_too_long</p> <p>They're getting this error on all browsers, all platforms. I can't reproduce the problem at all.</p> <p>My server and myself are located in the USA, the customer is located in India.</p> <p>I googled on the problem, and the main source seems to be that the SSL port is speaking in HTTP. I checked my server, and this is not happening. I tried <a href="http://support.servertastic.com/error-code-ssl-error-rx-record-too-long/" rel="noreferrer">the solution mentioned here</a>, but the customer has stated it did not fix the issue.</p> <p>Can anyone tell me how I can fix this, or how I can reproduce this???</p> <p><strong>THE SOLUTION</strong></p> <p>Turns out the customer had a misconfigured local proxy!</p> <p>Hope that helps anyone finding this question trying to debug it in the future.</p>
[ { "answer_id": 331044, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$HTTPD -k $ARGV\n $HTTPD -k $ARGV -DSSL\n" }, { "answer_id": 853883, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": 4, "selected": false, "text": "SSLEngine On <VirtualHost _default_:443>\n SSLEngine On\n ...\n</VirtualHost>\n" }, { "answer_id": 893109, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "netsh interface ipv4 show inter\n\nIdx Met MTU State Name\n--- --- ----- ----------- -------------------\n 1 4275 4294967295 connected Loopback Pseudo-Interface 1\n 10 4250 **1300** connected Wireless Network Connection\n 31 25 1400 connected Remote Access to XYZ Network\n" }, { "answer_id": 2547884, "author": "Ben", "author_id": 197606, "author_profile": "https://Stackoverflow.com/users/197606", "pm_score": 7, "selected": false, "text": "default-ssl SSLEngine On a2ensite default-ssl" }, { "answer_id": 3371811, "author": "rogovsky", "author_id": 406747, "author_profile": "https://Stackoverflow.com/users/406747", "pm_score": 2, "selected": false, "text": "<VirtualHost> _default_ fqdn" }, { "answer_id": 4214783, "author": "drillingman", "author_id": 413122, "author_profile": "https://Stackoverflow.com/users/413122", "pm_score": 4, "selected": false, "text": "sites-enabled" }, { "answer_id": 4762977, "author": "Randall", "author_id": 584940, "author_profile": "https://Stackoverflow.com/users/584940", "pm_score": 9, "selected": true, "text": "<VirtualHost myserver.example.com:443> <VirtualHost _default_:443> ssl_error_rx_record_too_long Listen 80\nListen 443 https\n <VirtualHost> _default_ SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3" }, { "answer_id": 6700450, "author": "fimbulvetr", "author_id": 220922, "author_profile": "https://Stackoverflow.com/users/220922", "pm_score": 2, "selected": false, "text": "<VirtualHost 192.168.0.1:443>" }, { "answer_id": 10178561, "author": "Tarka", "author_id": 210226, "author_profile": "https://Stackoverflow.com/users/210226", "pm_score": 3, "selected": false, "text": "mod_ssl ./mods-available ./sites-available ./mods-enabled ./sites-enabled cd /etc/apache2\ncd ./mods-enabled\nsudo ln -s ../mods-available/ssl.* ./\ncd ../sites-enabled\nsudo ln -s ../sites-available/default-ssl ./\n" }, { "answer_id": 11504885, "author": "Anna B", "author_id": 252124, "author_profile": "https://Stackoverflow.com/users/252124", "pm_score": 2, "selected": false, "text": "ip.ip.ip.ip name name.domain.com\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10596/" ]
119,390
<p>Does anyone know how to change the from user when sending email using the mail command? I have looked through the man page and can not see how to do this. </p> <p>We are running Redhat Linux 5.</p>
[ { "answer_id": 119406, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": " $mail -s \"Subject\" destination@example.com\n From: Joel <joel@example.com>\n\n Hi!\n .\n" }, { "answer_id": 119438, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 6, "selected": true, "text": "echo \"This is the main body of the mail\" | mail -s \"Subject of the Email\" recipent_address@example.com -- -f from_user@example.com" }, { "answer_id": 119484, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 6, "selected": false, "text": "$mail -s \"Some random subject\" -a \"From: some@mail.tld\" to@mail.tld\n" }, { "answer_id": 19190674, "author": "Le Droid", "author_id": 1431079, "author_profile": "https://Stackoverflow.com/users/1431079", "pm_score": 3, "selected": false, "text": "echo 'my message blabla\\nSecond line (optional of course)' | \nmail -s \"Your message title\"\n-r 'Your full name<yourSenderAdress@yourDomain.abc>'\n-Sreplyto=\"yourReplyAdressIfDifferent@domain.abc\"\ndestinatorEmail@destDomain.abc[,otherDestinator@otherDomain.abc]\n apt-get install mailutils\n" }, { "answer_id": 21114458, "author": "Hardus", "author_id": 3194128, "author_profile": "https://Stackoverflow.com/users/3194128", "pm_score": 2, "selected": false, "text": "-aFrom:Servername-Server@mydomain.com\n cat /root/Reports/ServerName-Report-$DATE.txt | mail -s \"Server-Name-Report-$DATE\" myemailadress@mydomain.com -aFrom:Servername-Server@mydomain.com\n" }, { "answer_id": 23095065, "author": "Federico Cassinelli", "author_id": 2345289, "author_profile": "https://Stackoverflow.com/users/2345289", "pm_score": 1, "selected": false, "text": "echo \"This is the main body of the mail\" | mail -s \"Subject of the Email\" recipent_address@example.com -- -f from_user@example.com -F \"Elvis Presley\"\n echo \"This is the main body of the mail\" | mail -s \"Subject of the Email\" recipent_address@example.com -aFrom:\"Elvis Presley<from_user@example.com>\"\n" }, { "answer_id": 23472153, "author": "G.J", "author_id": 1663941, "author_profile": "https://Stackoverflow.com/users/1663941", "pm_score": 4, "selected": false, "text": "mail from mail -s Subject -S from=sender@example.com recipient@example.com\n -a mail -s Subject -S from=sender@example.com -a path_to_attachement recipient@example.com\n" }, { "answer_id": 28368999, "author": "Jerad", "author_id": 4537783, "author_profile": "https://Stackoverflow.com/users/4537783", "pm_score": 1, "selected": false, "text": "\necho \"test\" | mail -s \"a test\" me@noone.com \nFeb 6 09:02:51 myserver postfix/qmgr[28875]: B10322269D: from=<root@myserver.com>, size=437, nrcpt=1 (queue active)\nFeb 6 09:02:52 myserver postfix/smtp[19848]: B10322269D: to=<me@noone.com>, relay=myMTA[x.x.x.x]:25, delay=0.34, delays=0.1/0/0.11/0.13, dsn=2.0.0, status=sent (250 Ok 0000014b5f678593-a0e399ef-a801-4655-ad6b-19864a220f38-000000)\n \necho \"test\" | mail -s \"a test\" me@noone.com -- dude@thisguy.com \nFeb 6 09:09:09 myserver postfix/qmgr[28875]: 6BD362269D: from=<root@myserver.com>, size=474, nrcpt=2 (queue active)\nFeb 6 09:09:09 myserver postfix/smtp[20505]: 6BD362269D: to=<me@noone>, orig_to=<dude@thisguy.com>, relay=myMTA[x.x.x.x]:25, delay=0.31, delays=0.06/0/0.09/0.15, dsn=2.0.0, status=sent (250 Ok 0000014b5f6d48e2-a98b70be-fb02-44e0-8eb3-e4f5b1820265-000000)\n \necho \"test\" | mail -s \"a test\" -r dude@comeguy.com me@noone.com -- dude@someguy.com \nFeb 6 09:17:11 myserver postfix/qmgr[28875]: E3B972264C: from=<dude@someguy.com>, size=459, nrcpt=2 (queue active)\nFeb 6 09:17:11 myserver postfix/smtp[21559]: E3B972264C: to=<me@noone.com>, orig_to=<dude@someguy.com>, relay=myMTA[x.x.x.x]:25, delay=1.1, delays=0.56/0.24/0.11/0.17, dsn=2.0.0, status=sent (250 Ok 0000014b5f74a2c0-c06709f0-4e8d-4d7e-9abf-dbcea2bee2ea-000000)\n" }, { "answer_id": 32702329, "author": "ayon", "author_id": 5360532, "author_profile": "https://Stackoverflow.com/users/5360532", "pm_score": 0, "selected": false, "text": "echo \"Sample body\" | mail -s \"Test email\" from=sender-addrs@example.com recepient-addres@example.com\n" }, { "answer_id": 37199560, "author": "Santiago Trias", "author_id": 3878927, "author_profile": "https://Stackoverflow.com/users/3878927", "pm_score": 1, "selected": false, "text": "echo \"This is the main body of the mail\" | mail -s \"Subject of the Email\" -r seneder_address@whatever.com recipent_address@example.com" }, { "answer_id": 49957075, "author": "scrat.squirrel", "author_id": 704879, "author_profile": "https://Stackoverflow.com/users/704879", "pm_score": 1, "selected": false, "text": "-e -r $ echo -e \"testing email via yourisp.com from command line\\n\\nsent on: $(date)\" | mailx -r \"Foghorn Leghorn <sender@yourisp.com>\" -s \"test cli email $(date)\" -- recipient@somedomain.com\n" }, { "answer_id": 57725753, "author": "Youssef ASEBRIY", "author_id": 4099865, "author_profile": "https://Stackoverflow.com/users/4099865", "pm_score": 1, "selected": false, "text": "mail -s Subject -S from=sender@example.com recipient@example.com\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5360/" ]
119,399
<p>I'm wondering if the need to alter the indentation of code to adjust the nesting has any adverse effects on merging changes in a system like SVN.</p>
[ { "answer_id": 119500, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "if" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
119,404
<p>What is the simplest way to determine the length (in seconds) of a given mp3 file, <strong>without using outside libraries</strong>? (python source highly appreciated)</p>
[ { "answer_id": 119418, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": true, "text": "import mad\n\nmf = mad.MadFile(\"foo.mp3\")\ntrack_length_in_milliseconds = mf.total_time() \n" }, { "answer_id": 119616, "author": "Matt Blaine", "author_id": 16272, "author_profile": "https://Stackoverflow.com/users/16272", "pm_score": 3, "selected": false, "text": "// determines the duration, in seconds, of an MP3;\n// assumes MPEG 1 (not 2 or 2.5) Audio Layer 3 (not 1 or 2)\n// constant bit rate (not variable)\n\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n\nusing namespace std;\n\n//Bitrates, assuming MPEG 1 Audio Layer 3\nconst int bitrates[16] = {\n 0, 32000, 40000, 48000, 56000, 64000, 80000, 96000,\n 112000, 128000, 160000, 192000, 224000, 256000, 320000, 0\n };\n\n\n//Intel processors are little-endian;\n//search Google or see: http://en.wikipedia.org/wiki/Endian\nint reverse(int i)\n{\n int toReturn = 0;\n toReturn |= ((i & 0x000000FF) << 24);\n toReturn |= ((i & 0x0000FF00) << 8);\n toReturn |= ((i & 0x00FF0000) >> 8);\n toReturn |= ((i & 0xFF000000) >> 24);\n return toReturn;\n}\n\n//In short, data in ID3v2 tags are stored as\n//\"syncsafe integers\". This is so the tag info\n//isn't mistaken for audio data, and attempted to\n//be \"played\". For more info, have fun Googling it.\nint syncsafe(int i)\n{\n int toReturn = 0;\n toReturn |= ((i & 0x7F000000) >> 24);\n toReturn |= ((i & 0x007F0000) >> 9);\n toReturn |= ((i & 0x00007F00) << 6);\n toReturn |= ((i & 0x0000007F) << 21);\n return toReturn; \n}\n\n//How much room does ID3 version 1 tag info\n//take up at the end of this file (if any)?\nint id3v1size(ifstream& infile)\n{\n streampos savePos = infile.tellg(); \n\n //get to 128 bytes from file end\n infile.seekg(0, ios::end);\n streampos length = infile.tellg() - (streampos)128;\n infile.seekg(length);\n\n int size;\n char buffer[3] = {0};\n infile.read(buffer, 3);\n if( buffer[0] == 'T' && buffer[1] == 'A' && buffer[2] == 'G' )\n size = 128; //found tag data\n else\n size = 0; //nothing there\n\n infile.seekg(savePos);\n\n return size;\n\n}\n\n//how much room does ID3 version 2 tag info\n//take up at the beginning of this file (if any)\nint id3v2size(ifstream& infile)\n{\n streampos savePos = infile.tellg(); \n infile.seekg(0, ios::beg);\n\n char buffer[6] = {0};\n infile.read(buffer, 6);\n if( buffer[0] != 'I' || buffer[1] != 'D' || buffer[2] != '3' )\n { \n //no tag data\n infile.seekg(savePos);\n return 0;\n }\n\n int size = 0;\n infile.read(reinterpret_cast<char*>(&size), sizeof(size));\n size = syncsafe(size);\n\n infile.seekg(savePos);\n //\"size\" doesn't include the 10 byte ID3v2 header\n return size + 10;\n}\n\nint main(int argCount, char* argValues[])\n{\n //you'll have to change this\n ifstream infile(\"C:/Music/Bush - Comedown.mp3\", ios::binary);\n\n if(!infile.is_open())\n {\n infile.close();\n cout << \"Error opening file\" << endl;\n system(\"PAUSE\");\n return 0;\n }\n\n //determine beginning and end of primary frame data (not ID3 tags)\n infile.seekg(0, ios::end);\n streampos dataEnd = infile.tellg();\n\n infile.seekg(0, ios::beg);\n streampos dataBegin = 0;\n\n dataEnd -= id3v1size(infile);\n dataBegin += id3v2size(infile);\n\n infile.seekg(dataBegin,ios::beg);\n\n //determine bitrate based on header for first frame of audio data\n int headerBytes = 0;\n infile.read(reinterpret_cast<char*>(&headerBytes),sizeof(headerBytes));\n\n headerBytes = reverse(headerBytes);\n int bitrate = bitrates[(int)((headerBytes >> 12) & 0xF)];\n\n //calculate duration, in seconds\n int duration = (dataEnd - dataBegin)/(bitrate/8);\n\n infile.close();\n\n //print duration in minutes : seconds\n cout << duration/60 << \":\" << duration%60 << endl;\n\n system(\"PAUSE\");\n return 0;\n}\n" }, { "answer_id": 10132100, "author": "Bala Clark", "author_id": 55825, "author_profile": "https://Stackoverflow.com/users/55825", "pm_score": 2, "selected": false, "text": "audio = audioread.audio_open('/path/to/mp3')\nprint audio.channels, audio.samplerate, audio.duration\n" }, { "answer_id": 29028948, "author": "Johnny Zhao", "author_id": 1523716, "author_profile": "https://Stackoverflow.com/users/1523716", "pm_score": 3, "selected": false, "text": "mutagen $pip install mutagen\n from mutagen.mp3 import MP3\naudio = MP3(file_path)\nprint audio.info.length\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9440/" ]
119,414
<p>There's a lot of people today who sell unittesting as bread-and-butter of development. That might even work for strongly algorithmically-oriented routines. However, how would you unit-test, for example, a memory allocator (think malloc()/realloc()/free()). It's not hard to produce a working (but absolutely useless) memory allocator that satisfies the specified interface. But how to provide the proper context for unit-testing functionality that is absolutely desired, yet not part of the contract: coalescing free blocks, reusing free blocks on next allocations, returning excess free memory to the system, asserting that the allocation policy (e.g. first-fit) really is respected, etc.</p> <p>My experience is that assertions, even if complex and time-consuming (e.g. traversing the whole free list to check invariants) are much less work and are more reliable than unit-testing, esp. when coding complex, time-dependent algorithms.</p> <p>Any thoughts?</p>
[ { "answer_id": 119437, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "void* AllocateMemory(int size); \nbool FreeMemory(void* handle);\nint MemoryAvailable();\n I_OS_MemoryFacade" }, { "answer_id": 30869154, "author": "Michael Conlen", "author_id": 974040, "author_profile": "https://Stackoverflow.com/users/974040", "pm_score": 0, "selected": false, "text": "prefix_malloc();\nprefix_free();\n #ifndef USE_PREFIX\n#define prefix_malloc malloc\n#define prefix_free free\n#endif\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2583/" ]
119,426
<p>Are there any industry standard conventions for naming jar files?</p>
[ { "answer_id": 119430, "author": "Ron Tuffin", "author_id": 939, "author_profile": "https://Stackoverflow.com/users/939", "pm_score": 6, "selected": true, "text": "*Informative*-*name*-*M*.*m*.*b*.jar\n major version number minor version number build number" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939/" ]
119,432
<p>Im running a ASP.NET Site where I have problems to find some JavaScript Errors just with manual testing.</p> <p>Is there a possibility to catch all JavaScript Errors on the Clientside and log them on the Server i.e. in the EventLog (via Webservice or something like that)?</p>
[ { "answer_id": 119510, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "window.onerror = function(msg, url, line)\n{\n var req = new XMLHttpRequest();\n var params = \"msg=\" + encodeURIComponent(msg) + '&amp;url=' + encodeURIComponent(url) + \"&amp;line=\" + line;\n req.open(\"POST\", \"/scripts/logerror.php\");\n req.send(params);\n};\n" }, { "answer_id": 120614, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 4, "selected": false, "text": "window.onerror window.onerror" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17558/" ]
119,441
<p>I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word &quot;dolor&quot; in this text:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; Lorem ipsum dolor sit amet, consectetuer adipiscing elit. &lt;/p&gt; &lt;p&gt; Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. &lt;/p&gt; </code></pre> <p>How do I convert the above to something like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt; Lorem ipsum &lt;span class=&quot;myClass&quot;&gt;dolor&lt;/span&gt; sit amet, consectetuer adipiscing elit. &lt;/p&gt; &lt;p&gt; Quisque bibendum sem ut lacus. Integer &lt;span class=&quot;myClass&quot;&gt;dolor&lt;/span&gt; ullamcorper libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris. &lt;/p&gt; </code></pre> <p>Is this possible with jQuery?</p> <p><strong>Edit</strong>: As <a href="https://stackoverflow.com/users/9535/sebastian-hoitz">Sebastian</a> <a href="https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery#119450">pointed out</a>, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.</p>
[ { "answer_id": 119473, "author": "mlarsen", "author_id": 17700, "author_profile": "https://Stackoverflow.com/users/17700", "pm_score": 7, "selected": true, "text": "/*\n\nhighlight v4\n\nHighlights arbitrary terms.\n\n<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>\n\nMIT license.\n\nJohann Burkard\n<http://johannburkard.de>\n<mailto:jb@eaio.com>\n\n*/\n\njQuery.fn.highlight = function(pat) {\n function innerHighlight(node, pat) {\n var skip = 0;\n if (node.nodeType == 3) {\n var pos = node.data.toUpperCase().indexOf(pat);\n if (pos >= 0) {\n var spannode = document.createElement('span');\n spannode.className = 'highlight';\n var middlebit = node.splitText(pos);\n var endbit = middlebit.splitText(pat.length);\n var middleclone = middlebit.cloneNode(true);\n spannode.appendChild(middleclone);\n middlebit.parentNode.replaceChild(spannode, middlebit);\n skip = 1;\n }\n }\n else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {\n for (var i = 0; i < node.childNodes.length; ++i) {\n i += innerHighlight(node.childNodes[i], pat);\n }\n }\n return skip;\n }\n return this.length && pat && pat.length ? this.each(function() {\n innerHighlight(this, pat.toUpperCase());\n }) : this;\n};\n\njQuery.fn.removeHighlight = function() {\n return this.find(\"span.highlight\").each(function() {\n this.parentNode.firstChild.nodeName;\n with (this.parentNode) {\n replaceChild(this.firstChild, this);\n normalize();\n }\n }).end();\n};\n /*\n * jQuery Highlight plugin\n *\n * Based on highlight v3 by Johann Burkard\n * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html\n *\n * Code a little bit refactored and cleaned (in my humble opinion).\n * Most important changes:\n * - has an option to highlight only entire words (wordsOnly - false by default),\n * - has an option to be case sensitive (caseSensitive - false by default)\n * - highlight element tag and class names can be specified in options\n *\n * Usage:\n * // wrap every occurrance of text 'lorem' in content\n * // with <span class='highlight'> (default options)\n * $('#content').highlight('lorem');\n *\n * // search for and highlight more terms at once\n * // so you can save some time on traversing DOM\n * $('#content').highlight(['lorem', 'ipsum']);\n * $('#content').highlight('lorem ipsum');\n *\n * // search only for entire word 'lorem'\n * $('#content').highlight('lorem', { wordsOnly: true });\n *\n * // don't ignore case during search of term 'lorem'\n * $('#content').highlight('lorem', { caseSensitive: true });\n *\n * // wrap every occurrance of term 'ipsum' in content\n * // with <em class='important'>\n * $('#content').highlight('ipsum', { element: 'em', className: 'important' });\n *\n * // remove default highlight\n * $('#content').unhighlight();\n *\n * // remove custom highlight\n * $('#content').unhighlight({ element: 'em', className: 'important' });\n *\n *\n * Copyright (c) 2009 Bartek Szopka\n *\n * Licensed under MIT license.\n *\n */\n\njQuery.extend({\n highlight: function (node, re, nodeName, className) {\n if (node.nodeType === 3) {\n var match = node.data.match(re);\n if (match) {\n var highlight = document.createElement(nodeName || 'span');\n highlight.className = className || 'highlight';\n var wordNode = node.splitText(match.index);\n wordNode.splitText(match[0].length);\n var wordClone = wordNode.cloneNode(true);\n highlight.appendChild(wordClone);\n wordNode.parentNode.replaceChild(highlight, wordNode);\n return 1; //skip added node in parent\n }\n } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children\n !/(script|style)/i.test(node.tagName) && // ignore script and style nodes\n !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted\n for (var i = 0; i < node.childNodes.length; i++) {\n i += jQuery.highlight(node.childNodes[i], re, nodeName, className);\n }\n }\n return 0;\n }\n});\n\njQuery.fn.unhighlight = function (options) {\n var settings = { className: 'highlight', element: 'span' };\n jQuery.extend(settings, options);\n\n return this.find(settings.element + \".\" + settings.className).each(function () {\n var parent = this.parentNode;\n parent.replaceChild(this.firstChild, this);\n parent.normalize();\n }).end();\n};\n\njQuery.fn.highlight = function (words, options) {\n var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };\n jQuery.extend(settings, options);\n \n if (words.constructor === String) {\n words = [words];\n }\n words = jQuery.grep(words, function(word, i){\n return word != '';\n });\n words = jQuery.map(words, function(word, i) {\n return word.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\");\n });\n if (words.length == 0) { return this; };\n\n var flag = settings.caseSensitive ? \"\" : \"i\";\n var pattern = \"(\" + words.join(\"|\") + \")\";\n if (settings.wordsOnly) {\n pattern = \"\\\\b\" + pattern + \"\\\\b\";\n }\n var re = new RegExp(pattern, flag);\n \n return this.each(function () {\n jQuery.highlight(this, re, settings.element, settings.className);\n });\n};\n" }, { "answer_id": 120161, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 5, "selected": false, "text": "function hiliter(word, element) {\n var rgxp = new RegExp(word, 'g');\n var repl = '<span class=\"myClass\">' + word + '</span>';\n element.innerHTML = element.innerHTML.replace(rgxp, repl);\n}\nhiliter('dolor');\n" }, { "answer_id": 405908, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "jQuery.fn.highlight = function (str, className)\n{\n var regex = new RegExp(str, \"g\");\n\n return this.each(function ()\n {\n this.innerHTML = this.innerHTML.replace(\n regex,\n \"<span class=\\\"\" + className + \"\\\">\" + str + \"</span>\"\n );\n });\n};\n" }, { "answer_id": 2676556, "author": "bjarlestam", "author_id": 321463, "author_profile": "https://Stackoverflow.com/users/321463", "pm_score": 4, "selected": false, "text": "jQuery.fn.highlight = function (str, className) {\n var regex = new RegExp(\"\\\\b\"+str+\"\\\\b\", \"gi\");\n\n return this.each(function () {\n this.innerHTML = this.innerHTML.replace(regex, function(matched) {return \"<span class=\\\"\" + className + \"\\\">\" + matched + \"</span>\";});\n });\n};\n" }, { "answer_id": 15007014, "author": "Hawkee", "author_id": 461272, "author_profile": "https://Stackoverflow.com/users/461272", "pm_score": 1, "selected": false, "text": "function highlight_words(word, element) {\n if(word) {\n var textNodes;\n word = word.replace(/\\W/g, '');\n var str = word.split(\" \");\n $(str).each(function() {\n var term = this;\n var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 });\n textNodes.each(function() {\n var content = $(this).text();\n var regex = new RegExp(term, \"gi\");\n content = content.replace(regex, '<span class=\"highlight\">' + term + '</span>');\n $(this).replaceWith(content);\n });\n });\n }\n}\n" }, { "answer_id": 30569608, "author": "iamawebgeek", "author_id": 3796431, "author_profile": "https://Stackoverflow.com/users/3796431", "pm_score": 2, "selected": false, "text": "npm install jquitelight --save\n bower install jquitelight \n // for strings\n$(\".element\").mark(\"query here\");\n// for RegExp\n$(\".element\").mark(new RegExp(/query h[a-z]+/));\n" }, { "answer_id": 32758672, "author": "dude", "author_id": 3894981, "author_profile": "https://Stackoverflow.com/users/3894981", "pm_score": 5, "selected": false, "text": "innerHTML // Highlight \"keyword\" in the specified context\n$(\".context\").mark(\"keyword\");\n\n// Highlight the custom regular expression in the specified context\n$(\".context\").markRegExp(/Lorem/gmi);\n" }, { "answer_id": 33545382, "author": "L.Grillo", "author_id": 1764509, "author_profile": "https://Stackoverflow.com/users/1764509", "pm_score": -1, "selected": false, "text": "$(function () {\n $(\"#txtSearch\").keyup(function (event) {\n var txt = $(\"#txtSearch\").val()\n if (txt.length > 3) {\n $(\"span.hilightable\").each(function (i, v) {\n v.innerHTML = v.innerText.replace(txt, \"<hilight>\" + txt + \"</hilight>\");\n });\n\n }\n });\n});\n" }, { "answer_id": 40007548, "author": "abe312", "author_id": 3719699, "author_profile": "https://Stackoverflow.com/users/3719699", "pm_score": -1, "selected": false, "text": "$( document ).ready(function() {\n \n function hiliter(word, element) {\n var rgxp = new RegExp(\"\\\\b\" + word + \"\\\\b\" , 'gi'); // g modifier for global and i for case insensitive \n var repl = '<span class=\"myClass\">' + word + '</span>';\n element.innerHTML = element.innerHTML.replace(rgxp, repl);\n \n };\n\n hiliter('dolor', document.getElementById('dolor'));\n}); .myClass{\n\nbackground-color:red;\n} <!DOCTYPE html>\n<html>\n <head>\n <title>highlight</title>\n \n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js\"></script>\n \n <link href=\"main.css\" type=\"text/css\" rel=\"stylesheet\"/>\n \n </head>\n <body id='dolor'>\n<p >\n Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\n</p>\n<p>\n Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.\n Aliquam rhoncus eros at augue. Suspendisse vitae mauris.\n</p>\n <script type=\"text/javascript\" src=\"main.js\" charset=\"utf-8\"></script>\n </body>\n</html>" }, { "answer_id": 44744765, "author": "Van Peer", "author_id": 1836483, "author_profile": "https://Stackoverflow.com/users/1836483", "pm_score": 2, "selected": false, "text": ".each() .replace() .html() .each() <body>\n <label name=\"lblKeyword\" id=\"lblKeyword\" class=\"highlight\">keyword</label>\n <p class=\"filename\">keyword</p>\n <p class=\"content\">keyword</p>\n <p class=\"system\"><i>keyword</i></p>\n</body>\n $(document).ready(function() {\n var keyWord = $(\"#lblKeyword\").text(); \n var replaceD = \"<span class='highlight'>\" + keyWord + \"</span>\";\n $(\".system, .filename, .content\").each(function() {\n var text = $(this).text();\n text = text.replace(keyWord, replaceD);\n $(this).html(text);\n });\n});\n .highlight {\n background-color: yellow;\n}\n" }, { "answer_id": 49041257, "author": "Cybernetic", "author_id": 1639594, "author_profile": "https://Stackoverflow.com/users/1639594", "pm_score": 2, "selected": false, "text": "function color_word(text_id, word, color) {\n words = $('#' + text_id).text().split(' ');\n words = words.map(function(item) { return item == word ? \"<span style='color: \" + color + \"'>\" + word + '</span>' : item });\n new_words = words.join(' ');\n $('#' + text_id).html(new_words);\n }\n <div id='my_words'>\nThis is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.\n</div>\n color_word('my_words', 'possible', 'hotpink')\n" }, { "answer_id": 73156791, "author": "Akhtarujjaman Shuvo", "author_id": 6286562, "author_profile": "https://Stackoverflow.com/users/6286562", "pm_score": 0, "selected": false, "text": "jQuery.fn.highlight = function(str) {\n var regex = new RegExp(str, \"gi\");\n return this.each(function() {\n this.innerHTML = this.innerText.replace(regex, function(matched) {\n return \"<span class='mark'>\" + matched + \"</span>\";\n });\n });\n};\n\n// Mark\njQuery('table tr td').highlight('desh') .mark {\n background: #fde293;\n color: #222;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<h2>HTML Table</h2>\n\n<table>\n <tr>\n <th>Company</th>\n <th>Contact</th>\n <th>Country</th>\n </tr>\n <tr>\n <td>Sodeshi</td>\n <td>Francisco Chang</td>\n <td>Mexico</td>\n </tr>\n <tr>\n <td>Ernst Handel</td>\n <td>Roland Mendel</td>\n <td>Austria</td>\n </tr>\n <tr>\n <td>Island Trading</td>\n <td>Helen Bennett</td>\n <td>Bangladesh</td>\n </tr>\n\n</table> jQuery('.selector').highlight('sample text')" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
119,444
<p>For one and a half years, I have been keeping my eyes on the git community in hopes of making the switch away from SVN. One particular issue holding me back is the inability to lock binary files. Throughout the past year I have yet to see developments on this issue. I understand that locking files goes against the fundamental principles of distributed source control, but I don't see how a web development company can take advantage of git to track source code and image file changes when there is the potential for binary file conflicts.</p> <p>To achieve the effects of locking, a "central" repository must be identified. Regardless of the distributed nature of git, most companies will have a "central" repository for a software project. We should be able to mark a file as requiring a lock from the governing git repository at a specified address. Perhaps this is made difficult because git tracks file contents not files?</p> <p>Do any of you have experience in dealing with git and binary files that should be locked before modification?</p> <p>NOTE: It looks like Source Gear's new open source distributed version control project, Veracity, has locking as one of its goals.</p>
[ { "answer_id": 119565, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "git-lock git-add" }, { "answer_id": 123841, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 3, "selected": false, "text": "svn:needs-lock" }, { "answer_id": 125682, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 3, "selected": false, "text": "users/a/feature1\nusers/a/feature2\nusers/b/feature3\nteams/d/featurey\n feature1\nfeature2\n git push origin feature1:users/a/feature1\n git checkout master\ngit pull\ngit merge users/name/feature1\ngit push\n" }, { "answer_id": 140931, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 3, "selected": false, "text": "alice/update alice/update bob/update master master" }, { "answer_id": 990571, "author": "Craig McQueen", "author_id": 60075, "author_profile": "https://Stackoverflow.com/users/60075", "pm_score": 6, "selected": false, "text": "svn:needs-lock svn:needs-lock" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472/" ]
119,462
<p>I'd like to remove all of the black from a picture attached to a sprite so that it becomes transparent. </p>
[ { "answer_id": 129688, "author": "thescreamingdrills", "author_id": 20824, "author_profile": "https://Stackoverflow.com/users/20824", "pm_score": 2, "selected": false, "text": "kernel vec4 darkToTransparent(sampler image)\n{\n vec4 color = sample(image, samplerCoord(image));\n color.a = (color.r+color.g+color.b) > 0.005 ? 1.0:0.;\n return color;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20824/" ]
119,467
<p>Is there a specific pattern that developers generally follow? I never really gave it much thought before in my web applications, but the ASP.NET MVC routing engine pretty much forces you to at least take it into consideration.</p> <p>So far I've liked the controller/action/index structure (e.g. Products/Edit/1), but I'm struggling with more complex urls.</p> <p>For instance, let's say you have a page that lists all the products a user has in their account. How would you do it? Off the top of my head I can think of the following possibilities for a listing page and an edit page:</p> <ol> <li>User/{user id}/Products/List, User/{user id}/Products/Edit/{product id}</li> <li>User/{user id}/Products, User/{user id}/Products/{product id}</li> <li>Products?UserID={user id}, Products/Edit/{product id}</li> </ol> <p>I'm sure there are plenty of others that I'm missing. Any advice?</p>
[ { "answer_id": 119545, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 1, "selected": false, "text": "[AcceptVerb(\"GET\")]\npublic ActionResult Edit(int id)\n{\n ViewData[\"Product\"] = _products.Get(id);\n return View();\n}\n\n[AcceptVerb(\"POST\")]\npublic ActionResult Edit(int id, string title, string description)\n{\n _products.Update(id, title, description);\n TempData[\"Message\"] = \"Changes saved successfully!\";\n\n return RedirectToAction(\"Edit\", new { id });\n}\n" }, { "answer_id": 123922, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 4, "selected": true, "text": "/Default.aspx?action=show&userID=140 /users/troethom /users" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
119,477
<p>I have an MSSQL2005 stored procedure here, which is supposed to take an XML message as input, and store it's content into a table. The table fields are varchars, because our delphi backend application could not handle unicode. Now, the messages that come in, are encoded ISO-8859-1. All is fine until characters over the > 128 standard set are included (in this case, ÄÖäö, which are an integral part of finnish). This causes the DB server to raise exception 0xc00ce508. The database's default, as well as the table's and field's, collation is set to latin1, which should be the same as ISO-8859-1.</p> <p>The XML message is parsed using the XML subsystem, like so:</p> <pre><code>ALTER PROCEDURE [dbo].[parse] @XmlIn NVARCHAR(1000) AS SET NOCOUNT ON DECLARE @XmlDocumentHandle INT DECLARE @XmlDocument VARCHAR(1000) BEGIN SET @XmlDocument = @XmlIn EXECUTE sp_xml_preparedocument @XmlDocumentHandle OUTPUT, @XmlDocument BEGIN TRANSACTION //the xml message's fields are looped through here, and rows added or modified in two tables accordingly // like ... DECLARE TempCursor CURSOR FOR SELECT AM_WORK_ID,CUSTNO,STYPE,REFE,VIN_NUMBER,REG_NO,VEHICLE_CONNO,READY_FOR_INVOICE,IS_SP,SMANID,INVOICENO,SUB_STATUS,TOTAL,TOTAL0,VAT,WRKORDNO FROM OPENXML (@XmlDocumentHandle, '/ORDER_NEW_CP_REQ/ORDER_NEW_CUSTOMER_REQ',8) WITH (AM_WORK_ID int '@EXIDNO',CUSTNO int '@CUSTNO',STYPE VARCHAR(1) '@STYPE',REFE VARCHAR(50) '@REFE',VIN_NUMBER VARCHAR(30) '@VEHICLE_VINNO', REG_NO VARCHAR(20) '@VEHICLE_LICNO',VEHICLE_CONNO VARCHAR(30) '@VEHICLE_CONNO',READY_FOR_INVOICE INT '@READY_FOR_INVOICE',IS_SP INT '@IS_SP', SMANID INT '@SMANID',INVOICENO INT '@INVOICENO',SUB_STATUS VARCHAR(1) '@SUB_STATUS',TOTAL NUMERIC(12,2) '@TOTAL',TOTAL0 NUMERIC(12,2) '@TOTAL0',VAT NUMERIC(12,2) '@VAT',WRKORDNO INT '@WRKORDNO') OPEN TempCursor FETCH NEXT FROM TempCursor INTO @wAmWork,@wCustNo,@wType,@wRefe,@wVIN,@wReg,@wConNo,@wRdy,@wIsSp,@wSMan,@wInvoNo,@wSubStatus,@wTot,@wTot0,@wVat,@wWrkOrdNo // ... etc COMMIT TRANSACTION EXECUTE sp_xml_removedocument @XmlDocumentHandle END </code></pre> <p>Previously, the stored procedure used to use nvarchar for input, but since that caused problems with the ancient backend application (Delphi 5 + ODBC), we had to switch the fields to varchars, at which point everything broke.</p> <p>I also tried taking in nvarchar and converting that to varchar at the start, but the result is the same.</p>
[ { "answer_id": 120489, "author": "anon6439", "author_id": 15477, "author_profile": "https://Stackoverflow.com/users/15477", "pm_score": 1, "selected": false, "text": "@XmlIn NVARCHAR(2000)\n@XmlDocument VARCHAR(2000)\nSELECT @XmlDocument = @XmlIn COLLATE SQL_Latin1_General_CP1_CI_AS\n <?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n" }, { "answer_id": 141394, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 2, "selected": true, "text": "DECLARE @XmlDocument VARCHAR(2000) COLLATE SQL_Latin1_General_CP1_CI_AS\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15477/" ]
119,506
<p>I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. </p> <p>Why would this be something not to do?</p>
[ { "answer_id": 119516, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": false, "text": "this" }, { "answer_id": 119531, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 10, "selected": false, "text": "Child class Parent\n{\n public Parent()\n {\n DoSomething();\n }\n\n protected virtual void DoSomething() \n {\n }\n}\n\nclass Child : Parent\n{\n private string foo;\n\n public Child() \n { \n foo = \"HELLO\"; \n }\n\n protected override void DoSomething()\n {\n Console.WriteLine(foo.ToLower()); //NullReferenceException!?!\n }\n}\n NullReferenceException foo virtual" }, { "answer_id": 119613, "author": "Lloyd", "author_id": 9952, "author_profile": "https://Stackoverflow.com/users/9952", "pm_score": 7, "selected": false, "text": "namespace Demo\n{\n class A \n {\n public A()\n {\n System.Console.WriteLine(\"This is a {0},\", this.GetType());\n }\n }\n\n class B : A\n { \n }\n\n // . . .\n\n B b = new B(); // Output: \"This is a Demo.B\"\n}\n" }, { "answer_id": 120923, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 7, "selected": false, "text": " class B\n {\n protected virtual void Foo() { }\n }\n\n class A : B\n {\n public A()\n {\n Foo(); // warning here\n }\n }\n sealed class A : B\n {\n public A()\n {\n Foo(); // no warning\n }\n }\n class A : B\n {\n public A()\n {\n Foo(); // no warning\n }\n\n protected sealed override void Foo()\n {\n base.Foo();\n }\n }\n" }, { "answer_id": 13076806, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 3, "selected": false, "text": "Dispose Dispose Dispose" }, { "answer_id": 14063392, "author": "Josh Kodroff", "author_id": 549, "author_profile": "https://Stackoverflow.com/users/549", "pm_score": 4, "selected": false, "text": "GetDependency() public class MyClass\n{\n private IDependency _myDependency;\n\n public MyClass(IDependency someValue = null)\n {\n _myDependency = someValue ?? GetDependency();\n }\n\n // If this were static, it could not be overridden\n // as static methods cannot be virtual in C#.\n protected virtual IDependency GetDependency() \n {\n return new SomeDependency();\n }\n}\n\npublic class MySubClass : MyClass\n{\n protected override IDependency GetDependency()\n {\n return new SomeOtherDependency();\n }\n}\n\npublic interface IDependency { }\npublic class SomeDependency : IDependency { }\npublic class SomeOtherDependency : IDependency { }\n" }, { "answer_id": 23812870, "author": "adityap", "author_id": 1654854, "author_profile": "https://Stackoverflow.com/users/1654854", "pm_score": -1, "selected": false, "text": "public class ConfigManager\n{\n public virtual int MyPropOne { get; private set; }\n public virtual string MyPropTwo { get; private set; }\n\n public ConfigManager()\n {\n Setup();\n }\n\n private void Setup()\n {\n MyPropOne = 1;\n MyPropTwo = \"test\";\n }\n}\n" }, { "answer_id": 32017672, "author": "Gustavo Mori", "author_id": 556595, "author_profile": "https://Stackoverflow.com/users/556595", "pm_score": 3, "selected": false, "text": "public class BadBaseClass\n{\n protected string state;\n\n public BadBaseClass()\n {\n this.state = \"BadBaseClass\";\n this.DisplayState();\n }\n\n public virtual void DisplayState()\n {\n }\n}\n\npublic class DerivedFromBad : BadBaseClass\n{\n public DerivedFromBad()\n {\n this.state = \"DerivedFromBad\";\n }\n\n public override void DisplayState()\n { \n Console.WriteLine(this.state);\n }\n}\n DerivedFromBad DisplayState BadBaseClass public class Tester\n{\n public static void Main()\n {\n var bad = new DerivedFromBad();\n }\n}\n Initialize DerivedFromBetter public class BetterBaseClass\n{\n protected string state;\n\n public BetterBaseClass()\n {\n this.state = \"BetterBaseClass\";\n this.Initialize();\n }\n\n public void Initialize()\n {\n this.DisplayState();\n }\n\n public virtual void DisplayState()\n {\n }\n}\n\npublic class DerivedFromBetter : BetterBaseClass\n{\n public DerivedFromBetter()\n {\n this.state = \"DerivedFromBetter\";\n }\n\n public override void DisplayState()\n {\n Console.WriteLine(this.state);\n }\n}\n" }, { "answer_id": 33130698, "author": "Jim Ma", "author_id": 2719128, "author_profile": "https://Stackoverflow.com/users/2719128", "pm_score": 1, "selected": false, "text": "class Parent\n{\n public Parent()\n {\n DoSomething();\n }\n protected virtual void DoSomething()\n {\n }\n}\n\nclass Child : Parent\n{\n private string foo = \"HELLO\";\n public Child() { /*Originally foo initialized here. Removed.*/ }\n protected override void DoSomething()\n {\n Console.WriteLine(foo.ToLower());\n }\n}\n" }, { "answer_id": 39194460, "author": "Biniam Eyakem", "author_id": 946931, "author_profile": "https://Stackoverflow.com/users/946931", "pm_score": 2, "selected": false, "text": "public class Parent\n{\n public virtual object Obj{get;set;}\n public Parent()\n {\n // Re-sharper warning: this is open to change from \n // inheriting class overriding virtual member\n this.Obj = new Object();\n }\n}\n public class Child: Parent\n{\n public Child():base()\n {\n this.Obj = \"Something\";\n }\n public override object Obj{get;set;}\n}\n public class Program\n{\n public static void Main()\n {\n var child = new Child();\n // anything that is done on parent virtual member is destroyed\n Console.WriteLine(child.Obj);\n // Output: \"Something\"\n }\n} \n" }, { "answer_id": 46593201, "author": "typhon04", "author_id": 5874476, "author_profile": "https://Stackoverflow.com/users/5874476", "pm_score": 2, "selected": false, "text": " public **virtual** User User{ get; set; }\n" }, { "answer_id": 59285281, "author": "pasx", "author_id": 683319, "author_profile": "https://Stackoverflow.com/users/683319", "pm_score": 1, "selected": false, "text": "internal class Parent\n{\n public Parent()\n {\n Console.WriteLine(\"Parent ctor\");\n Console.WriteLine(Something);\n }\n\n protected virtual string Something { get; } = \"Parent\";\n}\n\ninternal class Child : Parent\n{\n public Child()\n {\n Console.WriteLine(\"Child ctor\");\n Console.WriteLine(Something);\n }\n\n protected override string Something { get; } = \"Child\";\n}\n Parent ctor\nChild\nChild ctor\nChild\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
119,540
<p>The age old question. Where should you put your business logic, in the database as stored procedures ( or packages ), or in the application/middle tier? And more importantly, Why?</p> <p>Assume database independence is not a goal.</p>
[ { "answer_id": 120842, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "PATH" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
119,548
<p>I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. </p> <p>The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:</p> <blockquote> <p>The process cannot access the file because it is being used by another process.</p> </blockquote> <p>The solutions that I have tried to implement in C# and failed are as below.</p> <ol> <li>Implemented singleton class that contains code that writes to a file.</li> <li>Used lock statement to wrap the code that writes to the file. </li> <li>I have also tried to use open source logger log4net but it also is not a perfect solution. </li> <li>I know about logging to system event logger, but I do not have that choice.</li> </ol> <p>I want to know if there exists a perfect and complete solution to such a problem? </p>
[ { "answer_id": 119599, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 5, "selected": true, "text": "lock(someobject) {...} Mutex lock = new Mutex(\"mymutex\", false);\n\nlock.WaitOne();\n\n// access file\n\nlock.ReleaseMutex();\n" }, { "answer_id": 119646, "author": "pradeeptp", "author_id": 20933, "author_profile": "https://Stackoverflow.com/users/20933", "pm_score": 0, "selected": false, "text": "private static volatile FileWriteTest instance;\n\nprivate static object syncRoot = new Object();\n\nprivate static Queue logMessages = new Queue();\n\nprivate static ErrorLogger oNetLogger = new ErrorLogger();\n\nprivate FileWriteTest() { }\n\npublic static FileWriteTest Instance\n{\n get\n {\n if (instance == null)\n {\n lock (syncRoot)\n {\n if (instance == null)\n {\n instance = new FileWriteTest();\n Thread MyThread = new Thread(new ThreadStart(StartCollectingLogs));\n MyThread.Start();\n\n }\n }\n }\n\n return instance;\n }\n}\n\nprivate static void StartCollectingLogs()\n{\n\n //Infinite loop\n while (true)\n {\n cdoLogMessage objMessage = new cdoLogMessage();\n if (logMessages.Count != 0)\n {\n objMessage = (cdoLogMessage)logMessages.Dequeue();\n oNetLogger.WriteLog(objMessage.LogText, objMessage.SeverityLevel);\n\n }\n }\n}\n\npublic void WriteLog(string logText, SeverityLevel errorSeverity)\n{\n cdoLogMessage objMessage = new cdoLogMessage();\n objMessage.LogText = logText;\n objMessage.SeverityLevel = errorSeverity;\n logMessages.Enqueue(objMessage);\n\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20933/" ]
119,550
<p>I want to log the Poison message that my wcf service is dropping using MSMQ 3.0 and windows 2003</p>
[ { "answer_id": 120299, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 0, "selected": false, "text": "<service name=\"YourPosionMessageHandler\"\n <endpoint\naddress=\"net.msq://localhost/private/YourServiceQueue;poison\"\nbinding=\"netMsmqBinding\"\n />\n</service>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,559
<p>Is there an easy way to programmatically determine the number of lines within a text file? </p>
[ { "answer_id": 119572, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 10, "selected": true, "text": "File ReadLines ReadAllLines var lineCount = File.ReadLines(@\"C:\\file.txt\").Count();\n var lineCount = File.ReadAllLines(@\"C:\\file.txt\").Length;\n var lineCount = 0;\nusing (var reader = File.OpenText(@\"C:\\file.txt\"))\n{\n while (reader.ReadLine() != null)\n {\n lineCount++;\n }\n}\n" }, { "answer_id": 119579, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": false, "text": "int lines = File.ReadAllLines(\"myfile\").Length;\n" }, { "answer_id": 119583, "author": "user8456", "author_id": 8456, "author_profile": "https://Stackoverflow.com/users/8456", "pm_score": 3, "selected": false, "text": "string[] lines = System.IO.File.RealAllLines($filename);\nint cnt = lines.Count();\n #for large files\nwhile (...reads into buffer){\nstring[] lines = Regex.Split(buffer,System.Enviorment.NewLine);\n}\n" }, { "answer_id": 119602, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": false, "text": "int count = 0;\nstring line;\nTextReader reader = new StreamReader(\"file.txt\");\nwhile ((line = reader.ReadLine()) != null)\n{\n count++;\n}\nreader.Close();\n" }, { "answer_id": 12769601, "author": "Muhammad Usman -kai hiwatari", "author_id": 1726814, "author_profile": "https://Stackoverflow.com/users/1726814", "pm_score": -1, "selected": false, "text": "try {\n string path = args[0];\n FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);\n int i;\n string s = \"\";\n while ((i = fh.ReadByte()) != -1)\n s = s + (char)i;\n\n //its for reading number of paragraphs\n int count = 0;\n for (int j = 0; j < s.Length - 1; j++) {\n if (s.Substring(j, 1) == \"\\n\")\n count++;\n }\n\n Console.WriteLine(\"The total searches were :\" + count);\n\n fh.Close();\n\n} catch(Exception ex) {\n Console.WriteLine(ex.Message);\n} \n" }, { "answer_id": 50508830, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "private const char CR = '\\r'; \nprivate const char LF = '\\n'; \nprivate const char NULL = (char)0;\n\npublic static long CountLinesMaybe(Stream stream) \n{\n Ensure.NotNull(stream, nameof(stream));\n\n var lineCount = 0L;\n\n var byteBuffer = new byte[1024 * 1024];\n const int BytesAtTheTime = 4;\n var detectedEOL = NULL;\n var currentChar = NULL;\n\n int bytesRead;\n while ((bytesRead = stream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)\n {\n var i = 0;\n for (; i <= bytesRead - BytesAtTheTime; i += BytesAtTheTime)\n {\n currentChar = (char)byteBuffer[i];\n\n if (detectedEOL != NULL)\n {\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 1];\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 2];\n if (currentChar == detectedEOL) { lineCount++; }\n\n currentChar = (char)byteBuffer[i + 3];\n if (currentChar == detectedEOL) { lineCount++; }\n }\n else\n {\n if (currentChar == LF || currentChar == CR)\n {\n detectedEOL = currentChar;\n lineCount++;\n }\n i -= BytesAtTheTime - 1;\n }\n }\n\n for (; i < bytesRead; i++)\n {\n currentChar = (char)byteBuffer[i];\n\n if (detectedEOL != NULL)\n {\n if (currentChar == detectedEOL) { lineCount++; }\n }\n else\n {\n if (currentChar == LF || currentChar == CR)\n {\n detectedEOL = currentChar;\n lineCount++;\n }\n }\n }\n }\n\n if (currentChar != LF && currentChar != CR && currentChar != NULL)\n {\n lineCount++;\n }\n return lineCount;\n}\n" }, { "answer_id": 63327465, "author": "Khalil Al-rahman Yossefi", "author_id": 5827730, "author_profile": "https://Stackoverflow.com/users/5827730", "pm_score": 0, "selected": false, "text": " int get_lines(string file)\n {\n var lineCount = 0;\n using (var stream = new StreamReader(file))\n {\n while (stream.ReadLine() != null)\n {\n lineCount++;\n }\n }\n return lineCount;\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
119,578
<p>What is the best way to disable the warnings generated via <code>_CRT_SECURE_NO_DEPRECATE</code> that allows them to be reinstated with ease and will work across Visual Studio versions?</p>
[ { "answer_id": 119752, "author": "Serge", "author_id": 1007, "author_profile": "https://Stackoverflow.com/users/1007", "pm_score": 8, "selected": true, "text": "_CRT_SECURE_NO_WARNINGS #ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n" }, { "answer_id": 120042, "author": "Drealmer", "author_id": 12291, "author_profile": "https://Stackoverflow.com/users/12291", "pm_score": 3, "selected": false, "text": "#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 \n" }, { "answer_id": 121573, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 6, "selected": false, "text": "#pragma warning(push)\n#pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent\n// deprecated code here\n#pragma warning(pop)\n" }, { "answer_id": 14107686, "author": "Adrian Borchardt", "author_id": 1940499, "author_profile": "https://Stackoverflow.com/users/1940499", "pm_score": 2, "selected": false, "text": "#ifndef _DEPRECATION_DISABLE /* One time only */\n#define _DEPRECATION_DISABLE /* Disable deprecation true */\n#if (_MSC_VER >= 1400) /* Check version */\n#pragma warning(disable: 4996) /* Disable deprecation */\n#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */\n#endif /* #ifndef _DEPRECATION_DISABLE */\n #pragma warning(disable: 4996)\n" }, { "answer_id": 14225814, "author": "Gustavo Litovsky", "author_id": 1628786, "author_profile": "https://Stackoverflow.com/users/1628786", "pm_score": 2, "selected": false, "text": "#pragma warning(disable: 4996) /* Disable deprecation */\n// Code that causes it goes here\n#pragma warning(default: 4996) /* Restore default */\n" }, { "answer_id": 17094446, "author": "PicoCreator", "author_id": 793842, "author_profile": "https://Stackoverflow.com/users/793842", "pm_score": 3, "selected": false, "text": "#if (_MSC_VER >= 1400) // Check MSC version\n#pragma warning(push)\n#pragma warning(disable: 4996) // Disable deprecation\n#endif \n//... // ...\nstrcat(base, cat); // Sample depreciated code\n//... // ...\n#if (_MSC_VER >= 1400) // Check MSC version\n#pragma warning(pop) // Renable previous depreciations\n#endif\n" }, { "answer_id": 32858904, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 0, "selected": false, "text": "wchar.h __inline _CRT_INSECURE_DEPRECATE_MEMORY(wmemcpy_s) wchar_t * __CRTDECL\nwmemcpy(_Out_opt_cap_(_N) wchar_t *_S1, _In_opt_count_(_N) const wchar_t *_S2, _In_ size_t _N)\n{\n #pragma warning( push )\n #pragma warning( disable : 4996 6386 )\n return (wchar_t *)memcpy(_S1, _S2, _N*sizeof(wchar_t));\n #pragma warning( pop )\n} \n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8516/" ]
119,609
<p>I have 20 ips from my isp. I have them bound to a router box running centos. What commands, and in what order, do I set up so that the other boxes on my lan, based either on their mac addresses or 192 ips can I have them route out my box on specific ips. For example I want mac addy <code>xxx:xxx:xxx0400</code> to go out <code>72.049.12.157</code> and <code>xxx:xxx:xxx:0500</code> to go out <code>72.049.12.158</code>.</p>
[ { "answer_id": 119970, "author": "BigMikeD", "author_id": 17782, "author_profile": "https://Stackoverflow.com/users/17782", "pm_score": 1, "selected": false, "text": "iptables NAT iptables -t nat -I POSTROUTING -s 192.168.0.0/24 -j SNAT --to-source 72.049.12.157\niptables -t nat -I POSTROUTING -s 192.168.1.0/24 -j SNAT --to-source 72.049.12.158\n 192.168.0.0 72.049.12.157 192.168.1.0 72.049.12.158 -m mac --mac-source MAC-ADDRESS -s 192.168.0.0/24 cat /proc/sys/net/ipv4/ip_forward\n 0 echo 1 > /proc/sys/net/ipv4/ip_forward\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8456/" ]
119,647
<p>Does anyone know of a library or bit of code that converts British English to American English and vice versa?</p> <p>I don't imagine there's too many differences (some examples that come to mind are doughnut/donut, colour/color, grey/gray, localised/localized) but it would be nice to be able to provide localised site content.</p>
[ { "answer_id": 26011527, "author": "Nick Ruiz", "author_id": 243372, "author_profile": "https://Stackoverflow.com/users/243372", "pm_score": 1, "selected": false, "text": "echo \"I apologise for my colourful tongue .\" | ./translate british american\n# >> I apologize for my colorful tongue .\n" }, { "answer_id": 46268763, "author": "HoldOffHunger", "author_id": 2430549, "author_profile": "https://Stackoverflow.com/users/2430549", "pm_score": 2, "selected": false, "text": "require('AmericanBritishSpellings.php');\n$american_british_spellings = new AmericanBritishSpellings();\n\n$text = \"Axiomatically ax that door, would you, my neighbour?\";\n$text = $american_british_spellings->SwapBritishSpellingsForAmericanSpellings(['text'=>$text]);\n\nprint($text); // output: Axiomatically axe that door, would you, my neighbor?\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
119,651
<p>Let me start off with a bit of background.</p> <p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p> <p>A now, for the actual question.</p> <p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p> <p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p> <pre><code>from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) </code></pre> <p>Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.</p>
[ { "answer_id": 119718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "@lcs = $tree->lcs;\n@lcs = $tree->lcs($min_len, $max_len);\n@lcs = $tree->longest_common_substrings;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
119,669
<p>How can I fetch data in a Winforms application or ASP.NET form from a SAP database? The .NET framework used is 2.0. , language is C# and SAP version is 7.10. </p>
[ { "answer_id": 119718, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "@lcs = $tree->lcs;\n@lcs = $tree->lcs($min_len, $max_len);\n@lcs = $tree->longest_common_substrings;\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
119,679
<p>I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.</p>
[ { "answer_id": 119719, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "SELECT Distinct SO.Name\nFROM sysobjects SO (NOLOCK)\nINNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID\nAND SO.Type = 'P'\nAND (SC.Text LIKE '%UPDATE%' OR SC.Text LIKE '%INSERT%')\nORDER BY SO.Name\n" }, { "answer_id": 119734, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 4, "selected": true, "text": "select\n so.name,\n sc.text\nfrom\n sysobjects so inner join syscomments sc on so.id = sc.id\nwhere\n sc.text like '%INSERT INTO xyz%'\n or sc.text like '%UPDATE xyz%'\n" }, { "answer_id": 119760, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "select \nso.name as [proc], \nso2.name as [table], \nsd.is_updated \nfrom sysobjects so \ninner join sys.sql_dependencies sd on so.id = sd.object_id \ninner join sysobjects so2 on sd.referenced_major_id = so2.id \nwhere so.xtype = 'p' -- procedure \nand is_updated = 1 -- proc updates table, or at least, I think that's what this means\n" }, { "answer_id": 121329, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "sys.sql_dependencies select sp.name as sproc_name\n ,t.name as table_name\n ,c.name as column_name\n from sys.sql_dependencies d\n join sys.objects t\n on t.object_id = d.referenced_major_id\n join sys.objects sp\n on sp.object_id = d.object_id\n join sys.columns c\n on c.object_id = t.object_id\n and c.column_id = d.referenced_minor_id\nwhere sp.type = 'P'\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
119,694
<p>We've got dozens of versions of an SWF modified for different customers of a big Flash project, and now would have to replace some strings embedded in scripts in each copy. The FLA file for some of these is very difficult to locate or even missing (I inherited this mess and refactoring it is currently not an option).</p> <p>Is there a (free) tool to replace strings used inside ActionScript? I tried swfmill to convert the files to XML and back but it can't handle international characters contained in the strings so I could get them only partially converted. Most of the strings were correctly extracted so another tool might do the job.</p>
[ { "answer_id": 120392, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 0, "selected": false, "text": "_root.loadedswf.clip1.box2.textField.text = \"New text\";" }, { "answer_id": 2131790, "author": "Joa Ebert", "author_id": 164128, "author_profile": "https://Stackoverflow.com/users/164128", "pm_score": 2, "selected": false, "text": "val swf = Swf from \"in.swf\"\nfor(tag <- swf.tags) {\n (Abc fromTag tag) match {\n case Some(abc) => {\n val strings = abc.cpool.strings\n for(i <- 1 until strings.length) {\n if(strings(i) == 'search) {\n strings(i) = 'replacement\n }\n }\n abc write tag\n }\n case None =>\n}\nswf write \"out.swf\"\n" }, { "answer_id": 38597546, "author": "Fausto Morales", "author_id": 845563, "author_profile": "https://Stackoverflow.com/users/845563", "pm_score": 0, "selected": false, "text": "javac -classpath \".;apparat/*;C:/path/to/scala/lib/*\" SwfEditor.java java -classpath \".;apparat/*;C:/path/to/scala/lib/*\" SwfEditor import apparat.swf.Swf;\nimport apparat.abc.Abc;\nimport apparat.swf.SwfTag;\nimport scala.collection.Iterator;\nimport scala.Symbol;\nimport apparat.swf.DoABC;\n\nclass SwfEditor {\n\n public static void main(String[] args){\n Swf input = Swf.fromFile(\"in.swf\");\n Iterator<SwfTag> iter = input.tags().iterator();\n while (iter.hasNext()) {\n SwfTag tag = iter.next();\n if(tag instanceof DoABC) {\n DoABC doABCTag = (DoABC) tag;\n Abc abc = Abc.fromTag(doABCTag).getOrElse(null);\n Symbol[] strings = abc.cpool().strings();\n for(int i=0; i<strings.length; i++) {\n String string = strings[i].toString();\n if(string == \"'search\")) {\n strings[i] = new Symbol(\"replacement\");\n }\n }\n abc.write(doABCTag);\n }\n }\n input.write(\"out.swf\");\n }\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16509/" ]
119,696
<p>Is there anywhere on the web free vista look and feel theme pack for java?</p>
[ { "answer_id": 120198, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 2, "selected": false, "text": "UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );\n" }, { "answer_id": 123743, "author": "Jay R.", "author_id": 5074, "author_profile": "https://Stackoverflow.com/users/5074", "pm_score": 0, "selected": false, "text": "UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15878/" ]
119,706
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/557081/how-do-i-get-the-hmodule-for-the-currently-executing-code">How do I get the HMODULE for the currently executing code?</a> </p> </blockquote> <p>I'm trying to find a resource in my own module. If this module is an executable, that's trivial - <code>GetModuleHandle(NULL)</code> returns the handle of the "main" module.</p> <p>My module, however, is a DLL that is loaded by another executable. So <code>GetModuleHandle(NULL)</code> will return the module handle to that executable, which is obviously not what I want.</p> <p>Is there any way to determine the module handle of the module that contains the currently running code? Using the DLL's name in a call to <code>GetModuleHandle()</code> seems like a hack to me (and is not easily maintainable in case the code in question is transplanted into a different DLL).</p>
[ { "answer_id": 7014377, "author": "Sergey Maruda", "author_id": 878573, "author_profile": "https://Stackoverflow.com/users/878573", "pm_score": 3, "selected": false, "text": "void dll_function()\n {\n AFX_MANAGE_STATE(AfxGetStaticModuleState());\n HINSTANCE dll_instance = AfxGetInstanceHandle();\n }\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2074/" ]
119,730
<p>I have a <code>VARCHAR</code> column in a <code>SQL Server 2000</code> database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. </p> <p>When it does contain numbers, I want it to be sorted numerically, e.g. as "1", "2", "10" instead of "1", "10", "2". Fields containing just letters, or letters and numbers (such as 'A1') can be sorted alphabetically as normal. For example, this would be an acceptable sort order.</p> <pre><code>1 2 10 A B B1 </code></pre> <p>What is the best way to achieve this? </p>
[ { "answer_id": 119780, "author": "Cowan", "author_id": 17041, "author_profile": "https://Stackoverflow.com/users/17041", "pm_score": 4, "selected": false, "text": "SELECT\n ...\nORDER BY\n CASE \n WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value) \n ELSE 9999999 -- or something huge\n END,\n value\n" }, { "answer_id": 119796, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": -1, "selected": false, "text": "SELECT FIELD FROM TABLE\nORDER BY \n isnumeric(FIELD) desc, \n CASE ISNUMERIC(test) \n WHEN 1 THEN CAST(CAST(test AS MONEY) AS INT)\n ELSE NULL \n END,\n FIELD\n" }, { "answer_id": 119800, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 3, "selected": false, "text": "select\n Field1, Field2...\nfrom\n Table1\norder by\n isnumeric(Field1) desc,\n case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,\n Field1\n" }, { "answer_id": 119817, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 2, "selected": false, "text": "select your_column \nfrom your_table \norder by \ncase when isnumeric(your_column) = 1 then your_column else 999999999 end, \nyour_column \n" }, { "answer_id": 119842, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 7, "selected": true, "text": "select MyColumn\nfrom MyTable\norder by \n case IsNumeric(MyColumn) \n when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn\n else MyColumn\n end\n 100" }, { "answer_id": 4685143, "author": "JohnB", "author_id": 287311, "author_profile": "https://Stackoverflow.com/users/287311", "pm_score": 3, "selected": false, "text": "SELECT *, CONVERT(int, your_column) AS your_column_int\nFROM your_table\nORDER BY your_column_int\n SELECT *, CAST(your_column AS int) AS your_column_int\nFROM your_table\nORDER BY your_column_int\n" }, { "answer_id": 6773742, "author": "Orz", "author_id": 855573, "author_profile": "https://Stackoverflow.com/users/855573", "pm_score": 2, "selected": false, "text": "ORDER BY (\nsr.codice +0\n)\nASC\n 16079 Customer X \n016082 Customer Y\n16413 Customer Z\n 0 16082" }, { "answer_id": 15781451, "author": "Bernhard", "author_id": 1498669, "author_profile": "https://Stackoverflow.com/users/1498669", "pm_score": 3, "selected": false, "text": "select cast([yourvarchar] as BIGINT)\n where ISNUMERIC([yourvarchar] +'e0') = 1\n SELECT\n *\nFROM\n Table\nORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , LEN([yourvarchar]) ASC\n SELECT\n *\n FROM\n Table\n ORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC\n SELECT\n *\n FROM\n Table\n ORDER BY\n ISNUMERIC([yourvarchar] +'e0') DESC\n , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1\n THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC\n ELSE LTRIM(RTRIM([yourvarchar]))\n END ASC\n" }, { "answer_id": 37144238, "author": "Param Yadav", "author_id": 6165840, "author_profile": "https://Stackoverflow.com/users/6165840", "pm_score": -1, "selected": false, "text": " SELECT *,\n ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical\n FROM\n (\n\n SELECT '1'Id UNION ALL\n SELECT '25.20' Id UNION ALL\n\n SELECT 'A115' Id UNION ALL\n SELECT '2541' Id UNION ALL\n SELECT '571.50' Id UNION ALL\n SELECT '67' Id UNION ALL\n SELECT 'B48' Id UNION ALL\n SELECT '500' Id UNION ALL\n SELECT '147.54' Id UNION ALL\n SELECT 'A-100' Id\n )A\n\n ORDER BY \n CASE WHEN ISNUMERIC (ID)=0 /* alphabetical sort */ \n THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0\n THEN LEFT(Id,PATINDEX('%[0-9]%',Id))\n ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)\n END\n END DESC\n" }, { "answer_id": 44110188, "author": "Nitika Chopra", "author_id": 7534013, "author_profile": "https://Stackoverflow.com/users/7534013", "pm_score": 0, "selected": false, "text": "SELECT *,\n (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum\nFROM table_name \nORDER BY IsNum, LEN(column_name), column_name;\n" }, { "answer_id": 50561956, "author": "Dennis Xavier", "author_id": 9056729, "author_profile": "https://Stackoverflow.com/users/9056729", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM tab\nORDER BY IIF(TRY_CAST(val AS INT) IS NULL, 1, 0),TRY_CAST(val AS INT);" }, { "answer_id": 72877808, "author": "Mikko", "author_id": 5553320, "author_profile": "https://Stackoverflow.com/users/5553320", "pm_score": 0, "selected": false, "text": "SELECT my_column \nFROM my_table\nWHERE <condition>\nORDER BY TRY_CAST(my_column AS NUMERIC) DESC\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
119,732
<p>When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?</p> <p>Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.</p> <p>I can imagine the following solutions:</p> <ol> <li><p>Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.</p></li> <li><p>Like 1. but create DTOs</p></li> <li><p>Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results</p></li> <li><p>The remote method takes a DetachedCriteria, which is created by the client and executed by the server</p></li> <li><p>Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.</p></li> </ol>
[ { "answer_id": 119966, "author": "Glever", "author_id": 15504, "author_profile": "https://Stackoverflow.com/users/15504", "pm_score": 1, "selected": false, "text": "CustomerService.getCustomerById(id, \"parent, address, address.city\")\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18722/" ]
119,754
<p>I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless:</p> <pre><code>Please print your &lt;a href=3D&quot;http://xxxxxxx.xxx.xx.edu= au//newsletter2/3/InnovExpoInviteVIP.pdf&quot;&gt; VIP invitation&lt;/a&gt; for future re= ference and check the Innovation Expo website &lt;a href=3D&quot;http://xxxxxxx.xx= xx.xx.edu.au/2008/&quot;&gt; xxxxxxx.xxxx.xx.edu.au&lt;/a&gt; for updates. </code></pre> <p>In the example above the period was lost between edu and au on the first hyperlink.</p> <p>We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email:</p> <p><a href="https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2</a></p> <p>My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place?</p> <p>UPDATE: After a <em>lot</em> of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a <em>very</em> old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours. JDK prior to 1.2 have this bug.</p>
[ { "answer_id": 119822, "author": "Jataro", "author_id": 9292, "author_profile": "https://Stackoverflow.com/users/9292", "pm_score": 0, "selected": false, "text": "BodyPart bp = new MimeBodyPart();\nbp.setContent(message,\"text/html\");\n" }, { "answer_id": 119891, "author": "Ioannis", "author_id": 20428, "author_profile": "https://Stackoverflow.com/users/20428", "pm_score": 1, "selected": false, "text": "\n private String mimeEncode (String input)\n {\n ByteArrayOutputStream bOut = new ByteArrayOutputStream();\n OutputStream out;\n try\n {\n out = MimeUtility.encode( bOut, \"quoted-printable\" );\n out.write( input.getBytes( ) );\n out.flush( );\n out.close( );\n bOut.close( );\n } catch (MessagingException e)\n {\n log.error( \"Encoding error occured:\",e );\n return input;\n } catch (IOException e)\n {\n log.error( \"Encoding error occured:\",e );\n return input;\n }\n\n return bOut.toString( );\n }\n\n" }, { "answer_id": 425596, "author": "Karl", "author_id": 36093, "author_profile": "https://Stackoverflow.com/users/36093", "pm_score": 0, "selected": false, "text": "var html;\nhtml = \"Blah Blah Blah Blah \";\nhtml = html & \" More Text Here....\";\n var html;\nhtml = \"Blah Blah Blah Blah \" & VbCrLf;\nhtml = html & \" More Text Here....\";\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9731/" ]
119,762
<p>I've got an ASP.NET app using NHibernate to transactionally update a few tables upon a user action. There is a date range involved whereby only one entry to a table 'Booking' can be made such that exclusive dates are specified.</p> <p>My problem is how to prevent a race condition whereby two user actions occur almost simultaneously and cause mutliple entries into 'Booking' for &gt;1 date. I can't check just prior to calling .Commit() because I think that will still leave be with a race condition?</p> <p>All I can see is to do a check AFTER the commit and roll the change back manually, but that leaves me with a very bad taste in my mouth! :)</p> <blockquote> <p>booking_ref (INT) PRIMARY_KEY AUTOINCREMENT</p> <p>booking_start (DATETIME)</p> <p>booking_end (DATETIME)</p> </blockquote>
[ { "answer_id": 120264, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "session.BeginTransaction(IsolationLevel.Serializable" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
119,788
<p>Before moving on to use SVN, I used to manage my project by simply keeping a <code>/develop/</code> directory and editing and testing files there, then moving them to the <code>/main/</code> directory. When I decided to move to SVN, I needed to be sure that the directories were indeed in sync.</p> <p>So, what is a good way to write a shell script [ bash ] to recursively compare files with the same name in two different directories?</p> <p>Note: The directory names used above are for sample only. I do not recommend storing your code in the top level :).</p>
[ { "answer_id": 119811, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "diff -r /develop /main\n" }, { "answer_id": 119812, "author": "Animesh", "author_id": 20386, "author_profile": "https://Stackoverflow.com/users/20386", "pm_score": 1, "selected": false, "text": "[/]$ cd /develop/\n[/develop/]$ find | while read line; do diff -ruN \"/main/$line\" $line; done |less\n [/]$ cd /develop/\n[/develop/]$ find -name \"*.php\" | while read line; do diff -ruN \"/main/$line\" $line; done |less\n" }, { "answer_id": 119830, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "diff -r main develop\n ( cd main ; find . -type f -exec diff {} ../develop/{} ';' )\n" }, { "answer_id": 119910, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "diff -rqu /develop /main\n diff -rqu /develop /main | grep \"^Only\n diff -rqu /develop /main | sed -rn \"/^Only/s/^Only in (.+?): /\\1/p\"\n" }, { "answer_id": 215409, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "dircmp dir1 dir2 pr cmp" }, { "answer_id": 6740823, "author": "sdaau", "author_id": 277826, "author_profile": "https://Stackoverflow.com/users/277826", "pm_score": 1, "selected": false, "text": "diff -q diff ~/.gvfs bash rsync $ # get example revision 4527 as testdir1\n$ svn co https://openbabel.svn.sf.net/svnroot/openbabel/openbabel/trunk/data@4527 testdir1\n\n$ # get earlier example revision 2729 as testdir2\n$ svn co https://openbabel.svn.sf.net/svnroot/openbabel/openbabel/trunk/data@2729 testdir2\n\n$ # use rsync to generate a list \n$ rsync -ivr --times --cvs-exclude --dry-run testdir1/ testdir2/\nsending incremental file list\n.d..t...... ./\n>f.st...... CMakeLists.txt\n>f.st...... MACCS.txt\n>f..t...... SMARTS_InteLigand.txt\n...\n>f.st...... atomtyp.txt\n>f+++++++++ babel_povray3.inc\n>f.st...... bin2hex.pl\n>f.st...... bondtyp.h\n>f..t...... bondtyp.txt\n...\n / rsync --dry-run -r -v --cvs-exclude .svn -i man rsync -i >f.st...... The \"%i\" escape has a cryptic output that is 11 letters long.\nThe general format is like the string YXcstpoguax, where Y is\nreplaced by the type of update being done, X is replaced by the\nfile-type, and the other letters represent attributes that may\nbe output if they are being modified.\n\nThe update types that replace the Y are as follows:\n\no A < means that a file is being transferred to the remote\n host (sent).\n\no A > means that a file is being transferred to the local\n host (received).\n\no A c means that a local change/creation is occurring for\n the item (such as the creation of a directory or the\n changing of a symlink, etc.).\n\n...\nThe file-types that replace the X are: f for a file, a d for a\ndirectory, an L for a symlink, a D for a device, and a S for a\nspecial file (e.g. named sockets and fifos).\n\nThe other letters in the string above are the actual letters\nthat will be output if the associated attribute for the item is\nbeing updated or a \".\" for no change. Three exceptions to this\nare: (1) a newly created item replaces each letter with a \"+\",\n(2) an identical item replaces the dots with spaces, and (3) an\n....\n ssh" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20386/" ]
119,792
<p>I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:</p> <pre><code>svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table: Invalid argument svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767]. svnadmin: bdb: end of log is [1083][354707] svnadmin: bdb: db/nodes: unexpected file type or format </code></pre> <p>I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.</p> <p>edit: even the db_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.</p>
[ { "answer_id": 119798, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "svnadmin dump svnadmin load" }, { "answer_id": 119957, "author": "Linor", "author_id": 3197, "author_profile": "https://Stackoverflow.com/users/3197", "pm_score": 1, "selected": false, "text": "db_recover -c -v -h <path to subversion db dir>\n" }, { "answer_id": 2851717, "author": "Yaşar Şentürk", "author_id": 248495, "author_profile": "https://Stackoverflow.com/users/248495", "pm_score": 1, "selected": false, "text": "svnadmin recover <svn path>" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197/" ]
119,802
<p>I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this:</p> <pre><code>server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() </code></pre> <p>I then have a ServiceRemote class that looks like this:</p> <pre><code>def __init__(self,ip,port): self.rpcClient = xmlrpclib.Server('http://%s:%d' %(ip,port)) def __getattr__(self, name): # forward all calls to the rpc client return getattr(self.rpcClient, name) </code></pre> <p>So all calls on the ServiceRemote object will be forwarded to xmlrpclib.Server, which then forwards it to the remote server. The problem is a method in the service that takes named varargs:</p> <pre><code>@useDb def select(self, db, fields, **kwargs): pass </code></pre> <p>The @useDb decorator wraps the function, creating the db before the call and opening it, then closing it after the call is done before returning the result.</p> <p>When I call this method, I get the error "<strong>call</strong>() got an unexpected keyword argument 'name'". So, is it possible to call methods taking variable named arguments remotely? Or will I have to create an override for each method variation I need.</p> <hr> <p>Thanks for the responses. I changed my code around a bit so the question is no longer an issue. However now I know this for future reference if I indeed do need to implement positional arguments and support remote invocation. I think a combination of Thomas and praptaks approaches would be good. Turning kwargs into positional args on the client through xmlrpclient, and having a wrapper on methods serverside to unpack positional arguments.</p>
[ { "answer_id": 119943, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 1, "selected": false, "text": "def select_wrapper(self, db, fields, kwargs):\n \"\"\"accepts an ordinary dict which can pass through xmlrpc\"\"\"\n return select(self,db,fields, **kwargs)\n def select(self, db, fields, **kwargs):\n \"\"\"you can call it with keyword arguments and they will be packed into a dict\"\"\"\n return self.rpcClient.select_wrapper(self,db,fields,kwargs)\n" }, { "answer_id": 119963, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 2, "selected": false, "text": "import xmlrpclib\n\n_orig_Method = xmlrpclib._Method\n\nclass KeywordArgMethod(_orig_Method): \n def __call__(self, *args, **kwargs):\n if args and kwargs:\n raise TypeError, \"Can't pass both positional and keyword args\"\n args = list(args) \n for key in kwargs:\n args.append('-%s' % key.upper())\n args.append(kwargs[key])\n return _orig_Method.__call__(self, *args) \n\nxmlrpclib._Method = KeywordArgMethod\n" }, { "answer_id": 120225, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 1, "selected": false, "text": "def unwrap_kwargs(func):\n def wrapper(*args, **kwargs):\n print args\n if args and isinstance(args[-1], list) and len(args[-1]) == 2 and \"kwargs\" == args[-1][0]:\n func(*args[:-1], **args[-1][1])\n else:\n func(*args, **kwargs)\n return wrapper\n _orig_Method = xmlrpclib._Method\n\nclass KeywordArgMethod(_orig_Method): \n def __call__(self, *args, **kwargs):\n args = list(args) \n if kwargs:\n args.append((\"kwargs\", kwargs))\n return _orig_Method.__call__(self, *args)\n\nxmlrpclib._Method = KeywordArgMethod\n" }, { "answer_id": 120291, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 5, "selected": true, "text": "from SimpleXMLRPCServer import SimpleXMLRPCServer\n\nclass Server(object):\n def __init__(self, hostport):\n self.server = SimpleXMLRPCServer(hostport)\n\n def register_function(self, function, name=None):\n def _function(args, kwargs):\n return function(*args, **kwargs)\n _function.__name__ = function.__name__\n self.server.register_function(_function, name)\n\n def serve_forever(self):\n self.server.serve_forever()\n\n#example usage\nserver = Server(('localhost', 8000))\ndef test(arg1, arg2):\n print 'arg1: %s arg2: %s' % (arg1, arg2)\n return 0\nserver.register_function(test)\nserver.serve_forever()\n import xmlrpclib\n\nclass ServerProxy(object):\n def __init__(self, url):\n self._xmlrpc_server_proxy = xmlrpclib.ServerProxy(url)\n def __getattr__(self, name):\n call_proxy = getattr(self._xmlrpc_server_proxy, name)\n def _call(*args, **kwargs):\n return call_proxy(args, kwargs)\n return _call\n\n#example usage\nserver = ServerProxy('http://localhost:8000')\nserver.test(1, 2)\nserver.test(arg2=2, arg1=1)\nserver.test(1, arg2=2)\nserver.test(*[1,2])\nserver.test(**{'arg1':1, 'arg2':2})\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ]
119,818
<p>I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.</p>
[ { "answer_id": 119907, "author": "TheZenker", "author_id": 10552, "author_profile": "https://Stackoverflow.com/users/10552", "pm_score": 2, "selected": true, "text": "function TrackMyCheckbox(ck)\n{\n //keep track of state\n}\n\n<input type=\"checkbox\" onClick=\"TrackMyCheckbox(this);\".... />\n" }, { "answer_id": 120717, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 0, "selected": false, "text": "<html>\n...\n\n<div id=\"grid\">\n <input type=\"checkbox\" id=\"checkbox1\" class=\"must-be-checked\" />\n <input type=\"checkbox\" id=\"checkbox2\" class=\"not-validated\" />\n <input type=\"checkbox\" id=\"checkbox3\" class=\"must-be-checked\" />\n ... \n <input type=\"checkbox\" id=\"checkboxN\" class=\"must-be-checked\" />\n</div>\n\n...\n</html>\n <script type=\"text/javascript\">\n\n // This will show an alert if any checkboxes with the class 'must-be-checked'\n // are not checked.\n // Checkboxes with any other class (or no class) are ignored\n if ($('#grid .must-be-checked:not(:checked)').length > 0) {\n alert('some checkboxes not checked!');\n }\n\n</script>\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
119,819
<p>I need to cleanup the HTML of pasted text into TinyMCE by passing it to a webservice and then getting it back into the textarea. So I need to override the Ctrl+V in TinyMCE to caputre the text, do a background request, and on return continue with whatever the paste handler was for TinyMCE. First off, where is TinyMCE's Ctrl+V handler, and is there a non-destructive way to override it? (instead of changing the source code)</p>
[ { "answer_id": 119901, "author": "Aleksi Yrttiaho", "author_id": 11427, "author_profile": "https://Stackoverflow.com/users/11427", "pm_score": 2, "selected": false, "text": " handleEvent : function(e) {\n // Force paste dialog if non IE browser\n if (!tinyMCE.isRealIE && tinyMCE.getParam(\"paste_auto_cleanup_on_paste\", false) && e.ctrlKey && e.keyCode == 86 && e.type == \"keydown\") {\n window.setTimeout('tinyMCE.selectedInstance.execCommand(\"mcePasteText\",true)', 1);\n return tinyMCE.cancelEvent(e);\n }\n\n return true;\n },\n" }, { "answer_id": 53214903, "author": "Wolfgang Blessen", "author_id": 2239334, "author_profile": "https://Stackoverflow.com/users/2239334", "pm_score": 0, "selected": false, "text": "/**\n * This option enables you to modify the pasted content BEFORE it gets\n * inserted into the editor.\n */\npaste_preprocess : function(plugin, args)\n{\n //Replace empty styles\n args.content = args.content.replace(/<style><\\/style>/gi, \"\");\n}\n /**\n * This option enables you to modify the pasted content before it gets inserted\n * into the editor ,but after it's been parsed into a DOM structure.\n *\n * @param plugin\n * @param args\n */\npaste_postprocess : function(plugin, args) {\n var paste_content= args.node.innerHTML;\n console.log('Node:');\n console.log(args.node);\n\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,826
<p>I would like to use javascript to develop general-purpose GUI applications. Initially these are to run on Windows, but I would like them to ultimately be cross-platform. </p> <p>Is there a way to do this without having to make the application run in a browser? </p>
[ { "answer_id": 64519154, "author": "Foad S. Farimani", "author_id": 4999991, "author_profile": "https://Stackoverflow.com/users/4999991", "pm_score": 0, "selected": false, "text": ".hta .wsf cscript.exe wscript.exe mshta.exe SUB" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
119,857
<p>I am reading image files in Java using</p> <pre><code>java.awt.Image img = Toolkit.getDefaultToolkit().createImage(filePath); </code></pre> <p>On some systems this doesn't work, it instead throws an AWTError complaining about sun/awt/motif/MToolkit.</p> <p>How else can you create a java.awt.Image object from an image file?</p>
[ { "answer_id": 119864, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 4, "selected": true, "text": "Image i = ImageIO.read(InputStream in);\n" }, { "answer_id": 119906, "author": "Mario Ortegón", "author_id": 2309, "author_profile": "https://Stackoverflow.com/users/2309", "pm_score": 2, "selected": false, "text": "BufferedImage read(ImageInputStream stream) \nBufferedImage read(File input)\nBufferedImage read(InputStream input)\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
119,860
<p>Using Visual Studio 2008 Team Edition, is it possible to assign a shortcut key that switches between markup and code? If not, is it possible to assign a shortcut key that goes from code to markup?</p>
[ { "answer_id": 119883, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 3, "selected": true, "text": "Sub SwitchToMarkup()\n Dim FileName\n\n If (DTE.ActiveWindow.Caption().EndsWith(\".cs\")) Then\n ' swith from .aspx.cs to .aspx\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".cs\", \"\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n ElseIf (DTE.ActiveWindow.Caption().EndsWith(\".aspx\")) Then\n ' swith from .aspx to .aspx.cs\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".aspx\", \".aspx.cs\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n ElseIf (DTE.ActiveWindow.Caption().EndsWith(\".ascx\")) Then\n FileName = DTE.ActiveWindow.Document.FullName.Replace(\".ascx\", \".ascx.cs\")\n If System.IO.File.Exists(FileName) Then\n DTE.ItemOperations.OpenFile(FileName)\n End If\n End If\nEnd Sub\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
119,869
<p>Can someone give me some working examples of how you can create, add messages, read from, and destroy a private message queue from C++ APIs? I tried the MSDN pieces of code but i can't make them work properly.</p> <p>Thanks</p>
[ { "answer_id": 120457, "author": "Nevermind", "author_id": 12366, "author_profile": "https://Stackoverflow.com/users/12366", "pm_score": -1, "selected": false, "text": "MSG msg;\nBOOL bRet; \nwhile( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)\n{ \n if (bRet == -1)\n {\n // handle the error and possibly exit\n }\n else\n {\n TranslateMessage(&msg); \n DispatchMessage(&msg); \n }\n} \n" }, { "answer_id": 120510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include \"windows.h\"\n#include \"mq.h\"\n#include \"tchar.h\"\n\n\nHRESULT CreateMSMQQueue(\n LPWSTR wszPathName, \n PSECURITY_DESCRIPTOR pSecurityDescriptor,\n LPWSTR wszOutFormatName,\n DWORD *pdwOutFormatNameLength\n )\n{\n\n // Define the maximum number of queue properties.\n const int NUMBEROFPROPERTIES = 2;\n\n\n // Define a queue property structure and the structures needed to initialize it.\n MQQUEUEPROPS QueueProps;\n MQPROPVARIANT aQueuePropVar[NUMBEROFPROPERTIES];\n QUEUEPROPID aQueuePropId[NUMBEROFPROPERTIES];\n HRESULT aQueueStatus[NUMBEROFPROPERTIES];\n HRESULT hr = MQ_OK;\n\n\n // Validate the input parameters.\n if (wszPathName == NULL || wszOutFormatName == NULL || pdwOutFormatNameLength == NULL)\n {\n return MQ_ERROR_INVALID_PARAMETER;\n }\n\n\n\n DWORD cPropId = 0;\n aQueuePropId[cPropId] = PROPID_Q_PATHNAME;\n aQueuePropVar[cPropId].vt = VT_LPWSTR;\n aQueuePropVar[cPropId].pwszVal = wszPathName;\n cPropId++;\n\n WCHAR wszLabel[MQ_MAX_Q_LABEL_LEN] = L\"Test Queue\";\n aQueuePropId[cPropId] = PROPID_Q_LABEL;\n aQueuePropVar[cPropId].vt = VT_LPWSTR;\n aQueuePropVar[cPropId].pwszVal = wszLabel;\n cPropId++;\n\n\n\n QueueProps.cProp = cPropId; // Number of properties\n QueueProps.aPropID = aQueuePropId; // IDs of the queue properties\n QueueProps.aPropVar = aQueuePropVar; // Values of the queue properties\n QueueProps.aStatus = aQueueStatus; // Pointer to the return status\n\n\n\n WCHAR wszFormatNameBuffer[256];\n DWORD dwFormatNameBufferLength = sizeof(wszFormatNameBuffer)/sizeof(wszFormatNameBuffer[0]);\n hr = MQCreateQueue(pSecurityDescriptor, // Security descriptor\n &QueueProps, // Address of queue property structure\n wszFormatNameBuffer, // Pointer to format name buffer\n &dwFormatNameBufferLength); // Pointer to receive the queue's format name length\n\n\n\n if (hr == MQ_OK || hr == MQ_INFORMATION_PROPERTY)\n {\n if (*pdwOutFormatNameLength >= dwFormatNameBufferLength)\n {\n wcsncpy_s(wszOutFormatName, *pdwOutFormatNameLength - 1, wszFormatNameBuffer, _TRUNCATE);\n\n wszOutFormatName[*pdwOutFormatNameLength - 1] = L'\\0';\n *pdwOutFormatNameLength = dwFormatNameBufferLength;\n }\n else\n {\n wprintf(L\"The queue was created, but its format name cannot be returned.\\n\");\n }\n }\n return hr;\n}\n" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
119,896
<p>I am writing a query in SQL server2005. This is returning me a duplicate rows in the result. Can i eliminate this duplication with a particular column as the key?</p>
[ { "answer_id": 119921, "author": "Chris Latta", "author_id": 20977, "author_profile": "https://Stackoverflow.com/users/20977", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT MyColumn FROM MyTable;\n SELECT MyFirstColumn, MySecondColumn, MAX(SomeDate) AS MaxDate, SUM(Amount) AS TotalAmount \nFROM MyTable \nGROUP BY MyFirstColumn, MySecondColumn;\n" }, { "answer_id": 120730, "author": "Pontus Gagge", "author_id": 20402, "author_profile": "https://Stackoverflow.com/users/20402", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT SELECT DISTINCT SELECT DISTINCT" } ]
2008/09/23
[ "https://Stackoverflow.com/questions/119896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]