qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
67,835
<p>Using VBA, how can I:</p> <ol> <li>test whether a file exists, and if so,</li> <li>delete it?</li> </ol>
[ { "answer_id": 67853, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 3, "selected": false, "text": "Dir Kill test = Dir(Filename)\nIf Not test = \"\" Then\n Kill (Filename)\nEnd If\n" }, { "answer_id": 67858, "author": "Rich Adams", "author_id": 10018, "author_profile": "https://Stackoverflow.com/users/10018", "pm_score": 4, "selected": false, "text": "Dim aFile As String\naFile = \"c:\\file_to_delete.txt\"\nIf Len(Dir$(aFile)) > 0 Then\n Kill aFile\nEnd If \n" }, { "answer_id": 67860, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 9, "selected": true, "text": "Function FileExists(ByVal FileToTest As String) As Boolean\n FileExists = (Dir(FileToTest) <> \"\")\nEnd Function\n Sub DeleteFile(ByVal FileToDelete As String)\n If FileExists(FileToDelete) Then 'See above \n ' First remove readonly attribute, if set\n SetAttr FileToDelete, vbNormal \n ' Then delete the file\n Kill FileToDelete\n End If\nEnd Sub\n" }, { "answer_id": 67956, "author": "JohnFx", "author_id": 30018, "author_profile": "https://Stackoverflow.com/users/30018", "pm_score": 4, "selected": false, "text": "On Error Resume Next\naFile = \"c:\\file_to_delete.txt\"\nKill aFile\nOn Error Goto 0\nreturn Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.\n" }, { "answer_id": 67994, "author": "Brettski", "author_id": 5836, "author_profile": "https://Stackoverflow.com/users/5836", "pm_score": 3, "selected": false, "text": "Dim fso as New FileSystemObject, aFile as File\n\nif (fso.FileExists(\"PathToFile\")) then\n aFile = fso.GetFile(\"PathToFile\")\n aFile.Delete\nEnd if\n" }, { "answer_id": 71236, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 6, "selected": false, "text": "With New FileSystemObject\n If .FileExists(yourFilePath) Then\n .DeleteFile yourFilepath\n End If\nEnd With\n" }, { "answer_id": 69582730, "author": "Claudio", "author_id": 9457690, "author_profile": "https://Stackoverflow.com/users/9457690", "pm_score": 0, "selected": false, "text": "Sub DeleteFile(ByVal FileToDelete As String)\n If (Dir(FileToDelete) <> \"\") Then\n ' First remove readonly attribute, if set\n SetAttr FileToDelete, vbNormal\n ' Then delete the file\n Kill FileToDelete\n End If\nEnd Sub\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
67,859
<p>I am trying to create a query string of variable assignments separated by the <code>&amp;</code> symbol (ex: <code>"var1=x&amp;var2=y&amp;..."</code>). I plan to pass this string into an embedded flash file.</p> <p>I am having trouble getting an <code>&amp;</code> symbol to show up in XSLT. If I just type <code>&amp;</code> with no tags around it, there is a problem rendering the XSLT document. If I type <code>&amp;amp;</code> with no tags around it, then the output of the document is <code>&amp;amp;</code> with no change. If I type <code>&lt;xsl:value-of select="&amp;" /&gt;</code> or <code>&lt;xsl:value-of select="&amp;amp;" /&gt;</code> I also get an error. Is this possible? Note: I have also tried <code>&amp;amp;amp;</code> with no success.</p>
[ { "answer_id": 67876, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 3, "selected": false, "text": "disable-output-escaping=\"yes\" value-of" }, { "answer_id": 67892, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 0, "selected": false, "text": "disable-output-escaping <xsl:value-of/> <xsl:text>" }, { "answer_id": 67931, "author": "user4010", "author_id": 4010, "author_profile": "https://Stackoverflow.com/users/4010", "pm_score": 3, "selected": false, "text": "<tag attr=\"http://foo.bar/?key=value&amp;key2=value2&amp;...\"/> &amp; &amp; &" }, { "answer_id": 71297, "author": "ashirley", "author_id": 6950, "author_profile": "https://Stackoverflow.com/users/6950", "pm_score": 2, "selected": false, "text": "&amp; & text xsl:stylesheet <xsl:output method=\"text\"/>\n <xsl:value-of select=\"'&amp;'\" /> &" }, { "answer_id": 86934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<xsl:value-of select=\"/node/here\" disable-output-escaping=\"yes\" />\n <xsl:value-of select=\"'&amp;'\" disable-output-escaping=\"yes\" />\n<xsl:text disable-output-escaping=\"yes\">Texas A&amp;M</xsl:text>\n <xsl:value-of select=\"/node/here/@ttribute\" disable-output-escaping=\"yes\" />\n <xsl:value-of /> <xsl:text />" }, { "answer_id": 142408, "author": "Kevin Hakanson", "author_id": 22514, "author_profile": "https://Stackoverflow.com/users/22514", "pm_score": 4, "selected": false, "text": "disable-output-escaping CDATA <xsl:text disable-output-escaping=\"yes\"><![CDATA[&]]></xsl:text>\n" }, { "answer_id": 180943, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<xsl:output> disable-output-escaping='yes' <xsl:value-of>" }, { "answer_id": 24011840, "author": "Taran", "author_id": 1504072, "author_profile": "https://Stackoverflow.com/users/1504072", "pm_score": 1, "selected": false, "text": " <xsl:variable name=\"replaced\">\n\n <xsl:call-template name='app'>\n <xsl:with-param name='name'/> \n </xsl:call-template>\n </xsl:variable>\n\n\n<xsl:value-of select=\"$replaced\" disable-output-escaping=\"yes\"/>\n" }, { "answer_id": 33093620, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 4, "selected": false, "text": "& \"var1=x&var2=y&...\" & <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:variable name=\"vX\" select=\"'x'\"/>\n <xsl:variable name=\"vY\" select=\"'y'\"/>\n <xsl:variable name=\"vZ\" select=\"'z'\"/>\n\n <xsl:template match=\"/\">\n <xsl:value-of select=\n\"concat('http://www.myUrl.com/?vA=a&amp;vX=', $vX, '&amp;vY=', $vY, '&amp;vZ=', $vZ)\"/>\n </xsl:template>\n</xsl:stylesheet>\n <t/>\n http://www.myUrl.com/?vA=a&vX=x&vY=y&vZ=z\n &amp; &amp; html xml method= http://www.myUrl.com/?vA=a&vX=x&vY=y&vZ=z &amp; &#38; &#x26; xsl:output <xsl:output method=\"text\"/>\n <xsl:output method=\"xml\"/>\n <xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output omit-xml-declaration=\"yes\" method=\"xml\"/>\n\n <xsl:variable name=\"vX\" select=\"'x'\"/>\n <xsl:variable name=\"vY\" select=\"'y'\"/>\n <xsl:variable name=\"vZ\" select=\"'z'\"/>\n\n <xsl:template match=\"/\">\n <t>\n <xsl:value-of select=\n \"concat('http://www.myUrl.com/?vA=a&amp;vX=', $vX, '&#38;vY=', $vY, '&#x26;vZ=', $vZ)\"/>\n </t>\n </xsl:template>\n</xsl:stylesheet>\n <t>http://www.myUrl.com/?vA=a&amp;vX=x&amp;vY=y&amp;vZ=z</t>\n html disable-output-escaping=\"yes\" disable-output-escaping=\"yes\" <input type=\"submit\" \nonClick=\"return confirm('are you sure?') && confirm('seriously?');\" />\n && &amp;&amp; <!DOCTYPE html> \n\n <html> \n <head> \n <link rel=\"stylesheet\" href=\"style.css\"> \n <script src=\"script.js\"></script> \n </head> \n <body> \n <h1>Hello Plunker!</h1> \n <input type=\"submit\" \nonClick=\"alert(confirm('are you sure?') &amp;&amp; confirm('seriously?'));\" /> \n </body> \n </html>\n function confirm(message) { \n alert(message); \n return message === 'are you sure?'; \n\n}\n OK OK && confirm() && <input> <input type=\"submit\" \nonClick=\"alert(confirm('really sure?') &amp;&amp; confirm('seriously?'));\" /> \n OK && && false && false && && &amp;&amp;" }, { "answer_id": 35429651, "author": "Ram", "author_id": 5934422, "author_profile": "https://Stackoverflow.com/users/5934422", "pm_score": 1, "selected": false, "text": "<![CDATA[&]]>\n <title>Empire <![CDATA[&]]> Burlesque</title>\n <xsl:value-of select=\"title\" />\n" }, { "answer_id": 54361599, "author": "Peter Dolland", "author_id": 10966296, "author_profile": "https://Stackoverflow.com/users/10966296", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>http://www.myUrl.com/?vA=a&amp;vX=x&amp;vY=y&amp;vZ=z11522\n omit-xml-declaration=\"yes\" method=\"text\"" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
67,879
<p>I have an application that runs as a child application in a virtual directory.</p> <p>I want to pass a value from the parent application, but I believe that Session is keyed per application, and won't work.</p> <p>To further complicate things, the parent application is WebForms, while the child is NVelocity MVC.</p> <p>Does anyone know a trick that allows me to use some sort of Session type functionality between virtual applications?</p> <p>EDIT: A webservice isn't really what I had in mind, all I need to do is pass the logged in users username to the child app. Besides, if calling a webservice back on the parent, I won't get the same session, so I won't know what user.</p>
[ { "answer_id": 67935, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 0, "selected": false, "text": "HttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"/ASPSession.ASP?SessionVar=\" + SessionVarName);\nreq.Headers.Add(\"Cookie: \" + SessionCookieName + \"=\" + SessionCookieValue);\n\nHttpWebResponse resp = (HttpWebResponse)req.GetResponse();\nStream receiveStream = resp.GetResponseStream();\n\nSystem.Text.Encoding encode = System.Text.Encoding.GetEncoding(\"utf-8\");\n\nStreamReader readStream = new StreamReader(receiveStream, encode);\n\nstring response = readStream.ReadToEnd();\n\nresp.Close();\nreadStream.Close();\nreturn response;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
67,890
<p>I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores.</p> <p>Any suggestions on the best way to solve this problem?</p> <p>Thanks!</p>
[ { "answer_id": 67900, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Digest::MD5.hexdigest(my_url)\n" }, { "answer_id": 68028, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 6, "selected": true, "text": "require 'digest'\nDigest.hexencode('http://foo-bar.com/yay/?foo=bar&a=22')\n# \"687474703a2f2f666f6f2d6261722e636f6d2f7961792f3f666f6f3d62617226613d3232\"\n\nrequire 'digest/md5'\nDigest::MD5.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')\n# \"43facc5eb5ce09fd41a6b55dba3fe2fe\"\n\nrequire 'digest/sha1'\nDigest::SHA1.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')\n# \"2aba83b05dc9c2d9db7e5d34e69787d0a5e28fc5\"\n\nrequire 'digest/sha2'\nDigest::SHA2.hexdigest('http://foo-bar.com/yay/?foo=bar&a=22')\n# \"e78f3d17c1c0f8d8c4f6bd91f175287516ecf78a4027d627ebcacfca822574b2\"\n salt = 'foobar'\nDigest::SHA1.hexdigest(salt + 'http://foo-bar.com/yay/?foo=bar&a=22')\n# \"dbf43aff5e808ae471aa1893c6ec992088219bbb\"\n" }, { "answer_id": 68954, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "require 'digest/md5'\ndef hash_url(url)\n Digest::MD5.hexdigest(\"#{Time.now.to_f}--#{url}\")\nend\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10461/" ]
67,894
<p>Why do we need to use:</p> <pre><code>extern "C" { #include &lt;foo.h&gt; } </code></pre> <p><strong>Specifically:</strong> </p> <ul> <li><p>When should we use it?</p></li> <li><p>What is happening at the compiler/linker level that requires us to use it? </p></li> <li><p>How in terms of compilation/linking does this solve the problems which require us to use it?</p></li> </ul>
[ { "answer_id": 67930, "author": "gnkdl_gansklgna", "author_id": 10470, "author_profile": "https://Stackoverflow.com/users/10470", "pm_score": 8, "selected": true, "text": "printf() _Zprintf extern \"C\" {...} extern extern \"C\"" }, { "answer_id": 67932, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 5, "selected": false, "text": "A::foo() B::foo() C::foo(int) C::foo(std::string)" }, { "answer_id": 67942, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 3, "selected": false, "text": "extern \"C\" {} extern \"C\"" }, { "answer_id": 67985, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 7, "selected": false, "text": "void foo() { }\n $ g++ -c test.C\n$ nm test.o\n0000000000000000 T _Z3foov\n U __gxx_personality_v0\n extern \"C\" {\n void foo() { }\n}\n $ g++ -c test.C\n$ nm test.o\n U __gxx_personality_v0\n0000000000000000 T foo\n #ifdef __cplusplus\nextern \"C\" {\n#endif\n\n... declarations ...\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "answer_id": 56136918, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 2, "selected": false, "text": "g++ extern void f() {}\nvoid g();\n\nextern \"C\" {\n void ef() {}\n void eg();\n}\n\n/* Prevent g and eg from being optimized away. */\nvoid h() { g(); eg(); }\n g++ -c main.cpp\n readelf -s main.o\n Num: Value Size Type Bind Vis Ndx Name\n 8: 0000000000000000 6 FUNC GLOBAL DEFAULT 1 _Z1fv\n 9: 0000000000000006 6 FUNC GLOBAL DEFAULT 1 ef\n 10: 000000000000000c 16 FUNC GLOBAL DEFAULT 1 _Z1hv\n 11: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z1gv\n 12: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND eg\n ef eg $ c++filt _Z1fv\nf()\n$ c++filt _Z1hv\nh()\n$ c++filt _Z1gv\ng()\n Ndx = UND extern \"C\" g++ gcc g++ gcc extern C extern \"C\" {\n // Overloading.\n // error: declaration of C function ‘void f(int)’ conflicts with\n void f();\n void f(int i);\n\n // Templates.\n // error: template with C linkage\n template <class C> void f(C i) { }\n}\n #include <cassert>\n\n#include \"c.h\"\n\nint main() {\n assert(f() == 1);\n}\n #ifndef C_H\n#define C_H\n\n/* This ifdef allows the header to be used from both C and C++. */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nint f();\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n #include \"c.h\"\n\nint f(void) { return 1; }\n g++ -c -o main.o -std=c++98 main.cpp\ngcc -c -o c.o -std=c89 c.c\ng++ -o main.out main.o c.o\n./main.out\n extern \"C\" main.cpp:6: undefined reference to `f()'\n g++ f gcc #include <assert.h>\n\n#include \"cpp.h\"\n\nint main(void) {\n assert(f_int(1) == 2);\n assert(f_float(1.0) == 3);\n return 0;\n}\n #ifndef CPP_H\n#define CPP_H\n\n#ifdef __cplusplus\n// C cannot see these overloaded prototypes, or else it would get confused.\nint f(int i);\nint f(float i);\nextern \"C\" {\n#endif\nint f_int(int i);\nint f_float(float i);\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n #include \"cpp.h\"\n\nint f(int i) {\n return i + 1;\n}\n\nint f(float i) {\n return i + 2;\n}\n\nint f_int(int i) {\n return f(i);\n}\n\nint f_float(float i) {\n return f(i);\n}\n gcc -c -o main.o -std=c89 -Wextra main.c\ng++ -c -o cpp.o -std=c++98 cpp.cpp\ng++ -o main.out main.o cpp.o\n./main.out\n extern \"C\" main.c:6: undefined reference to `f_int'\nmain.c:7: undefined reference to `f_float'\n g++ gcc" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
67,916
<p>I have something that is driving me absolutely crazy...</p> <pre><code> Public Function GetAccountGroups() As IList(Of AccountGroup) Dim raw_account_groups As IList(Of AccountGroup) raw_account_groups = _repository.GetAccountGroups().ToList() Dim parents = (From ag In raw_account_groups _ Where ag.parent_id = 0 _ Select ag).ToList() parents(0).sub_account_groups = (From sag In raw_account_groups _ Where sag.parent_id = 0 _ Select sag).ToList() Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _ (From sag In raw_account_groups _ Where sag.parent_id = p.id _ Select sag).ToList() parents.ForEach(Function(p) p.sub_account_groups = sql_func(p)) Return parents End Function </code></pre> <p>The line <code>parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))</code> has this error...</p> <blockquote> <p>Operator '=' is not defined for types 'System.Collections.Generic.IList(Of st.data.AccountGroup)' and 'System.Collections.Generic.List(Of st.data.AccountGroup)'. </p> </blockquote> <p>but I really can't see how it is any different from this code from Rob Connery</p> <pre><code>public IList&lt;Category&gt; GetCategories() { IList&lt;Category&gt; rawCategories = _repository.GetCategories().ToList(); var parents = (from c in rawCategories where c.ParentID == 0 select c).ToList(); parents.ForEach(p =&gt; { p.SubCategories = (from subs in rawCategories where subs.ParentID == p.ID select subs).ToList(); }); return parents; } </code></pre> <p>which compiles perfectly... what am I doing incorrectly?</p>
[ { "answer_id": 68795, "author": "Jeff Moser", "author_id": 1869, "author_profile": "https://Stackoverflow.com/users/1869", "pm_score": 0, "selected": false, "text": "Module Module1\n Sub Main()\n End Sub\nEnd Module\n\nClass AccountGroup\n Public parent_id As Integer\n Public id As Integer\n Public sub_account_groups As List(Of AccountGroup)\nEnd Class\nClass AccountRepository\n Private _repository As AccountRepository\n\n Public Function GetAccountGroups() As IList(Of AccountGroup)\n Dim raw_account_groups As IList(Of AccountGroup)\n raw_account_groups = _repository.GetAccountGroups().ToList()\n Dim parents = (From ag In raw_account_groups _\n Where ag.parent_id = 0 _\n Select ag).ToList()\n parents(0).sub_account_groups = (From sag In raw_account_groups _\n Where sag.parent_id = 0 _\n Select sag).ToList()\n\n Dim sql_func As Func(Of AccountGroup, List(Of AccountGroup)) = Function(p) _\n (From sag In raw_account_groups _\n Where sag.parent_id = p.id _\n Select sag).ToList()\n\n\n\n parents.ForEach(Function(p) p.sub_account_groups = sql_func(p))\n Return parents\n End Function\n End Class\n" }, { "answer_id": 892437, "author": "Tore Nestenius", "author_id": 68490, "author_profile": "https://Stackoverflow.com/users/68490", "pm_score": 0, "selected": false, "text": "ag.parent_id = 0 ag.parent_id == 0" }, { "answer_id": 892842, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "For Each p In parents\n p.sub_account_groups = sql_func(p)\nNext\n parents.ForEach(Sub (p) p.sub_account_groups = sql_func(p))\n" }, { "answer_id": 2892799, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "parents.ForEach(Sub(p) p.sub_account_groups = sql_func(p))\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10479/" ]
67,937
<p>Does anyone know an easy way to import a raw, XML RSS feed into C#? Am looking for an easy way to get the XML as a string so I can parse it with a Regex.</p> <p>Thanks, -Greg</p>
[ { "answer_id": 68008, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 4, "selected": false, "text": "using System.Net \n\nWebClient wc = new WebClient();\n\nStream st = wc.OpenRead(“http://example.com/feed.rss”);\n\nusing (StreamReader sr = new StreamReader(st)) {\n string rss = sr.ReadToEnd();\n}\n" }, { "answer_id": 68038, "author": "Alan Le", "author_id": 1133, "author_profile": "https://Stackoverflow.com/users/1133", "pm_score": 2, "selected": false, "text": "XmlDocument doc = new XmlDocument();\n\nHttpWebRequest request = WebRequest.Create(feedUrl) as HttpWebRequest;\n\nusing (HttpWebResponse response = request.GetResponse() as HttpWebResponse)\n{\n StreamReader reader = new StreamReader(response.GetResponseStream());\n doc.Load(reader);\n\n <parse with XPATH>\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8855/" ]
67,959
<p>I've run into a few gotchas when doing C# XML serialization that I thought I'd share:</p> <ul> <li>You can't serialize items that are read-only (like KeyValuePairs)</li> <li>You can't serialize a generic dictionary. Instead, try this wrapper class (from <a href="http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx" rel="noreferrer">http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx</a>):</li> </ul> <hr/> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; [XmlRoot("dictionary")] public class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("item"); reader.ReadStartElement("key"); TKey key = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue value = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySerializer = new XmlSerializer(typeof(TKey)); XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue)); foreach (TKey key in this.Keys) { writer.WriteStartElement("item"); writer.WriteStartElement("key"); keySerializer.Serialize(writer, key); writer.WriteEndElement(); writer.WriteStartElement("value"); TValue value = this[key]; valueSerializer.Serialize(writer, value); writer.WriteEndElement(); writer.WriteEndElement(); } } } </code></pre> <p>Any other XML Serialization gotchas out there?</p>
[ { "answer_id": 68476, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "IEnumerables<T>" }, { "answer_id": 69072, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 2, "selected": false, "text": "System.InvalidOperationException: There was an error generating the XML document.\n---System.InvalidCastException: Unable to cast object\nof type 'MyNamespace.Settings' to type 'MyNamespace.Settings'. at\nMicrosoft.Xml.Serialization.GeneratedAssembly.\n XmlSerializationWriterSettings.Write3_Settings(Object o)\n" }, { "answer_id": 97376, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 5, "selected": false, "text": "XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.Encoding.UTF8);\n XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.UTF8Encoding(false))\n Encoding.UTF8 UTF8Encoding" }, { "answer_id": 138713, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 2, "selected": false, "text": "[XmlElement(\"item\")]\npublic myClass[] item\n{\n get { return this.privateList.ToArray(); }\n}\n [XmlElement(\"item\")]\npublic List<myClass> item\n{\n get { return this.privateList; }\n}\n" }, { "answer_id": 138846, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": false, "text": "<xs:complexType name=\"MessageType\" abstract=\"true\">\n <xs:attributeGroup ref=\"commonMessageAttributes\"/>\n</xs:complexType>\n\n<xs:element name=\"Message\" type=\"MessageType\"/>\n\n<xs:element name=\"Envelope\">\n <xs:complexType mixed=\"false\">\n <xs:complexContent mixed=\"false\">\n <xs:element ref=\"Message\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:complexContent>\n </xs:complexType>\n</xs:element>\n\n<xs:element name=\"ExampleMessageA\" substitutionGroup=\"Message\">\n <xs:complexType mixed=\"false\">\n <xs:complexContent mixed=\"false\">\n <xs:attribute name=\"messageCode\"/>\n </xs:complexContent>\n </xs:complexType>\n</xs:element>\n\n<xs:element name=\"ExampleMessageB\" substitutionGroup=\"Message\">\n <xs:complexType mixed=\"false\">\n <xs:complexContent mixed=\"false\">\n <xs:attribute name=\"messageCode\"/>\n </xs:complexContent>\n </xs:complexType>\n</xs:element>\n" }, { "answer_id": 552603, "author": "Benjol", "author_id": 11410, "author_profile": "https://Stackoverflow.com/users/11410", "pm_score": 3, "selected": false, "text": " public string FullName { get; set; }\n public double Value { get; set; }\n" }, { "answer_id": 1218763, "author": "Allon Guralnek", "author_id": 149265, "author_profile": "https://Stackoverflow.com/users/149265", "pm_score": 3, "selected": false, "text": "public class ValuePair\n{\n public ICompareable Value1 { get; set; }\n public ICompareable Value2 { get; set; }\n}\n public class ValuePair\n{\n public object Value1 { get; set; }\n public object Value2 { get; set; }\n}\n" }, { "answer_id": 7236099, "author": "James Hulse", "author_id": 400193, "author_profile": "https://Stackoverflow.com/users/400193", "pm_score": 2, "selected": false, "text": "Obsolete Deprecated" }, { "answer_id": 9760461, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 2, "selected": false, "text": "List<T> IEnumerable<T> T System.InvalidOperationException public class Group\n{ \n /* The XmlArrayItemAttribute allows the XmlSerializer to insert both the base \n type (Employee) and derived type (Manager) into serialized arrays. */\n\n [XmlArrayItem(typeof(Manager)), XmlArrayItem(typeof(Employee))]\n public Employee[] Employees;\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
67,980
<p>I need to pass a UUID instance via http request parameter. Spring needs a custom type converter (from String) to be registered. How do I register one?</p>
[ { "answer_id": 69314, "author": "alexei.vidmich", "author_id": 7199, "author_profile": "https://Stackoverflow.com/users/7199", "pm_score": 2, "selected": false, "text": "@InitBinder\npublic void initBinder(WebDataBinder binder) {\n binder.registerCustomEditor(UUID.class, new UUIDEditor());\n}\n" }, { "answer_id": 1555102, "author": "David Newcomb", "author_id": 52070, "author_profile": "https://Stackoverflow.com/users/52070", "pm_score": 2, "selected": false, "text": "@Controller\n@RequestMapping(\"/showuuid.html\")\npublic class ShowUUIDController\n{\n\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n binder.registerCustomEditor(UUID.class, new UUIDEditor());\n }\n\n public String showuuidHandler (@RequestParam(\"id\") UUID id, Model model)\n {\n model.addAttribute (\"id\", id) ;\n return \"showuuid\" ;\n }\n}\n class UUIDEditor extends java.beans.PropertyEditorSupport\n{\n\n @Override\n public String getAsText ()\n {\n UUID u = (UUID) getValue () ;\n return u.toString () ;\n }\n\n @Override\n public void setAsText (String s)\n {\n setValue (UUID.fromString (s)) ;\n }\n\n}\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/67980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7199/" ]
68,012
<p>I am relatively new to JavaScript and am trying to understand how to use it correctly.</p> <p>If I wrap JavaScript code in an anonymous function to avoid making variables <code>public</code> the functions within the JavaScript are not available from within the html that includes the JavaScript. </p> <p>On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using <code>httprequest</code> to get that from a PHP file and passes the returned data to a callback function that in <em>onsuccess</em> processes the data, if I could call the function that does the <code>httprequest</code> from within the html in a </p> <pre><code>&lt;script type="text/javascript" &gt;&lt;/script&gt; </code></pre> <p>block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.</p>
[ { "answer_id": 68046, "author": "HFLW", "author_id": 252822, "author_profile": "https://Stackoverflow.com/users/252822", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\n(function() {\n var private = \"private var\";\n window.onload = function() {\n console.log(private);\n }\n})();\n</script>\n" }, { "answer_id": 68056, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<div id=\"special\">Hello World!</div>\n<script>\n (function(){\n var foo = document.getElementById('special');\n foo.mySpecialMethod = function(otherID, newData){\n var bar = document.getElementById(otherID);\n bar.innerHTML = newData;\n };\n //do some ajax... set callback to call \"special\" method above...\n doAJAX(url, 'get', foo.mySpecialMethod);\n })();\n</script>\n" }, { "answer_id": 68083, "author": "Anutron", "author_id": 10071, "author_profile": "https://Stackoverflow.com/users/10071", "pm_score": 2, "selected": false, "text": "window.onload = function(){...};\n window.addEvent('domready', function(){...});\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,018
<p>If I have a Resource bundle property file:</p> <p>A.properties:</p> <pre><code>thekey={0} This is a test </code></pre> <p>And then I have java code that loads the resource bundle:</p> <pre><code>ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale); labels.getString("thekey"); </code></pre> <p>How can I replace the {0} text with some value</p> <pre><code>labels.getString("thekey", "Yes!!!"); </code></pre> <p>Such that the output comes out as:</p> <pre><code>Yes!!! This is a test. </code></pre> <p>There are no methods that are part of Resource Bundle to do this. Also, I am in Struts, is there some way to use MessageProperties to do the replacement.</p>
[ { "answer_id": 68075, "author": "user10544", "author_id": 10544, "author_profile": "https://Stackoverflow.com/users/10544", "pm_score": 5, "selected": true, "text": "MessageFormat.format(\"{0} This {1} a test\", new Object[] {\"Yes!!!\", \"is\"});\n MessageFormat.format(\"{0} This {1} a test\", \"Yes!!!\", \"is\");\n \"Yes!!! This is a test\"\n" }, { "answer_id": 68163, "author": "Lukáš Rampa", "author_id": 10560, "author_profile": "https://Stackoverflow.com/users/10560", "pm_score": 2, "selected": false, "text": "messageResources.getMessage(\"thekey\", \"Yes!!!\");\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
68,029
<p>Got this from some mysql queries, puzzled since error 122 is usually a 'out of space' error but there's plenty of space left on the server... any ideas?</p>
[ { "answer_id": 28057763, "author": "Archil", "author_id": 4476218, "author_profile": "https://Stackoverflow.com/users/4476218", "pm_score": 2, "selected": false, "text": "quotaoff -a\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,042
<p>Let's say that on the C++ side my function takes a variable of type <code>jstring</code> named <code>myString</code>. I can convert it to an ANSI string as follows:</p> <pre><code>const char* ansiString = env-&gt;GetStringUTFChars(myString, 0); </code></pre> <p>is there a way of getting</p> <p><code>const wchar_t* unicodeString =</code> ...</p>
[ { "answer_id": 68065, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "wchar_t" }, { "answer_id": 1666532, "author": "Benj", "author_id": 193128, "author_profile": "https://Stackoverflow.com/users/193128", "pm_score": 2, "selected": false, "text": "wchar_t * JavaToWSZ(JNIEnv* env, jstring string)\n{\n if (string == NULL)\n return NULL;\n int len = env->GetStringLength(string);\n const jchar* raw = env->GetStringChars(string, NULL);\n if (raw == NULL)\n return NULL;\n\n wchar_t* wsz = new wchar_t[len+1];\n memcpy(wsz, raw, len*2);\n wsz[len] = 0;\n\n env->ReleaseStringChars(string, raw);\n\n return wsz;\n}\n" }, { "answer_id": 2295676, "author": "Andreas Rieder", "author_id": 276886, "author_profile": "https://Stackoverflow.com/users/276886", "pm_score": 2, "selected": false, "text": "std::wstring JavaToWSZ(JNIEnv* env, jstring string)\n{\n std::wstring value;\n if (string == NULL) {\n return value; // empty string\n }\n const jchar* raw = env->GetStringChars(string, NULL);\n if (raw != NULL) {\n jsize len = env->GetStringLength(string);\n value.assign(raw, len);\n env->ReleaseStringChars(string, raw);\n }\n return value;\n}\n" }, { "answer_id": 4154448, "author": "Vladimir Ivanov", "author_id": 473070, "author_profile": "https://Stackoverflow.com/users/473070", "pm_score": 0, "selected": false, "text": "JNIEXPORT jboolean JNICALL Java_TestClass_test(JNIEnv * env, jobject, jstring string)\n{\n const wchar_t * utf16 = (wchar_t *)env->GetStringChars(string, NULL);\n ...\n env->ReleaseStringChars(string, utf16);\n}\n" }, { "answer_id": 9100041, "author": "gergonzalez", "author_id": 973036, "author_profile": "https://Stackoverflow.com/users/973036", "pm_score": 4, "selected": false, "text": "std::wstring Java_To_WStr(JNIEnv *env, jstring string)\n{\n std::wstring value;\n\n const jchar *raw = env->GetStringChars(string, 0);\n jsize len = env->GetStringLength(string);\n const jchar *temp = raw;\n while (len > 0)\n {\n value += *(temp++);\n len--;\n }\n env->ReleaseStringChars(string, raw);\n\n return value;\n}\n std::wstring Java_To_WStr(JNIEnv *env, jstring string)\n{\n std::wstring value;\n\n const jchar *raw = env->GetStringChars(string, 0);\n jsize len = env->GetStringLength(string);\n\n value.assign(raw, raw + len);\n\n env->ReleaseStringChars(string, raw);\n\n return value;\n}\n" }, { "answer_id": 53702206, "author": "shizhen wang", "author_id": 10769816, "author_profile": "https://Stackoverflow.com/users/10769816", "pm_score": 0, "selected": false, "text": "char* js2c(JNIEnv* env, jstring jstr)\n{\n char* rtn = NULL;\n jclass clsstring = env->FindClass(\"java/lang/String\");\n jstring strencode = env->NewStringUTF(\"utf-8\");\n jmethodID mid = env->GetMethodID(clsstring, \"getBytes\", \"(Ljava/lang/String;)[B\");\n jbyteArray barr = (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);\n jsize alen = env->GetArrayLength(barr);\n jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);\n if (alen > 0)\n {\n rtn = (char*)malloc(alen + 1);\n memcpy(rtn, ba, alen);\n rtn[alen] = 0;\n }\n env->ReleaseByteArrayElements(barr, ba, 0);\n return rtn;\n}\n\njstring c2js(JNIEnv* env, const char* str) {\n jstring rtn = 0;\n int slen = strlen(str);\n unsigned short * buffer = 0;\n if (slen == 0)\n rtn = (env)->NewStringUTF(str);\n else {\n int length = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str, slen, NULL, 0);\n buffer = (unsigned short *)malloc(length * 2 + 1);\n if (MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length) > 0)\n rtn = (env)->NewString((jchar*)buffer, length);\n free(buffer);\n }\n return rtn;\n}\n\n\n\njstring w2js(JNIEnv *env, wchar_t *src)\n{\n size_t len = wcslen(src) + 1;\n size_t converted = 0;\n char *dest;\n dest = (char*)malloc(len * sizeof(char));\n wcstombs_s(&converted, dest, len, src, _TRUNCATE);\n\n jstring dst = c2js(env, dest);\n return dst;\n}\n\nwchar_t *js2w(JNIEnv *env, jstring src) {\n\n char *dest = js2c(env, src);\n size_t len = strlen(dest) + 1;\n size_t converted = 0;\n wchar_t *dst;\n dst = (wchar_t*)malloc(len * sizeof(wchar_t));\n mbstowcs_s(&converted, dst, len, dest, _TRUNCATE);\n return dst;\n}\n" }, { "answer_id": 57033639, "author": "Eng.Fouad", "author_id": 597657, "author_profile": "https://Stackoverflow.com/users/597657", "pm_score": 0, "selected": false, "text": "jstring LPWSTR const char* nativeString = env->GetStringUTFChars(javaString, 0);\nsize_t size = strlen(nativeString) + 1;\nLPWSTR lpwstr = new wchar_t[size];\nsize_t outSize;\nmbstowcs_s(&outSize, lpwstr, size, nativeString, size - 1);\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,067
<p>I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file:</p> <p><code>external_link_list_url : "example_link_list.js"</code></p> <p>this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed.</p> <p>Thanks!</p>
[ { "answer_id": 68132, "author": "JustAsItSounds", "author_id": 10586, "author_profile": "https://Stackoverflow.com/users/10586", "pm_score": 2, "selected": false, "text": "context.Response.ContentType = \"text/javascript\";\n" }, { "answer_id": 68831, "author": "JustAsItSounds", "author_id": 10586, "author_profile": "https://Stackoverflow.com/users/10586", "pm_score": 1, "selected": false, "text": "<system.web>\n <httpHandlers>\n <add verb=\"*\" path=\"example_link_list.axd\" type= \"MyProject.MyTinyMCE, MyAssembly\" />\n </httpHandlers>\n</system.web>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/68067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7173/" ]
68,103
<p>I have a XULRunner application that needs to copy image data to the clipboard. I have figured out how to handle copying text to the clipboard, and I can paste PNG data from the clipboard. What I can't figure out is how to get data from a data URL into the clipboard so that it can be pasted into other applications.</p> <p>This is the code I use to copy text (well, XUL):</p> <pre><code>var transferObject=Components.classes["@mozilla.org/widget/transferable;1"]. createInstance(Components.interfaces.nsITransferable); var stringWrapper=Components.classes["@mozilla.org/supports-string;1"]. createInstance(Components.interfaces.nsISupportsString); var systemClipboard=Components.classes["@mozilla.org/widget/clipboard;1"]. createInstance(Components.interfaces.nsIClipboard); var objToSerialize=aDOMNode; transferObject.addDataFlavor("text/xul"); var xmls=new XMLSerializer(); var serializedObj=xmls.serializeToString(objToSerialize); stringWrapper.data=serializedObj; transferObject.setTransferData("text/xul",stringWrapper,serializedObj.length*2); </code></pre> <p>And, as I said, the data I'm trying to transfer is a PNG as a data URL. So I'm looking for the equivalent to the above that will allow, e.g. Paint.NET to paste my app's data.</p>
[ { "answer_id": 130880, "author": "Joel Anair", "author_id": 7441, "author_profile": "https://Stackoverflow.com/users/7441", "pm_score": 3, "selected": true, "text": "dataURL var newImg=document.createElement('img');\nnewImg.src=dataURL;\n\ndocument.popupNode=newImg;\n\nvar command='cmd_copyImageContents'\n\nvar controller=document.commandDispatcher.getControllerForCommand(command);\n\nif(controller && controller.isCommandEnabled(command)){\n controller.doCommand(command);\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7441/" ]
68,109
<p>My professor did an informal benchmark on a little program and the Java times were: 1.7 seconds for the first run, and 0.8 seconds for the runs thereafter. </p> <ul> <li><p>Is this due entirely to the loading of the runtime environment into the operating environment ?</p> <p>OR </p></li> <li><p>Is it influenced by Java's optimizing the code and storing the results of those optimizations (sorry, I don't know the technical term for that)?</p></li> </ul>
[ { "answer_id": 68602, "author": "big_peanut_horse", "author_id": 10720, "author_profile": "https://Stackoverflow.com/users/10720", "pm_score": 2, "selected": false, "text": "java.lang.String.equals(...)" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577/" ]
68,113
<p>I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.</p>
[ { "answer_id": 10756495, "author": "11101101b", "author_id": 875305, "author_profile": "https://Stackoverflow.com/users/875305", "pm_score": 6, "selected": false, "text": "MyServiceName.exe MyServiceNamew.exe RCEDIT.exe > RCEDIT.exe /I MyServiceName.exe customIcon.ico\n> RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico\n > MyServiceName.exe //IS//MyServiceName \\\n --Install=\"C:\\path-to\\MyServiceName.exe\" \\\n --Jvm=auto --Startup=auto --StartMode=jvm \\\n --Classpath=\"C:\\path-to\\MyJarWithClassWithMainMethod.jar\" \\\n --StartClass=com.mydomain.MyClassWithMainMethod\n > MyServiceNamew.exe //MS//MyServiceName\n" }, { "answer_id": 42204087, "author": "Ravi Parekh", "author_id": 410439, "author_profile": "https://Stackoverflow.com/users/410439", "pm_score": 2, "selected": false, "text": "C:\\users\\All Users\\Start Menu\\Programs\\Startup User home directory(%userProfile%) shell:startup java.exe -jar D:\\..\\runJar.jar sc create serviceName binpath= \"java.exe -jar D:\\..\\runJar.jar\" cmd /c D:\\JAVA7~1\\jdk1.7.0_51\\bin\\java.exe -jar d:\\jenkins\\jenkins.war Startup Type" }, { "answer_id": 45443208, "author": "Alexey Lisyutenko", "author_id": 8400888, "author_profile": "https://Stackoverflow.com/users/8400888", "pm_score": 3, "selected": false, "text": "public class MyService {\n\n public static void main(String[] args) {\n String command = \"start\";\n if (args.length > 0) {\n command = args[0];\n }\n if (\"start\".equals(command)) {\n // process service start function\n } else {\n // process service stop function\n }\n }\n\n}\n build.gradle buildscript {\n repositories {\n maven {\n url \"https://plugins.gradle.org/m2/\"\n }\n }\n dependencies {\n classpath \"gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0\"\n }\n}\n\napply plugin: \"com.github.alexeylisyutenko.windows-service-plugin\"\n plugins {\n id \"com.github.alexeylisyutenko.windows-service-plugin\" version \"1.1.0\"\n}\n windowsService {\n architecture = 'amd64'\n displayName = 'TestService'\n description = 'Service generated with using gradle plugin' \n startClass = 'MyService'\n startMethod = 'main'\n startParams = 'start'\n stopClass = 'MyService'\n stopMethod = 'main'\n stopParams = 'stop'\n startup = 'auto'\n}\n ${project.buildDir}/windows-service <project-name>-install.bat <project-name>-uninstall.bat <project-name>w.exe" }, { "answer_id": 45851799, "author": "Steephen", "author_id": 1144157, "author_profile": "https://Stackoverflow.com/users/1144157", "pm_score": 2, "selected": false, "text": "-native type\nGenerate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.\n\nThe following values are valid for type:\n\nall: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.\ninstaller: Runs all of the installers for the platform on which it is running.\nimage: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.\ndmg: Generates a DMG file for OS X.\npkg: Generates a .pkg package for OS X.\nmac.appStore: Generates a package for the Mac App Store.\nrpm: Generates an RPM package for Linux.\ndeb: Generates a Debian package for Linux.\n exe: Generates a Windows .exe package.\nmsi: Generates a Windows Installer package.\n" }, { "answer_id": 72658268, "author": "DuncG", "author_id": 4712734, "author_profile": "https://Stackoverflow.com/users/4712734", "pm_score": 0, "selected": false, "text": "Advapi.DLL main()\n Must register ServiceMain using StartServiceCtrlDispatcherW\n Above call blocks until ServiceMain exits\n \nvoid ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)\n Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW\n Use SetServiceStatus(SERVICE_START_PENDING)\n Initialise app\n Use SetServiceStatus(SERVICE_RUNNING)\n wait for app shutdown notification\n Use SetServiceStatus(SERVICE_STOPPED)\n\nint SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)\n Must respond to service control events and report back using SetServiceStatus\n On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)\n then set app shutdown notification\n sc create YourJavaServiceName type= own binpath= \"c:\\Program Files\\Your Release Dir\\yourjavaservice.exe\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10273/" ]
68,120
<p>I'm not overly familiar with Tomcat, but my team has inherited a complex project that revolves around a Java Servlet being hosted in Tomcat across many servers. Custom configuration management software is used to write out the server.xml, and various resources (connection pools, beans, server variables, etc) written into server.xml configure the servlet. This is all well and good.</p> <p>However, the names of some of the resources aren't known in advance. For example, the Servlet may need access to any number of "Anonymizers" as configured by the operator. Each anonymizer has a unique name associated with it. We create and configure each anonymizer using java beans similar to the following:</p> <pre><code>&lt;Resource name="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="50" /&gt; &lt;Resource name="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean" factory="org.apache.naming.factory.BeanFactory" className="teAnonymizer" databaseId="54" /&gt; </code></pre> <p>However, this appears to require us to have explicit entries in the Servlet's context.xml file for each an every possible resource name in advance. I'd like to replace the explicit context.xml entries with wildcards, or know if there is a better solution to this type of problem.</p> <p>Currently:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_default" global="bean/Anonymizer_default" type="com.company.tomcatutil.AnonymizerBean"/&gt; &lt;ResourceLink name="bean/Anonymizer_toon" global="bean/Anonymizer_toon" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>Replaced with something like:</p> <pre><code> &lt;ResourceLink name="bean/Anonymizer_*" global="bean/Anonymizer_*" type="com.company.tomcatutil.AnonymizerBean"/&gt; </code></pre> <p>However, I haven't been able to figure out if this is possible or what the correct syntax might be. Can anyone make any suggestions about better ways to handle this?</p>
[ { "answer_id": 10756495, "author": "11101101b", "author_id": 875305, "author_profile": "https://Stackoverflow.com/users/875305", "pm_score": 6, "selected": false, "text": "MyServiceName.exe MyServiceNamew.exe RCEDIT.exe > RCEDIT.exe /I MyServiceName.exe customIcon.ico\n> RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico\n > MyServiceName.exe //IS//MyServiceName \\\n --Install=\"C:\\path-to\\MyServiceName.exe\" \\\n --Jvm=auto --Startup=auto --StartMode=jvm \\\n --Classpath=\"C:\\path-to\\MyJarWithClassWithMainMethod.jar\" \\\n --StartClass=com.mydomain.MyClassWithMainMethod\n > MyServiceNamew.exe //MS//MyServiceName\n" }, { "answer_id": 42204087, "author": "Ravi Parekh", "author_id": 410439, "author_profile": "https://Stackoverflow.com/users/410439", "pm_score": 2, "selected": false, "text": "C:\\users\\All Users\\Start Menu\\Programs\\Startup User home directory(%userProfile%) shell:startup java.exe -jar D:\\..\\runJar.jar sc create serviceName binpath= \"java.exe -jar D:\\..\\runJar.jar\" cmd /c D:\\JAVA7~1\\jdk1.7.0_51\\bin\\java.exe -jar d:\\jenkins\\jenkins.war Startup Type" }, { "answer_id": 45443208, "author": "Alexey Lisyutenko", "author_id": 8400888, "author_profile": "https://Stackoverflow.com/users/8400888", "pm_score": 3, "selected": false, "text": "public class MyService {\n\n public static void main(String[] args) {\n String command = \"start\";\n if (args.length > 0) {\n command = args[0];\n }\n if (\"start\".equals(command)) {\n // process service start function\n } else {\n // process service stop function\n }\n }\n\n}\n build.gradle buildscript {\n repositories {\n maven {\n url \"https://plugins.gradle.org/m2/\"\n }\n }\n dependencies {\n classpath \"gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0\"\n }\n}\n\napply plugin: \"com.github.alexeylisyutenko.windows-service-plugin\"\n plugins {\n id \"com.github.alexeylisyutenko.windows-service-plugin\" version \"1.1.0\"\n}\n windowsService {\n architecture = 'amd64'\n displayName = 'TestService'\n description = 'Service generated with using gradle plugin' \n startClass = 'MyService'\n startMethod = 'main'\n startParams = 'start'\n stopClass = 'MyService'\n stopMethod = 'main'\n stopParams = 'stop'\n startup = 'auto'\n}\n ${project.buildDir}/windows-service <project-name>-install.bat <project-name>-uninstall.bat <project-name>w.exe" }, { "answer_id": 45851799, "author": "Steephen", "author_id": 1144157, "author_profile": "https://Stackoverflow.com/users/1144157", "pm_score": 2, "selected": false, "text": "-native type\nGenerate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.\n\nThe following values are valid for type:\n\nall: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.\ninstaller: Runs all of the installers for the platform on which it is running.\nimage: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.\ndmg: Generates a DMG file for OS X.\npkg: Generates a .pkg package for OS X.\nmac.appStore: Generates a package for the Mac App Store.\nrpm: Generates an RPM package for Linux.\ndeb: Generates a Debian package for Linux.\n exe: Generates a Windows .exe package.\nmsi: Generates a Windows Installer package.\n" }, { "answer_id": 72658268, "author": "DuncG", "author_id": 4712734, "author_profile": "https://Stackoverflow.com/users/4712734", "pm_score": 0, "selected": false, "text": "Advapi.DLL main()\n Must register ServiceMain using StartServiceCtrlDispatcherW\n Above call blocks until ServiceMain exits\n \nvoid ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)\n Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW\n Use SetServiceStatus(SERVICE_START_PENDING)\n Initialise app\n Use SetServiceStatus(SERVICE_RUNNING)\n wait for app shutdown notification\n Use SetServiceStatus(SERVICE_STOPPED)\n\nint SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)\n Must respond to service control events and report back using SetServiceStatus\n On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)\n then set app shutdown notification\n sc create YourJavaServiceName type= own binpath= \"c:\\Program Files\\Your Release Dir\\yourjavaservice.exe\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ]
68,150
<p>I took a data structures class in C++ last year, and consequently implemented all the major data structures in templated code. I saved it all on a flash drive because I have a feeling that at some point in my life, I'll use it again. I imagine <em>something</em> I end up programming will need a B-Tree, or is that just delusional? How long do you typically save the code you write for possible reuse? </p>
[ { "answer_id": 68170, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "junk/" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
68,160
<p>Is it possible to get gdb or use some other tools to create a core dump of a running process and it's symbol table? It would be great if there's a way to do this without terminating the process. </p> <p>If this is possible, what commands would you use? (I'm trying to do this on a Linux box)</p>
[ { "answer_id": 14279282, "author": "Alex Zeffertt", "author_id": 779147, "author_profile": "https://Stackoverflow.com/users/779147", "pm_score": 6, "selected": false, "text": "gcore $(pidof processname)" }, { "answer_id": 43099251, "author": "dev", "author_id": 2456048, "author_profile": "https://Stackoverflow.com/users/2456048", "pm_score": 1, "selected": false, "text": "generate-core-file" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
68,165
<p>I have a link on a long HTML page. When I click it, I wish a <code>div</code> on another part of the page to be visible in the window by scrolling into view.</p> <p>A bit like <code>EnsureVisible</code> in other languages.</p> <p>I've checked out <code>scrollTop</code> and <code>scrollTo</code> but they seem like red herrings.</p> <p>Can anyone help?</p>
[ { "answer_id": 68175, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 4, "selected": false, "text": "<a href=\"#myAnchorALongWayDownThePage\">Click here to scroll</a>\n\n<A name='myAnchorALongWayDownThePage\"></a>\n" }, { "answer_id": 68671, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 3, "selected": false, "text": "function scrollIntoView(node) {\n var parent = node.parent;\n var parentCHeight = parent.clientHeight;\n var parentSHeight = parent.scrollHeight;\n if (parentSHeight > parentCHeight) {\n var nodeHeight = node.clientHeight;\n var nodeOffset = node.offsetTop;\n var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);\n parent.scrollTop = scrollOffset;\n }\n if (parent.parent) {\n scrollIntoView(parent);\n }\n}\n" }, { "answer_id": 69042, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 5, "selected": false, "text": "$('a[href=#target]').\n click(function(){\n var target = $('a[name=target]');\n if (target.length)\n {\n var top = target.offset().top;\n $('html,body').animate({scrollTop: top}, 1000);\n return false;\n }\n });\n" }, { "answer_id": 71726, "author": "Andrey Fedorov", "author_id": 10728, "author_profile": "https://Stackoverflow.com/users/10728", "pm_score": 1, "selected": false, "text": "function absoluteOffset(elem) {\n return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);\n}\n window.scroll function scrollToElement(elem) {\n window.scroll(0, absoluteOffset(elem));\n}\n" }, { "answer_id": 2368393, "author": "futtta", "author_id": 237449, "author_profile": "https://Stackoverflow.com/users/237449", "pm_score": 9, "selected": false, "text": "document.getElementById('youridhere').scrollIntoView();\n" }, { "answer_id": 34277133, "author": "Swarnendu Paul", "author_id": 1531473, "author_profile": "https://Stackoverflow.com/users/1531473", "pm_score": 0, "selected": false, "text": "$('a[href*=#scrollToDivId]').click(function() {\n if (location.pathname.replace(/^\\//,'') == this.pathname.replace(/^\\//,'') && location.hostname == this.hostname) {\n var target = $(this.hash);\n target = target.length ? target : $('[name=' + this.hash.slice(1) +']');\n var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here\n if (target.length) {\n $('html,body').animate({\n scrollTop: target.offset().top - head_height\n }, 1000);\n return false;\n }\n }\n });\n" }, { "answer_id": 34788466, "author": "funnyfish", "author_id": 5763789, "author_profile": "https://Stackoverflow.com/users/5763789", "pm_score": 2, "selected": false, "text": "onClick=\"document.getElementById('more').scrollIntoView({block: 'start', behavior: 'smooth'});\"\n" }, { "answer_id": 41236967, "author": "Xcoder", "author_id": 1181017, "author_profile": "https://Stackoverflow.com/users/1181017", "pm_score": 3, "selected": false, "text": "document.getElementById('divElem').scrollIntoView();\n" }, { "answer_id": 49916889, "author": "Smelino", "author_id": 9515260, "author_profile": "https://Stackoverflow.com/users/9515260", "pm_score": 4, "selected": false, "text": "Element.scrollIntoView() behavior:\"smooth\" document.getElementById('scroll-here-plz').scrollIntoView({behavior: \"smooth\", block: \"start\", inline: \"nearest\"});\n scroll-here-plz div block: \"\" block: \"start\" block: \"end\" block: \"center\"" }, { "answer_id": 69253570, "author": "Nagev", "author_id": 5362795, "author_profile": "https://Stackoverflow.com/users/5362795", "pm_score": 1, "selected": false, "text": "<a id=\"link1\" href=\"#\">Scroll With Link</a>\n const link = document.getElementById(\"link1\");\nlink.onclick = showBox12;\n\nfunction showBox12()\n{\n const box = document.getElementById(\"box12\");\n box.scrollIntoView();\n console.log(\"Showing Box:\" + box);\n}\n # href=\"\" <a id=\"link1\" href=\"javascript:void(0);\">Scroll With Link</a>\n" }, { "answer_id": 70434427, "author": "Lekens", "author_id": 7575288, "author_profile": "https://Stackoverflow.com/users/7575288", "pm_score": 2, "selected": false, "text": "<button onClick=\"scrollIntoView()\"></button>\n<br>\n<div id=\"scroll-to\"></div>\n\n\nfunction scrollIntoView() {\n document.getElementById('scroll-to').scrollIntoView({\n behavior: 'smooth'\n });\n}\n document.getElementById('scroll-to').scrollIntoView({\n behavior: 'smooth'\n });\n document.getElementById('scroll-to').scrollIntoView();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,234
<p>Let’s say I'm developing a helpdesk application that will be used by multiple departments. Every URL in the application will include a key indicating the specific department. The key will always be the first parameter of every action in the system. For example</p> <pre><code>http://helpdesk/HR/Members http://helpdesk/HR/Members/PeterParker http://helpdesk/HR/Categories http://helpdesk/Finance/Members http://helpdesk/Finance/Members/BruceWayne http://helpdesk/Finance/Categories </code></pre> <p>The problem is that in each action on each request, I have to take this parameter and then retrieve the Helpdesk Department model from the repository based on that key. From that model I can retrieve the list of members, categories etc., which is different for each Helpdesk Department. This obviously violates DRY.</p> <p>My question is, how can I create a base controller, which does this for me so that the particular Helpdesk Department specified in the URL is available to all derived controllers, and I can just focus on the actions?</p>
[ { "answer_id": 72330, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 0, "selected": false, "text": "public abstract class BaseController : Controller \n{\n}\n\npublic class DerivedController : BaseController \n{\n}\n" }, { "answer_id": 83192, "author": "Jeremy Skinner", "author_id": 8560, "author_profile": "https://Stackoverflow.com/users/8560", "pm_score": 3, "selected": true, "text": "public class HelpdeskDepartmentBinder : CustomModelBinderAttribute, IModelBinder {\n\n public override IModelBinder GetBinder() {\n return this;\n }\n\n public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) {\n //... extract appropriate value from RouteData and fetch corresponding entity from database. \n }\n}\n public class MyController : Controller {\n public ActionResult Index([HelpdeskDepartmentBinder] HelpdeskDepartment department) {\n return View();\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,243
<p>I'm looking to write a programming language for fun, however most of the resource I have seen are for writing a context free language, however I wish to write a language that, like python, uses indentation, which to my understanding means it can't be context free.</p>
[ { "answer_id": 68362, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 0, "selected": false, "text": "my_essay = << END_STR\nThis is within the string\nEND_STR\n\n<< self\n def other_method\n ...\n end\nend\n def doSomething() = {\n val xml = <code>def val <tag/> class</code>\n xml\n}\n" }, { "answer_id": 1473209, "author": "Imagist", "author_id": 130640, "author_profile": "https://Stackoverflow.com/users/130640", "pm_score": 2, "selected": false, "text": "int main()\n{\n int i;\n i = 1;\n return 0;\n}\n\nint main()\n{\n int i;\n i = \"Hello, world\";\n return 0;\n}\n i = \"Hello, world\"; char* i;" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,247
<p>I sometimes need to modify OSS code or other peoples' code (usually C-based, but sometimes C++/Java) and find myself "grep"ing headers for types, function declarations etc. as I follow code flow and try to understand the system. Is there a good tool that exists to aid in code browsing. I'd love to be able to click on a type and be taken to the declaration or click on a function name and be taken to it's implementation. I'm on a linux box, so replies like "just use Visual Studio" won't necessarily work for me. Thanks!</p>
[ { "answer_id": 68367, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " Find this C symbol:\n Find this function definition:\n Find functions called by this function:\n Find functions calling this function:\n Find this text string:\n Change this text string:\n Find this egrep pattern:\n Find this file:\n Find files #including this file:\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,282
<p>When defining a method on a class in Python, it looks something like this:</p> <pre><code>class MyClass(object): def __init__(self, x, y): self.x = x self.y = y </code></pre> <p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p> <p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p>
[ { "answer_id": 68320, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 6, "selected": false, "text": ">>> class C:\n... def foo(self):\n... print(\"Hi!\")\n...\n>>>\n>>> def bar(self):\n... print(\"Bork bork bork!\")\n...\n>>>\n>>> c = C()\n>>> C.bar = bar\n>>> c.bar()\nBork bork bork!\n>>> c.foo()\nHi!\n>>>\n" }, { "answer_id": 68324, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 8, "selected": true, "text": "this. self.__class__ self.__dict__" }, { "answer_id": 31367197, "author": "vlad-ardelean", "author_id": 1037251, "author_profile": "https://Stackoverflow.com/users/1037251", "pm_score": 3, "selected": false, "text": "Outer(3).create_inner_class(4)().weird_sum_with_closure_scope(5) class Outer(object):\n def __init__(self, outer_num):\n self.outer_num = outer_num\n\n def create_inner_class(outer_self, inner_arg):\n class Inner(object):\n inner_arg = inner_arg\n def weird_sum_with_closure_scope(inner_self, num)\n return num + outer_self.outer_num + inner_arg\n return Inner\n Method from functools import partial\n\nclass MagicMethod(object):\n \"\"\"Does black magic when called\"\"\"\n def __get__(self, obj, obj_type):\n # This binds the <other> class instance to the <innocent_self> parameter\n # of the method MagicMethod.invoke\n return partial(self.invoke, obj)\n\n\n def invoke(magic_self, innocent_self, *args, **kwargs):\n # do black magic here\n ...\n print magic_self, innocent_self, args, kwargs\n\nclass InnocentClass(object):\n magic_method = MagicMethod()\n InnocentClass().magic_method() innocent_self InnocentClass magic_self this1 this2" }, { "answer_id": 54510770, "author": "mon", "author_id": 4281353, "author_profile": "https://Stackoverflow.com/users/4281353", "pm_score": 1, "selected": false, "text": "class Point(object):\n def __init__(self,x = 0,y = 0):\n self.x = x\n self.y = y\n\n def distance(self):\n \"\"\"Find distance from origin\"\"\"\n return (self.x**2 + self.y**2) ** 0.5\n >>> p1 = Point(6,8)\n>>> p1.distance()\n10.0\n" }, { "answer_id": 63481620, "author": "Sanmitha Sadhishkumar", "author_id": 13827419, "author_profile": "https://Stackoverflow.com/users/13827419", "pm_score": 0, "selected": false, "text": "class class_name:\n class_variable\n def method_name(self,arg):\n self.var=arg \nobj=class_name()\nobj.method_name()\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
68,283
<p>What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#?</p>
[ { "answer_id": 68407, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 6, "selected": false, "text": "class MusicID3Tag\n\n{\n\n public byte[] TAGID = new byte[3]; // 3\n public byte[] Title = new byte[30]; // 30\n public byte[] Artist = new byte[30]; // 30 \n public byte[] Album = new byte[30]; // 30 \n public byte[] Year = new byte[4]; // 4 \n public byte[] Comment = new byte[30]; // 30 \n public byte[] Genre = new byte[1]; // 1\n\n}\n\nstring filePath = @\"C:\\Documents and Settings\\All Users\\Documents\\My Music\\Sample Music\\041105.mp3\";\n\n using (FileStream fs = File.OpenRead(filePath))\n {\n if (fs.Length >= 128)\n {\n MusicID3Tag tag = new MusicID3Tag();\n fs.Seek(-128, SeekOrigin.End);\n fs.Read(tag.TAGID, 0, tag.TAGID.Length);\n fs.Read(tag.Title, 0, tag.Title.Length);\n fs.Read(tag.Artist, 0, tag.Artist.Length);\n fs.Read(tag.Album, 0, tag.Album.Length);\n fs.Read(tag.Year, 0, tag.Year.Length);\n fs.Read(tag.Comment, 0, tag.Comment.Length);\n fs.Read(tag.Genre, 0, tag.Genre.Length);\n string theTAGID = Encoding.Default.GetString(tag.TAGID);\n\n if (theTAGID.Equals(\"TAG\"))\n {\n string Title = Encoding.Default.GetString(tag.Title);\n string Artist = Encoding.Default.GetString(tag.Artist);\n string Album = Encoding.Default.GetString(tag.Album);\n string Year = Encoding.Default.GetString(tag.Year);\n string Comment = Encoding.Default.GetString(tag.Comment);\n string Genre = Encoding.Default.GetString(tag.Genre);\n\n Console.WriteLine(Title);\n Console.WriteLine(Artist);\n Console.WriteLine(Album);\n Console.WriteLine(Year);\n Console.WriteLine(Comment);\n Console.WriteLine(Genre);\n Console.WriteLine();\n }\n }\n }\n" }, { "answer_id": 281381, "author": "Matt", "author_id": 12747, "author_profile": "https://Stackoverflow.com/users/12747", "pm_score": 5, "selected": false, "text": "//using HundredMilesSoftware.UltraID3Lib;\nUltraID3 u = new UltraID3();\nu.Read(@\"C:\\mp3\\song.mp3\");\n//view\nConsole.WriteLine(u.Artist);\n//edit\nu.Artist = \"New Artist\";\nu.Write();\n" }, { "answer_id": 281413, "author": "Luke", "author_id": 261917, "author_profile": "https://Stackoverflow.com/users/261917", "pm_score": 9, "selected": true, "text": "TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = \"New Album Title\";\nf.Save();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10606/" ]
68,291
<p>If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this? </p> <p>Simple Click logging in the DB associated with the post entry? </p> <p>A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks? </p> <p>What sort of characteristics would you base your decision on as to whether the changes were better? </p>
[ { "answer_id": 68407, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 6, "selected": false, "text": "class MusicID3Tag\n\n{\n\n public byte[] TAGID = new byte[3]; // 3\n public byte[] Title = new byte[30]; // 30\n public byte[] Artist = new byte[30]; // 30 \n public byte[] Album = new byte[30]; // 30 \n public byte[] Year = new byte[4]; // 4 \n public byte[] Comment = new byte[30]; // 30 \n public byte[] Genre = new byte[1]; // 1\n\n}\n\nstring filePath = @\"C:\\Documents and Settings\\All Users\\Documents\\My Music\\Sample Music\\041105.mp3\";\n\n using (FileStream fs = File.OpenRead(filePath))\n {\n if (fs.Length >= 128)\n {\n MusicID3Tag tag = new MusicID3Tag();\n fs.Seek(-128, SeekOrigin.End);\n fs.Read(tag.TAGID, 0, tag.TAGID.Length);\n fs.Read(tag.Title, 0, tag.Title.Length);\n fs.Read(tag.Artist, 0, tag.Artist.Length);\n fs.Read(tag.Album, 0, tag.Album.Length);\n fs.Read(tag.Year, 0, tag.Year.Length);\n fs.Read(tag.Comment, 0, tag.Comment.Length);\n fs.Read(tag.Genre, 0, tag.Genre.Length);\n string theTAGID = Encoding.Default.GetString(tag.TAGID);\n\n if (theTAGID.Equals(\"TAG\"))\n {\n string Title = Encoding.Default.GetString(tag.Title);\n string Artist = Encoding.Default.GetString(tag.Artist);\n string Album = Encoding.Default.GetString(tag.Album);\n string Year = Encoding.Default.GetString(tag.Year);\n string Comment = Encoding.Default.GetString(tag.Comment);\n string Genre = Encoding.Default.GetString(tag.Genre);\n\n Console.WriteLine(Title);\n Console.WriteLine(Artist);\n Console.WriteLine(Album);\n Console.WriteLine(Year);\n Console.WriteLine(Comment);\n Console.WriteLine(Genre);\n Console.WriteLine();\n }\n }\n }\n" }, { "answer_id": 281381, "author": "Matt", "author_id": 12747, "author_profile": "https://Stackoverflow.com/users/12747", "pm_score": 5, "selected": false, "text": "//using HundredMilesSoftware.UltraID3Lib;\nUltraID3 u = new UltraID3();\nu.Read(@\"C:\\mp3\\song.mp3\");\n//view\nConsole.WriteLine(u.Artist);\n//edit\nu.Artist = \"New Artist\";\nu.Write();\n" }, { "answer_id": 281413, "author": "Luke", "author_id": 261917, "author_profile": "https://Stackoverflow.com/users/261917", "pm_score": 9, "selected": true, "text": "TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = \"New Album Title\";\nf.Save();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281/" ]
68,323
<p>Working on a project at the moment and we have to implement soft deletion for the majority of users (user roles). We decided to add an <code>is_deleted='0'</code> field on each table in the database and set it to <code>'1'</code> if particular user roles hit a delete button on a specific record.</p> <p>For future maintenance now, each <code>SELECT</code> query will need to ensure they do not include records <code>where is_deleted='1'</code>.</p> <p>Is there a better solution for implementing soft deletion?</p> <p>Update: I should also note that we have an Audit database that tracks changes (field, old value, new value, time, user, ip) to all tables/fields within the Application database.</p>
[ { "answer_id": 68328, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 7, "selected": true, "text": "WHERE IS_DELETED='0'" }, { "answer_id": 68338, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 7, "selected": false, "text": "deleted_at SELECT WHERE deleted_at IS NULL" }, { "answer_id": 68380, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 3, "selected": false, "text": "where deleted=0 deleted" }, { "answer_id": 68396, "author": "Sergey Stadnik", "author_id": 10557, "author_profile": "https://Stackoverflow.com/users/10557", "pm_score": 5, "selected": false, "text": "is_deleted is_deleted SELECT * FROM table_name WHERE is_deleted = 1\n is_deleted = 0 is_deleted = 1 is_deleted WHERE ... AND IS_DELETED=0\n" }, { "answer_id": 69160, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "is_deleted = 0 is_deleted" }, { "answer_id": 23786134, "author": "Kalpesh Soni", "author_id": 255139, "author_profile": "https://Stackoverflow.com/users/255139", "pm_score": -1, "selected": false, "text": "@AdditionalCriteria(\"this.status <> 'deleted'\")\n @entity" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
68,327
<p>I create a new Button object but did not specify the <code>command</code> option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?</p>
[ { "answer_id": 68455, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "bind from Tkinter import Tk, Button\n\nroot = Tk()\nbutton = Button(root, text=\"Click Me!\")\nbutton.pack()\n\ndef callback(event):\n print \"Hello World!\"\n\nbutton.bind(\"<Button-1>\", callback)\nroot.mainloop()\n" }, { "answer_id": 68524, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 6, "selected": true, "text": "from Tkinter import Tk, Button\n\ndef goodbye_world():\n print \"Goodbye World!\\nWait, I changed my mind!\"\n button.configure(text = \"Hello World!\", command=hello_world)\n\ndef hello_world():\n print \"Hello World!\\nWait, I changed my mind!\"\n button.configure(text = \"Goodbye World!\", command=goodbye_world)\n\nroot = Tk()\nbutton = Button(root, text=\"Hello World!\", command=hello_world)\nbutton.pack()\n\nroot.mainloop()\n command .configure name" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
68,335
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p> <p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
[ { "answer_id": 68365, "author": "pdq", "author_id": 8598, "author_profile": "https://Stackoverflow.com/users/8598", "pm_score": 7, "selected": true, "text": "scp subprocess.run import subprocess\nsubprocess.run([\"scp\", FILE, \"USER@SERVER:PATH\"])\n#e.g. subprocess.run([\"scp\", \"foo.bar\", \"[email protected]:/path/to/foo.bar\"])\n subprocess.run with .close() with" }, { "answer_id": 68377, "author": "Drew Olson", "author_id": 9434, "author_profile": "https://Stackoverflow.com/users/9434", "pm_score": -1, "selected": false, "text": "import os\nfilePath = \"/foo/bar/baz.py\"\nserverPath = \"/blah/boo/boom.py\"\nos.system(\"scp \"+filePath+\" [email protected]:\"+serverPath)\n" }, { "answer_id": 68382, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "import subprocess\np = subprocess.Popen([\"scp\", myfile, destination])\nsts = os.waitpid(p.pid, 0)\n destination user@remotehost:remotepath shell=True" }, { "answer_id": 69596, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 7, "selected": false, "text": "import os\nimport paramiko\n\nssh = paramiko.SSHClient() \nssh.load_host_keys(os.path.expanduser(os.path.join(\"~\", \".ssh\", \"known_hosts\")))\nssh.connect(server, username=username, password=password)\nsftp = ssh.open_sftp()\nsftp.put(localpath, remotepath)\nsftp.close()\nssh.close()\n" }, { "answer_id": 22710513, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "fabric #!/usr/bin/env python\nfrom fabric.api import execute, put\nfrom fabric.network import disconnect_all\n\nif __name__==\"__main__\":\n import sys\n # specify hostname to connect to and the remote/local paths\n srcdir, remote_dirname, hostname = sys.argv[1:]\n try:\n s = execute(put, srcdir, remote_dirname, host=hostname)\n print(repr(s))\n finally:\n disconnect_all()\n" }, { "answer_id": 22710752, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "scp pexpect import pipes\nimport re\nimport pexpect # $ pip install pexpect\n\ndef progress(locals):\n # extract percents\n print(int(re.search(br'(\\d+)%$', locals['child'].after).group(1)))\n\ncommand = \"scp %s %s\" % tuple(map(pipes.quote, [srcfile, destination]))\npexpect.run(command, events={r'\\d+%': progress})\n" }, { "answer_id": 38556319, "author": "Maviles", "author_id": 2653486, "author_profile": "https://Stackoverflow.com/users/2653486", "pm_score": 4, "selected": false, "text": "from paramiko import SSHClient\nfrom scp import SCPClient\n\nssh = SSHClient()\nssh.load_system_host_keys()\nssh.connect('example.com')\n\nwith SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n scp.get('test2.txt')\n" }, { "answer_id": 45047041, "author": "michael", "author_id": 3055831, "author_profile": "https://Stackoverflow.com/users/3055831", "pm_score": 2, "selected": false, "text": " from paramiko import SSHClient\n from scp import SCPClient\n import os\n\n ssh = SSHClient() \n ssh.load_host_keys(os.path.expanduser(os.path.join(\"~\", \".ssh\", \"known_hosts\")))\n ssh.connect(server, username='username', password='password')\n with SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n" }, { "answer_id": 48098653, "author": "Roberto Marzocchi", "author_id": 4903301, "author_profile": "https://Stackoverflow.com/users/4903301", "pm_score": 1, "selected": false, "text": "import os\nos.system('sshpass -p \"password\" scp user@host:/path/to/file ./')\n" }, { "answer_id": 48634769, "author": "Jonno_FTW", "author_id": 150851, "author_profile": "https://Stackoverflow.com/users/150851", "pm_score": 1, "selected": false, "text": "$ mkdir ~/sshmount\n$ sshfs user@remotehost:/path/to/remote/dst ~/sshmount\n import shutil\nshutil.copy('a.txt', '~/sshmount')\n" }, { "answer_id": 53344419, "author": "Shawn", "author_id": 7476764, "author_profile": "https://Stackoverflow.com/users/7476764", "pm_score": 2, "selected": false, "text": "from vassal.terminal import Terminal\nshell = Terminal([\"scp username@host:/home/foo.txt foo_local.txt\"])\nshell.run()\n" }, { "answer_id": 53505120, "author": "JavDomGom", "author_id": 10691828, "author_profile": "https://Stackoverflow.com/users/10691828", "pm_score": 1, "selected": false, "text": "import subprocess\n\ntry:\n # Set scp and ssh data.\n connUser = 'john'\n connHost = 'my.host.com'\n connPath = '/home/john/'\n connPrivateKey = '/home/user/myKey.pem'\n\n # Use scp to send file from local to host.\n scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])\n\nexcept CalledProcessError:\n print('ERROR: Connection to host failed!')\n" }, { "answer_id": 56850195, "author": "Pradeep Pathak", "author_id": 8092005, "author_profile": "https://Stackoverflow.com/users/8092005", "pm_score": 3, "selected": false, "text": "import os\nos.system(\"sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path\")\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10668/" ]
68,346
<p>Here's a problem I've been trying to solve at work. I'm not a database expert, so that perhaps this is a bit sophomoric. All apologies.</p> <p>I have a given database D, which has been duplicated on another machine (in a perhaps dubious manner), resulting in database D'. It is my task to check that database D and D' are in fact exactly identical.</p> <p>The problem, of course, is what to actually do if they are not. For this purpose, my thought was to run a symmetric difference on each corresponding table and see the differences.</p> <p>There is a "large" number of tables, so I do not wish to run each symmetric difference by hand. How do I then implement a symmetric difference "function" (or stored procedure, or whatever you'd like) that can run on arbitrary tables without having to explicitly enumerate the columns?</p> <p>This is running on Windows, and your hedge fund will explode if you don't follow through. Good luck.</p>
[ { "answer_id": 2533784, "author": "user303677", "author_id": 303677, "author_profile": "https://Stackoverflow.com/users/303677", "pm_score": 2, "selected": false, "text": "SELECT s.name, s.type \nFROM \n(\n SELECT s1.name, s1.type\n FROM syscolumns s1\n WHERE object_name(s1.id) = 'executionlog2'\n UNION ALL \n SELECT s2.name, s2.type\n FROM syscolumns s2 \n WHERE object_name(s2.id) = 'executionlog3'\n) AS s \nGROUP BY s.name, s.type \nHAVING COUNT(s.name) = 1\n" }, { "answer_id": 10819534, "author": "user1426412", "author_id": 1426412, "author_profile": "https://Stackoverflow.com/users/1426412", "pm_score": 1, "selected": false, "text": "SELECT * FROM TBL_A WHERE ...\nEXCEPT\nSELECT * FROM TBL_B WHERE ...\n" }, { "answer_id": 12780872, "author": "user1498198", "author_id": 1498198, "author_profile": "https://Stackoverflow.com/users/1498198", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION [dbo].[Split]\n(\n @RowData nvarchar(2000),\n @SplitOn nvarchar(5)\n) \nRETURNS @RtnValue table \n(\n Id int identity(1,1),\n Data nvarchar(100)\n) \nAS \nBEGIN \n Declare @Cnt int\n Set @Cnt = 1\n\n While (Charindex(@SplitOn,@RowData)>0)\n Begin\n Insert Into @RtnValue (data)\n Select \n Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))\n\n Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))\n Set @Cnt = @Cnt + 1\n End\n\n Insert Into @RtnValue (data)\n Select Data = ltrim(rtrim(@RowData))\n\n Return\nEND\nGO\n\n\nDECLARE @WB_LIST varchar(1024) = '123,125,764,256,157';\nDECLARE @WB_LIST_IN_DB varchar(1024) = '123,125,795,256,157,789';\n\nDECLARE @TABLE_UPDATE_LIST_IN_DB TABLE ( id varchar(20));\nDECLARE @TABLE_UPDATE_LIST TABLE ( id varchar(20));\n\nINSERT INTO @TABLE_UPDATE_LIST\nSELECT data FROM dbo.Split(@WB_LIST,',');\n\nINSERT INTO @TABLE_UPDATE_LIST_IN_DB\nSELECT data FROM dbo.Split(@LIST_IN_DB,',');\n\n\nSELECT * FROM @TABLE_UPDATE_LIST\nEXCEPT\nSELECT * FROM @TABLE_UPDATE_LIST_IN_DB\nUNION\nSELECT * FROM @TABLE_UPDATE_LIST_IN_DB\nEXCEPT\nSELECT * FROM @TABLE_UPDATE_LIST;\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
68,352
<p>I use this question in interviews and I wonder what the best solution is.</p> <p>Write a Perl sub that takes <em>n</em> lists, and then returns 2^<em>n</em>-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that <em>n</em> is reasonably small (less than 20).</p> <p>For example:</p> <pre><code>list_compare([1, 3], [2, 3]); =&gt; ([1], [2], [3]); </code></pre> <p>Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.</p> <pre><code>list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7]) =&gt; ([1], [2], [3], [4], [5], [6], [7]) </code></pre> <p>Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.</p> <p>I usually give this problem as a follow up to the subset of this problem for <em>n</em>=2.</p> <p>What is the solution? </p> <p>Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.</p>
[ { "answer_id": 68417, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 0, "selected": false, "text": "sub list_compare {\n my (@lists) = @_;\n my %compare;\n my $bit = 1;\n foreach my $list (@lists) {\n $compare{$_} |= $bit foreach @$list;\n $bit *= 2; # shift over one bit\n }\n\n\n my @output_lists;\n foreach my $item (keys %compare) {\n push @{ $output_lists[ $compare{$item} - 1 ] }, $item;\n }\n\n return \\@output_lists;\n\n}\n" }, { "answer_id": 70024, "author": "user11318", "author_id": 11318, "author_profile": "https://Stackoverflow.com/users/11318", "pm_score": 1, "selected": false, "text": "sub list_compare {\n my @lists = @_;\n\n my @answers;\n for my $list (@lists) {\n my %in_list = map {$_=>1} @$list;\n # We have this list.\n my @more_answers = [keys %in_list];\n for my $answer (@answers) {\n push @more_answers, [grep $in_list{$_}, @$answer];\n }\n push @answers, @more_answers;\n }\n\n return @answers;\n}\n sub list_compare {\n my @lists = @_;\n\n my @answers;\n for my $list (@lists) {\n my %in_list = map {$_=>1} @$list;\n # We have this list.\n my @more_answers = [@$list];\n for my $answer (@answers) {\n push @more_answers, [grep $in_list{$_}, @$answer];\n }\n push @answers, @more_answers;\n }\n\n return @answers;\n}\n" }, { "answer_id": 70741, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 2, "selected": false, "text": "$bit shift sub list_compare {\n my ( @list ) = @_;\n my %dest;\n\n for my $i ( 0 .. $#list ) {\n my $bit = 2**$i;\n $dest{$_} += $bit for @{ $list[ $i ] };\n }\n\n my @output_list;\n\n for my $val ( keys %dest ) {\n push @{ $output_list[ $dest{ $val } - 1 ] }, $val;\n }\n\n return \\@output_list;\n}\n use List::Part;\n\nsub list_compare {\n my ( @list ) = @_;\n my %dest;\n\n for my $i ( 0 .. $#list ) {\n my $bit = 2**$i;\n $dest{$_} += $bit for @{ $list[ $i ] };\n }\n\n return [ part { $dest{ $_ } - 1 } keys %dest ];\n}\n list_compare part_elems_by_membership" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101/" ]
68,372
<p>We all know how to use <code>&lt;ctrl&gt;-R</code> to reverse search through history, but did you know you can use <code>&lt;ctrl&gt;-S</code> to forward search if you set <code>stty stop ""</code>? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. </p> <p>What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash?</p>
[ { "answer_id": 68388, "author": "HFLW", "author_id": 252822, "author_profile": "https://Stackoverflow.com/users/252822", "pm_score": 4, "selected": false, "text": "watch --interval=10 lynx -dump http://dslrouter/stats.html\n" }, { "answer_id": 68390, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 5, "selected": false, "text": "$ history | awk '{print $2}' | awk 'BEGIN {FS=\"|\"}{print $1}' | sort | uniq -c | sort -nr | head\n 242 git\n 83 rake\n 43 cd\n 33 ss\n 24 ls\n 15 rsg\n 11 cap\n 10 dig\n 9 ping\n 3 vi\n" }, { "answer_id": 68397, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 7, "selected": false, "text": "cd -\n" }, { "answer_id": 68411, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 2, "selected": false, "text": "export PS1=\"\\[\\033[07;31m\\] \\h \\[\\033[47;30m\\] \\W \\[\\033[00;31m\\] \\$ \\[\\e[m\\]\"\n [RED BACK WHITE TEXT] Computer name \n[BLACK BACK WHITE TEXT] Working Directory \n[WHITE BACK RED TEXT] $\n :)" }, { "answer_id": 68412, "author": "dreamlax", "author_id": 10320, "author_profile": "https://Stackoverflow.com/users/10320", "pm_score": 3, "selected": false, "text": "while ls -la <filename>; do sleep 5; done\n ls watch watch nc nc -l -p 9100 > printjob.prn\n printjob.prn" }, { "answer_id": 68413, "author": "Sergio Morales", "author_id": 9506, "author_profile": "https://Stackoverflow.com/users/9506", "pm_score": 0, "selected": false, "text": "mencoder movie.wmv -o movie.avi -ovc lavc -oac lavc \n mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile fileout.mp3 filein.avi \n" }, { "answer_id": 68419, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 5, "selected": false, "text": "cp file /to/some/long/path\n" }, { "answer_id": 68421, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 7, "selected": true, "text": "$ mkdir /tmp/new\n$ cd !!:*\n for file in *.wav; do lame \"$file\" \"$(basename \"$file\" .wav).mp3\" ; done;\n export HISTCONTROL=\"erasedups:ignoreboth\"\n export HISTFILESIZE=500000\nexport HISTSIZE=100000\n export HISTIGNORE=\"&:[ ]*:exit\"\n shopt -s histappend\n shopt -s cmdhist\n stty stop \"\"\n" }, { "answer_id": 68424, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 6, "selected": false, "text": "$ ls\nthis_has_text_to_find_1.txt\nthis_has_text_to_find_2.txt\nthis_has_text_to_find_3.txt\nthis_has_text_to_find_4.txt\n\n$ rename 's/text_to_find/been_renamed/' *.txt\n$ ls\nthis_has_been_renamed_1.txt\nthis_has_been_renamed_2.txt\nthis_has_been_renamed_3.txt\nthis_has_been_renamed_4.txt\n\n" }, { "answer_id": 68429, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 7, "selected": false, "text": "!!\n sudo !!\n" }, { "answer_id": 68441, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 4, "selected": false, "text": "$ find dir -name \\*~ | xargs echo rm\n...\n$ find dir -name \\*~ | xargs echo rm | ksh -s\n" }, { "answer_id": 68449, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 4, "selected": false, "text": "~/.inputrc \"\\C-[[A\": history-search-backward\n\"\\C-[[B\": history-search-forward\n ^R cd /media/ cd /media/ ~/.bashrc if [ -f /etc/bash_completion ]; then\n . /etc/bash_completion\nfi\n evince ~/.inputrc set completion-ignore-case on\nset show-all-if-ambiguous on\nset show-all-if-unmodified on\n" }, { "answer_id": 68489, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "\"\\M-p\": history-search-backward > make <ESC p> > make some_really_painfully_long_target" }, { "answer_id": 68496, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 6, "selected": false, "text": "!$ !^ !* $ echo foo bar baz\nfoo bar baz\n$ echo bang-dollar: !$ bang-hat: !^ bang-star: !*\necho bang-dollar: baz bang-hat: foo bang-star: foo bar baz\nbang-dollar: baz bang-hat: foo bang-star: foo bar baz\n ls filea fileb vi !$ vimdiff !* n $ echo foo bar baz\n$ echo !:2\necho bar\nbar\n :h :t $ ls /usr/bin/id\n/usr/bin/id\n$ echo Head: !$:h Tail: !$:t\necho Head: /usr/bin Tail: id\nHead: /usr/bin Tail: id\n" }, { "answer_id": 68547, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 3, "selected": false, "text": "$ touch {1,2}.txt\n$ ls [12].txt\n1.txt 2.txt\n$ rm !:1\nrm [12].txt\n$ history | tail -10\n...\n10007 touch {1,2}.txt\n...\n$ !10007\ntouch {1,2}.txt\n$ for f in *.txt; do mv $f ${f/txt/doc}; done\n" }, { "answer_id": 68590, "author": "baudtack", "author_id": 10738, "author_profile": "https://Stackoverflow.com/users/10738", "pm_score": 1, "selected": false, "text": "ls <up-arrow>" }, { "answer_id": 68600, "author": "user10765", "author_id": 10765, "author_profile": "https://Stackoverflow.com/users/10765", "pm_score": 7, "selected": false, "text": "cp /home/foo/realllylongname.cpp{,-old} cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old" }, { "answer_id": 68781, "author": "jdt141", "author_id": 10774, "author_profile": "https://Stackoverflow.com/users/10774", "pm_score": 3, "selected": false, "text": "pushd popd" }, { "answer_id": 69031, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 1, "selected": false, "text": "export LESS=\"-X\"\n" }, { "answer_id": 69033, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 0, "selected": false, "text": "man () {\n sought=$*\n /usr/bin/man $sought | col -b | vim -R -c \"set nonumber\" -c \"set syntax=man\" -\n}\n" }, { "answer_id": 69039, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 2, "selected": false, "text": "alias mkae=make\n\nalias mroe=less\n" }, { "answer_id": 69056, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 2, "selected": false, "text": "echo what the heck?\n\nwhat the heck?\n\necho !$\n\nheck?\n" }, { "answer_id": 69058, "author": "TChen", "author_id": 10913, "author_profile": "https://Stackoverflow.com/users/10913", "pm_score": 3, "selected": false, "text": "./run.sh && tail -f log.txt\n kill -9 1111 && ./start.sh\n" }, { "answer_id": 69087, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 3, "selected": false, "text": "# do \". acd_func.sh\"\n# acd_func 1.0.5, 10-nov-2004\n# petar marinov, http:/geocities.com/h2428, this is public domain\n\ncd_func ()\n{\n local x2 the_new_dir adir index\n local -i cnt\n\n if [[ $1 == \"--\" ]]; then\n dirs -v\n return 0\n fi\n\n the_new_dir=$1\n [[ -z $1 ]] && the_new_dir=$HOME\n\n if [[ ${the_new_dir:0:1} == '-' ]]; then\n #\n # Extract dir N from dirs\n index=${the_new_dir:1}\n [[ -z $index ]] && index=1\n adir=$(dirs +$index)\n [[ -z $adir ]] && return 1\n the_new_dir=$adir\n fi\n\n #\n # '~' has to be substituted by ${HOME}\n [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir=\"${HOME}${the_new_dir:1}\"\n\n #\n # Now change to the new dir and add to the top of the stack\n pushd \"${the_new_dir}\" > /dev/null\n [[ $? -ne 0 ]] && return 1\n the_new_dir=$(pwd)\n\n #\n # Trim down everything beyond 11th entry\n popd -n +11 2>/dev/null 1>/dev/null\n\n #\n # Remove any other occurence of this dir, skipping the top of the stack\n for ((cnt=1; cnt <= 10; cnt++)); do\n x2=$(dirs +${cnt} 2>/dev/null)\n [[ $? -ne 0 ]] && return 0\n [[ ${x2:0:1} == '~' ]] && x2=\"${HOME}${x2:1}\"\n if [[ \"${x2}\" == \"${the_new_dir}\" ]]; then\n popd -n +$cnt 2>/dev/null 1>/dev/null\n cnt=cnt-1\n fi\n done\n\n return 0\n}\n\nalias cd=cd_func\n\nif [[ $BASH_VERSION > \"2.05a\" ]]; then\n # ctrl+w shows the menu\n bind -x \"\\\"\\C-w\\\":cd_func -- ;\"\nfi\n" }, { "answer_id": 69118, "author": "Leonard", "author_id": 10888, "author_profile": "https://Stackoverflow.com/users/10888", "pm_score": 1, "selected": false, "text": "cd /some/where/long\nsrc=`pwd`\ncd /other/where/long\ndest=`pwd`\n\ncp $src/foo $dest\n\ncommand completion will work by expanding the variable, so you can use tab completion to specify a file you're working with.\n" }, { "answer_id": 69198, "author": "Drew Frezell", "author_id": 10954, "author_profile": "https://Stackoverflow.com/users/10954", "pm_score": 3, "selected": false, "text": "ctrl-E # move cursor to end of line\nctrl-A # move cursor to beginning of line\n shopt -s cdable_vars export Dcentmain=\"/var/localdata/p4ws/centaur/main/apps/core\"\n cd Dcentmain" }, { "answer_id": 69449, "author": "Steve Lacey", "author_id": 11077, "author_profile": "https://Stackoverflow.com/users/11077", "pm_score": 4, "selected": false, "text": ":p !!:p\n !! !?foo?:p\n !?foo\n" }, { "answer_id": 69475, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "$_ !$ !$" }, { "answer_id": 69560, "author": "shiva", "author_id": 11018, "author_profile": "https://Stackoverflow.com/users/11018", "pm_score": 2, "selected": false, "text": "#sort -u filename > filename.new\n #grep -v ajsk filename\n ls -thor" }, { "answer_id": 69716, "author": "dajobe", "author_id": 11177, "author_profile": "https://Stackoverflow.com/users/11177", "pm_score": 4, "selected": false, "text": "type -a PROG\n" }, { "answer_id": 69737, "author": "paranoio", "author_id": 11124, "author_profile": "https://Stackoverflow.com/users/11124", "pm_score": 0, "selected": false, "text": "alias mycommand = 'verylongcommand -with -a -lot -of -parameters'\nalias grep='grep --color'\n netstat -c |grep 'msn\\|skype\\|icq'\n" }, { "answer_id": 69756, "author": "seth", "author_id": 8590, "author_profile": "https://Stackoverflow.com/users/8590", "pm_score": 6, "selected": false, "text": "$ ehco foo bar baz\nbash: ehco: command not found\n$ ^ehco^echo\nfoo bar baz\n" }, { "answer_id": 69870, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "mv file $OLDPWD" }, { "answer_id": 69974, "author": "user11285", "author_id": 11285, "author_profile": "https://Stackoverflow.com/users/11285", "pm_score": 0, "selected": false, "text": "find . -exec grep whatIWantToFind {} \\;\n" }, { "answer_id": 70190, "author": "Weidenrinde", "author_id": 11344, "author_profile": "https://Stackoverflow.com/users/11344", "pm_score": 0, "selected": false, "text": "alias -- ddt='ls -trFld'\ndt () { ddt --color \"$@\" | tail -n 30; }\n" }, { "answer_id": 70523, "author": "user11535", "author_id": 11535, "author_profile": "https://Stackoverflow.com/users/11535", "pm_score": 3, "selected": false, "text": "mkdir -p /tmp/test/blah/oops/something\ncd [alt].\n" }, { "answer_id": 71285, "author": "Srikanth", "author_id": 7205, "author_profile": "https://Stackoverflow.com/users/7205", "pm_score": 4, "selected": false, "text": "$ alias vi=vim\n$ # To escape the alias for vi:\n$ \\vi # This doesn't open VIM\n" }, { "answer_id": 71326, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 2, "selected": false, "text": "e=\"\\033[\"\nfor f in 0 7 `seq 6`; do\n no=\"\" bo=\"\"\n for b in n 7 0 `seq 6`; do\n co=\"3$f\"; p=\" \"\n [ $b = n ] || { co=\"$co;4$b\";p=\"\"; }\n no=\"${no}${e}${co}m ${p}${co} ${e}0m\"\n bo=\"${bo}${e}1;${co}m ${p}1;${co} ${e}0m\"\n done\n echo -e \"$no\\n$bo\"\ndone\n yes \"$(seq 232 255;seq 254 -1 233)\" |\nwhile read i; do printf \"\\x1b[48;5;${i}m\\n\"; sleep .01; done\n" }, { "answer_id": 71418, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 1, "selected": false, "text": "tail /var/log/syslog\n tail -f /var/log/syslog\n more /var/log/syslog\n grep \"find this text\" /var/log/syslog\n" }, { "answer_id": 75005, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function viscr { vi $(which $*); }\n" }, { "answer_id": 75152, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function histgrep { fc -l -$((HISTSIZE-1)) | egrep \"$@\" ;}\n" }, { "answer_id": 75765, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "export FIGNORE=\"CVS:.svn:~\"\n export IFS=\"\n\"\n $ touch \"with spaces\" withoutspaces\n$ for i in `ls *`; do echo $i; done\nwith\nspaces\nwithoutspaces\n$ IFS=\"\n\"\n$ for i in `ls *`; do echo $i; done\nwith spaces\nwithoutspaces\n" }, { "answer_id": 76086, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 3, "selected": false, "text": "! !b !. ./a.out" }, { "answer_id": 88815, "author": "Robert Swisher", "author_id": 1852, "author_profile": "https://Stackoverflow.com/users/1852", "pm_score": 1, "selected": false, "text": "$ mkdir new_dir\n$ cd old_dir\n$ tar cf - . | ( cd ../old_dir; tar xf - )\n" }, { "answer_id": 93587, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "ping blah.really.long.domain.name.foo.com ping blah.<tab>\n" }, { "answer_id": 94725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$ date\nThu Sep 18 12:55:33 EDT 2008\n$ answers=60\n$ curl \"http://stackoverflow.com/questions/68372/what-are-some-of-your-favorite-command-line-tricks-using-bash\" > tmp.html\n$ words=`awk '/class=\"post-text\"/ {s = s $0} \\\n> /<\\/div>/ { gsub(\"<[^>]*>\", \"\", s); print s; s = \"\"} \\\n> length(s) > 0 {s = s $0}' tmp.html \\\n> | awk '{n = n + NF} END {print n}'`\n$ answers=`awk '/([0-9]+) Answers/ {sub(\"<h2>\", \"\", $1); print $1}' tmp.html`\n $ echo $words words, $answers answers, $((words / $answers)) words per answer\n4126 words, 60 answers, 68 words per answer\n$\n" }, { "answer_id": 95627, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "history | awk '{ print $2 }' | sort | uniq -c |sort -rn | head\n" }, { "answer_id": 103337, "author": "rgcb", "author_id": 8178, "author_profile": "https://Stackoverflow.com/users/8178", "pm_score": 1, "selected": false, "text": "function macvim\n{\n/Applications/MacVim.app/Contents/MacOS/Vim \"$@\" -gp &\n}\n" }, { "answer_id": 104649, "author": "dr-jan", "author_id": 2599, "author_profile": "https://Stackoverflow.com/users/2599", "pm_score": 0, "selected": false, "text": "PS1='\\u@\\h:\\w> '\nexport PS1\n" }, { "answer_id": 109998, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "while IFS= read -r line; do\necho \"$line\"\ndone < somefile.txt\n" }, { "answer_id": 111118, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 4, "selected": false, "text": "alias webshare='python -m SimpleHTTPServer'\n $ :(){ :|:& };:\n" }, { "answer_id": 139674, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 1, "selected": false, "text": "(cd /path/to/source/dir/ ; tar cf - * ) | (cd /path/to/destination/ ; tar xf - )" }, { "answer_id": 139785, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 2, "selected": false, "text": "# shopt -s extglob\n# rm -rf !(important-file)\n # rm -rf *~important-file\n" }, { "answer_id": 152576, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "alias cd6=\"cd ../../../../../..\"\nalias cd5=\"cd ../../../../..\"\nalias cd4=\"cd ../../../..\"\nalias cd3=\"cd ../../..\"\nalias cd2=\"cd ../..\"\n" }, { "answer_id": 153700, "author": "Florian Jenn", "author_id": 23813, "author_profile": "https://Stackoverflow.com/users/23813", "pm_score": 2, "selected": false, "text": "!# ^ $ mv file-with-long-name-typed-with-tab-completion.txt old-!#^" }, { "answer_id": 164795, "author": "Philip Durbin", "author_id": 19464, "author_profile": "https://Stackoverflow.com/users/19464", "pm_score": 5, "selected": false, "text": "diff file1.txt file2.txt diff diff $ cat myscript.sh\n#!/bin/sh\necho -e \"one\\nthree\"\n$\n$ ./myscript.sh \none\nthree\n$\n$ cat expected_output.txt\none\ntwo\nthree\n$\n$ diff <(./myscript.sh) expected_output.txt\n1a2\n> two\n$\n diff diff $ diff <(ssh server1 'rpm -qa | sort') <(ssh server2 'rpm -qa | sort')\n241c240\n< kernel-2.6.18-92.1.6.el5\n---\n> kernel-2.6.18-92.el5\n317d315\n< libsmi-0.4.5-2.el5\n727,728d724\n< wireshark-0.99.7-1.el5\n< wireshark-gnome-0.99.7-1.el5\n$\n" }, { "answer_id": 164842, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 1, "selected": false, "text": "ESC .\n ESC . ALT+. !! $!" }, { "answer_id": 171938, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 5, "selected": false, "text": "ls -d */\n" }, { "answer_id": 171943, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": 1, "selected": false, "text": "sudo !!\n" }, { "answer_id": 173682, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 0, "selected": false, "text": "find -iregex '.*\\.py$\\|.*\\.xml$' | xargs egrep -niH 'a.search.pattern' | vi -R -\n" }, { "answer_id": 328497, "author": "kchoose2", "author_id": 39870, "author_profile": "https://Stackoverflow.com/users/39870", "pm_score": 0, "selected": false, "text": "$ type cdhome\ncdhome is aliased to 'cd ~'\n$ type bash\nbash is /bin/bash\n" }, { "answer_id": 347005, "author": "Adrian Pronk", "author_id": 41861, "author_profile": "https://Stackoverflow.com/users/41861", "pm_score": 0, "selected": false, "text": "PROMPT_COMMAND='echo -e \"\\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\\007\\033[1;31m${PWD/#$HOME/~}\\033[1;34m\"'\nPS1='\\[\\e[1;31m\\]\\t \\$ \\[\\e[0m\\]'\n \\[ \\]" }, { "answer_id": 417987, "author": "Epitaph", "author_id": 48725, "author_profile": "https://Stackoverflow.com/users/48725", "pm_score": 2, "selected": false, "text": "alias myDir = \"cd /this/is/a/long/directory; pwd\"\n" }, { "answer_id": 752702, "author": "Rob Hruska", "author_id": 29995, "author_profile": "https://Stackoverflow.com/users/29995", "pm_score": 2, "selected": false, "text": "Control-Z fg Control-Z fg" }, { "answer_id": 1138910, "author": "cb0", "author_id": 85737, "author_profile": "https://Stackoverflow.com/users/85737", "pm_score": 1, "selected": false, "text": "for i in $(ls) fea(){\n if test -z ${2:0:1}; then action=echo; else action=$2; fi\n for i in $(ls $1);\n do $action $i ;\n done;\n}\n echo ${!B*}\n" }, { "answer_id": 1250809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "sudo !!\n mount | column -t\n" }, { "answer_id": 1520801, "author": "Max Masnick", "author_id": 173351, "author_profile": "https://Stackoverflow.com/users/173351", "pm_score": 3, "selected": false, "text": "pbcopy pwd | pbcopy" }, { "answer_id": 1581540, "author": "Fergal", "author_id": 102641, "author_profile": "https://Stackoverflow.com/users/102641", "pm_score": 2, "selected": false, "text": "alias ..='cd ..' ..<Enter>" }, { "answer_id": 2469330, "author": "kubi", "author_id": 28422, "author_profile": "https://Stackoverflow.com/users/28422", "pm_score": 0, "selected": false, "text": "open ./\n http://" }, { "answer_id": 2890180, "author": "amphetamachine", "author_id": 237955, "author_profile": "https://Stackoverflow.com/users/237955", "pm_score": 2, "selected": false, "text": "./configure ./configure --{prefix=/usr,mandir=/usr/man,{,sh}libdir=/usr/lib64,\\\nenable-{gpl,pthreads,bzlib,lib{faad{,bin},mp3lame,schroedinger,speex,theora,vorbis,xvid,x264},\\\npic,shared,postproc,avfilter{-lavf,}},disable-static}\n echo \"I can count to a thousand!\" ...{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}...\n" }, { "answer_id": 2922141, "author": "amphetamachine", "author_id": 237955, "author_profile": "https://Stackoverflow.com/users/237955", "pm_score": 1, "selected": false, "text": ".inputrc # redirection short cuts\n\"\\ew\": \"2>&1\"\n\"\\eq\": \"&>/dev/null &\"\n\"\\e\\C-q\": \"2>/dev/null\"\n\"\\eg\": \"&>~/.garbage.out &\"\n\"\\e\\C-g\": \"2>~/.garbage.out\"\n\n$if term=xterm\n\"\\M-w\": \"2>&1\"\n\"\\M-q\": \"&>/dev/null &\"\n\"\\M-\\C-q\": \"2>/dev/null\"\n\"\\M-g\": \"&>~/.garbage.out &\"\n\"\\M-\\C-g\": \"2>~/.garbage.out\"\n$endif\n" }, { "answer_id": 2922147, "author": "amphetamachine", "author_id": 237955, "author_profile": "https://Stackoverflow.com/users/237955", "pm_score": 1, "selected": false, "text": "shopt -s progcomp\n\ncomplete -A stopped -P '%' bg\ncomplete -A job -P '%' fg jobs disown wait\ncomplete -A variable readonly export\ncomplete -A variable -A function unset\ncomplete -A setopt set\ncomplete -A shopt shopt\ncomplete -A helptopic help\ncomplete -A alias alias unalias\ncomplete -A binding bind\ncomplete -A command type which \\\n killall pidof\ncomplete -A builtin builtin\ncomplete -A disabled enable\n" }, { "answer_id": 2922191, "author": "amphetamachine", "author_id": 237955, "author_profile": "https://Stackoverflow.com/users/237955", "pm_score": 1, "selected": false, "text": "while getopts 'vo:' flag; do\n case \"$flag\" in\n 'v')\n VERBOSE=1\n ;;\n 'o')\n OUT=\"$OPTARG\"\n ;;\n esac\ndone\nshift \"$((OPTIND-1))\"\n xargs if [ \"$#\" -gt 1 ]; then\n # schedule using xargs\n (for file; do\n echo -n \"$file\"\n echo -ne '\\0'\n done) |xargs -0 -n 1 -P \"$NUM_JOBS\" -- \"$0\"\nelse\n # do the actual processing\nfi\n make -j [NUM_JOBS]" }, { "answer_id": 2922244, "author": "amphetamachine", "author_id": 237955, "author_profile": "https://Stackoverflow.com/users/237955", "pm_score": 1, "selected": false, "text": "# TERM or QUIT probably means the system is shutting down; make sure history is\n# saved to $HISTFILE (does not do this by default)\ntrap 'logout' TERM QUIT\n\n# save history when signalled by cron(1) script with USR1\ntrap 'history -a && history -n' USR1\n" }, { "answer_id": 3436445, "author": "jlucktay", "author_id": 380599, "author_profile": "https://Stackoverflow.com/users/380599", "pm_score": 3, "selected": false, "text": "find ./ -type f -print0 | xargs -0 -n1 md5sum | sort -k 1,32 | uniq -w 32 -d --all-repeated=separate | sed -e 's/^[0-9a-f]*\\ *//;'\n" }, { "answer_id": 3539492, "author": "Omar Ali", "author_id": 383819, "author_profile": "https://Stackoverflow.com/users/383819", "pm_score": 2, "selected": false, "text": "ssh -fNR 1234:localhost:22 [email protected]\n" }, { "answer_id": 3549013, "author": "Ken Chen", "author_id": 312123, "author_profile": "https://Stackoverflow.com/users/312123", "pm_score": 1, "selected": false, "text": "$ touch myself" }, { "answer_id": 3724298, "author": "Gadolin", "author_id": 410737, "author_profile": "https://Stackoverflow.com/users/410737", "pm_score": 3, "selected": false, "text": "CDPATH export CDPATH=.:/home/gadolin/sth:/home/gadolin/dir1/importantDir\n cd /home/gadolin/sth /home/gadolin/dir1/importantDir <tab> /home/gadolin/sth/1 /home/gadolin/sth/2 cd 1" }, { "answer_id": 4199377, "author": "Wesley Rice", "author_id": 534235, "author_profile": "https://Stackoverflow.com/users/534235", "pm_score": 0, "selected": false, "text": "# Batch extension renamer (usage: renamer txt mkd)\nrenamer() {\n local fn\n for fn in *.\"$1\"; do\n mv \"$fn\" \"${fn%.*}\".\"$2\"\n done\n}\n" }, { "answer_id": 4199491, "author": "chris", "author_id": 469276, "author_profile": "https://Stackoverflow.com/users/469276", "pm_score": 1, "selected": false, "text": "rm !(foo|bar)\n * foo bar $ ls\nfoo\nbar\nfoobar\nFOO\n$ echo !(foo|bar)\nfoobar FOO\n" }, { "answer_id": 4201124, "author": "Bauna", "author_id": 450778, "author_profile": "https://Stackoverflow.com/users/450778", "pm_score": 1, "selected": false, "text": "alias pbcopy='xclip -selection clipboard'\nalias pbpaste='xclip -selection clipboard -o'\n" }, { "answer_id": 4615572, "author": "bobbogo", "author_id": 470195, "author_profile": "https://Stackoverflow.com/users/470195", "pm_score": 3, "selected": false, "text": "echo !$ !-2^ * echo aword someotherword * echo !$ !-2^ * echo !$ !-2^ LOG Makefile bar.c foo.h" }, { "answer_id": 5163728, "author": "Mikel", "author_id": 102182, "author_profile": "https://Stackoverflow.com/users/102182", "pm_score": 2, "selected": false, "text": "function $\n{\n \"$@\"\n}\n $" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
68,391
<p>In an effort to reduce code duplication in my little Rails app, I've been working on getting common code between my models into it's own separate module, so far so good.</p> <p>The model stuff is fairly easy, I just have to include the module at the beginning, e.g.:</p> <pre><code>class Iso &lt; Sale include Shared::TracksSerialNumberExtension include Shared::OrderLines extend Shared::Filtered include Sendable::Model validates_presence_of :customer validates_associated :lines owned_by :customer def initialize( params = nil ) super self.created_at ||= Time.now.to_date end def after_initialize end order_lines :despatched # tracks_serial_numbers :items sendable :customer def created_at=( date ) write_attribute( :created_at, Chronic.parse( date ) ) end end </code></pre> <p>This is working fine, now however, I'm going to have some controller and view code that's going to be common between these models as well, so far I have this for my sendable stuff:</p> <pre><code># This is a module that is used for pages/forms that are can be "sent" # either via fax, email, or printed. module Sendable module Model def self.included( klass ) klass.extend ClassMethods end module ClassMethods def sendable( class_to_send_to ) attr_accessor :fax_number, :email_address, :to_be_faxed, :to_be_emailed, :to_be_printed @_class_sending_to ||= class_to_send_to include InstanceMethods end def class_sending_to @_class_sending_to end end # ClassMethods module InstanceMethods def after_initialize( ) super self.to_be_faxed = false self.to_be_emailed = false self.to_be_printed = false target_class = self.send( self.class.class_sending_to ) if !target_class.nil? self.fax_number = target_class.send( :fax_number ) self.email_address = target_class.send( :email_address ) end end end end # Module Model end # Module Sendable </code></pre> <p>Basically I'm planning on just doing an include Sendable::Controller, and Sendable::View (or the equivalent) for the controller and the view, but, is there a cleaner way to do this? I 'm after a neat way to have a bunch of common code between my model, controller, and view.</p> <p>Edit: Just to clarify, this just has to be shared across 2 or 3 models.</p>
[ { "answer_id": 68934, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": false, "text": "# maybe put this in environment.rb or in your module declaration\nclass ActiveRecord::Base\n include Iso\nend\n\n# application.rb\nclass ApplicationController\n include Iso\nend\n helper_method" }, { "answer_id": 69190, "author": "nikz", "author_id": 3977, "author_profile": "https://Stackoverflow.com/users/3977", "pm_score": 4, "selected": true, "text": "ActiveRecord::Base.send(:include, PluginName::Sendable)\nActionController::Base.send(:include, PluginName::SendableController)\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/841/" ]
68,408
<p>Is there any <strong>simple algorithm</strong> to determine the likeliness of 2 names representing the same person? </p> <p>I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.</p> <p>If there is an algorithm in <code>C#</code> that would be great, but I can translate from any language.</p>
[ { "answer_id": 68570, "author": "Stanislav Kniazev", "author_id": 10757, "author_profile": "https://Stackoverflow.com/users/10757", "pm_score": 3, "selected": true, "text": "PartialStringComparer cmp = new PartialStringComparer();\ntbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString();\n public class SubstringRange {\n string masterString;\n\n public string MasterString {\n get { return masterString; }\n set { masterString = value; }\n }\n int start;\n\n public int Start {\n get { return start; }\n set { start = value; }\n }\n int end;\n\n public int End {\n get { return end; }\n set { end = value; }\n }\n public int Length {\n get { return End - Start; }\n set { End = Start + value;}\n }\n\n public bool IsValid {\n get { return MasterString.Length >= End && End >= Start && Start >= 0; }\n }\n\n public string Contents {\n get {\n if(IsValid) {\n return MasterString.Substring(Start, Length);\n } else {\n return \"\";\n }\n }\n }\n public bool OverlapsRange(SubstringRange range) {\n return !(End < range.Start || Start > range.End);\n }\n public bool ContainsRange(SubstringRange range) {\n return range.Start >= Start && range.End <= End;\n }\n public bool ExpandTo(string newContents) {\n if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) && newContents.Length > Length) {\n Length = newContents.Length;\n return true;\n } else {\n return false;\n }\n }\n}\n\npublic class SubstringRangeList: List<SubstringRange> {\n string masterString;\n\n public string MasterString {\n get { return masterString; }\n set { masterString = value; }\n }\n\n public SubstringRangeList(string masterString) {\n this.MasterString = masterString;\n }\n\n public SubstringRange FindString(string s){\n foreach(SubstringRange r in this){\n if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase))\n return r;\n }\n return null;\n }\n\n public SubstringRange FindSubstring(string s){\n foreach(SubstringRange r in this){\n if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase))\n return r;\n }\n return null;\n }\n\n public bool ContainsRange(SubstringRange range) {\n foreach(SubstringRange r in this) {\n if(r.ContainsRange(range))\n return true;\n }\n return false;\n }\n\n public bool AddSubstring(string substring) {\n bool result = false;\n foreach(SubstringRange r in this) {\n if(r.ExpandTo(substring)) {\n result = true;\n }\n }\n if(FindSubstring(substring) == null) {\n bool patternfound = true;\n int start = 0;\n while(patternfound){\n patternfound = false;\n start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase);\n patternfound = start != -1;\n if(patternfound) {\n SubstringRange r = new SubstringRange();\n r.MasterString = this.MasterString;\n r.Start = start++;\n r.Length = substring.Length;\n if(!ContainsRange(r)) {\n this.Add(r);\n result = true;\n }\n }\n }\n }\n return result;\n }\n\n private static bool SubstringRangeMoreThanOneChar(SubstringRange range) {\n return range.Length > 1;\n }\n\n public float Weight {\n get {\n if(MasterString.Length == 0 || Count == 0)\n return 0;\n float numerator = 0;\n int denominator = 0;\n foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) {\n numerator += r.Length;\n denominator++;\n }\n if(denominator == 0)\n return 0;\n return numerator / denominator / MasterString.Length;\n }\n }\n\n public void RemoveOverlappingRanges() {\n SubstringRangeList l = new SubstringRangeList(this.MasterString);\n l.AddRange(this);//create a copy of this list\n foreach(SubstringRange r in l) {\n if(this.Contains(r) && this.ContainsRange(r)) {\n Remove(r);//try to remove the range\n if(!ContainsRange(r)) {//see if the list still contains \"superset\" of this range\n Add(r);//if not, add it back\n }\n }\n }\n }\n\n public void AddStringToCompare(string s) {\n for(int start = 0; start < s.Length; start++) {\n for(int len = 1; start + len <= s.Length; len++) {\n string part = s.Substring(start, len);\n if(!AddSubstring(part))\n break;\n }\n }\n RemoveOverlappingRanges();\n }\n}\n\npublic class PartialStringComparer {\n public float Compare(string s1, string s2) {\n SubstringRangeList srl1 = new SubstringRangeList(s1);\n srl1.AddStringToCompare(s2);\n SubstringRangeList srl2 = new SubstringRangeList(s2);\n srl2.AddStringToCompare(s1);\n return (srl1.Weight + srl2.Weight) / 2;\n }\n}\n public class Distance {\n /// <summary>\n /// Compute Levenshtein distance\n /// </summary>\n /// <param name=\"s\">String 1</param>\n /// <param name=\"t\">String 2</param>\n /// <returns>Distance between the two strings.\n /// The larger the number, the bigger the difference.\n /// </returns>\n public static int LD(string s, string t) {\n int n = s.Length; //length of s\n int m = t.Length; //length of t\n int[,] d = new int[n + 1, m + 1]; // matrix\n int cost; // cost\n // Step 1\n if(n == 0) return m;\n if(m == 0) return n;\n // Step 2\n for(int i = 0; i <= n; d[i, 0] = i++) ;\n for(int j = 0; j <= m; d[0, j] = j++) ;\n // Step 3\n for(int i = 1; i <= n; i++) {\n //Step 4\n for(int j = 1; j <= m; j++) {\n // Step 5\n cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);\n // Step 6\n d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);\n }\n }\n // Step 7\n return d[n, m];\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610/" ]
68,444
<p>We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.</p> <p>Is there a program or technique out there for wrapping all these files together into a single SWF file?</p>
[ { "answer_id": 192919, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": false, "text": "mxmlc package {\n\n\n public class Assets {\n\n [Embed(source=\"another.swf\")]\n public var another : Class;\n\n }\n\n}\n another.swf package {\n\n import flash.display.Sprite;\n\n\n public class MyFancySite extends Sprite {\n\n public function MyFancySprite( ) {\n var theOther : DisplayObject = new Assets.another();\n\n addChild(theOther);\n }\n\n }\n\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6277/" ]
68,447
<p>From the Displays pane in System Preferences, I can manually change the main monitor by dragging the menu bar from one display to the other. I'd like to automate this and make it part of an AppleScript.</p>
[ { "answer_id": 1906298, "author": "Laurent Etiemble", "author_id": 121278, "author_profile": "https://Stackoverflow.com/users/121278", "pm_score": 2, "selected": false, "text": "/Library/Preferences/com.apple.windowserver.plist DisplayMainOnInternal DisplaySets IOFlags /Library/Preferences/com.apple.windowserver.plist /Library/Preferences/com.apple.windowserver.plist DisplaySets IOFlags defaults killall -KILL SystemUIServer" }, { "answer_id": 1911234, "author": "apaderno", "author_id": 225647, "author_profile": "https://Stackoverflow.com/users/225647", "pm_score": 0, "selected": false, "text": "default" }, { "answer_id": 56201151, "author": "Jake Hilborn", "author_id": 1330546, "author_profile": "https://Stackoverflow.com/users/1330546", "pm_score": 3, "selected": false, "text": "displayplacer list origin:(0,0) displayplacer \"id:<leftScreenId> res:1920x1080 scaling:on origin:(0,0) degree:0\" \"id:<rightScreenId> res:1920x1080 scaling:on origin:(1920,0) degree:0\" displayplacer \"id:<leftScreenId> res:1920x1080 scaling:on origin:(1920,0) degree:0\" \"id:<rightScreenId> res:1920x1080 scaling:on origin:(0,0) degree:0\" brew tap jakehilborn/jakehilborn && brew install displayplacer" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6311/" ]
68,477
<p>Is there a way to send a file using POST from a Python script?</p>
[ { "answer_id": 68502, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": false, "text": "urllib2 multipart/form-data user_agent = \"image uploader\"\ndefault_message = \"Image $current of $total\"\n\nimport logging\nimport os\nfrom os.path import abspath, isabs, isdir, isfile, join\nimport random\nimport string\nimport sys\nimport mimetypes\nimport urllib2\nimport httplib\nimport time\nimport re\n\ndef random_string (length):\n return ''.join (random.choice (string.letters) for ii in range (length + 1))\n\ndef encode_multipart_data (data, files):\n boundary = random_string (30)\n\n def get_content_type (filename):\n return mimetypes.guess_type (filename)[0] or 'application/octet-stream'\n\n def encode_field (field_name):\n return ('--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"' % field_name,\n '', str (data [field_name]))\n\n def encode_file (field_name):\n filename = files [field_name]\n return ('--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (field_name, filename),\n 'Content-Type: %s' % get_content_type(filename),\n '', open (filename, 'rb').read ())\n\n lines = []\n for name in data:\n lines.extend (encode_field (name))\n for name in files:\n lines.extend (encode_file (name))\n lines.extend (('--%s--' % boundary, ''))\n body = '\\r\\n'.join (lines)\n\n headers = {'content-type': 'multipart/form-data; boundary=' + boundary,\n 'content-length': str (len (body))}\n\n return body, headers\n\ndef send_post (url, data, files):\n req = urllib2.Request (url)\n connection = httplib.HTTPConnection (req.get_host ())\n connection.request ('POST', req.get_selector (),\n *encode_multipart_data (data, files))\n response = connection.getresponse ()\n logging.debug ('response = %s', response.read ())\n logging.debug ('Code: %s %s', response.status, response.reason)\n\ndef make_upload_file (server, thread, delay = 15, message = None,\n username = None, email = None, password = None):\n\n delay = max (int (delay or '0'), 15)\n\n def upload_file (path, current, total):\n assert isabs (path)\n assert isfile (path)\n\n logging.debug ('Uploading %r to %r', path, server)\n message_template = string.Template (message or default_message)\n\n data = {'MAX_FILE_SIZE': '3145728',\n 'sub': '',\n 'mode': 'regist',\n 'com': message_template.safe_substitute (current = current, total = total),\n 'resto': thread,\n 'name': username or '',\n 'email': email or '',\n 'pwd': password or random_string (20),}\n files = {'upfile': path}\n\n send_post (server, data, files)\n\n logging.info ('Uploaded %r', path)\n rand_delay = random.randint (delay, delay + 5)\n logging.debug ('Sleeping for %.2f seconds------------------------------\\n\\n', rand_delay)\n time.sleep (rand_delay)\n\n return upload_file\n\ndef upload_directory (path, upload_file):\n assert isabs (path)\n assert isdir (path)\n\n matching_filenames = []\n file_matcher = re.compile (r'\\.(?:jpe?g|gif|png)$', re.IGNORECASE)\n\n for dirpath, dirnames, filenames in os.walk (path):\n for name in filenames:\n file_path = join (dirpath, name)\n logging.debug ('Testing file_path %r', file_path)\n if file_matcher.search (file_path):\n matching_filenames.append (file_path)\n else:\n logging.info ('Ignoring non-image file %r', path)\n\n total_count = len (matching_filenames)\n for index, file_path in enumerate (matching_filenames):\n upload_file (file_path, index + 1, total_count)\n\ndef run_upload (options, paths):\n upload_file = make_upload_file (**options)\n\n for arg in paths:\n path = abspath (arg)\n if isdir (path):\n upload_directory (path, upload_file)\n elif isfile (path):\n upload_file (path)\n else:\n logging.error ('No such path: %r' % path)\n\n logging.info ('Done!')\n" }, { "answer_id": 525193, "author": "gotgenes", "author_id": 38140, "author_profile": "https://Stackoverflow.com/users/38140", "pm_score": 2, "selected": false, "text": "poster.encode.multipart_encode()" }, { "answer_id": 7969778, "author": "ilmarinen", "author_id": 1024114, "author_profile": "https://Stackoverflow.com/users/1024114", "pm_score": 2, "selected": false, "text": "import os\nimport urllib2\nclass EnhancedFile(file):\n def __init__(self, *args, **keyws):\n file.__init__(self, *args, **keyws)\n\n def __len__(self):\n return int(os.fstat(self.fileno())[6])\n\ntheFile = EnhancedFile('a.xml', 'r')\ntheUrl = \"http://example.com/abcde\"\ntheHeaders= {'Content-Type': 'text/xml'}\n\ntheRequest = urllib2.Request(theUrl, theFile, theHeaders)\n\nresponse = urllib2.urlopen(theRequest)\n\ntheFile.close()\n\n\nfor line in response:\n print line\n" }, { "answer_id": 10234640, "author": "Piotr Dobrogost", "author_id": 95735, "author_profile": "https://Stackoverflow.com/users/95735", "pm_score": 8, "selected": false, "text": "with open('report.xls', 'rb') as f:\n r = requests.post('http://httpbin.org/post', files={'report.xls': f})\n >>> r.text\n{\n \"origin\": \"179.13.100.4\",\n \"files\": {\n \"report.xls\": \"<censored...binary...data>\"\n },\n \"form\": {},\n \"url\": \"http://httpbin.org/post\",\n \"args\": {},\n \"headers\": {\n \"Content-Length\": \"3196\",\n \"Accept-Encoding\": \"identity, deflate, compress, gzip\",\n \"Accept\": \"*/*\",\n \"User-Agent\": \"python-requests/0.8.0\",\n \"Host\": \"httpbin.org:80\",\n \"Content-Type\": \"multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1\"\n },\n \"data\": \"\"\n}\n" }, { "answer_id": 31305207, "author": "rye", "author_id": 5091149, "author_profile": "https://Stackoverflow.com/users/5091149", "pm_score": 3, "selected": false, "text": "requests-toolbelt" }, { "answer_id": 36078069, "author": "user6081103", "author_id": 6081103, "author_profile": "https://Stackoverflow.com/users/6081103", "pm_score": 0, "selected": false, "text": "def visit_v2(device_code, camera_code):\n image1 = MultipartParam.from_file(\"files\", \"/home/yuzx/1.txt\")\n image2 = MultipartParam.from_file(\"files\", \"/home/yuzx/2.txt\")\n datagen, headers = multipart_encode([('device_code', device_code), ('position', 3), ('person_data', person_data), image1, image2])\n print \"\".join(datagen)\n if server_port == 80:\n port_str = \"\"\n else:\n port_str = \":%s\" % (server_port,)\n url_str = \"http://\" + server_ip + port_str + \"/adopen/device/visit_v2\"\n headers['nothing'] = 'nothing'\n request = urllib2.Request(url_str, datagen, headers)\n try:\n response = urllib2.urlopen(request)\n resp = response.read()\n print \"http_status =\", response.code\n result = json.loads(resp)\n print resp\n return result\n except urllib2.HTTPError, e:\n print \"http_status =\", e.code\n print e.read()\n" }, { "answer_id": 37142773, "author": "Ranvijay Sachan", "author_id": 2654232, "author_profile": "https://Stackoverflow.com/users/2654232", "pm_score": 2, "selected": false, "text": "def test_upload_file(self):\n filename = \"/Users/Ranvijay/tests/test_price_matrix.csv\"\n data = {'file': open(filename, 'rb')}\n client = APIClient()\n # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n response = client.post(reverse('price-matrix-csv'), data, format='multipart')\n\n print response\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n" }, { "answer_id": 67273481, "author": "Станислав Тышко", "author_id": 15771153, "author_profile": "https://Stackoverflow.com/users/15771153", "pm_score": 1, "selected": false, "text": "pip install http_file #импорт вспомогательных библиотек\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nimport requests\n#импорт http_file\nfrom http_file import download_file\n#создание новой сессии\ns = requests.Session()\n#соеденение с сервером через созданную сессию\ns.get('URL_MAIN', verify=False)\n#загрузка файла в 'local_filename' из 'fileUrl' через созданную сессию\ndownload_file('local_filename', 'fileUrl', s)\n" }, { "answer_id": 74142597, "author": "xCovelus", "author_id": 1550930, "author_profile": "https://Stackoverflow.com/users/1550930", "pm_score": 0, "selected": false, "text": "import requests\n\nurl = 'http://127.0.0.1:54321/upload'\nfile_to_send = '25893538.pdf'\n\nfiles = {'file': (file_to_send,\n open(file_to_send, 'rb'),\n 'application/pdf',\n {'Expires': '0'})}\n\nreply = requests.post(url=url, files=files)\nprint(reply.text)\n import os\nfrom flask import Flask, request, render_template\n\nrx_file_listener = Flask(__name__)\n\nfiles_store = \"/tmp\"\n@rx_file_listener.route(\"/upload\", methods=['POST'])\ndef upload_file():\n storage = os.path.join(files_store, \"uploaded/\")\n print(storage)\n \n if not os.path.isdir(storage):\n os.mkdir(storage)\n\n try:\n for file_rx in request.files.getlist(\"file\"):\n name = file_rx.filename\n destination = \"/\".join([storage, name])\n file_rx.save(destination)\n \n return \"200\"\n except Exception:\n return \"500\"\n\nif __name__ == \"__main__\":\n rx_file_listener.run(port=54321, debug=True)\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
68,485
<p>In <b>Prototype</b> I can show a "loading..." image with this code:</p> <pre><code>var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); function showLoad () { ... } </code></pre> <p>In <b>jQuery</b>, I can load a server page into an element with this:</p> <pre><code>$('#message').load('index.php?pg=ajaxFlashcard'); </code></pre> <p>but how do I attach a loading spinner to this command as I did in Prototype?</p>
[ { "answer_id": 68503, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 11, "selected": true, "text": "$('#loadingDiv')\n .hide() // Hide it initially\n .ajaxStart(function() {\n $(this).show();\n })\n .ajaxStop(function() {\n $(this).hide();\n })\n;\n .ajaxStart/Stop document var $loading = $('#loadingDiv').hide();\n$(document)\n .ajaxStart(function () {\n $loading.show();\n })\n .ajaxStop(function () {\n $loading.hide();\n });\n" }, { "answer_id": 68517, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 4, "selected": false, "text": "$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);\nshowLoad();\n\nfunction showResponse() {\n hideLoad();\n ...\n}\n" }, { "answer_id": 68546, "author": "Josh Stodola", "author_id": 54420, "author_profile": "https://Stackoverflow.com/users/54420", "pm_score": 5, "selected": false, "text": "$(\"#myDiv\").html('<img src=\"images/spinner.gif\" alt=\"Wait\" />');\n$('#message').load('index.php?pg=ajaxFlashcard', null, function() {\n $(\"#myDiv\").html('');\n});\n" }, { "answer_id": 238563, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$.listen('click', '#captcha', function() {\n $('#captcha-block').html('<div id=\"loading\" style=\"width: 70px; height: 40px; display: inline-block;\" />');\n $.get(\"/captcha/new\", null, function(data) {\n $('#captcha-block').html(data);\n }); \n return false;\n});\n #loading { background: url(/image/loading.gif) no-repeat center; }\n" }, { "answer_id": 1201403, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 4, "selected": false, "text": "$.loading.onAjax({img:'loading.gif'});\n" }, { "answer_id": 2387709, "author": "kr00lix", "author_id": 183887, "author_profile": "https://Stackoverflow.com/users/183887", "pm_score": 8, "selected": false, "text": "jQuery.ajaxSetup({\n beforeSend: function() {\n $('#loader').show();\n },\n complete: function(){\n $('#loader').hide();\n },\n success: function() {}\n});\n" }, { "answer_id": 5863245, "author": "Paul", "author_id": 735217, "author_profile": "https://Stackoverflow.com/users/735217", "pm_score": 3, "selected": false, "text": "jQuery.ajaxSetup({\n beforeSend: function() {\n $('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')\n },\n complete: function(){\n $('#logo').css('background', 'none')\n },\n success: function() {}\n});\n" }, { "answer_id": 7389431, "author": "Umesh kumar", "author_id": 940764, "author_profile": "https://Stackoverflow.com/users/940764", "pm_score": 3, "selected": false, "text": "$(\"#message\").html('<span>Loading...</span>');\n\n$('#message').load('index.php?pg=ajaxFlashcard');\n" }, { "answer_id": 7597533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var preloaderdiv = '<div class=\"thumbs_preloader\">Loading...</div>';\n $('#detail_thumbnails').html(preloaderdiv);\n $.ajax({\n async:true,\n url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),\n success:function(data){\n $('#detail_thumbnails').html(data);\n }\n });\n" }, { "answer_id": 8360518, "author": "Quinn Comendant", "author_id": 277303, "author_profile": "https://Stackoverflow.com/users/277303", "pm_score": 2, "selected": false, "text": "$('<div><img src=\"/i/loading.gif\" id=\"loading\" /></div>').load('/ajax.html').dialog({\n height: 300,\n width: 600,\n title: 'Wait for it...'\n});\n" }, { "answer_id": 11454964, "author": "guy mograbi", "author_id": 1068746, "author_profile": "https://Stackoverflow.com/users/1068746", "pm_score": 1, "selected": false, "text": "$(\"#component_to_refresh\").ajax( { ... } ); \n <!-- assume you have this HTML and you would like to refresh \n it / load the content with ajax -->\n\n<span id=\"email\" name=\"name\" class=\"ajax-loading\">\n</span>\n\n<!-- then you have the following javascript --> \n\n$(document).ready(function(){\n $(\"#email\").ajax({'url':\"/my/url\", load:true, global:false});\n })\n jQuery.fn.ajax = function(options)\n{\n var $this = $(this);\n debugger;\n function invokeFunc(func, arguments)\n {\n if ( typeof(func) == \"function\")\n {\n func( arguments ) ;\n }\n }\n\n function _think( obj, think )\n {\n if ( think )\n {\n obj.html('<div class=\"loading\" style=\"background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;\"> Loading ... </div>');\n }\n else\n {\n obj.find(\".loading\").hide();\n }\n }\n\n function makeMeThink( think )\n {\n if ( $this.is(\".ajax-loading\") )\n {\n _think($this,think);\n }\n else\n {\n _think($this, think);\n }\n }\n\n options = $.extend({}, options); // make options not null - ridiculous, but still.\n // read more about ajax events\n var newoptions = $.extend({\n beforeSend: function()\n {\n invokeFunc(options.beforeSend, null);\n makeMeThink(true);\n },\n\n complete: function()\n {\n invokeFunc(options.complete);\n makeMeThink(false);\n },\n success:function(result)\n {\n invokeFunc(options.success);\n if ( options.load )\n {\n $this.html(result);\n }\n }\n\n }, options);\n\n $.ajax(newoptions);\n};\n" }, { "answer_id": 12190482, "author": "Seeker", "author_id": 468202, "author_profile": "https://Stackoverflow.com/users/468202", "pm_score": 6, "selected": false, "text": ".ajax beforeSend jQuery.ajax({\n type: \"POST\",\n url: 'YOU_URL_TO_WHICH_DATA_SEND',\n data:'YOUR_DATA_TO_SEND',\n beforeSend: function() {\n $(\"#loaderDiv\").show();\n },\n success: function(data) {\n $(\"#loaderDiv\").hide();\n }\n});\n" }, { "answer_id": 12268009, "author": "Lee Goddard", "author_id": 418150, "author_profile": "https://Stackoverflow.com/users/418150", "pm_score": 3, "selected": false, "text": "$('#myForm').ajaxSend( function() {\n $(this).addClass('loading');\n});\n$('#myForm').ajaxComplete( function(){\n $(this).removeClass('loading');\n});\n .loading {\n display: block;\n background: url(spinner.gif) no-repeat center middle;\n width: 124px;\n height: 124px;\n margin: 0 auto;\n}\n/* Hide all the children of the 'loading' element */\n.loading * {\n display: none; \n}\n" }, { "answer_id": 15763341, "author": "Emil Stenström", "author_id": 117268, "author_profile": "https://Stackoverflow.com/users/117268", "pm_score": 3, "selected": false, "text": "document $(document)\n .hide() // hide it initially\n .ajaxSend(function(event, jqxhr, settings) {\n if (settings.url !== \"ajax/request.php\") return;\n $(\".spinner\").show();\n })\n .ajaxComplete(function(event, jqxhr, settings) {\n if (settings.url !== \"ajax/request.php\") return;\n $(\".spinner\").hide();\n })\n" }, { "answer_id": 16938360, "author": "Amin Saqi", "author_id": 1814343, "author_profile": "https://Stackoverflow.com/users/1814343", "pm_score": 5, "selected": false, "text": "$.ajax() $.ajax({\n url: \"destination url\",\n success: sdialog,\n error: edialog,\n // shows the loader element before sending.\n beforeSend: function() {\n $(\"#imgSpinner1\").show();\n },\n // hides the loader after completion of request, whether successfull or failor. \n complete: function() {\n $(\"#imgSpinner1\").hide();\n },\n type: 'POST',\n dataType: 'json'\n});\n .show() type: 'GET'" }, { "answer_id": 19910389, "author": "Fred K", "author_id": 1252920, "author_profile": "https://Stackoverflow.com/users/1252920", "pm_score": 2, "selected": false, "text": "$(document).ajaxStart(function() {\n $(\".loading\").show();\n});\n\n$(document).ajaxStop(function() {\n $(\".loading\").hide();\n});\n $(document).ajaxStart ->\n $(\".loading\").show()\n\n $(document).ajaxStop ->\n $(\".loading\").hide()\n" }, { "answer_id": 21930015, "author": "Brendan Vogt", "author_id": 225799, "author_profile": "https://Stackoverflow.com/users/225799", "pm_score": 3, "selected": false, "text": "<style>\n #ajaxSpinnerImage {\n display: none;\n }\n</style>\n\n<div id=\"ajaxSpinnerContainer\">\n <img src=\"~/Content/ajax-loader.gif\" id=\"ajaxSpinnerImage\" title=\"working...\" />\n</div>\n <script>\n $(document).ready(function () {\n $(document)\n .ajaxStart(function () {\n $(\"#ajaxSpinnerImage\").show();\n })\n .ajaxStop(function () {\n $(\"#ajaxSpinnerImage\").hide();\n });\n\n var owmAPI = \"http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID\";\n $.getJSON(owmAPI)\n .done(function (data) {\n alert(data.coord.lon);\n })\n .fail(function () {\n alert('error');\n });\n });\n</script>\n" }, { "answer_id": 26523067, "author": "Shane Rowatt", "author_id": 1273319, "author_profile": "https://Stackoverflow.com/users/1273319", "pm_score": 2, "selected": false, "text": "$.ajax({\n url: requestUrl,\n data: data,\n dataType: 'JSON',\n processData: false,\n type: requestMethod,\n async: true, <<<<<<------ set async to true\n accepts: 'application/json',\n contentType: 'application/json',\n success: function (restResponse) {\n // something here\n },\n error: function (restResponse) {\n // something here \n }\n });\n" }, { "answer_id": 35783093, "author": "ling", "author_id": 405042, "author_profile": "https://Stackoverflow.com/users/405042", "pm_score": 1, "selected": false, "text": " jTarget.ajaxloader(); // (re)start the loader\n $.post('/libs/jajaxloader/demo/service/service.php', function (content) {\n jTarget.append(content); // or do something with the content\n })\n .always(function () {\n jTarget.ajaxloader(\"stop\");\n });\n" }, { "answer_id": 39982956, "author": "Izabela Skibinska", "author_id": 2176086, "author_profile": "https://Stackoverflow.com/users/2176086", "pm_score": 2, "selected": false, "text": "$('#loading-image').html('<img src=\"/images/ajax-loader.gif\"> Sending...');\n\n $.ajax({\n url: uri,\n cache: false,\n success: function(){\n $('#loading-image').html(''); \n },\n\n error: function(jqXHR, textStatus, errorThrown) {\n var text = \"Error has occured when submitting the job: \"+jqXHR.status+ \" Contact IT dept\";\n $('#loading-image').html('<span style=\"color:red\">'+text +' </span>');\n\n }\n });\n" }, { "answer_id": 50678783, "author": "Jaggan_j", "author_id": 2093481, "author_profile": "https://Stackoverflow.com/users/2093481", "pm_score": 1, "selected": false, "text": "$.ajax({\n url: \"@Url.Action(\"MyJsonAction\", \"Home\")\",\n type: \"POST\",\n dataType: \"json\",\n data: {parameter:variable},\n //async: false, \n\n error: function () {\n },\n\n success: function (data) {\n if (Object.keys(data).length > 0) {\n //use data \n }\n $('#ajaxspinner').hide();\n }\n });\n $(\"#MyDropDownID\").change(function () {\n $('#ajaxspinner').show();\n <i id=\"ajaxspinner\" class=\"fas fa-spinner fa-spin fa-3x fa-fw\" style=\"display:none\"></i>" }, { "answer_id": 72977140, "author": "Ravi Sharma", "author_id": 11027707, "author_profile": "https://Stackoverflow.com/users/11027707", "pm_score": 0, "selected": false, "text": "<script>\n $(window).on('beforeunload', function (e) {\n $(\"#loader\").show();\n });\n $(document).ready(function () {\n $(window).load(function () {\n $(\"#loader\").hide();\n });\n });\n </script>\n\n<div id=\"loader\">\n <img src=\"../images/loader.png\" \n style=\"width:90px;\">\n </div>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
68,509
<p>If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them</p> <pre><code>&lt;a href='&lt;%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %&gt;'&gt;Edit&lt;/a&gt; </code></pre> <p>I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name. My preferred approach is to do something like this</p> <pre><code>&lt;a runat="server" id="MyLink"&gt;Edit&lt;/a&gt; </code></pre> <p>and then in the code behind</p> <pre><code>MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id; </code></pre> <p>I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time.</p>
[ { "answer_id": 70100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<a href='<%# DataBinder.Eval(Container.DataItem,\"Id\",\"\"/Admin/Content/EditResource.aspx?ResourceId={0}\") %'>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6084/" ]
68,537
<p>A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;</p> <p><em>Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.</em></p> <p><em>Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.</em></p> <p>A very rough pseudo code example follows:</p> <pre><code>public interface ITerrain { void AffectUnit(IUnit unit); } public class Water : ITerrain { public void AffectUnit(IUnit unit) { if (unit is HoverCraft) { // Don't affect it anyhow } if (unit is FootSoldier) { unit.SpeedMultiplier = 0.75f; } if (unit is Jeep) { unit.SpeedMultiplier = 0.70f; unit.Health -= 5.0f; } if (unit is Boat) { // Don't affect it anyhow } /* * List grows larger each day... */ } } public class Grass : ITerrain { public void AffectUnit(IUnit unit) { if (unit is HoverCraft) { // Don't affect it anyhow } if (unit is FootSoldier) { unit.SpeedMultiplier = 0.95f; } if (unit is Jeep) { unit.SpeedMultiplier = 0.85f; } if (unit is Boat) { unit.SpeedMultiplier = 0.0f; unit.Health = 0.0f; Boat boat = unit as Boat; boat.DamagePropeller(); // Perhaps throw in an explosion aswell? } /* * List grows larger each day... */ } } </code></pre> <p>As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface. </p> <p>Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. <em>An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.</em></p> <p>I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.</p> <p>Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together?</p>
[ { "answer_id": 68560, "author": "Jiaaro", "author_id": 2908, "author_profile": "https://Stackoverflow.com/users/2908", "pm_score": 0, "selected": false, "text": " boat = new\niUnit(\"watercraft\") field = new\niTerrain(\"grass\")\nfield.effects(boat) \npublic class hovercraft : unit {\n #You make a base class for defaults and redefine as necessary\n speed_multiplier.water = 1\n}\n\npublic class boat : unit {\n speed_multiplier.land = 0\n}\n" }, { "answer_id": 68888, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 1, "selected": false, "text": "public class Base\n{\n public virtual void Go() { Console.WriteLine(\"in Base\"); }\n}\n\npublic class Derived : Base\n{\n public virtual void Go() { Console.WriteLine(\"in Derived\"); }\n}\n public void Test()\n{\n Base obj = new Derived();\n obj.Go();\n}\n public class TestClass\n{\n public void Go(Base b)\n {\n Console.WriteLine(\"Base arg\");\n }\n\n public void Go(Derived d)\n {\n Console.WriteLine(\"Derived arg\");\n }\n\n public void Test()\n {\n Base obj = new Derived();\n Go(obj);\n }\n}\n public class Dispatcher\n{\n public void Dispatch(IUnit unit, ITerrain terrain)\n {\n Type unitType = unit.GetType();\n Type terrainType = terrain.GetType();\n\n // go through the list and find the action that corresponds to the\n // most-derived IUnit and ITerrain types that are in the ancestor\n // chain for unitType and terrainType.\n Action<IUnit, ITerrain> action = /* left as exercise for reader ;) */\n\n action(unit, terrain);\n }\n\n // add functions to this\n public List<Action<IUnit, ITerrain>> Actions = new List<Action<IUnit, ITerrain>>();\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2166173/" ]
68,541
<p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p> <p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
[ { "answer_id": 69513, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 2, "selected": false, "text": "'echo $PATH'\n" }, { "answer_id": 77114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "PATH" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,543
<p>So, I am kinda new to ASP.net development still, and I already don't like the stock ASP.net controls for displaying my database query results in table format. (I.e. I would much rather handle the HTML myself and so would the designer!)</p> <p>So my question is: What is the best and most secure practice for doing this without using ASP.net controls? So far my only idea involves populating my query result during the Page_Load event and then exposing a DataTable through a getter to the *.aspx page. From there I think I could just iterate with a foreach loop and craft my table as I see fit.</p>
[ { "answer_id": 68556, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 3, "selected": true, "text": "<Repeater>" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506/" ]
68,561
<p>1, Create and build a default Windows Forms project and look at the project properties. It says that the project is targetting .NET Framework 2.0. </p> <p>2, Create a Setup project that installs just the single executable from the Windows Forms project. </p> <p>3, Run that installer and it always says that it needs to install .NET 3.5 SP1 on the machine. But it obviously only really needs 2.0 and so I do not want customers to be forced to install .NET 3.5 when they do not need it. They might already have 2.0 installed and so forcing the upgrade is not desirable!</p> <p>I have looked at the prerequisites of the setup project and checked the .NET Framework 2.0 entry and all the rest are unchecked. So I cannot find any reason for this strange runtime requirement. Anybody know how to resolve this one?</p>
[ { "answer_id": 71018, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 1, "selected": false, "text": "\"Deployable\"\n{\n \"CustomAction\"\n {\n }\n \"DefaultFeature\"\n {\n \"Name\" = \"8:DefaultFeature\"\n \"Title\" = \"8:\"\n \"Description\" = \"8:\"\n }\n \"ExternalPersistence\"\n {\n \"LaunchCondition\"\n {\n \"{A06ECF26-33A3-4562-8140-9B0E340D4F24}:_FC497D835F7243569DCCC3E3ACE4196D\"\n {\n \"Name\" = \"8:.NET Framework\"\n \"Message\" = \"8:[VSDNETMSG]\"\n \"Version\" = \"8:3.5.30729\" <--- UPDATE THIS TO 8:2.0.50727\n \"AllowLaterVersions\" = \"11:FALSE\"\n \"InstallUrl\" = \"8:http://go.microsoft.com/fwlink/?LinkId=76617\"\n }\n }\n }\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
68,565
<p>I like the XMLReader class for it's simplicity and speed. But I like the xml_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning.</p>
[ { "answer_id": 68615, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "<p>\n Here is <strong>a very simple</strong> XML document.\n</p>\n" }, { "answer_id": 77607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$simplexml = simplexml_load_string(\"<xml></xml>\");\n$simplexml->simple = \"it is simple.\";\n\n$domxml = dom_import_simplexml($simplexml);\n$node = $domxml->ownerDocument->createElement(\"dom\", \"yes, with DOM too.\");\n$domxml->ownerDocument->firstChild->appendChild($node);\n\necho (string)$simplexml->dom;\n \"yes, with DOM too.\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,569
<p>I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection. </p> <p>I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. </p>
[ { "answer_id": 68591, "author": "dawnerd", "author_id": 69503, "author_profile": "https://Stackoverflow.com/users/69503", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\n.watermark{background:url(urltoimage.png);}\n</style>\n<div class=\"watermark\">\n<p>this is some text with the watermark as the background.</p>\n</div>\n" }, { "answer_id": 2486786, "author": "user136776", "author_id": 136776, "author_profile": "https://Stackoverflow.com/users/136776", "pm_score": 5, "selected": false, "text": "<style type=\"text/css\">\n#watermark {\n color: #d0d0d0;\n font-size: 200pt;\n -webkit-transform: rotate(-45deg);\n -moz-transform: rotate(-45deg);\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: -1;\n left:-100px;\n top:-200px;\n}\n</style>\n <div id=\"watermark\">\n<p>This is the test version.</p>\n</div>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10755/" ]
68,572
<p>I have a question that I may be over thinking at this point but here goes...</p> <p>I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization). </p> <p><strong>Would you recommend creating a class for the join table as well as the User and Groups table?</strong> Currently my classes look like this.</p> <pre><code>public class Groups { public Groups() { members = new List&lt;Person&gt;(); } ... public virtual IList&lt;Person&gt; members { get; set; } } public class User { public User() { groups = new Groups() } ... public virtual IList&lt;Groups&gt; groups{ get; set; } } </code></pre> <p>My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar):</p> <pre><code>HasManyToMany&lt;Groups&gt;(x =&gt; x.Groups) .WithTableName("GroupMembers") .WithParentKeyColumn("UserID") .WithChildKeyColumn("GroupID") .Cascade.SaveUpdate(); </code></pre> <p><strong>Should I write a class for the join table that looks like this?</strong></p> <pre><code>public class GroupMembers { public virtual string GroupID { get; set; } public virtual string PersonID { get; set; } public virtual bool WaitingForAccept { get; set; } } </code></pre> <p>I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. </p>
[ { "answer_id": 68591, "author": "dawnerd", "author_id": 69503, "author_profile": "https://Stackoverflow.com/users/69503", "pm_score": 2, "selected": false, "text": "<style type=\"text/css\">\n.watermark{background:url(urltoimage.png);}\n</style>\n<div class=\"watermark\">\n<p>this is some text with the watermark as the background.</p>\n</div>\n" }, { "answer_id": 2486786, "author": "user136776", "author_id": 136776, "author_profile": "https://Stackoverflow.com/users/136776", "pm_score": 5, "selected": false, "text": "<style type=\"text/css\">\n#watermark {\n color: #d0d0d0;\n font-size: 200pt;\n -webkit-transform: rotate(-45deg);\n -moz-transform: rotate(-45deg);\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: -1;\n left:-100px;\n top:-200px;\n}\n</style>\n <div id=\"watermark\">\n<p>This is the test version.</p>\n</div>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385358/" ]
68,578
<p>Is there a way to fall through multiple case statements without stating <code>case value:</code> repeatedly?</p> <p>I know this works:</p> <pre><code>switch (value) { case 1: case 2: case 3: // Do some stuff break; case 4: case 5: case 6: // Do some different stuff break; default: // Default stuff break; } </code></pre> <p>but I'd like to do something like this:</p> <pre><code>switch (value) { case 1,2,3: // Do something break; case 4,5,6: // Do something break; default: // Do the Default break; } </code></pre> <p>Is this syntax I'm thinking of from a different language, or am I missing something?</p>
[ { "answer_id": 68620, "author": "Neal", "author_id": 7071, "author_profile": "https://Stackoverflow.com/users/7071", "pm_score": 6, "selected": false, "text": "Dim number As Integer = 8\nSelect Case number\n Case 1 To 5\n Debug.WriteLine(\"Between 1 and 5, inclusive\")\n ' The following is the only Case clause that evaluates to True.\n Case 6, 7, 8\n Debug.WriteLine(\"Between 6 and 8, inclusive\")\n Case Is < 1\n Debug.WriteLine(\"Equal to 9 or 10\")\n Case Else\n Debug.WriteLine(\"Not between 1 and 10, inclusive\")\nEnd Select\n" }, { "answer_id": 68829, "author": "Cyber Oliveira", "author_id": 9793, "author_profile": "https://Stackoverflow.com/users/9793", "pm_score": 3, "selected": false, "text": "\nstring s = foo();\n\nswitch (s) {\n case \"abc\": /*...*/ break;\n case \"def\": /*...*/ break;\n}\n" }, { "answer_id": 69047, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 3, "selected": false, "text": "switch (value)\n{\n case 1...3:\n //Do Something\n break;\n case 4...6:\n //Do Something\n break;\n default:\n //Do the Default\n break;\n}\n" }, { "answer_id": 69106, "author": "Allan Wind", "author_id": 9706, "author_profile": "https://Stackoverflow.com/users/9706", "pm_score": 5, "selected": false, "text": "case 1: case 2: case 3:\n break;\n" }, { "answer_id": 69173, "author": "Dr8k", "author_id": 6014, "author_profile": "https://Stackoverflow.com/users/6014", "pm_score": 3, "selected": false, "text": "switch (x)\n{\n case 1:\n DoSomething();\n break;\n case 2:\n DoSomething();\n break;\n case 3:\n DoSomething();\n break;\n ...\n}\n\nprivate void DoSomething()\n{\n ...\n}\n switch (x)\n{\n case 1:\n case 2:\n case 3:\n DoSomething();\n break;\n ...\n}\n\nprivate void DoSomething()\n{\n ...\n}\n" }, { "answer_id": 71023, "author": "Luca Molteni", "author_id": 4206, "author_profile": "https://Stackoverflow.com/users/4206", "pm_score": 4, "selected": false, "text": "int c = 2;\nif(Enumerable.Range(0,10).Contains(c))\n DoThing();\nelse if(Enumerable.Range(11,20).Contains(c))\n DoAnotherThing();\n public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)\n{\n if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))\n action();\n}\n MySwitchWithEnumerable(c, 0, 10, DoThing);\nMySwitchWithEnumerable(c, 10, 20, DoAnotherThing);\n Action Action<ParameterType> Func<ParameterType, ReturnType> public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){ \n MySwitchWithEnumerable(3, startNumber, endNumber, action); \n}\n" }, { "answer_id": 3382204, "author": "Carlos Quintanilla", "author_id": 407944, "author_profile": "https://Stackoverflow.com/users/407944", "pm_score": 10, "selected": false, "text": "switch (value)\n{\n case 1: case 2: case 3: \n // Do Something\n break;\n case 4: case 5: case 6: \n // Do Something\n break;\n default:\n // Do Something\n break;\n}\n" }, { "answer_id": 6637962, "author": "scone", "author_id": 421329, "author_profile": "https://Stackoverflow.com/users/421329", "pm_score": -1, "selected": false, "text": " switch(value){\n case 1:\n goto case 3;\n case 2:\n goto case 3;\n case 3:\n DoCase123();\n //This would work too, but I'm not sure if it's slower\n case 4:\n goto case 5;\n case 5:\n goto case 6;\n case 6:\n goto case 7;\n case 7:\n DoCase4567();\n }\n" }, { "answer_id": 7345127, "author": "Jiří Herník", "author_id": 905959, "author_profile": "https://Stackoverflow.com/users/905959", "pm_score": 2, "selected": false, "text": "switch (i) {\ncase 0:\n CaseZero();\n break;\ncase 1:\n CaseOne();\n break;\ndefault:\n CaseOthers();\n break;\n}\n switch (i) {\ncase 0:\n CaseZero();\ncase 1:\n CaseZeroOrOne();\ndefault:\n CaseAny();\n}\n switch (i) {\ncase 0:\n CaseZero();\n goto case 1;\ncase 1:\n CaseZeroOrOne();\n goto default;\ndefault:\n CaseAny();\n break;\n}\n switch (i) {\ncase 0:\n CaseZero();\n break;\ncase 1:\n CaseOne();\n break;\ncase 2:\ndefault:\n CaseTwo();\n break;\n}\n" }, { "answer_id": 9408179, "author": "Darin", "author_id": 1227621, "author_profile": "https://Stackoverflow.com/users/1227621", "pm_score": 2, "selected": false, "text": " bool[] Primes = new bool[] {\n false, false, true, true, false, true, false, \n true, false, false, false, true, false, true,\n false,false,false,true,false,true,false};\n private void button1_Click(object sender, EventArgs e) {\n int Value = Convert.ToInt32(textBox1.Text);\n if ((Value >= 0) && (Value < Primes.Length)) {\n bool IsPrime = Primes[Value];\n textBox2.Text = IsPrime.ToString();\n }\n }\n private void textBox2_TextChanged(object sender, EventArgs e) {\n try {\n textBox1.Text = (\"0123456789ABCDEFGabcdefg\".IndexOf(textBox2.Text[0]) >= 0).ToString();\n } catch {\n }\n }\n" }, { "answer_id": 13214755, "author": "none", "author_id": 1682740, "author_profile": "https://Stackoverflow.com/users/1682740", "pm_score": 4, "selected": false, "text": "case 1 | 3 | 5:\n// Not working do something\n case 1: case 2: case 3:\n// Do something\nbreak;\n none switch if else Select Case" }, { "answer_id": 44848705, "author": "Steve Gomez", "author_id": 3180489, "author_profile": "https://Stackoverflow.com/users/3180489", "pm_score": 7, "selected": false, "text": "int i = 5;\n\nswitch (i)\n{\n case int n when (n >= 7):\n Console.WriteLine($\"I am 7 or above: {n}\");\n break;\n\n case int n when (n >= 4 && n <= 6 ):\n Console.WriteLine($\"I am between 4 and 6: {n}\");\n break;\n\n case int n when (n <= 3):\n Console.WriteLine($\"I am 3 or less: {n}\");\n break;\n}\n\n// Output: I am between 4 and 6: 5\n ( ) when var int case var n when n >= 7: switch(myValue)\n{\n case <= 0:\n Console.WriteLine(\"Less than or equal to 0\");\n break;\n case > 0 and <= 10:\n Console.WriteLine(\"More than 0 but less than or equal to 10\");\n break;\n default:\n Console.WriteLine(\"More than 10\");\n break;\n}\n var message = myValue switch\n{\n <= 0 => \"Less than or equal to 0\",\n > 0 and <= 10 => \"More than 0 but less than or equal to 10\",\n _ => \"More than 10\"\n};\nConsole.WriteLine(message);\n" }, { "answer_id": 49560460, "author": "Maxter", "author_id": 9448877, "author_profile": "https://Stackoverflow.com/users/9448877", "pm_score": 2, "selected": false, "text": "switch (stringValue)\n{\n case \"cat\":\n case \"dog\":\n case \"string3\":\n ...\n case \"+1000 more string\": // Too many string to write a case for all!\n // Do something;\n case \"a lonely case\"\n // Do something else;\n .\n .\n .\n}\n if // Define all the similar \"case\" string in a List\nList<string> listString = new List<string>(){ \"cat\", \"dog\", \"string3\", \"+1000 more string\"};\n// Use string.Contains to find what you are looking for\nif (listString.Contains(stringValue))\n{\n // Do something;\n}\nelse\n{\n // Then go back to a switch statement inside the else for the remaining cases if you really need to\n}\n" }, { "answer_id": 53951944, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 4, "selected": false, "text": "switch (value)\n{\n case var s when new[] { 1,2,3 }.Contains(s):\n // Do something\n break;\n case var s when new[] { 4,5,6 }.Contains(s):\n // Do something\n break;\n default:\n // Do the default\n break;\n}\n switch (mystring)\n{\n case var s when new[] { \"Alpha\",\"Beta\",\"Gamma\" }.Contains(s):\n // Do something\n break;\n...\n}\n" }, { "answer_id": 56861502, "author": "JeffS", "author_id": 935140, "author_profile": "https://Stackoverflow.com/users/935140", "pm_score": 1, "selected": false, "text": " switch (value)\n {\n case string a when a.Contains(\"text1\"):\n // Do Something\n break;\n case string b when b.Contains(\"text3\") || b.Contains(\"text4\") || b.Contains(\"text5\"):\n // Do Something else\n break;\n default:\n // Or do this by default\n break;\n }\n string[] statuses = { \"text3\", \"text4\", \"text5\"};\n\n switch (value)\n {\n case string a when a.Contains(\"text1\"):\n // Do Something\n break;\n case string b when statuses.Contains(value): \n // Do Something else\n break;\n default:\n // Or do this by default\n break;\n }\n" }, { "answer_id": 57801972, "author": "Luke T O'Brien", "author_id": 2137483, "author_profile": "https://Stackoverflow.com/users/2137483", "pm_score": 3, "selected": false, "text": "switch (age)\n{\n case 50:\n ageBlock = \"the big five-oh\";\n break;\n case var testAge when (new List<int>()\n { 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):\n ageBlock = \"octogenarian\";\n break;\n case var testAge when ((testAge >= 90) & (testAge <= 99)):\n ageBlock = \"nonagenarian\";\n break;\n case var testAge when (testAge >= 100):\n ageBlock = \"centenarian\";\n break;\n default:\n ageBlock = \"just old\";\n break;\n}\n" }, { "answer_id": 61410938, "author": "Vikas Lalwani", "author_id": 3559462, "author_profile": "https://Stackoverflow.com/users/3559462", "pm_score": 2, "selected": false, "text": "switch (value)\n{\n case var s when new[] { 1,2 }.Contains(s):\n // Do something\n break;\n \n default:\n // Do the default\n break;\n }\n int i = 3;\n\n switch (i)\n {\n case int n when (n >= 7):\n Console.WriteLine($\"I am 7 or above: {n}\");\n break;\n\n case int n when (n >= 4 && n <= 6):\n Console.WriteLine($\"I am between 4 and 6: {n}\");\n break;\n\n case int n when (n <= 3):\n Console.WriteLine($\"I am 3 or less: {n}\");\n break;\n }\n" }, { "answer_id": 65864240, "author": "Esset", "author_id": 8055755, "author_profile": "https://Stackoverflow.com/users/8055755", "pm_score": 5, "selected": false, "text": "switch (value)\n{\n case 1 or 2 or 3:\n // Do stuff\n break;\n case 4 or 5 or 6:\n // Do stuff\n break;\n default:\n // Do stuff\n break;\n}\n" }, { "answer_id": 66138570, "author": "AWhatley", "author_id": 1289955, "author_profile": "https://Stackoverflow.com/users/1289955", "pm_score": 2, "selected": false, "text": " bool isTrue = true;\n\n switch (isTrue)\n {\n case bool ifTrue when (ex.Message.Contains(\"not found\")):\n case bool ifTrue when (thing.number = 123):\n case bool ifTrue when (thing.othernumber != 456):\n response.respCode = 5010;\n break;\n case bool ifTrue when (otherthing.text = \"something else\"):\n response.respCode = 5020;\n break;\n default:\n response.respCode = 5000;\n break;\n }\n" }, { "answer_id": 68091589, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 2, "selected": false, "text": "var someOutput = value switch\n{\n >= 1 and <= 3 => <Do some stuff>,\n >= 4 and <= 6 => <Do some different stuff>,\n _ => <Default stuff>\n};\n" }, { "answer_id": 69088932, "author": "Abraham", "author_id": 14487032, "author_profile": "https://Stackoverflow.com/users/14487032", "pm_score": 2, "selected": false, "text": "if ([4, 5, 6, 7].indexOf(value) > -1)\n //Do something\n" }, { "answer_id": 70326316, "author": "Osama Hussain", "author_id": 8513973, "author_profile": "https://Stackoverflow.com/users/8513973", "pm_score": 0, "selected": false, "text": " int i = 209;\n int a = 0;\n switch (a = (i>=1 && i<=100) ? 1 : a){ \n case 1:\n System.out.println (\"The Number is Between 1 to 100 ==> \" + i);\n break;\n default:\n switch (a = (i>100 && i<=200) ? 2 : a) {\n case 2:\n System.out.println(\"This Number is Between 101 to 200 ==> \" + i);\n break;\n \n default:\n switch (a = (i>200 && i<=300) ? 3 : a) {\n case 3:\n System.out.println(\"This Number is Between 201 to 300 ==> \" + i);\n break;\n \n default:\n // You can make as many conditions as you want;\n break;\n }\n }\n \n }\n" }, { "answer_id": 74102541, "author": "Nic", "author_id": 16414383, "author_profile": "https://Stackoverflow.com/users/16414383", "pm_score": 0, "selected": false, "text": "public string GetValue(string name)\n {\n return name switch\n {\n var x when name is \"test1\" || name is \"test2\" => \"finch\",\n \"test2\" => somevalue,\n _ => name\n };\n }\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7870/" ]
68,583
<p>I have the following code snippet.</p> <pre><code>$items['A'] = "Test"; $items['B'] = "Test"; $items['C'] = "Test"; $items['D'] = "Test"; $index = 0; foreach($items as $key =&gt; $value) { echo "$index is a $key containing $value\n"; $index++; } </code></pre> <p>Expected output:</p> <pre><code>0 is a A containing Test 1 is a B containing Test 2 is a C containing Test 3 is a D containing Test </code></pre> <p>Is there a way to leave out the <code>$index</code> variable?</p>
[ { "answer_id": 68647, "author": "dawnerd", "author_id": 69503, "author_profile": "https://Stackoverflow.com/users/69503", "pm_score": 2, "selected": false, "text": "$items[A] = \"Test\";\n$items[B] = \"Test\";\n$items[C] = \"Test\";\n$items[D] = \"Test\";\n\nfor($i=0;$i<count($items);$i++)\n{\n list($key,$value) = each($items[$i]);\n echo \"$i $key contains $value\";\n}\n" }, { "answer_id": 68918, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "$myArr = array();\n$myArr[A] = \"a\"; // \"A\" is assumed.\necho $myArr['A']; // \"a\" - this is expected.\n\ndefine ('A', 'aye');\n\n$myArr2 = array();\n$myArr2[A] = \"a\"; // A is a constant\n\necho $myArr['A']; // error, no key.\nprint_r($myArr);\n\n// Array\n// (\n// [aye] => a\n// )\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264/" ]
68,598
<p>I've seen this done in Borland's <a href="https://en.wikipedia.org/wiki/Turbo_C++" rel="noreferrer">Turbo C++</a> environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?</p>
[ { "answer_id": 68722, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 6, "selected": false, "text": "DragEnter AllowedEffect e.Effect = DragDropEffects.Move DragDrop" }, { "answer_id": 89470, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 9, "selected": false, "text": " public partial class Form1 : Form {\n public Form1() {\n InitializeComponent();\n this.AllowDrop = true;\n this.DragEnter += new DragEventHandler(Form1_DragEnter);\n this.DragDrop += new DragEventHandler(Form1_DragDrop);\n }\n\n void Form1_DragEnter(object sender, DragEventArgs e) {\n if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;\n }\n\n void Form1_DragDrop(object sender, DragEventArgs e) {\n string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n foreach (string file in files) Console.WriteLine(file);\n }\n }\n" }, { "answer_id": 36721291, "author": "CAD bloke", "author_id": 492, "author_profile": "https://Stackoverflow.com/users/492", "pm_score": 3, "selected": false, "text": "*.dwg fileList IEnumerable var fileList = (IList)FileList.ItemsSource;\n private void FileList_OnDrop(object sender, DragEventArgs e)\n {\n var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));\n var files = dropped.ToList();\n\n if (!files.Any())\n return;\n\n foreach (string drop in dropped)\n if (Directory.Exists(drop))\n files.AddRange(Directory.GetFiles(drop, \"*.dwg\", SearchOption.AllDirectories));\n\n foreach (string file in files)\n {\n if (!fileList.Contains(file) && file.ToLower().EndsWith(\".dwg\"))\n fileList.Add(file);\n }\n }\n" }, { "answer_id": 61456003, "author": "Ernest Rutherford", "author_id": 11660685, "author_profile": "https://Stackoverflow.com/users/11660685", "pm_score": 0, "selected": false, "text": "private void YourElementControl_MouseMove(object sender, MouseEventArgs e)\n\n {\n ...\n if (e.Button == MouseButtons.Left)\n {\n DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);\n }\n ...\n }\n {\n ...\n foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))\n {\n File.Copy(path, DirPath + Path.GetFileName(path));\n }\n ...\n }\n" }, { "answer_id": 62944471, "author": "Jack", "author_id": 3646777, "author_profile": "https://Stackoverflow.com/users/3646777", "pm_score": 0, "selected": false, "text": "private void Form1_DragEnter(object sender, DragEventArgs e)\n{\n Console.WriteLine(\"DragEnter!\");\n e.Effect = DragDropEffects.Copy;\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,610
<p>I am having problems getting text within a table to appear centered in IE. </p> <p>In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7. </p> <p>I'm using:</p> <pre class="lang-css prettyprint-override"><code>h2 { font: 300 12px "Helvetica", serif; text-align: center; text-transform: uppercase; } </code></pre> <p>I've also tried adding <code>margin-left:auto;</code>, <code>margin-right:auto</code> and <code>position:relative;</code> </p> <p>to no avail. </p>
[ { "answer_id": 68637, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "text-align: center font" }, { "answer_id": 68643, "author": "1077", "author_id": 10776, "author_profile": "https://Stackoverflow.com/users/10776", "pm_score": 0, "selected": false, "text": "<table style = \"width:400px;border:solid 1px;\">\n <tr>\n <td style = \"text-align:center;\"><h2>hi</h2></td>\n </tr>\n</table>\n" }, { "answer_id": 68678, "author": "Alex Achinfiev", "author_id": 10785, "author_profile": "https://Stackoverflow.com/users/10785", "pm_score": 3, "selected": false, "text": "<div style=\"text-align: center\">\n <h2 style=\"margin: 0 auto\">Some text</h2>\n</div>\n" }, { "answer_id": 68709, "author": "dawnerd", "author_id": 69503, "author_profile": "https://Stackoverflow.com/users/69503", "pm_score": 2, "selected": false, "text": "margin-left:auto; margin-right:auto position:relative;\n margin-left:auto; margin-right:auto; position:relative;\n" }, { "answer_id": 46956006, "author": "Rahi.Shah", "author_id": 7394106, "author_profile": "https://Stackoverflow.com/users/7394106", "pm_score": 0, "selected": false, "text": "display: flex;\njustify-content: center;\nalign-items:center\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10761/" ]
68,614
<p>I have a large application that uses EJB 2.x entity beans (BMP). This is well-known to be a horrible persistence strategy (I can elaborate if necessary).</p> <p>I'd like to start migrating this application to use a much more expressive, transparent, and non-invasive persistence strategy, and given my company's previous experience with it, Hibernate 3.x is the obvious choice.</p> <p>Migrating to Hibernate is going to take a while, as over 100 tables in the application use entity beans. So I'm looking at a phased approach where the two persistence strategies run in parallel, ideally on the same tables at the same time, if possible.</p> <p>My question is, what are the pitfalls (if any) of combining these two persistence strategies? Will they get in each other's way?</p>
[ { "answer_id": 68637, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "text-align: center font" }, { "answer_id": 68643, "author": "1077", "author_id": 10776, "author_profile": "https://Stackoverflow.com/users/10776", "pm_score": 0, "selected": false, "text": "<table style = \"width:400px;border:solid 1px;\">\n <tr>\n <td style = \"text-align:center;\"><h2>hi</h2></td>\n </tr>\n</table>\n" }, { "answer_id": 68678, "author": "Alex Achinfiev", "author_id": 10785, "author_profile": "https://Stackoverflow.com/users/10785", "pm_score": 3, "selected": false, "text": "<div style=\"text-align: center\">\n <h2 style=\"margin: 0 auto\">Some text</h2>\n</div>\n" }, { "answer_id": 68709, "author": "dawnerd", "author_id": 69503, "author_profile": "https://Stackoverflow.com/users/69503", "pm_score": 2, "selected": false, "text": "margin-left:auto; margin-right:auto position:relative;\n margin-left:auto; margin-right:auto; position:relative;\n" }, { "answer_id": 46956006, "author": "Rahi.Shah", "author_id": 7394106, "author_profile": "https://Stackoverflow.com/users/7394106", "pm_score": 0, "selected": false, "text": "display: flex;\njustify-content: center;\nalign-items:center\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10433/" ]
68,617
<p>This is re-posted from something I posted on the DDD Yahoo! group.</p> <p>All things being equal, do you write phone.dial(phoneNumber) or phoneNumber.dialOn(phone)? Keep in mind possible future requirements (account numbers in addition to phone numbers, calculators in addition to phones).</p> <p>The choice tends to illustrate how the idioms of Information Expert, Single Responsibility Principle, and Tell Don't Ask are at odds with each other.</p> <p>phoneNumber.dialOn(phone) favors Information Expert and Tell Don't Ask, while phone.dial(phoneNumber) favors Single Responsibility Principle.</p> <p>If you are familiar with Ken Pugh's work in Prefactoring, this is the <a href="http://moffdub.wordpress.com/2008/09/10/the-spreadsheet-conundrum/" rel="noreferrer">Spreadsheet Conundrum</a>; do you add rows or columns?</p>
[ { "answer_id": 68625, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "phone.dial()" }, { "answer_id": 69023, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "Phone p1 = new Phone(phoneNumber1);\nPhone p2 = new Phone(phoneNumber2);\nConnection conn = new Connection(p1,p2);\nconn.Open();\n//...talk\nconn.Close();\n Connection confCall = new Connection(p1,p2,p3,p4,p5,p6);\nconfCall.Open();\n\nConnection joinCall = new Connection(confCall,p7,p8,conn);\njoinCall.Open();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10759/" ]
68,624
<p>I would like to parse a string such as <code>p1=6&amp;p2=7&amp;p3=8</code> into a <code>NameValueCollection</code>.</p> <p>What is the most elegant way of doing this when you don't have access to the <code>Page.Request</code> object?</p>
[ { "answer_id": 68648, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 10, "selected": true, "text": "// C#\nNameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);\n ' VB.NET\nDim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n querystring new Uri(fullUrl).Query" }, { "answer_id": 68733, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 2, "selected": false, "text": " private void button1_Click( object sender, EventArgs e )\n {\n string s = @\"p1=6&p2=7&p3=8\";\n NameValueCollection nvc = new NameValueCollection();\n\n foreach ( string vp in Regex.Split( s, \"&\" ) )\n {\n string[] singlePair = Regex.Split( vp, \"=\" );\n if ( singlePair.Length == 2 )\n {\n nvc.Add( singlePair[ 0 ], singlePair[ 1 ] ); \n } \n }\n }\n" }, { "answer_id": 68803, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 6, "selected": false, "text": "NameValueCollection queryParameters = new NameValueCollection();\nstring[] querySegments = queryString.Split('&');\nforeach(string segment in querySegments)\n{\n string[] parts = segment.Split('=');\n if (parts.Length > 0)\n {\n string key = parts[0].Trim(new char[] { '?', ' ' });\n string val = parts[1].Trim();\n\n queryParameters.Add(key, val);\n }\n}\n" }, { "answer_id": 1322960, "author": "densom", "author_id": 158581, "author_profile": "https://Stackoverflow.com/users/158581", "pm_score": 4, "selected": false, "text": "public static NameValueCollection ParseQueryString(string s)\n {\n NameValueCollection nvc = new NameValueCollection();\n\n // remove anything other than query string from url\n if(s.Contains(\"?\"))\n {\n s = s.Substring(s.IndexOf('?') + 1);\n }\n\n foreach (string vp in Regex.Split(s, \"&\"))\n {\n string[] singlePair = Regex.Split(vp, \"=\");\n if (singlePair.Length == 2)\n {\n nvc.Add(singlePair[0], singlePair[1]);\n }\n else\n {\n // only one key with no value specified in query string\n nvc.Add(singlePair[0], string.Empty);\n }\n }\n\n return nvc;\n }\n" }, { "answer_id": 8169365, "author": "alex1kirch", "author_id": 991442, "author_profile": "https://Stackoverflow.com/users/991442", "pm_score": 1, "selected": false, "text": "HttpUtility.ParseQueryString(Request.Url.Query) HttpValueCollection NameValueCollection var qs = HttpUtility.ParseQueryString(Request.Url.Query);\n qs.Remove(\"foo\"); \n\n string url = \"~/Default.aspx\"; \n if (qs.Count > 0)\n url = url + \"?\" + qs.ToString();\n\n Response.Redirect(url); \n" }, { "answer_id": 16565615, "author": "Josh Brown", "author_id": 341536, "author_profile": "https://Stackoverflow.com/users/341536", "pm_score": 3, "selected": false, "text": "Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection\n Dim result = New System.Collections.Specialized.NameValueCollection(4)\n Dim query = uri.Query\n If Not String.IsNullOrEmpty(query) Then\n Dim pairs = query.Substring(1).Split(\"&\"c)\n For Each pair In pairs\n Dim parts = pair.Split({\"=\"c}, 2)\n\n Dim name = System.Uri.UnescapeDataString(parts(0))\n Dim value = If(parts.Length = 1, String.Empty,\n System.Uri.UnescapeDataString(parts(1)))\n\n result.Add(name, value)\n Next\n End If\n Return result\nEnd Function\n <Extension()>" }, { "answer_id": 19893289, "author": "Farhawd", "author_id": 998276, "author_profile": "https://Stackoverflow.com/users/998276", "pm_score": -1, "selected": false, "text": "public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )\n{\n System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);\n if (ItemToRemoveOrInsert != null)\n {\n filtered.Remove(ItemToRemoveOrInsert);\n if (!string.IsNullOrWhiteSpace(InsertValue))\n {\n filtered.Add(ItemToRemoveOrInsert, InsertValue);\n }\n }\n\n string StrQr = string.Join(\"&\", filtered.AllKeys.Select(key => key + \"=\" + filtered[key]).ToArray());\n if (!string.IsNullOrWhiteSpace(StrQr)){\n StrQr=\"?\" + StrQr;\n }\n\n return StrQr;\n}\n" }, { "answer_id": 21309603, "author": "Tiele Declercq", "author_id": 1683154, "author_profile": "https://Stackoverflow.com/users/1683154", "pm_score": 1, "selected": false, "text": "System.Web public static class Statics\n public static Dictionary<string, string> QueryParse(string url)\n {\n Dictionary<string, string> qDict = new Dictionary<string, string>();\n foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))\n {\n string[] qVal = qPair.Split('=');\n qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));\n }\n return qDict;\n }\n\n public static string QueryGet(string url, string param)\n {\n var qDict = QueryParse(url);\n return qDict[param];\n }\n}\n Statics.QueryGet(url, \"id\")\n" }, { "answer_id": 22167748, "author": "James Skimming", "author_id": 495964, "author_profile": "https://Stackoverflow.com/users/495964", "pm_score": 5, "selected": false, "text": "var uri = new Uri(\"https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8\");\nNameValueCollection query = uri.ParseQueryString();\n" }, { "answer_id": 24921357, "author": "Thomas Levesque", "author_id": 98713, "author_profile": "https://Stackoverflow.com/users/98713", "pm_score": 2, "selected": false, "text": "ParseQueryString Uri HttpValueCollection var parameters = uri.ParseQueryString();\nstring foo = parameters[\"foo\"];\n" }, { "answer_id": 28693490, "author": "mirko cro 1234", "author_id": 3386904, "author_profile": "https://Stackoverflow.com/users/3386904", "pm_score": 0, "selected": false, "text": " Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n\nDim sb As New StringBuilder(\"<br />\")\nFor Each s As String In qscoll.AllKeys\n\n Response.Write(s & \" - \" & qscoll(s) & \"<br />\")\n\nNext s\n" }, { "answer_id": 33224447, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 3, "selected": false, "text": "System.Web System.Net.Http.Formatting using System.Net.Http; new Uri(uri).ParseQueryString()\n" }, { "answer_id": 34920103, "author": "Hamit YILDIRIM", "author_id": 914284, "author_profile": "https://Stackoverflow.com/users/914284", "pm_score": 0, "selected": false, "text": " var q = Request.QueryString;\n NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());\n" }, { "answer_id": 38171014, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "HttpUtility.ParseQueryString" }, { "answer_id": 39055664, "author": "elgoya", "author_id": 1828356, "author_profile": "https://Stackoverflow.com/users/1828356", "pm_score": -1, "selected": false, "text": "private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)\n{\n var result = new System.Collections.Specialized.NameValueCollection(4);\n var query = uri.Query;\n if (!String.IsNullOrEmpty(query))\n {\n var pairs = query.Substring(1).Split(\"&\".ToCharArray());\n foreach (var pair in pairs)\n {\n var parts = pair.Split(\"=\".ToCharArray(), 2);\n var name = System.Uri.UnescapeDataString(parts[0]);\n var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);\n result.Add(name, value);\n }\n }\n return result;\n}\n" }, { "answer_id": 45716527, "author": "Amadeus Sánchez", "author_id": 1698964, "author_profile": "https://Stackoverflow.com/users/1698964", "pm_score": 2, "selected": false, "text": "Uri ParseQueryString System.Net.Http System.Net.Http Uri ParseQueryString System.Net.Http string body = \"value1=randomvalue1&value2=randomValue2\";\n\n// \"http://localhost/query?\" is added to the string \"body\" in order to create a valid Uri.\nstring urlBody = \"http://localhost/query?\" + body;\nNameValueCollection coll = new Uri(urlBody).ParseQueryString();\n" }, { "answer_id": 61217955, "author": "Nahom Haile", "author_id": 12178449, "author_profile": "https://Stackoverflow.com/users/12178449", "pm_score": -1, "selected": false, "text": "let search = window.location.search;\n\nconsole.log(search);\n\nlet qString = search.substring(1);\n\nwhile(qString.indexOf(\"+\") !== -1)\n\n qString = qString.replace(\"+\", \"\");\n\nlet qArray = qString.split(\"&\");\n\nlet values = [];\n\nfor(let i = 0; i < qArray.length; i++){\n let pos = qArray[i].search(\"=\");\n let keyVal = qArray[i].substring(0, pos);\n let dataVal = qArray[i].substring(pos + 1);\n dataVal = decodeURIComponent(dataVal);\n values[keyVal] = dataVal;\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4998/" ]
68,630
<p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
[ { "answer_id": 68712, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": false, "text": "$ python -m timeit \"x=(1,2,3,4,5,6,7,8)\"\n10000000 loops, best of 3: 0.0388 usec per loop\n\n$ python -m timeit \"x=[1,2,3,4,5,6,7,8]\"\n1000000 loops, best of 3: 0.363 usec per loop\n $ python -m timeit -s \"x=(1,2,3,4,5,6,7,8)\" \"y=x[3]\"\n10000000 loops, best of 3: 0.0938 usec per loop\n\n$ python -m timeit -s \"x=[1,2,3,4,5,6,7,8]\" \"y=x[3]\"\n10000000 loops, best of 3: 0.0649 usec per loop\n" }, { "answer_id": 68817, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 9, "selected": true, "text": "dis >>> def a():\n... x=[1,2,3,4,5]\n... y=x[2]\n...\n>>> def b():\n... x=(1,2,3,4,5)\n... y=x[2]\n...\n>>> import dis\n>>> dis.dis(a)\n 2 0 LOAD_CONST 1 (1)\n 3 LOAD_CONST 2 (2)\n 6 LOAD_CONST 3 (3)\n 9 LOAD_CONST 4 (4)\n 12 LOAD_CONST 5 (5)\n 15 BUILD_LIST 5\n 18 STORE_FAST 0 (x)\n\n 3 21 LOAD_FAST 0 (x)\n 24 LOAD_CONST 2 (2)\n 27 BINARY_SUBSCR\n 28 STORE_FAST 1 (y)\n 31 LOAD_CONST 0 (None)\n 34 RETURN_VALUE\n>>> dis.dis(b)\n 2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5))\n 3 STORE_FAST 0 (x)\n\n 3 6 LOAD_FAST 0 (x)\n 9 LOAD_CONST 2 (2)\n 12 BINARY_SUBSCR\n 13 STORE_FAST 1 (y)\n 16 LOAD_CONST 0 (None)\n 19 RETURN_VALUE\n" }, { "answer_id": 70968, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "realloc for direction in 'up', 'right', 'down', 'left': alist.append(item) atuple+= (item,)" }, { "answer_id": 71295, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "array" }, { "answer_id": 22140115, "author": "Raymond Hettinger", "author_id": 424499, "author_profile": "https://Stackoverflow.com/users/424499", "pm_score": 8, "selected": false, "text": " >>> from dis import dis\n\n >>> dis(compile(\"(10, 'abc')\", '', 'eval'))\n 1 0 LOAD_CONST 2 ((10, 'abc'))\n 3 RETURN_VALUE \n \n >>> dis(compile(\"[10, 'abc']\", '', 'eval'))\n 1 0 LOAD_CONST 0 (10)\n 3 LOAD_CONST 1 ('abc')\n 6 BUILD_LIST 2\n 9 RETURN_VALUE \n tuple(some_tuple) >>> a = (10, 20, 30)\n>>> b = tuple(a)\n>>> a is b\nTrue\n list(some_list) >>> a = [10, 20, 30]\n>>> b = list(a)\n>>> a is b\nFalse\n append() >>> import sys\n>>> sys.getsizeof(tuple(iter(range(10))))\n128\n>>> sys.getsizeof(list(iter(range(10))))\n200\n /* This over-allocates proportional to the list size, making room\n * for additional growth. The over-allocation is mild, but is\n * enough to give linear-time amortized behavior over a long\n * sequence of appends() in the presence of a poorly-performing\n * system realloc().\n * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...\n * Note: new_allocated won't overflow because the largest possible value\n * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.\n */\n $ python3.6 -m timeit -s 'a = (10, 20, 30)' 'a[1]'\n10000000 loops, best of 3: 0.0304 usec per loop\n$ python3.6 -m timeit -s 'a = [10, 20, 30]' 'a[1]'\n10000000 loops, best of 3: 0.0309 usec per loop\n\n$ python3.6 -m timeit -s 'a = (10, 20, 30)' 'x, y, z = a'\n10000000 loops, best of 3: 0.0249 usec per loop\n$ python3.6 -m timeit -s 'a = [10, 20, 30]' 'x, y, z = a'\n10000000 loops, best of 3: 0.0251 usec per loop\n (10, 20) typedef struct {\n Py_ssize_t ob_refcnt;\n struct _typeobject *ob_type;\n Py_ssize_t ob_size;\n PyObject *ob_item[2]; /* store a pointer to 10 and a pointer to 20 */\n } PyTupleObject;\n [10, 20] PyObject arr[2]; /* store a pointer to 10 and a pointer to 20 */\n\n typedef struct {\n Py_ssize_t ob_refcnt;\n struct _typeobject *ob_type;\n Py_ssize_t ob_size;\n PyObject **ob_item = arr; /* store a pointer to the two-pointer array */\n Py_ssize_t allocated;\n } PyListObject;\n" }, { "answer_id": 52015256, "author": "Dev Aggarwal", "author_id": 7061265, "author_profile": "https://Stackoverflow.com/users/7061265", "pm_score": 4, "selected": false, "text": "In [11]: %timeit list(range(100))\n749 ns ± 2.41 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [12]: %timeit tuple(range(100))\n781 ns ± 3.34 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n In [1]: %timeit list(range(1_000))\n13.5 µs ± 466 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [2]: %timeit tuple(range(1_000))\n12.4 µs ± 182 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n In [7]: %timeit list(range(10_000))\n182 µs ± 810 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\nIn [8]: %timeit tuple(range(10_000))\n188 µs ± 2.38 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n In [3]: %timeit list(range(1_00_000))\n2.76 ms ± 30.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [4]: %timeit tuple(range(1_00_000))\n2.74 ms ± 31.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n In [10]: %timeit list(range(10_00_000))\n28.1 ms ± 266 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\nIn [9]: %timeit tuple(range(10_00_000))\n28.5 ms ± 447 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n In [3]: l = np.array([749 * 10 ** -9, 13.5 * 10 ** -6, 182 * 10 ** -6, 2.76 * 10 ** -3, 28.1 * 10 ** -3])\n\nIn [2]: t = np.array([781 * 10 ** -9, 12.4 * 10 ** -6, 188 * 10 ** -6, 2.74 * 10 ** -3, 28.5 * 10 ** -3])\n\nIn [11]: np.average(l)\nOut[11]: 0.0062112498000000006\n\nIn [12]: np.average(t)\nOut[12]: 0.0062882362\n\nIn [17]: np.average(t) / np.average(l) * 100\nOut[17]: 101.23946713590554\n 101.239% 1.239%" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
68,633
<p>I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.</p> <p>Here is my regex: <code>"\w+ +\w+ *\(.*\) *\{"</code></p> <p>For those who do not know what a java method looks like I'll provide a basic one:</p> <pre><code>int foo() { } </code></pre> <p>There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.</p> <p>Update: My current Regex is <code>"\w+ +\w+ *\([^\)]*\) *\{"</code> so as to prevent the situation that Mike and adkom described.</p>
[ { "answer_id": 68669, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": true, "text": "(?:(?:public)|(?:private)|(?:static)|(?:protected)\\s+)*\n" }, { "answer_id": 68697, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 2, "selected": false, "text": "\"\\w+ +\\w+ *\\(.*\\) *\\{\" .* .*" }, { "answer_id": 68890, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": false, "text": "\\b\\w*\\s*\\w*\\(.*?\\)\\s*\\{[\\x21-\\x7E\\s]*\\}\n function getProfilePic($url)\n {\n if(@open_image($url) !== FALSE)\n {\n @imagepng($image, 'images/profiles/' . $_SESSION['id'] . '.png');\n @imagedestroy($image);\n return TRUE;\n }\n else \n {\n return FALSE;\n }\n }\n Options: case insensitive\n\nAssert position at a word boundary «\\b»\nMatch a single character that is a “word character” (letters, digits, etc.) «\\w*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\\s*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch a single character that is a “word character” (letters, digits, etc.) «\\w*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “(” literally «\\(»\nMatch any single character that is not a line break character «.*?»\n Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»\nMatch the character “)” literally «\\)»\nMatch a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\\s*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “{” literally «\\{»\nMatch a single character present in the list below «[\\x21-\\x7E\\s]*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n A character in the range between ASCII character 0x21 (33 decimal) and ASCII character 0x7E (126 decimal) «\\x21-\\x7E»\n A whitespace character (spaces, tabs, line breaks, etc.) «\\s»\nMatch the character “}” literally «\\}»\n\n\nCreated with RegexBuddy\n" }, { "answer_id": 69604, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " m{\\w+ \\s+ #return type\n \\w+ \\s* #function name\n [(] [^)]* [)] #params\n \\s* [{] #open paren\n }xms\n" }, { "answer_id": 847507, "author": "Georgios Gousios", "author_id": 51681, "author_profile": "https://Stackoverflow.com/users/51681", "pm_score": 5, "selected": false, "text": "(public|protected|private|static|\\s) +[\\w\\<\\>\\[\\]]+\\s+(\\w+) *\\([^\\)]*\\) *(\\{?|[^;])\n" }, { "answer_id": 11672271, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 0, "selected": false, "text": " let regex = '\\v^\\s+' \" preamble\n let regex .= '%(<\\w+>\\s+){0,3}' \" visibility, static, final\n let regex .= '%(\\w|[<>[\\]])+\\s+' \" return type\n let regex .= '\\w+\\s*' \" method name\n let regex .= '\\([^\\)]*\\)' \" method parameters\n let regex .= '%(\\w|\\s|\\{)+$' \" postamble\n ^\\s+(?:<\\w+>\\s+){0,3}(?:[\\w\\<\\>\\[\\]])+\\s+\\w+\\s*\\([^\\)]*\\)(?:\\w|\\s|\\{)+$\n" }, { "answer_id": 16118844, "author": "sbaltes", "author_id": 1974143, "author_profile": "https://Stackoverflow.com/users/1974143", "pm_score": 3, "selected": false, "text": "(?:(?:public|private|protected|static|final|native|synchronized|abstract|transient)+\\s+)+[$_\\w<>\\[\\]\\s]*\\s+[\\$_\\w]+\\([^\\)]*\\)?\\s*\\{?[^\\}]*\\}?\n" }, { "answer_id": 19030300, "author": "aliteralmind", "author_id": 2736496, "author_profile": "https://Stackoverflow.com/users/2736496", "pm_score": 3, "selected": false, "text": "#permission\n ^[ \\t]*(?:(?:public|protected|private)\\s+)?\n#keywords\n (?:(static|final|native|synchronized|abstract|threadsafe|transient|{#insert zJRgx123GenericsNotInGroup})\\s+){0,}\n#return type\n #If return type is \"return\" then it's actually a 'return funcName();' line. Ignore.\n (?!return)\n \\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})\\s+\n#function name\n \\b\\w+\\b\\s*\n#parameters\n \\(\n #one\n \\s*(?:\\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\n #two and up\n \\(\\s*(?:,\\s+\\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*){0,})?\\s*\n \\)\n#post parameters\n (?:\\s*throws [\\w.]+(\\s*,\\s*[\\w.]+))?\n#close-curly (concrete) or semi-colon (abstract)\n \\s*(?:\\{|;)[ \\t]*$\n {#insert zJRgx123GenericsNotInGroup} `(?:<[?\\w\\[\\] ,.&]+>)|(?:<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>[^>]*>)`\n <...<...<...>...>...> <...<...<...<...>...>...>...> {#insert zJRgxJavaFuncSigThrSemicOrOpnCrly} ^[ \\t]*(?:(?:public|protected|private)\\s+)?(?:(static|final|native|synchronized|abstract|threadsafe|transient|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))\\s+){0,}(?!return)\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})\\s+\\b\\w+\\b\\s*\\(\\s*(?:\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*(?:,\\s+\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*){0,})?\\s*\\)(?:\\s*throws [\\w.]+(\\s*,\\s*[\\w.]+))?\\s*(?:\\{|;)[ \\t]*$\n zJRgx123GenericsNotInGroup -- To precede return-type (?:<[?\\w\\[\\] ,.&]+>)|(?:<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>[^>]*>) zJRgx123GenericsNotInGroup\nzJRgx0OrMoreParams \\s*(?:{#insert zJRgxParamTypeName}\\s*(?:,\\s+{#insert zJRgxParamTypeName}\\s*){0,})?\\s* zJRgx0OrMoreParams\nzJRgxJavaFuncNmThrClsPrn_M_fnm -- Needs zvFOBJ_NAME (?<=\\s)\\b{#insert zvFOBJ_NAME}{#insert zzJRgxPostFuncNmThrClsPrn} zJRgxJavaFuncNmThrClsPrn_M_fnm\nzJRgxJavaFuncSigThrSemicOrOpnCrly -(**)- {#insert zzJRgxJavaFuncSigPreFuncName}\\w+{#insert zzJRgxJavaFuncSigPostFuncName} zJRgxJavaFuncSigThrSemicOrOpnCrly\nzJRgxJavaFuncSigThrSemicOrOpnCrly_M_fnm -- Needs zvFOBJ_NAME {#insert zzJRgxJavaFuncSigPreFuncName}{#insert zvFOBJ_NAME}{#insert zzJRgxJavaFuncSigPostFuncName} zJRgxJavaFuncSigThrSemicOrOpnCrly_M_fnm\nzJRgxOptKeywordsBtwScopeAndRetType (?:(static|final|native|synchronized|abstract|threadsafe|transient|{#insert zJRgx123GenericsNotInGroup})\\s+){0,} zJRgxOptKeywordsBtwScopeAndRetType\nzJRgxOptionalPubProtPriv (?:(?:public|protected|private)\\s+)? zJRgxOptionalPubProtPriv\nzJRgxParamTypeName -(**)- Ends w/ '\\b(?![>\\[])' to NOT find <? 'extends XClass'> or ...[]> (*Original: zJRgxParamTypeName, Needed by: zJRgxParamTypeName[4FQPTV,ForDel[NmsOnly,Types]]*){#insert zJRgxTypeW0123GenericsArry}(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[]) zJRgxParamTypeName\nzJRgxTypeW0123GenericsArry -- Grp1=Type, Grp2='[]', if any \\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,}) zJRgxTypeW0123GenericsArry\nzvTTL_PRMS_stL1c {#insert zCutL1c}{#SETPHRASE -description zvTTL_PRMS -content {#INSERTCLIPBOARD} -autotext zvTTL_PRMS -folder ctvv_folder} zvTTL_PRMS_stL1c\nzvTTL_PRMS_stL1cSvRstrCB {#insert zvCB_CONTENTS_stCB}{#insert zvTTL_PRMS_stL1c}{#insert zSetCBToCB_CONTENTS} zvTTL_PRMS_stL1cSvRstrCB\nzvTTL_PRMS_stPrompt {#SETPHRASE -description zvTTL_PRMS -content {#INPUT -head How many parameters? -single} -autotext zvTTL_PRMS -folder ctvv_folder} zvTTL_PRMS_stPrompt\nzzJRgxJavaFuncNmThrClsPrn_M_fnmTtlp -- Needs zvFOBJ_NAME, zvTTL_PRMS (?<=[ \\t])\\b{#insert zvFOBJ_NAME}\\b\\s*\\(\\s*{#insert {#COND -if {#insert zvTTL_PRMS} = 0 -then z1slp -else zzParamsGT0_M_ttlp}}\\) zzJRgxJavaFuncNmThrClsPrn_M_fnmTtlp\nzzJRgxJavaFuncSigPostFuncName {#insert zzJRgxPostFuncNmThrClsPrn}(?:\\s*throws \\b(?:[\\w.]+)\\b(\\s*,\\s*\\b(?:[\\w.]+)\\b))?\\s*(?:\\{|;)[ \\t]*$ zzJRgxJavaFuncSigPostFuncName\nzzJRgxJavaFuncSigPreFuncName (*If a type has generics, there may be no spaces between it and the first open '<', also requires generics with three nestings at the most (<...<...<...>...>...> okay, <...<...<...<...>...>...>...> not)*)^[ \\t]*{#insert zJRgxOptionalPubProtPriv}{#insert zJRgxOptKeywordsBtwScopeAndRetType}(*To prevent 'return funcName();' from being recognized:*)(?!return){#insert zJRgxTypeW0123GenericsArry}\\s+\\b zzJRgxJavaFuncSigPreFuncName\nzzJRgxPostFuncNmThrClsPrn \\b\\s*\\({#insert zJRgx0OrMoreParams}\\) zzJRgxPostFuncNmThrClsPrn\nzzParamsGT0_M_ttlp -- Needs zvTTL_PRMS {#insert zJRgxParamTypeName}\\s*{#insert {#COND -if {#insert zvTTL_PRMS} = 1 -then z1slp -else zzParamsGT1_M_ttlp}} zzParamsGT0_M_ttlp\nzzParamsGT1_M_ttlp {#LOOP ,\\s+{#insert zJRgxParamTypeName}\\s* -count {#CALC {#insert zvTTL_PRMS} - 1 -round 0 -thousands none}} zzParamsGT1_M_ttlp\n" }, { "answer_id": 21172210, "author": "Dexygen", "author_id": 34806, "author_profile": "https://Stackoverflow.com/users/34806", "pm_score": 1, "selected": false, "text": "cat Foobar.java | grep -Pzo '(?s)public static void.*?\\)\\s+{'\n public static void activeWorkEventStations (String type,\n String symbol,\n String section,\n String day,\n String priority,\n @As(\"yyyy-MM-dd\") Date scheduleDepartureDate) {\npublic static void getActiveScheduleChangeLogs(String type,\n String symbol,\n String section,\n String day,\n String priority,\n @As(\"yyyy-MM-dd\") Date scheduleDepartureDate) {\n" }, { "answer_id": 36217245, "author": "tharindu_DG", "author_id": 1894198, "author_profile": "https://Stackoverflow.com/users/1894198", "pm_score": 0, "selected": false, "text": "public <T> T name(final Class<T> x, final T y)\n ((public|private|protected|static|final|native|synchronized|abstract|transient)+\\s)+[\\$_\\w\\<\\>\\w\\s\\[\\]]*\\s+[\\$_\\w]+\\([^\\)]*\\)?\\s*\n" }, { "answer_id": 45900932, "author": "user1122069", "author_id": 1122069, "author_profile": "https://Stackoverflow.com/users/1122069", "pm_score": 0, "selected": false, "text": "(public|private|static|protected) ([A-Za-z0-9<>.]+) ([A-Za-z0-9]+)\\(\n $1 $2 $3(\n $1 $2 aaa$3(\n" }, { "answer_id": 48072172, "author": "Souvik Das", "author_id": 9166774, "author_profile": "https://Stackoverflow.com/users/9166774", "pm_score": 2, "selected": false, "text": "(public|private|static|protected|abstract|native|synchronized) +([a-zA-Z0-9<>._?, ]+) +([a-zA-Z0-9_]+) *\\\\([a-zA-Z0-9<>\\\\[\\\\]._?, \\n]*\\\\) *([a-zA-Z0-9_ ,\\n]*) *\\\\{ (public|private|static|protected|abstract|native|synchronized) +([a-zA-Z0-9<>._?, ]*) +([a-zA-Z0-9_]+) *\\\\([a-zA-Z0-9<>\\\\[\\\\]._?, \\n]*\\\\) *([a-zA-Z0-9_ ,\\n]*) *\\\\{" }, { "answer_id": 52996479, "author": "LarsH", "author_id": 423105, "author_profile": "https://Stackoverflow.com/users/423105", "pm_score": 1, "selected": false, "text": "\"!^[ \\t]*(catch|do|for|if|instanceof|new|return|switch|throw|while)\\n\"\n\"^[ \\t]*(([A-Za-z_][A-Za-z_0-9]*[ \\t]+)+[A-Za-z_][A-Za-z_0-9]*[ \\t]*\\\\([^;]*)$\"\n" }, { "answer_id": 55051029, "author": "Abdullah Khan", "author_id": 9758506, "author_profile": "https://Stackoverflow.com/users/9758506", "pm_score": 1, "selected": false, "text": "(?<=public static void )\\w+|(?<=private static void )\\w+|(?<=protected static void )\\w+|(?<=public void )\\w+|(?<=private void )\\w+|(?<=protected void )\\w+|(?<=public final void)\\w+|(?<=private final void)\\w+|(?<=protected final void)\\w+|(?<=private void )\\w+|(?<=protected void )\\w+|(?<=public static final void )\\w+|(?<=private static final void )\\w+|(?<=public final static void )\\w+|(?<=protected final static void )\\\\w+|(?<=private final static void )\\w+|(?<=protected final static void )\\w+|(?<=void )\\w+|(?<=private static )\\w+\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ]
68,640
<p>Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?</p>
[ { "answer_id": 68681, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 6, "selected": true, "text": "using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n MyStr m = new MyStr();\n m.Foo();\n\n MyStr.MyStrInner mi = new MyStr.MyStrInner();\n mi.Bar();\n\n Console.ReadLine();\n }\n }\n\n public class Myclass\n {\n public int a;\n }\n\n struct MyStr\n {\n Myclass mc;\n\n public void Foo()\n {\n mc = new Myclass();\n mc.a = 1;\n }\n\n public class MyStrInner\n {\n string x = \"abc\";\n\n public string Bar()\n {\n return x;\n }\n }\n }\n}\n" }, { "answer_id": 11887584, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "string KeyValuePair Value List<T> Add Add" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10722/" ]
68,645
<p>How do I create class (i.e. <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="nofollow noreferrer">static</a>) variables or methods in Python?</p>
[ { "answer_id": 68672, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 12, "selected": true, "text": ">>> class MyClass:\n... i = 3\n...\n>>> MyClass.i\n3 \n i i >>> m = MyClass()\n>>> m.i = 4\n>>> MyClass.i, m.i\n>>> (3, 4)\n class C:\n @staticmethod\n def f(arg1, arg2, ...): ...\n" }, { "answer_id": 68747, "author": "emb", "author_id": 10739, "author_profile": "https://Stackoverflow.com/users/10739", "pm_score": 5, "selected": false, "text": "class myObj(object):\n def myMethod(cls)\n ...\n myMethod = classmethod(myMethod) \n class myObj(object):\n @classmethod\n def myMethod(cls)\n" }, { "answer_id": 68770, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 5, "selected": false, "text": "class MyClass:\n\n def myInstanceMethod(self):\n print 'output from an instance method'\n\n @classmethod\n def myStaticMethod(cls):\n print 'output from a static method'\n\n>>> MyClass.myInstanceMethod()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method myInstanceMethod() must be called [...]\n\n>>> MyClass.myStaticMethod()\noutput from a static method\n >>> MyClass.myInstanceMethod(MyClass())\noutput from an instance method\n" }, { "answer_id": 69067, "author": "millerdev", "author_id": 10840, "author_profile": "https://Stackoverflow.com/users/10840", "pm_score": 10, "selected": false, "text": ">>> class Test(object):\n... i = 3\n...\n>>> Test.i\n3\n >>> t = Test()\n>>> t.i # \"static\" variable accessed via instance\n3\n>>> t.i = 5 # but if we assign to the instance ...\n>>> Test.i # we have not changed the \"static\" variable\n3\n>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i\n5\n>>> Test.i = 6 # to change the \"static\" variable we do it by assigning to the class\n>>> t.i\n5\n>>> Test.i\n6\n>>> u = Test()\n>>> u.i\n6 # changes to t do not affect new instances of Test\n\n# Namespaces are one honking great idea -- let's do more of those!\n>>> Test.__dict__\n{'i': 6, ...}\n>>> t.__dict__\n{'i': 5}\n>>> u.__dict__\n{}\n t.i i t i t Test class Test(object):\n @staticmethod\n def f(arg1, arg2, ...):\n ...\n class Test(object):\n i = 3 # class (or static) variable\n @classmethod\n def g(cls, arg):\n # here we can use 'cls' instead of the class name (Test)\n if arg > cls.i:\n cls.i = arg # would be the same as Test.i = arg1\n" }, { "answer_id": 81002, "author": "Gregory", "author_id": 14351, "author_profile": "https://Stackoverflow.com/users/14351", "pm_score": 6, "selected": false, "text": ">>> class X:\n... pass\n... \n>>> X.bar = 0\n>>> x = X()\n>>> x.bar\n0\n>>> x.foo\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\nAttributeError: X instance has no attribute 'foo'\n>>> X.foo = 1\n>>> x.foo\n1\n class X:\n l = []\n def __init__(self):\n self.l.append(1)\n\nprint X().l\nprint X().l\n\n>python test.py\n[1]\n[1, 1]\n" }, { "answer_id": 8201368, "author": "Bartosz Ptaszynski", "author_id": 27098, "author_profile": "https://Stackoverflow.com/users/27098", "pm_score": 4, "selected": false, "text": "class StaticClassError(Exception):\n pass\n\n\nclass StaticClass:\n __metaclass__ = abc.ABCMeta\n\n def __new__(cls, *args, **kw):\n raise StaticClassError(\"%s is a static class and cannot be initiated.\"\n % cls)\n\nclass MyClass(StaticClass):\n a = 1\n b = 3\n\n @staticmethod\n def add(x, y):\n return x+y\n" }, { "answer_id": 9613563, "author": "jondinham", "author_id": 905418, "author_profile": "https://Stackoverflow.com/users/905418", "pm_score": 5, "selected": false, "text": "class my_cls:\n my_prop = 0\n\n#static property\nprint my_cls.my_prop #--> 0\n\n#assign value to static property\nmy_cls.my_prop = 1 \nprint my_cls.my_prop #--> 1\n\n#access static property thru' instance\nmy_inst = my_cls()\nprint my_inst.my_prop #--> 1\n\n#instance property is different from static property \n#after being assigned a value\nmy_inst.my_prop = 2\nprint my_cls.my_prop #--> 1\nprint my_inst.my_prop #--> 2\n" }, { "answer_id": 15117875, "author": "Tomer Zait", "author_id": 1261677, "author_profile": "https://Stackoverflow.com/users/1261677", "pm_score": 3, "selected": false, "text": "class staticFlag:\n def __init__(self):\n self.__success = False\n def isSuccess(self):\n return self.__success\n def succeed(self):\n self.__success = True\n\nclass tryIt:\n def __init__(self, staticFlag):\n self.isSuccess = staticFlag.isSuccess\n self.succeed = staticFlag.succeed\n\ntryArr = []\nflag = staticFlag()\nfor i in range(10):\n tryArr.append(tryIt(flag))\n if i == 5:\n tryArr[i].succeed()\n print tryArr[i].isSuccess()\n staticFlag __success tryIt staticFlag tryArr False\nFalse\nFalse\nFalse\nFalse\nTrue\nTrue\nTrue\nTrue\nTrue\n" }, { "answer_id": 15644143, "author": "user2209576", "author_id": 2209576, "author_profile": "https://Stackoverflow.com/users/2209576", "pm_score": 4, "selected": false, "text": "#!/usr/bin/python\n\nclass A:\n var=1\n\n def printvar(self):\n print \"self.var is %d\" % self.var\n print \"A.var is %d\" % A.var\n\n\n a = A()\n a.var = 2\n a.printvar()\n\n A.var = 3\n a.printvar()\n self.var is 2\nA.var is 1\nself.var is 2\nA.var is 3\n" }, { "answer_id": 24553443, "author": "Yann", "author_id": 717357, "author_profile": "https://Stackoverflow.com/users/717357", "pm_score": 3, "selected": false, "text": "class ConstantAttribute(object):\n '''You can initialize my value but not change it.'''\n def __init__(self, value):\n self.value = value\n\n def __get__(self, obj, type=None):\n return self.value\n\n def __set__(self, obj, val):\n pass\n\n\nclass Demo(object):\n x = ConstantAttribute(10)\n\n\nclass SubDemo(Demo):\n x = 10\n\n\ndemo = Demo()\nsubdemo = SubDemo()\n# should not change\ndemo.x = 100\n# should change\nsubdemo.x = 100\nprint \"small demo\", demo.x\nprint \"small subdemo\", subdemo.x\nprint \"big demo\", Demo.x\nprint \"big subdemo\", SubDemo.x\n small demo 10\nsmall subdemo 100\nbig demo 10\nbig subdemo 10\n pass class StaticAttribute(object):\n def __init__(self, value):\n self.value = value\n\n def __get__(self, obj, type=None):\n return self.value\n\n def __set__(self, obj, val):\n self.value = val\n" }, { "answer_id": 27568860, "author": "Rick", "author_id": 2437514, "author_profile": "https://Stackoverflow.com/users/2437514", "pm_score": 8, "selected": false, "text": "class Test(object):\n\n # regular instance method:\n def my_method(self):\n pass\n\n # class method:\n @classmethod\n def my_class_method(cls):\n pass\n\n # static method:\n @staticmethod\n def my_static_method():\n pass\n my_method() my_class_method() Test my_static_method() class Test(object):\n i = 3 # This is a class attribute\n\nx = Test()\nx.i = 12 # Attempt to change the value of the class attribute using x instance\nassert x.i == Test.i # ERROR\nassert Test.i == 3 # Test.i was not affected\nassert x.i == 12 # x.i is a different object than Test.i\n x.i = 12 i x Test i class Test(object):\n\n _i = 3\n\n @property\n def i(self):\n return type(self)._i\n\n @i.setter\n def i(self,val):\n type(self)._i = val\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting and setting i) ##\n\nclass Test(object):\n\n _i = 3\n\n def get_i(self):\n return type(self)._i\n\n def set_i(self,val):\n type(self)._i = val\n\n i = property(get_i, set_i)\n x1 = Test()\nx2 = Test()\nx1.i = 50\nassert x2.i == x1.i # no error\nassert x2.i == 50 # the property is synced\n _i i property property property class Test(object):\n\n _i = 3\n\n @property\n def i(self):\n return type(self)._i\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting i) ##\n\nclass Test(object):\n\n _i = 3\n\n def get_i(self):\n return type(self)._i\n\n i = property(get_i)\n i AttributeError x = Test()\nassert x.i == 3 # success\nx.i = 12 # ERROR\n x = Test()\nassert x.i == Test.i # ERROR\n\n# x.i and Test.i are two different objects:\ntype(Test.i) # class 'property'\ntype(x.i) # class 'int'\n assert Test.i == x.i i Test x Test i = property(get_i) \n i Test property property property assert Test.i = x.i Test.i == x.i type type(int) # class 'type'\ntype(str) # class 'type'\nclass Test(): pass\ntype(Test) # class 'type'\n class MyMeta(type): pass\n class MyClass(metaclass = MyMeta):\n pass\n\ntype(MyClass) # class MyMeta\n StaticVarMeta.statics from functools import wraps\n\nclass StaticVarsMeta(type):\n '''A metaclass for creating classes that emulate the \"static variable\" behavior\n of other languages. I do not advise actually using this for anything!!!\n \n Behavior is intended to be similar to classes that use __slots__. However, \"normal\"\n attributes and __statics___ can coexist (unlike with __slots__). \n \n Example usage: \n \n class MyBaseClass(metaclass = StaticVarsMeta):\n __statics__ = {'a','b','c'}\n i = 0 # regular attribute\n a = 1 # static var defined (optional)\n \n class MyParentClass(MyBaseClass):\n __statics__ = {'d','e','f'}\n j = 2 # regular attribute\n d, e, f = 3, 4, 5 # Static vars\n a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)\n \n class MyChildClass(MyParentClass):\n __statics__ = {'a','b','c'}\n j = 2 # regular attribute (redefines j from MyParentClass)\n d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)\n a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''\n statics = {}\n def __new__(mcls, name, bases, namespace):\n # Get the class object\n cls = super().__new__(mcls, name, bases, namespace)\n # Establish the \"statics resolution order\"\n cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))\n \n # Replace class getter, setter, and deleter for instance attributes\n cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)\n cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)\n cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)\n # Store the list of static variables for the class object\n # This list is permanent and cannot be changed, similar to __slots__\n try:\n mcls.statics[cls] = getattr(cls,'__statics__')\n except AttributeError:\n mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided\n # Check and make sure the statics var names are strings\n if any(not isinstance(static,str) for static in mcls.statics[cls]):\n typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__\n raise TypeError('__statics__ items must be strings, not {0}'.format(typ))\n # Move any previously existing, not overridden statics to the static var parent class(es)\n if len(cls.__sro__) > 1:\n for attr,value in namespace.items():\n if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:\n for c in cls.__sro__[1:]:\n if attr in StaticVarsMeta.statics[c]:\n setattr(c,attr,value)\n delattr(cls,attr)\n return cls\n def __inst_getattribute__(self, orig_getattribute):\n '''Replaces the class __getattribute__'''\n @wraps(orig_getattribute)\n def wrapper(self, attr):\n if StaticVarsMeta.is_static(type(self),attr):\n return StaticVarsMeta.__getstatic__(type(self),attr)\n else:\n return orig_getattribute(self, attr)\n return wrapper\n def __inst_setattr__(self, orig_setattribute):\n '''Replaces the class __setattr__'''\n @wraps(orig_setattribute)\n def wrapper(self, attr, value):\n if StaticVarsMeta.is_static(type(self),attr):\n StaticVarsMeta.__setstatic__(type(self),attr, value)\n else:\n orig_setattribute(self, attr, value)\n return wrapper\n def __inst_delattr__(self, orig_delattribute):\n '''Replaces the class __delattr__'''\n @wraps(orig_delattribute)\n def wrapper(self, attr):\n if StaticVarsMeta.is_static(type(self),attr):\n StaticVarsMeta.__delstatic__(type(self),attr)\n else:\n orig_delattribute(self, attr)\n return wrapper\n def __getstatic__(cls,attr):\n '''Static variable getter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n try:\n return getattr(c,attr)\n except AttributeError:\n pass\n raise AttributeError(cls.__name__ + \" object has no attribute '{0}'\".format(attr))\n def __setstatic__(cls,attr,value):\n '''Static variable setter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n setattr(c,attr,value)\n break\n def __delstatic__(cls,attr):\n '''Static variable deleter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n try:\n delattr(c,attr)\n break\n except AttributeError:\n pass\n raise AttributeError(cls.__name__ + \" object has no attribute '{0}'\".format(attr))\n def __delattr__(cls,attr):\n '''Prevent __sro__ attribute from deletion'''\n if attr == '__sro__':\n raise AttributeError('readonly attribute')\n super().__delattr__(attr)\n def is_static(cls,attr):\n '''Returns True if an attribute is a static variable of any class in the __sro__'''\n if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):\n return True\n return False\n" }, { "answer_id": 36216964, "author": "Ethan Furman", "author_id": 208880, "author_profile": "https://Stackoverflow.com/users/208880", "pm_score": 4, "selected": false, "text": "static static variable class Static:\n def __init__(self, value, doc=None):\n self.deleted = False\n self.value = value\n self.__doc__ = doc\n def __get__(self, inst, cls=None):\n if self.deleted:\n raise AttributeError('Attribute not set')\n return self.value\n def __set__(self, inst, value):\n self.deleted = False\n self.value = value\n def __delete__(self, inst):\n self.deleted = True\n\nclass StaticType(type):\n def __delattr__(cls, name):\n obj = cls.__dict__.get(name)\n if isinstance(obj, Static):\n obj.__delete__(name)\n else:\n super(StaticType, cls).__delattr__(name)\n def __getattribute__(cls, *args):\n obj = super(StaticType, cls).__getattribute__(*args)\n if isinstance(obj, Static):\n obj = obj.__get__(cls, cls.__class__)\n return obj\n def __setattr__(cls, name, val):\n # check if object already exists\n obj = cls.__dict__.get(name)\n if isinstance(obj, Static):\n obj.__set__(name, val)\n else:\n super(StaticType, cls).__setattr__(name, val)\n class MyStatic(metaclass=StaticType):\n \"\"\"\n Testing static vars\n \"\"\"\n a = Static(9)\n b = Static(12)\n c = 3\n\nclass YourStatic(MyStatic):\n d = Static('woo hoo')\n e = Static('doo wop')\n ms1 = MyStatic()\nms2 = MyStatic()\nms3 = MyStatic()\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nassert ms1.c == ms2.c == ms3.c == MyStatic.c\nms1.a = 77\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nms2.b = 99\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nMyStatic.a = 101\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nMyStatic.b = 139\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\ndel MyStatic.b\nfor inst in (ms1, ms2, ms3):\n try:\n getattr(inst, 'b')\n except AttributeError:\n pass\n else:\n print('AttributeError not raised on %r' % attr)\nms1.c = 13\nms2.c = 17\nms3.c = 19\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\nMyStatic.c = 43\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\n\nys1 = YourStatic()\nys2 = YourStatic()\nys3 = YourStatic()\nMyStatic.b = 'burgler'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nys1.a = 'blah'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nys2.b = 'kelp'\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nys1.d = 'fee'\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nys2.e = 'fie'\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nMyStatic.a = 'aargh'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\n" }, { "answer_id": 41413059, "author": "jmunsch", "author_id": 2026508, "author_profile": "https://Stackoverflow.com/users/2026508", "pm_score": 2, "selected": false, "text": "nonlocal >>> def SomeFactory(some_var=None):\n... class SomeClass(object):\n... nonlocal some_var\n... def print():\n... print(some_var)\n... return SomeClass\n... \n>>> SomeFactory(some_var=\"hello world\").print()\nhello world\n" }, { "answer_id": 42392246, "author": "Mari Selvan", "author_id": 5483135, "author_profile": "https://Stackoverflow.com/users/5483135", "pm_score": 3, "selected": false, "text": "class A:\n counter =0\n def callme (self):\n A.counter +=1\n def getcount (self):\n return self.counter \n>>> x=A()\n>>> y=A()\n>>> print(x.getcount())\n>>> print(y.getcount())\n>>> x.callme() \n>>> print(x.getcount())\n>>> print(y.getcount())\n 0\n0\n1\n1\n here object (x) alone increment the counter variable\nfrom 0 to 1 by not object y. But result it as \"static counter\"\n" }, { "answer_id": 46335281, "author": "Davis Herring", "author_id": 8586227, "author_profile": "https://Stackoverflow.com/users/8586227", "pm_score": 4, "selected": false, "text": "class A(object):\n\n label=\"Amazing\"\n\n def __init__(self,d): \n self.data=d\n\n def say(self): \n print(\"%s %s!\"%(self.label,self.data))\n\nclass B(A):\n label=\"Bold\" # overrides A.label\n\nA(5).say() # Amazing 5!\nB(3).say() # Bold 3!\n self label" }, { "answer_id": 53775598, "author": "Shagun Pruthi", "author_id": 6136001, "author_profile": "https://Stackoverflow.com/users/6136001", "pm_score": 3, "selected": false, "text": " >>> class A:\n ...my_var = \"shagun\"\n\n >>> print(A.my_var)\n shagun\n >>> a = A()\n >>> a.my_var = \"pruthi\"\n >>> print(A.my_var,a.my_var)\n shagun pruthi\n >>> class A:\n ... @staticmethod\n ... def my_static_method():\n ... print(\"Yippey!!\")\n ... \n >>> A.my_static_method()\n Yippey!!\n" }, { "answer_id": 58683325, "author": "Jay", "author_id": 5387972, "author_profile": "https://Stackoverflow.com/users/5387972", "pm_score": 2, "selected": false, "text": "class Fud:\n\n class_vars = {'origin_open':False}\n\n def __init__(self, origin = True):\n self.origin = origin\n self.opened = True\n if origin:\n self.class_vars['origin_open'] = True\n\n\n def make_another_fud(self):\n ''' Generating another Fud() from the origin instance '''\n\n return Fud(False)\n\n\n def close(self):\n self.opened = False\n if self.origin:\n self.class_vars['origin_open'] = False\n\n\nfud1 = Fud()\nfud2 = fud1.make_another_fud()\n\nprint (f\"is this the original fud: {fud2.origin}\")\nprint (f\"is the original fud open: {fud2.class_vars['origin_open']}\")\n# is this the original fud: False\n# is the original fud open: True\n\nfud1.close()\n\nprint (f\"is the original fud open: {fud2.class_vars['origin_open']}\")\n# is the original fud open: False\n" }, { "answer_id": 61080153, "author": "Christopher Hoffman", "author_id": 7497211, "author_profile": "https://Stackoverflow.com/users/7497211", "pm_score": 2, "selected": false, "text": "eval(str) class import Records object_name = 'RecordOne' cur_type = eval(object_name) cur_inst = cur_type(args) cur_type.getName()" }, { "answer_id": 61805905, "author": "Winter Squad", "author_id": 8566159, "author_profile": "https://Stackoverflow.com/users/8566159", "pm_score": 2, "selected": false, "text": "# -*- coding: utf-8 -*-\nclass Worker:\n id = 1\n\n def __init__(self):\n self.name = ''\n self.document = ''\n self.id = Worker.id\n Worker.id += 1\n\n def __str__(self):\n return u\"{}.- {} {}\".format(self.id, self.name, self.document).encode('utf8')\n\n\nclass Workers:\n def __init__(self):\n self.list = []\n\n def add(self, name, doc):\n worker = Worker()\n worker.name = name\n worker.document = doc\n self.list.append(worker)\n\n\nif __name__ == \"__main__\":\n workers = Workers()\n for item in (('Fiona', '0009898'), ('Maria', '66328191'), (\"Sandra\", '2342184'), ('Elvira', '425872')):\n workers.add(item[0], item[1])\n for worker in workers.list:\n print(worker)\n print(\"next id: %i\" % Worker.id)\n" }, { "answer_id": 62960717, "author": "ganja", "author_id": 13864415, "author_profile": "https://Stackoverflow.com/users/13864415", "pm_score": 1, "selected": false, "text": "class Student:\n\n the correct way of static declaration\n i = 10\n\n incorrect\n self.i = 10\n" }, { "answer_id": 65918726, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 4, "selected": false, "text": "__init__() @dataclass typing.ClassVar ClassVar from typing import ClassVar\nfrom dataclasses import dataclass\n\n@dataclass\nclass Test:\n i: ClassVar[int] = 10\n x: int\n y: int\n \n def __repr__(self):\n return f\"Test({self.x=}, {self.y=}, {Test.i=})\"\n > test1 = Test(5, 6)\n> test2 = Test(10, 11)\n\n> test1\nTest(self.x=5, self.y=6, Test.i=10)\n> test2\nTest(self.x=10, self.y=11, Test.i=10)\n" }, { "answer_id": 66255775, "author": "Sunil Garg", "author_id": 2172547, "author_profile": "https://Stackoverflow.com/users/2172547", "pm_score": 0, "selected": false, "text": "@staticmethod instance = MyClass()\nprint(instance.i)\n print(MyClass.i)\n class MyClass:\n i: str\n i is not attribute of MyClass\n" }, { "answer_id": 68682495, "author": "alda78", "author_id": 2161600, "author_profile": "https://Stackoverflow.com/users/2161600", "pm_score": 4, "selected": false, "text": "bool int float str class A:\n static = 1\n\n\nclass B(A):\n pass\n\n\nprint(f\"int {A.static}\") # get 1 correctly\nprint(f\"int {B.static}\") # get 1 correctly\n\nA.static = 5\nprint(f\"int {A.static}\") # get 5 correctly\nprint(f\"int {B.static}\") # get 5 correctly\n\nB.static = 6\nprint(f\"int {A.static}\") # expected 6, but get 5 incorrectly\nprint(f\"int {B.static}\") # get 6 correctly\n\nA.static = 7\nprint(f\"int {A.static}\") # get 7 correctly\nprint(f\"int {B.static}\") # get unchanged 6\n from refdatatypes.refint import RefInt\n\n\nclass AAA:\n static = RefInt(1)\n\n\nclass BBB(AAA):\n pass\n\n\nprint(f\"refint {AAA.static.value}\") # get 1 correctly\nprint(f\"refint {BBB.static.value}\") # get 1 correctly\n\nAAA.static.value = 5\nprint(f\"refint {AAA.static.value}\") # get 5 correctly\nprint(f\"refint {BBB.static.value}\") # get 5 correctly\n\nBBB.static.value = 6\nprint(f\"refint {AAA.static.value}\") # get 6 correctly\nprint(f\"refint {BBB.static.value}\") # get 6 correctly\n\nAAA.static.value = 7\nprint(f\"refint {AAA.static.value}\") # get 7 correctly\nprint(f\"refint {BBB.static.value}\") # get 7 correctly\n" }, { "answer_id": 69723203, "author": "HIMANSHU PANDEY", "author_id": 14952627, "author_profile": "https://Stackoverflow.com/users/14952627", "pm_score": 3, "selected": false, "text": "class Calculator:\n @staticmethod\n def multiply(n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 * n2 * Res\n\nprint(Calculator.multiply(1, 2, 3, 4)) # 24\n class Calculator:\n def add(n1, n2, *args):\n return n1 + n2 + sum(args)\n\nCalculator.add = staticmethod(Calculator.add)\nprint(Calculator.add(1, 2, 3, 4)) # 10\n class Calculator:\n num = 0\n def __init__(self, digits) -> None:\n Calculator.num = int(''.join(digits))\n\n @classmethod\n def get_digits(cls, num):\n digits = list(str(num))\n calc = cls(digits)\n return calc.num\n\nprint(Calculator.get_digits(314159)) # 314159\n class Calculator:\n def divide(cls, n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 / n2 / Res\n\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.divide(15, 3, 5)) # 1.0\n class Calculator: \n def subtract(n1, n2, *args):\n return n1 - n2 - sum(args)\n\nprint(Calculator.subtract(10, 2, 3, 4)) # 1\n class Calculator:\n num = 0\n def __init__(self, digits) -> None:\n Calculator.num = int(''.join(digits))\n \n \n @staticmethod\n def multiply(n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 * n2 * Res\n\n\n def add(n1, n2, *args):\n return n1 + n2 + sum(args)\n \n\n @classmethod\n def get_digits(cls, num):\n digits = list(str(num))\n calc = cls(digits)\n return calc.num\n\n\n def divide(cls, n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 / n2 / Res\n\n\n def subtract(n1, n2, *args):\n return n1 - n2 - sum(args)\n \n\n\n\nCalculator.add = staticmethod(Calculator.add)\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.multiply(1, 2, 3, 4)) # 24\nprint(Calculator.add(1, 2, 3, 4)) # 10\nprint(Calculator.get_digits(314159)) # 314159\nprint(Calculator.divide(15, 3, 5)) # 1.0\nprint(Calculator.subtract(10, 2, 3, 4)) # 1\n" }, { "answer_id": 72141879, "author": "MusicalNinja", "author_id": 3305998, "author_profile": "https://Stackoverflow.com/users/3305998", "pm_score": 0, "selected": false, "text": "from contextlib import contextmanager\n\nclass Sheldon(object):\n foo = 73\n\n def __init__(self, n):\n self.n = n\n\n def times(self):\n cls = self.__class__\n return cls.foo * self.n\n #self.foo * self.n would give the same result here but is less readable\n # it will also create a local variable which will make it easier to break your code\n \n def updatefoo(self):\n cls = self.__class__\n cls.foo *= self.n\n #self.foo *= self.n will not work here\n # assignment will try to create a instance variable foo\n\n @classmethod\n @contextmanager\n def reset_after_test(cls):\n originalfoo = cls.foo\n yield\n cls.foo = originalfoo\n #if you don't do this then running a full test suite will fail\n #updates to foo in one test will be kept for later tests\n Sheldon.foo def test_times():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n assert s.times() == 146\n\ndef test_update():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n s.updatefoo()\n assert Sheldon.foo == 146\n\ndef test_two_instances():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n s3 = Sheldon(3)\n assert s.times() == 146\n assert s3.times() == 219\n s3.updatefoo()\n assert s.times() == 438\n class Douglas(Sheldon):\n foo = 42\n def test_subclassing():\n with Sheldon.reset_after_test(), Douglas.reset_after_test():\n s = Sheldon(2)\n d = Douglas(2)\n assert d.times() == 84\n assert s.times() == 146\n d.updatefoo()\n assert d.times() == 168 #Douglas.Foo was updated\n assert s.times() == 146 #Seldon.Foo is still 73\n\ndef test_subclassing_reset():\n with Sheldon.reset_after_test(), Douglas.reset_after_test():\n s = Sheldon(2)\n d = Douglas(2)\n assert d.times() == 84 #Douglas.foo was reset after the last test\n assert s.times() == 146 #and so was Sheldon.foo\n" }, { "answer_id": 74501446, "author": "Kai - Kazuya Ito", "author_id": 8172439, "author_profile": "https://Stackoverflow.com/users/8172439", "pm_score": 0, "selected": false, "text": "x name test1(self) test2(cls) test3() class Person:\n x = \"Hello\" # Class variable\n\n def __init__(self, name):\n self.name = name # Instance variable\n \n def test1(self): # Instance method\n print(\"Test1\")\n\n @classmethod\n def test2(cls): # Class method\n print(\"Test2\")\n \n @staticmethod\n def test3(): # Static method\n print(\"Test3\")\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246/" ]
68,651
<p>If I pass PHP variables with <code>.</code> in their names via $_GET PHP auto-replaces them with <code>_</code> characters. For example:</p> <pre><code>&lt;?php echo "url is ".$_SERVER['REQUEST_URI']."&lt;p&gt;"; echo "x.y is ".$_GET['x.y'].".&lt;p&gt;"; echo "x_y is ".$_GET['x_y'].".&lt;p&gt;"; </code></pre> <p>... outputs the following:</p> <pre><code>url is /SpShipTool/php/testGetUrl.php?x.y=a.b x.y is . x_y is a.b. </code></pre> <p>... my question is this: is there <strong>any</strong> way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this</p> <p>PHP version I'm running with is 5.2.4-2ubuntu5.3.</p>
[ { "answer_id": 68742, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 7, "selected": true, "text": "<?php\n$varname.ext; /* invalid variable name */\n?>\n" }, { "answer_id": 1939911, "author": "crb", "author_id": 51691, "author_profile": "https://Stackoverflow.com/users/51691", "pm_score": 6, "selected": false, "text": "$query_string = file_get_contents('php://input');\n <?php\n// Function to fix up PHP's messing up input containing dots, etc.\n// `$source` can be either 'POST' or 'GET'\nfunction getRealInput($source) {\n $pairs = explode(\"&\", $source == 'POST' ? file_get_contents(\"php://input\") : $_SERVER['QUERY_STRING']);\n $vars = array();\n foreach ($pairs as $pair) {\n $nv = explode(\"=\", $pair);\n $name = urldecode($nv[0]);\n $value = urldecode($nv[1]);\n $vars[$name] = $value;\n }\n return $vars;\n}\n\n// Wrapper functions specifically for GET and POST:\nfunction getRealGET() { return getRealInput('GET'); }\nfunction getRealPOST() { return getRealInput('POST'); }\n?>\n" }, { "answer_id": 4927461, "author": "Jason", "author_id": 607256, "author_profile": "https://Stackoverflow.com/users/607256", "pm_score": 2, "selected": false, "text": "base64_encode base64_decode" }, { "answer_id": 14432765, "author": "Ja͢ck", "author_id": 1338292, "author_profile": "https://Stackoverflow.com/users/1338292", "pm_score": 3, "selected": false, "text": "php://input $_SERVER['QUERY_STRING'] parse_str() function parse_qs($data)\n{\n $data = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) {\n return bin2hex(urldecode($match[0]));\n }, $data);\n\n parse_str($data, $values);\n\n return array_combine(array_map('hex2bin', array_keys($values)), $values);\n}\n\n// work with the raw query string\n$data = parse_qs($_SERVER['QUERY_STRING']);\n // handle posted data (this only works with application/x-www-form-urlencoded)\n$data = parse_qs(file_get_contents('php://input'));\n" }, { "answer_id": 18028493, "author": "El Yobo", "author_id": 217588, "author_profile": "https://Stackoverflow.com/users/217588", "pm_score": 2, "selected": false, "text": "<?php\n\npublic function fix2(&$target, $source, $keep = false) { \n if (!$source) { \n return; \n } \n preg_match_all( \n '/ \n # Match at start of string or & \n (?:^|(?<=&)) \n # Exclude cases where the period is in brackets, e.g. foo[bar.blarg]\n [^=&\\[]* \n # Affected cases: periods and spaces \n (?:\\.|%20) \n # Keep matching until assignment, next variable, end of string or \n # start of an array \n [^=&\\[]* \n /x', \n $source, \n $matches \n ); \n\n foreach (current($matches) as $key) { \n $key = urldecode($key); \n $badKey = preg_replace('/(\\.| )/', '_', $key); \n\n if (isset($target[$badKey])) { \n // Duplicate values may have already unset this \n $target[$key] = $target[$badKey]; \n\n if (!$keep) { \n unset($target[$badKey]); \n } \n } \n } \n} \n" }, { "answer_id": 18163411, "author": "El Yobo", "author_id": 217588, "author_profile": "https://Stackoverflow.com/users/217588", "pm_score": 3, "selected": false, "text": "public function fix(&$target, $source, $keep = false) { \n if (!$source) { \n return; \n } \n $keys = array(); \n\n $source = preg_replace_callback( \n '/ \n # Match at start of string or & \n (?:^|(?<=&)) \n # Exclude cases where the period is in brackets, e.g. foo[bar.blarg]\n [^=&\\[]* \n # Affected cases: periods and spaces \n (?:\\.|%20) \n # Keep matching until assignment, next variable, end of string or \n # start of an array \n [^=&\\[]* \n /x', \n function ($key) use (&$keys) { \n $keys[] = $key = base64_encode(urldecode($key[0])); \n return urlencode($key); \n }, \n $source \n ); \n\n if (!$keep) { \n $target = array(); \n } \n\n parse_str($source, $data); \n foreach ($data as $key => $val) { \n // Only unprocess encoded keys \n if (!in_array($key, $keys)) { \n $target[$key] = $val; \n continue; \n } \n\n $key = base64_decode($key); \n $target[$key] = $val; \n\n if ($keep) { \n // Keep a copy in the underscore key version \n $key = preg_replace('/(\\.| )/', '_', $key); \n $target[$key] = $val; \n } \n } \n} \n" }, { "answer_id": 18209799, "author": "Rok Kralj", "author_id": 924109, "author_profile": "https://Stackoverflow.com/users/924109", "pm_score": 4, "selected": false, "text": "?param[2][5]=10 $_GET = fix( $_SERVER['QUERY_STRING'] );\n$_POST = fix( file_get_contents('php://input') );\n$_COOKIE = fix( $_SERVER['HTTP_COOKIE'] );\n parse_str() function fix($source) {\n $source = preg_replace_callback(\n '/(^|(?<=&))[^=[&]+/',\n function($key) { return bin2hex(urldecode($key[0])); },\n $source\n );\n\n parse_str($source, $post);\n \n $result = array();\n foreach ($post as $key => $val) {\n $result[hex2bin($key)] = $val;\n }\n return $result;\n}\n" }, { "answer_id": 18244502, "author": "humbletim", "author_id": 1684079, "author_profile": "https://Stackoverflow.com/users/1684079", "pm_score": 2, "selected": false, "text": ". main/php_variables.c ....\n/* ensure that we don't have spaces or dots in the variable name (not binary safe) */\nfor (p = var; *p; p++) {\n if (*p == ' ' /*|| *p == '.'*/) {\n *p='_';\n....\n || *p == '.' a.a[]=bb&a.a[]=BB&c%20c=dd <?php print_r($_GET); parse_str()" }, { "answer_id": 20365198, "author": "scipilot", "author_id": 209288, "author_profile": "https://Stackoverflow.com/users/209288", "pm_score": 5, "selected": false, "text": "<input name=\"data[database.username]\"> \n<input name=\"data[database.password]\"> \n<input name=\"data[something.else.really.deep]\"> \n <input name=\"database.username\"> \n<input name=\"database.password\"> \n<input name=\"something.else.really.deep\"> \n $posdata = $_POST['data'];\n" }, { "answer_id": 25799378, "author": "ChrisNY", "author_id": 420274, "author_profile": "https://Stackoverflow.com/users/420274", "pm_score": 0, "selected": false, "text": " <input type='text' value='First-.' name='alpha.beta[a.b][]' /><br>\n <input type='text' value='Second-.' name='alpha.beta[a.b][]' /><br>\n <input type='text' value='First-_' name='alpha_beta[a.b][]' /><br>\n <input type='text' value='Second-_' name='alpha_beta[a.b][]' /><br>\n 'alpha_beta' => \n array (size=1)\n 'a.b' => \n array (size=4)\n 0 => string 'First-.' (length=7)\n 1 => string 'Second-.' (length=8)\n 2 => string 'First-_' (length=7)\n 3 => string 'Second-_' (length=8)\n 'alpha.beta' => \n array (size=1)\n 'a.b' => \n array (size=2)\n 0 => string 'First-.' (length=7)\n 1 => string 'Second-.' (length=8)\n 'alpha_beta' => \n array (size=1)\n 'a.b' => \n array (size=2)\n 0 => string 'First-_' (length=7)\n 1 => string 'Second-_' (length=8)\n function getRealPostArray() {\n if ($_SERVER['REQUEST_METHOD'] !== 'POST') {#Nothing to do\n return null;\n }\n $neverANamePart = '~#~'; #Any arbitrary string never expected in a 'name'\n $postdata = file_get_contents(\"php://input\");\n $post = [];\n $rebuiltpairs = [];\n $postraws = explode('&', $postdata);\n foreach ($postraws as $postraw) { #Each is a string like: 'xxxx=yyyy'\n $keyvalpair = explode('=',$postraw);\n if (empty($keyvalpair[1])) {\n $keyvalpair[1] = '';\n }\n $pos = strpos($keyvalpair[0],'%5B');\n if ($pos !== false) {\n $str1 = substr($keyvalpair[0], 0, $pos);\n $str2 = substr($keyvalpair[0], $pos);\n $str1 = str_replace('.',$neverANamePart,$str1);\n $keyvalpair[0] = $str1.$str2;\n } else {\n $keyvalpair[0] = str_replace('.',$neverANamePart,$keyvalpair[0]);\n }\n $rebuiltpair = implode('=',$keyvalpair);\n $rebuiltpairs[]=$rebuiltpair;\n }\n $rebuiltpostdata = implode('&',$rebuiltpairs);\n parse_str($rebuiltpostdata, $post);\n $fixedpost = [];\n foreach ($post as $key => $val) {\n $fixedpost[str_replace($neverANamePart,'.',$key)] = $val;\n }\n return $fixedpost;\n}\n" }, { "answer_id": 26206877, "author": "John", "author_id": 606371, "author_profile": "https://Stackoverflow.com/users/606371", "pm_score": 0, "selected": false, "text": "$_POST <?php\nunset($_POST);\n$_POST = array();\n$p0 = explode('&',file_get_contents('php://input'));\nforeach ($p0 as $key => $value)\n{\n $p1 = explode('=',$value);\n $_POST[$p1[0]] = $p1[1];\n //OR...\n //$_POST[urldecode($p1[0])] = urldecode($p1[1]);\n}\nprint_r($_POST);\n?>\n" }, { "answer_id": 33735559, "author": "sasha-ch", "author_id": 4541523, "author_profile": "https://Stackoverflow.com/users/4541523", "pm_score": 0, "selected": false, "text": "function parseQueryString($data)\n{\n $data = rawurldecode($data); \n $pattern = '/(?:^|(?<=&))[^=&\\[]*[^=&\\[]*/'; \n $data = preg_replace_callback($pattern, function ($match){\n return bin2hex(urldecode($match[0]));\n }, $data);\n parse_str($data, $values);\n\n return array_combine(array_map('hex2bin', array_keys($values)), $values);\n}\n\n$_GET = parseQueryString($_SERVER['QUERY_STRING']);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,664
<p>Suppose I have:</p> <ol> <li>Toby</li> <li>Tiny</li> <li>Tory</li> <li>Tily</li> </ol> <p>Is there an algorithm that can easily create a list of common characters in the same positions in all these strings? (in this case the common characters are 'T' at position 0 and 'y' at position 3)</p> <p>I tried looking at some of the algorithms used for DNA sequence matching but it seems most of them are just used for finding common substrings regardless of their positions.</p>
[ { "answer_id": 68752, "author": "Josh Smeaton", "author_id": 10583, "author_profile": "https://Stackoverflow.com/users/10583", "pm_score": 1, "selected": false, "text": "str[] = { \"Toby\", \"Tiny\", \"Tory\", \"Tily\" };\nresult = null;\nlargestString = str.getLargestString(); // Made up function\nstr.remove(largestString)\nfor (i = 0; i < largestString.length; i++) {\n hits = 0;\n foreach (str as value) {\n if (i < value.length) {\n if (value.charAt(i) == largestString.charAt(i))\n hits++;\n }\n }\n if (hits == str.length)\n result += largestString.charAt(i);\n}\nprint(str.items);\n" }, { "answer_id": 68780, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 1, "selected": false, "text": " //c# -- assuming your strings are in a List<string> named Names\n int shortestLength = Names[0].Length, j;\n char[] CommonCharacters;\n char single;\n\n for (int i = 1; i < Names.Count; i++)\n {\n if (Names[i].Length < shortestLength) shortestLength = Names[i].Length;\n }\n\n CommonCharacters = new char[shortestLength];\n for (int i = 0; i < shortestLength; i++)\n {\n j = 1;\n single = Names[0][i];\n CommonCharacters[i] = single;\n while (j < shortestLength)\n {\n if (single != Names[j][i])\n {\n CommonCharacters[i] = \" \"[0];\n break;\n }\n j++;\n }\n }\n" }, { "answer_id": 68813, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 1, "selected": false, "text": "strings = %w(Tony Tiny Tory Tily)\npositions = Hash.new { |h,k| h[k] = Hash.new { |h,k| h[k] = 0 } }\nstrings.each { |str| \n 0.upto(str.length-1) { |i| \n positions[i][str[i,1]]+=1 \n }\n}\n positions = {\n 0=>{\"T\"=>4},\n 1=>{\"o\"=>2, \"i\"=>2}, \n 2=>{\"l\"=>1, \"n\"=>2, \"r\"=>1},\n 3=>{\"y\"=>4}\n}\n" }, { "answer_id": 68877, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env ruby\nchars = STDIN.gets.chomp.split(\"\")\nSTDIN.each do |string|\n chars = string.chomp.split(\"\").zip(chars).map {|x,y| x == y ? x : nil }\nend\nchars.each_index {|i| puts \"#{chars[i]} #{i}\" if chars[i] }\n $ commonletters.rb < input.txt\nT 0\ny 3\n Toby\nTiny\nTory\nTily\n" }, { "answer_id": 103810, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 1, "selected": false, "text": "items = ['Toby', 'Tiny', 'Tory', 'Tily']\ntuples = sorted(x for item in items for x in enumerate(item))\nprint [x[0] for x in itertools.groupby(tuples) if len(list(x[1])) == len(items)]\n [(0, 'T'), (3, 'y')]\n items = ['Toby', 'Tiny', 'Tory', 'Tily']\nminlen = min(len(x) for x in items)\nprint [(i, items[0][i]) for i in range(minlen) if all(x[i] == items[0][i] for x in items)]\n" }, { "answer_id": 104370, "author": "Morikal", "author_id": 18272, "author_profile": "https://Stackoverflow.com/users/18272", "pm_score": 0, "selected": false, "text": "CL-USER> (defun common-chars (&rest strings)\n (apply #'map 'list #'char= strings))\nCOMMON-CHARS\n CL-USER> (common-chars \"Toby\" \"Tiny\" \"Tory\" \"Tily\")\n(T NIL NIL T)\n CL-USER> (defun common-chars2 (&rest strings)\n (apply #'map\n 'list\n #'(lambda (&rest chars)\n (when (apply #'char= chars)\n (first chars))) ; return the char instead of T\n strings))\nCOMMON-CHARS2\n\nCL-USER> (common-chars2 \"Toby\" \"Tiny\" \"Tory\" \"Tily\")\n(#\\T NIL NIL #\\y)\n CL-USER> (format t \"~{~@[~A ~]~}\" (common-chars2 \"Toby\" \"Tiny\" \"Tory\" \"Tily\"))\nT y \nNIL\n" }, { "answer_id": 111699, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": false, "text": "#include <iostream>\n\nint main(void)\n{\n char words[4][5] = \n {\n \"Toby\",\n \"Tiny\",\n \"Tory\",\n \"Tily\"\n };\n\n int wordsCount = 4;\n int lettersPerWord = 4;\n\n int z;\n for (z = 1; z < wordsCount; z++)\n {\n int y;\n for (y = 0; y < lettersPerWord; y++)\n {\n if (words[0][y] != words[z][y])\n {\n words[0][y] = ' ';\n }\n }\n }\n\n std::cout << words[0] << std::endl;\n\n return 0;\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
68,666
<p>Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":</p> <pre><code>Clipboard.SetText(str); </code></pre> <p>This usually occurs the first time the Clipboard is used in the application and not after that.</p>
[ { "answer_id": 69081, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 6, "selected": false, "text": "for (int i = 0; i < 10; i++)\n{\n try\n {\n Clipboard.SetText(str);\n return;\n }\n catch { }\n System.Threading.Thread.Sleep(10);\n} \n" }, { "answer_id": 11726104, "author": "Yishai Galatzer", "author_id": 1048066, "author_profile": "https://Stackoverflow.com/users/1048066", "pm_score": 3, "selected": false, "text": "private static void SetDataInternal(string format, object data)\n{\n bool flag;\n if (IsDataFormatAutoConvert(format))\n {\n flag = true;\n }\n else\n {\n flag = false;\n }\n IDataObject obj2 = new DataObject();\n obj2.SetData(format, data, flag);\n SetDataObject(obj2, true);\n}\n" }, { "answer_id": 30165665, "author": "Mar", "author_id": 44217, "author_profile": "https://Stackoverflow.com/users/44217", "pm_score": 4, "selected": false, "text": "public static class ClipboardNative\n{\n [DllImport(\"user32.dll\")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\")]\n private static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetClipboardData(uint uFormat, IntPtr data);\n\n private const uint CF_UNICODETEXT = 13;\n\n public static bool CopyTextToClipboard(string text)\n {\n if (!OpenClipboard(IntPtr.Zero)){\n return false;\n }\n\n var global = Marshal.StringToHGlobalUni(text);\n\n SetClipboardData(CF_UNICODETEXT, global);\n CloseClipboard();\n\n //-------------------------------------------\n // Not sure, but it looks like we do not need \n // to free HGLOBAL because Clipboard is now \n // responsible for the copied data. (?)\n //\n // Otherwise the second call will crash\n // the app with a Win32 exception \n // inside OpenClipboard() function\n //-------------------------------------------\n // Marshal.FreeHGlobal(global);\n\n return true;\n }\n}\n" }, { "answer_id": 39125098, "author": "pr0gg3r", "author_id": 1159244, "author_profile": "https://Stackoverflow.com/users/1159244", "pm_score": 5, "selected": false, "text": "Clipboard.SetText(str) Clipboard.SetText(str);\n Clipboard.SetDataObject(str);\n" }, { "answer_id": 43910453, "author": "Ellix4u", "author_id": 3690683, "author_profile": "https://Stackoverflow.com/users/3690683", "pm_score": 1, "selected": false, "text": "ApplicationCommands.Copy.Execute(null, myDataGrid);\n Clipboard.Clear();\nApplicationCommands.Copy.Execute(null, myDataGrid);\n" }, { "answer_id": 64685710, "author": "Bret Pehrson", "author_id": 7547283, "author_profile": "https://Stackoverflow.com/users/7547283", "pm_score": 2, "selected": false, "text": "System.Windows.Forms.Clipboard.SetDataObject(yourText, true, 10, 100);\n" }, { "answer_id": 74564870, "author": "Marek J", "author_id": 6423994, "author_profile": "https://Stackoverflow.com/users/6423994", "pm_score": 0, "selected": false, "text": "IDataObject CopyStringToClipboard(string s)\n{\n var dataObject = new DataObject(s);\n Clipboard.SetDataObject(dataObject, false);\n return dataObject;\n}\n try\n{\n if ((clipboardData != null) && Clipboard.IsCurrent(clipboardData))\n Clipboard.Flush();\n}\ncatch (COMException ex) {}\n" }, { "answer_id": 74679767, "author": "sarh", "author_id": 282694, "author_profile": "https://Stackoverflow.com/users/282694", "pm_score": 0, "selected": false, "text": "class Program\n{\n [DllImport(\"user32.dll\")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\")]\n private static extern bool CloseClipboard();\n\n static void Main(string[] args)\n {\n bool res = OpenClipboard(IntPtr.Zero);\n Console.Write(res);\n Console.Read();\n CloseClipboard();\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10784/" ]
68,677
<p>I'm using SQL Server 2000 to print out some values from a table using <code>PRINT</code>. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:</p> <pre><code>DECLARE @binvalue binary(4) SET @binvalue = 0x12345678 PRINT CAST(@binvalue AS nvarchar) </code></pre> <p>Expected:</p> <blockquote> <p>0x12345678</p> </blockquote> <p>Instead, it prints two gibberish characters.</p> <p>How can I print the value of binary data? Is there a built-in or do I need to roll my own?</p> <p>Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself.</p>
[ { "answer_id": 68858, "author": "Ricardo C", "author_id": 232589, "author_profile": "https://Stackoverflow.com/users/232589", "pm_score": 2, "selected": false, "text": "DECLARE @binvalue binary(4)\nSET @binvalue = 0x61000000\nPRINT @binvalue \nPRINT cast('a' AS binary(4))\nPRINT cast(0x61 AS varchar)\n DECLARE @mybin1 binary(16)\nDECLARE @s varchar(100)\nSET @mybin1 = 0x098F6BCD4621D373CADE4E832627B4F6\nSET @s = 'The value of @mybin1 is: ' + sys.fn_varbintohexsubstring(0, @mybin1,1,0)\nPRINT @s\n sp_helptext 'fn_varbintohexsubstring'\n" }, { "answer_id": 68872, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 6, "selected": true, "text": "print master.sys.fn_varbintohexstr(@binvalue)\n" }, { "answer_id": 12016386, "author": "Ihor B.", "author_id": 1253118, "author_profile": "https://Stackoverflow.com/users/1253118", "pm_score": 6, "selected": false, "text": "master.sys.fn_varbintohexstr binary(16) convert convert(char(34), @binvalue, 1)\n 16*2 + 2 = 34 select master.sys.fn_varbintohexstr(field)\nfrom table`\n select convert(char(34), field, 1)\nfrom table`\n" }, { "answer_id": 12549880, "author": "Charlie Affumigato", "author_id": 1691857, "author_profile": "https://Stackoverflow.com/users/1691857", "pm_score": 5, "selected": false, "text": "select convert(varchar(max), field , 1) \nfrom table\n using varchar(max)" }, { "answer_id": 17951174, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "timestamp varchar SELECT \n CONVERT(\n varchar(50), \n CAST(MAX(timestamp) AS varbinary(8)), \n 1) AS LastTS\nFROM Users\n LastTS\n==================\n0x000000000086862C\n CONVERT varbinary -> varchar CAST SELECT \n CAST(\n CAST(MAX(timestamp) AS varbinary(8)) \n AS varchar(50) ) AS LastTS\nFROM Users\n SELECT CAST(CONVERT(varbinary(50), '0x000000000086862C', 1) AS timestamp)\n" }, { "answer_id": 19399525, "author": "David Claughton", "author_id": 2885723, "author_profile": "https://Stackoverflow.com/users/2885723", "pm_score": 2, "selected": false, "text": "DECLARE @binvalue binary(4)\nSET @binvalue = 0x12345678\nPRINT 'cast(@binvalue AS nvarchar): ' + CAST(@binvalue AS nvarchar)\nPRINT 'convert(varchar(max), @binvalue, 0): ' + CONVERT(varchar(max), @binvalue, 0)\nPRINT 'convert(varchar(max), @binvalue, 1): ' + CONVERT(varchar(max), @binvalue, 1)\nPRINT 'convert(varchar(max), @binvalue, 2): ' + CONVERT(varchar(max), @binvalue, 2)\nprint 'master.sys.fn_varbintohexstr(@binvalue): ' + master.sys.fn_varbintohexstr(@binvalue)\n cast(@binvalue AS nvarchar): 㐒硖\nconvert(varchar(max), @binvalue, 0): 4Vx\nconvert(varchar(max), @binvalue, 1): 4Vx\nconvert(varchar(max), @binvalue, 2): 4Vx\nmaster.sys.fn_varbintohexstr(@binvalue): 0x12345678\n cast(@binvalue AS nvarchar): 㐒硖\nconvert(varchar(max), @binvalue, 0): 4Vx\nconvert(varchar(max), @binvalue, 1): 0x12345678\nconvert(varchar(max), @binvalue, 2): 12345678\nmaster.sys.fn_varbintohexstr(@binvalue): 0x12345678\n" }, { "answer_id": 65160592, "author": "Nick Legend", "author_id": 3868454, "author_profile": "https://Stackoverflow.com/users/3868454", "pm_score": 0, "selected": false, "text": "with \nsq1 as (select '41424344' as v), -- this is 'ABCD'\n-- Need binary size, otherwise it sets binary(30) in my case\nsq2 as (select v, convert(binary(4), v, 2) as b from sq1), \nsq3 as (select b, v, convert(varchar, b, 2) as v1 from sq2)\n--\nselect b, v, v1 from sq3\nwhere v = v1\n;\n b |v |v1 |\n----|--------|--------|\nABCD|41424344|41424344|\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3750/" ]
68,691
<p>After cleaning a folder full of HTML files with TIDY, how can the tables content be extracted for further processing?</p>
[ { "answer_id": 73418, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 2, "selected": true, "text": "Content-Type application/ms-vnd.excel" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359937/" ]
68,711
<p>any idea how if the following is possible in PHP as a single line ?:</p> <pre><code>&lt;?php $firstElement = functionThatReturnsAnArray()[0]; </code></pre> <p>... It doesn't seem to 'take'. I need to do this as a 2-stepper:</p> <pre><code>&lt;?php $allElements = functionThatReturnsAnArray(); $firstElement = $allElements[0]; </code></pre> <p>... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ...</p>
[ { "answer_id": 68745, "author": "calebbrown", "author_id": 7007, "author_profile": "https://Stackoverflow.com/users/7007", "pm_score": 4, "selected": true, "text": "<?php\n$firstElement = reset(functionThatReturnsAnArray());\n" }, { "answer_id": 68828, "author": "Scott Reynen", "author_id": 10837, "author_profile": "https://Stackoverflow.com/users/10837", "pm_score": 2, "selected": false, "text": "list( $firstElement ) = functionThatReturnsAnArray();\nlist( $firstElement , $secondElement ) = functionThatReturnsAnArray();\n" }, { "answer_id": 68841, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": false, "text": "list(,,$thirdElement) = $myArray;\n" }, { "answer_id": 68965, "author": "neouser99", "author_id": 10669, "author_profile": "https://Stackoverflow.com/users/10669", "pm_score": -1, "selected": false, "text": "function func($first = false) {\n ...\n if $first return $array[0];\n else return $array;\n}\n\n$array = func();\n$item = func(true);\n array(func())[0][i];\n" }, { "answer_id": 69303, "author": "Garrett Albright", "author_id": 11023, "author_profile": "https://Stackoverflow.com/users/11023", "pm_score": 3, "selected": false, "text": "<?php\n\necho array_shift(i_return_an_array());\n\nfunction i_return_an_array() {\n return array('foo', 'bar', 'baz');\n}\n foo" }, { "answer_id": 70092, "author": "Greg", "author_id": 1916, "author_profile": "https://Stackoverflow.com/users/1916", "pm_score": 1, "selected": false, "text": "current($array) array_shift($array)" }, { "answer_id": 70310, "author": "Draco777", "author_id": 11473, "author_profile": "https://Stackoverflow.com/users/11473", "pm_score": 0, "selected": false, "text": "$firstElement = ($t = functionThatReturnsAnArray()) ? $t[0] : false;\n $string = (($t = functionThatReturnsAnArray())==0) . $t[0];\n" }, { "answer_id": 70699, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "array_slice() $elementX = array_slice(functionThatReturnsAnArray(), $x, 1);\n end()" }, { "answer_id": 72510, "author": "Adam Hopkinson", "author_id": 12280, "author_profile": "https://Stackoverflow.com/users/12280", "pm_score": 0, "selected": false, "text": "$element = functionThatReturnsArray();\n$element = $element[0];\n" }, { "answer_id": 72916, "author": "deceze", "author_id": 476, "author_profile": "https://Stackoverflow.com/users/476", "pm_score": 0, "selected": false, "text": "$firstItem = current(returnsArray());\n" }, { "answer_id": 73923, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": -1, "selected": false, "text": "<?php\nfunction functionThatReturnsAnArray($n = NULL) {\n return ($n === NULL ? $myArray : $myArray[$n]);\n}\n$firstElement = functionThatReturnsAnArray(0);\n" }, { "answer_id": 74530, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 1, "selected": false, "text": "/**\n * Grabs an element from an array using a key much like array_pop\n */\nfunction array_key_value($array, $key) {\n if(!empty($array) && array_key_exists($key, $array)) {\n return $array[$key];\n }\n else {\n return FALSE;\n }\n}\n $result = array_key_value(getMeAnArray(), 'arrayKey');\n" }, { "answer_id": 299108, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function functionThatReturnsOneElement( $arg )\n{\n $result = functionThatReturnsAnArray( $arg );\n return $result[0];\n}\n$firstElement = functionThatReturnsOneElement();\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,749
<p>Using .Net (C#), how can you work with USB devices? </p> <p>How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write).</p> <p>Is there a native .Net solution to do this?</p>
[ { "answer_id": 13829628, "author": "Syn", "author_id": 1895588, "author_profile": "https://Stackoverflow.com/users/1895588", "pm_score": 4, "selected": false, "text": "class USBControl : IDisposable\n {\n // used for monitoring plugging and unplugging of USB devices.\n private ManagementEventWatcher watcherAttach;\n private ManagementEventWatcher watcherRemove;\n\n public USBControl()\n {\n // Add USB plugged event watching\n watcherAttach = new ManagementEventWatcher();\n //var queryAttach = new WqlEventQuery(\"SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2\");\n watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);\n watcherAttach.Query = new WqlEventQuery(\"SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2\");\n watcherAttach.Start();\n\n // Add USB unplugged event watching\n watcherRemove = new ManagementEventWatcher();\n //var queryRemove = new WqlEventQuery(\"SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3\");\n watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);\n watcherRemove.Query = new WqlEventQuery(\"SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3\");\n watcherRemove.Start();\n }\n\n /// <summary>\n /// Used to dispose of the USB device watchers when the USBControl class is disposed of.\n /// </summary>\n public void Dispose()\n {\n watcherAttach.Stop();\n watcherRemove.Stop();\n //Thread.Sleep(1000);\n watcherAttach.Dispose();\n watcherRemove.Dispose();\n //Thread.Sleep(1000);\n }\n\n void watcher_EventArrived(object sender, EventArrivedEventArgs e)\n {\n Debug.WriteLine(\"watcher_EventArrived\");\n }\n\n void watcher_EventRemoved(object sender, EventArrivedEventArgs e)\n {\n Debug.WriteLine(\"watcher_EventRemoved\");\n }\n\n ~USBControl()\n {\n this.Dispose();\n }\n\n\n }\n" }, { "answer_id": 28775687, "author": "Pabinator", "author_id": 1933253, "author_profile": "https://Stackoverflow.com/users/1933253", "pm_score": 1, "selected": false, "text": " using NationalInstruments.VisaNS;\n\n #region UsbRaw\n /// <summary>\n /// Class to communicate with USB Devices using the UsbRaw Class of National Instruments\n /// </summary>\n public class UsbRaw\n {\n private NationalInstruments.VisaNS.UsbRaw usbRaw;\n private List<byte> DataReceived = new List<byte>();\n\n /// <summary>\n /// Initialize the USB Device to interact with\n /// </summary>\n /// <param name=\"ResourseName\">In this format: \"USB0::0x1448::0x8CA0::NI-VISA-30004::RAW\". Use the NI-VISA Driver Wizard from Start»All Programs»National Instruments»VISA»Driver Wizard to create the USB Driver for the device you need to talk to.</param>\n public UsbRaw(string ResourseName)\n {\n usbRaw = new NationalInstruments.VisaNS.UsbRaw(ResourseName, AccessModes.NoLock, 10000, false);\n usbRaw.UsbInterrupt += new UsbRawInterruptEventHandler(OnUSBInterrupt);\n usbRaw.EnableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);\n }\n\n /// <summary>\n /// Clears a USB Device from any previous commands\n /// </summary>\n public void Clear()\n {\n usbRaw.Clear();\n }\n\n /// <summary>\n /// Writes Bytes to the USB Device\n /// </summary>\n /// <param name=\"EndPoint\">USB Bulk Out Pipe attribute to send the data to. For example: If you see on the Bus Hound sniffer tool that data is coming out from something like 28.4 (Device column), this means that the USB is using Endpoint 4 (Number after the dot)</param>\n /// <param name=\"BytesToSend\">Data to send to the USB device</param>\n public void Write(short EndPoint, byte[] BytesToSend)\n {\n usbRaw.BulkOutPipe = EndPoint;\n usbRaw.Write(BytesToSend); // Write to USB\n }\n\n /// <summary>\n /// Reads bytes from a USB Device\n /// </summary>\n /// <returns>Bytes Read</returns>\n public byte[] Read()\n {\n usbRaw.ReadByteArray(); // This fires the UsbRawInterruptEventHandler \n\n byte[] rxBytes = DataReceived.ToArray(); // Collects the data received\n\n return rxBytes;\n }\n\n /// <summary>\n /// This is used to get the data received by the USB device\n /// </summary>\n /// <param name=\"sender\"></param>\n /// <param name=\"e\"></param>\n private void OnUSBInterrupt(object sender, UsbRawInterruptEventArgs e)\n {\n try\n {\n DataReceived.Clear(); // Clear previous data received\n DataReceived.AddRange(e.DataBuffer); \n }\n catch (Exception exp)\n {\n string errorMsg = \"Error: \" + exp.Message;\n DataReceived.AddRange(ASCIIEncoding.ASCII.GetBytes(errorMsg));\n }\n }\n\n /// <summary>\n /// Use this function to clean up the UsbRaw class\n /// </summary>\n public void Dispose()\n {\n usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);\n\n if (usbRaw != null)\n {\n usbRaw.Dispose();\n } \n }\n\n }\n #endregion UsbRaw\n UsbRaw usbRaw = new UsbRaw(\"USB0::0x1448::0x8CA0::NI-VISA-30004::RAW\");\n\nbyte[] sendData = new byte[] { 0x53, 0x4c, 0x56 };\nusbRaw.Write(4, sendData); // Write bytes to the USB Device\nbyte[] readData = usbRaw.Read(); // Read bytes from the USB Device\n\nusbRaw.Dispose();\n" }, { "answer_id": 50936836, "author": "Mike Lowery", "author_id": 298511, "author_profile": "https://Stackoverflow.com/users/298511", "pm_score": 0, "selected": false, "text": "Process.Start()" }, { "answer_id": 51854202, "author": "Christian Findlay", "author_id": 1878141, "author_profile": "https://Stackoverflow.com/users/1878141", "pm_score": 2, "selected": false, "text": "public static class HidAPICalls \n{\n #region Constants\n private const int DigcfDeviceinterface = 16;\n private const int DigcfPresent = 2;\n private const uint FileShareRead = 1;\n private const uint FileShareWrite = 2;\n private const uint GenericRead = 2147483648;\n private const uint GenericWrite = 1073741824;\n private const uint OpenExisting = 3;\n private const int HIDP_STATUS_SUCCESS = 0x110000;\n private const int HIDP_STATUS_INVALID_PREPARSED_DATA = -0x3FEF0000;\n #endregion\n\n #region API Calls\n\n [DllImport(\"hid.dll\", SetLastError = true)]\n private static extern bool HidD_GetPreparsedData(SafeFileHandle hidDeviceObject, out IntPtr pointerToPreparsedData);\n\n [DllImport(\"hid.dll\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n private static extern bool HidD_GetManufacturerString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n [DllImport(\"hid.dll\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n private static extern bool HidD_GetProductString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n [DllImport(\"hid.dll\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n private static extern bool HidD_GetSerialNumberString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n [DllImport(\"hid.dll\", SetLastError = true)]\n private static extern int HidP_GetCaps(IntPtr pointerToPreparsedData, out HidCollectionCapabilities hidCollectionCapabilities);\n\n [DllImport(\"hid.dll\", SetLastError = true)]\n private static extern bool HidD_GetAttributes(SafeFileHandle hidDeviceObject, out HidAttributes attributes);\n\n [DllImport(\"hid.dll\", SetLastError = true)]\n private static extern bool HidD_FreePreparsedData(ref IntPtr pointerToPreparsedData);\n\n [DllImport(\"hid.dll\", SetLastError = true)]\n private static extern void HidD_GetHidGuid(ref Guid hidGuid);\n\n private delegate bool GetString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n #endregion\n\n #region Helper Methods\n\n #region Public Methods\n public static HidAttributes GetHidAttributes(SafeFileHandle safeFileHandle)\n {\n var isSuccess = HidD_GetAttributes(safeFileHandle, out var hidAttributes);\n WindowsDeviceBase.HandleError(isSuccess, \"Could not get Hid Attributes\");\n return hidAttributes;\n }\n\n public static HidCollectionCapabilities GetHidCapabilities(SafeFileHandle readSafeFileHandle)\n {\n var isSuccess = HidD_GetPreparsedData(readSafeFileHandle, out var pointerToPreParsedData);\n WindowsDeviceBase.HandleError(isSuccess, \"Could not get pre parsed data\");\n\n var result = HidP_GetCaps(pointerToPreParsedData, out var hidCollectionCapabilities);\n if (result != HIDP_STATUS_SUCCESS)\n {\n throw new Exception($\"Could not get Hid capabilities. Return code: {result}\");\n }\n\n isSuccess = HidD_FreePreparsedData(ref pointerToPreParsedData);\n WindowsDeviceBase.HandleError(isSuccess, \"Could not release handle for getting Hid capabilities\");\n\n return hidCollectionCapabilities;\n }\n\n public static string GetManufacturer(SafeFileHandle safeFileHandle)\n {\n return GetHidString(safeFileHandle, HidD_GetManufacturerString);\n }\n\n public static string GetProduct(SafeFileHandle safeFileHandle)\n {\n return GetHidString(safeFileHandle, HidD_GetProductString);\n }\n\n public static string GetSerialNumber(SafeFileHandle safeFileHandle)\n {\n return GetHidString(safeFileHandle, HidD_GetSerialNumberString);\n }\n #endregion\n\n #region Private Static Methods\n private static string GetHidString(SafeFileHandle safeFileHandle, GetString getString)\n {\n var pointerToBuffer = Marshal.AllocHGlobal(126);\n var isSuccess = getString(safeFileHandle, pointerToBuffer, 126);\n Marshal.FreeHGlobal(pointerToBuffer);\n WindowsDeviceBase.HandleError(isSuccess, \"Could not get Hid string\");\n return Marshal.PtrToStringUni(pointerToBuffer); \n }\n #endregion\n\n #endregion\n public static partial class WinUsbApiCalls\n{\n #region Constants\n public const int EnglishLanguageID = 1033;\n public const uint DEVICE_SPEED = 1;\n public const byte USB_ENDPOINT_DIRECTION_MASK = 0X80;\n public const int WritePipeId = 0x80;\n\n /// <summary>\n /// Not sure where this constant is defined...\n /// </summary>\n public const int DEFAULT_DESCRIPTOR_TYPE = 0x01;\n public const int USB_STRING_DESCRIPTOR_TYPE = 0x03;\n #endregion\n\n #region API Calls\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, byte[] Buffer, uint BufferLength, ref uint LengthTransferred, IntPtr Overlapped);\n\n [DllImport(\"winusb.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n public static extern bool WinUsb_GetAssociatedInterface(SafeFileHandle InterfaceHandle, byte AssociatedInterfaceIndex, out SafeFileHandle AssociatedInterfaceHandle);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, ushort LanguageID, out USB_DEVICE_DESCRIPTOR deviceDesc, uint BufferLength, out uint LengthTransfered);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, UInt16 LanguageID, byte[] Buffer, UInt32 BufferLength, out UInt32 LengthTransfered);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_Free(SafeFileHandle InterfaceHandle);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle, out SafeFileHandle InterfaceHandle);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_QueryDeviceInformation(IntPtr InterfaceHandle, uint InformationType, ref uint BufferLength, ref byte Buffer);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_QueryInterfaceSettings(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, out USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_QueryPipe(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, byte PipeIndex, out WINUSB_PIPE_INFORMATION PipeInformation);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_ReadPipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, byte PipeID, uint PolicyType, uint ValueLength, ref uint Value);\n\n [DllImport(\"winusb.dll\", SetLastError = true)]\n public static extern bool WinUsb_WritePipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);\n #endregion\n\n #region Public Methods\n public static string GetDescriptor(SafeFileHandle defaultInterfaceHandle, byte index, string errorMessage)\n {\n var buffer = new byte[256];\n var isSuccess = WinUsb_GetDescriptor(defaultInterfaceHandle, USB_STRING_DESCRIPTOR_TYPE, index, EnglishLanguageID, buffer, (uint)buffer.Length, out var transfered);\n WindowsDeviceBase.HandleError(isSuccess, errorMessage);\n var descriptor = new string(Encoding.Unicode.GetChars(buffer, 2, (int)transfered));\n return descriptor.Substring(0, descriptor.Length - 1);\n }\n #endregion\n}\n internal class TrezorExample : IDisposable\n{\n #region Fields\n //Define the types of devices to search for. This particular device can be connected to via USB, or Hid\n private readonly List<FilterDeviceDefinition> _DeviceDefinitions = new List<FilterDeviceDefinition>\n {\n new FilterDeviceDefinition{ DeviceType= DeviceType.Hid, VendorId= 0x534C, ProductId=0x0001, Label=\"Trezor One Firmware 1.6.x\", UsagePage=65280 },\n new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x534C, ProductId=0x0001, Label=\"Trezor One Firmware 1.6.x (Android Only)\" },\n new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C1, Label=\"Trezor One Firmware 1.7.x\" },\n new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C0, Label=\"Model T\" }\n };\n #endregion\n\n #region Events\n public event EventHandler TrezorInitialized;\n public event EventHandler TrezorDisconnected;\n #endregion\n\n #region Public Properties\n public IDevice TrezorDevice { get; private set; }\n public DeviceListener DeviceListener { get; private set; }\n #endregion\n\n #region Event Handlers\n private void DevicePoller_DeviceInitialized(object sender, DeviceEventArgs e)\n {\n TrezorDevice = e.Device;\n TrezorInitialized?.Invoke(this, new EventArgs());\n }\n\n private void DevicePoller_DeviceDisconnected(object sender, DeviceEventArgs e)\n {\n TrezorDevice = null;\n TrezorDisconnected?.Invoke(this, new EventArgs());\n }\n #endregion\n\n #region Public Methods\n public void StartListening()\n {\n TrezorDevice?.Dispose();\n DeviceListener = new DeviceListener(_DeviceDefinitions, 3000);\n DeviceListener.DeviceDisconnected += DevicePoller_DeviceDisconnected;\n DeviceListener.DeviceInitialized += DevicePoller_DeviceInitialized;\n }\n\n public async Task InitializeTrezorAsync()\n {\n //Get the first available device and connect to it\n var devices = await DeviceManager.Current.GetDevices(_DeviceDefinitions);\n TrezorDevice = devices.FirstOrDefault();\n await TrezorDevice.InitializeAsync();\n }\n\n public async Task<byte[]> WriteAndReadFromDeviceAsync()\n {\n //Create a buffer with 3 bytes (initialize)\n var writeBuffer = new byte[64];\n writeBuffer[0] = 0x3f;\n writeBuffer[1] = 0x23;\n writeBuffer[2] = 0x23;\n\n //Write the data to the device\n return await TrezorDevice.WriteAndReadAsync(writeBuffer);\n }\n\n public void Dispose()\n {\n TrezorDevice?.Dispose();\n }\n #endregion\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5903/" ]
68,750
<p>This should hopefully be a simple one.</p> <p>I would like to add an extension method to the System.Web.Mvc.ViewPage&lt; T > class.</p> <p>How should this extension method look?</p> <p>My first intuitive thought is something like this:</p> <pre><code>namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle(this ViewPage&lt;Type&gt; v) { return ""; } } } </code></pre> <p><strong>Solution</strong></p> <p>The general solution is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">this answer</a>.</p> <p>The specific solution to extending the System.Web.Mvc.ViewPage class is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802">my answer</a> below, which started from the <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">general solution</a>.</p> <p>The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.</p>
[ { "answer_id": 68772, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 5, "selected": true, "text": "namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> v)\n {\n return \"\";\n }\n }\n}\n" }, { "answer_id": 68779, "author": "Corey Ross", "author_id": 5927, "author_profile": "https://Stackoverflow.com/users/5927", "pm_score": 2, "selected": false, "text": "namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<Type>(this ViewPage<Type> v)\n {\n return \"\";\n }\n }\n}\n" }, { "answer_id": 68802, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": false, "text": "namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> v) \n where T : class\n {\n return \"\";\n }\n }\n}\n" }, { "answer_id": 68826, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 1, "selected": false, "text": "public static string GetDefaultPageTitle(this ViewPage<YourSpecificType> v)\n{\n ...\n}\n" }, { "answer_id": 68864, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "ForEach IEnumerable<T> public static class IEnumerableUtils\n{\n public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)\n {\n foreach(T item in collection)\n action(item);\n }\n}\n" }, { "answer_id": 68935, "author": "chadmyers", "author_id": 10862, "author_profile": "https://Stackoverflow.com/users/10862", "pm_score": 2, "selected": false, "text": "namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> view)\n where T : class\n {\n return \"\";\n }\n }\n}\n" }, { "answer_id": 11771468, "author": "Tod Thomson", "author_id": 372666, "author_profile": "https://Stackoverflow.com/users/372666", "pm_score": 1, "selected": false, "text": "public static class WebViewPageExtensions\n{\n public static string GetFormActionUrl(this WebViewPage view)\n {\n return string.Format(\"/{0}/{1}/{2}\", view.GetController(), view.GetAction(), view.GetId());\n }\n\n public static string GetController(this WebViewPage view)\n {\n return Get(view, \"controller\");\n }\n\n public static string GetAction(this WebViewPage view)\n {\n return Get(view, \"action\");\n }\n\n public static string GetId(this WebViewPage view)\n {\n return Get(view, \"id\");\n }\n\n private static string Get(WebViewPage view, string key)\n {\n return view.ViewContext.Controller.ValueProvider.GetValue(key).RawValue.ToString();\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
68,774
<p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
[ { "answer_id": 68796, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 7, "selected": true, "text": "import socket\nsock = socket.socket()\nsock.connect((address, port))\n send() recv()" }, { "answer_id": 68911, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 4, "selected": false, "text": "s = socket.socket()\ns.connect((ip,port))\ns.send(\"my request\\r\")\nprint s.recv(256)\ns.close()\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
68,821
<p>I want to dynamically hide/show some of the columns in a NSTableView, based on the data that is going to be displayed - basically, if a column is empty I'd like the column to be hidden. I'm currently populating the table with a controller class as the delegate for the table.</p> <p>Any ideas? I see that I can set the column hidden in Interface Builder, however there doesn't seem to be a good time to go through the columns and check if they are empty or not, since there doesn't seem to be a method that is called before/after all of the data in the table is populated.</p>
[ { "answer_id": 71609, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 2, "selected": false, "text": "NSTableColumn *aColumn = [[NSTableColumn alloc] initWithIdentifier:attr];\n[aColumn setWidth:DEFAULTCOLWIDTH];\n[aColumn setMinWidth:MINCOLWIDTH];\n[[aColumn headerCell] setStringValue:columnLabel];\n\n[aColumn bind:@\"value\"\n toObject:arrayController \n withKeyPath:keyPath \n options:nil]; \n\n[tableView addTableColumn:aColumn];\n[aColumn release];\n" }, { "answer_id": 9490225, "author": "Cameron Hotchkies", "author_id": 463465, "author_profile": "https://Stackoverflow.com/users/463465", "pm_score": 4, "selected": false, "text": "setHidden: NSInteger colIdx;\nNSTableColumn* col;\n\ncolIdx = [myTable columnWithIdentifier:@\"columnIdent\"];\ncol = [myTable.tableColumns objectAtIndex:colIdx];\n[col setHidden:YES];\n" }, { "answer_id": 33037710, "author": "Daniel", "author_id": 345258, "author_profile": "https://Stackoverflow.com/users/345258", "pm_score": 2, "selected": false, "text": "tableView.tableColumnWithIdentifier(\"Status\")?.bind(\"hidden\", toObject: NSUserDefaults.standardUserDefaults(), withKeyPath: \"TableColumnStatus\", options: nil)\n [[self.tableView tableColumnWithIdentifier:@\"Status\"] bind:@\"hidden\" toObject:[NSUserDefaults standardUserDefaults] withKeyPath:@\"TableColumnStatus\" options:nil];\n" }, { "answer_id": 53111511, "author": "Lookaji", "author_id": 4111774, "author_profile": "https://Stackoverflow.com/users/4111774", "pm_score": 0, "selected": false, "text": "isHidden hideColumnsFlag class ViewController: NSViewController {\n\n // define the boolean binding variable to hide the columns and use its name as keypath\n @objc dynamic var hideColumnsFlag = true\n\n // Referring the column(s)\n // Method 1: creating IBOutlet(s) for the column(s): just ctrl-drag each column here to add it\n @IBOutlet weak var hideableTableColumn: NSTableColumn!\n // add as many column outlets as you need...\n\n // or, if you prefer working with columns' string keypaths\n // Method 2: use just the table view IBOutlet and its column identifiers (you **must** anyway set the latter identifiers manually via IB for each column)\n @IBOutlet weak var theTableView: NSTableView! // this line could be actually removed if using the first method on this example, but in a real case, you will probably need it anyway.\n\n // MARK: View Controller Lifecycle\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n // Method 1\n // referring the columns by using the outlets as such:\n hideableTableColumn.bind(.hidden, to: self, withKeyPath: \"hideColumnsFlag\", options: nil)\n // repeat for each column outlet.\n\n // Method 2\n // or if you need/prefer to use the column identifiers strings then:\n // theTableView.tableColumn(withIdentifier: .init(\"columnName\"))?.bind(.hidden, to: self, withKeyPath: \"hideColumnsFlag\", options: nil)\n // repeat for each column identifier you have set.\n\n // obviously use just one method by commenting/uncommenting one or the other.\n }\n\n // MARK: Actions\n\n // this is the checkBox action method, just toggling the boolean variable bound to the columns in the viewDidLoad method.\n @IBAction func hideColumnsCheckboxAction(_ sender: NSButton) {\n hideColumnsFlag = sender.state == .on\n }\n}\n Hidden Enabled Editable isHidden" }, { "answer_id": 68811090, "author": "Ruben Kazumov", "author_id": 1543083, "author_profile": "https://Stackoverflow.com/users/1543083", "pm_score": 0, "selected": false, "text": "NSArrayController, NSNumber maxWidth maxWidth import Cocoa\n\nclass Column: NSTableColumn {\n\n /// Observe the binding messages\n override func setValue(_ value: Any?, forKey key: String) {\n if key == \"maxWidth\" && value != nil { // Filters the signal\n let w = value as! NSNumber // Explores change\n if w == NSNumber(integerLiteral: 0) {\n self.isHidden = true\n } else {\n self.isHidden = false\n }\n return // No propagation for the value change\n }\n super.setValue(value, forKey: key) // Propagate the signal\n }\n \n}\n\n Column." } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3857/" ]
68,843
<p>How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?</p> <p>Moreover, if I specify <code>sleep(1,1,"xyz")</code> or any arbitrary number of arguments, the compiler still compiles it. But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual <code>sleep()</code> function takes a single argument only, but our program mentioned three arguments.</p> <pre><code>/********************************/ int main() { short int i; for(i = 0; i&lt;5; i++) { printf("%d",i);`print("code sample");` sleep(1); } return 0; } </code></pre>
[ { "answer_id": 68861, "author": "Jason Dagit", "author_id": 5113, "author_profile": "https://Stackoverflow.com/users/5113", "pm_score": 2, "selected": false, "text": "int sleep(int);\n" }, { "answer_id": 68874, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 1, "selected": false, "text": "-fno-builtin -fno-builtin-function" }, { "answer_id": 69147, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 3, "selected": false, "text": "int sleep();\n int sleep(t)\nint t;\n{\n /* do something with t */\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
68,851
<p>I am trying out FirePHP.</p> <p>I installed it and restarted Firefox, enabled Firebug for my localhost, moved the demo <code>oo.php</code> file that comes with the download into an IIS virtual directory, changed the include path, removed the <code>apache_request_headers()</code> call since I am running IIS, and the only output I see is</p> <blockquote> <p>Notice: Undefined offset: 1 in C:\Documents and Settings\georgem\My Documents\projects\auctronic\FirePHPCore\FirePHP.class.php on line 167 <br/> Hello World</p> </blockquote> <p>Nothing appears in the Firebug console. </p> <p>Am I missing something?</p> <p><strong>EDIT:</strong> Noticed it said that output buffering has to be enabled so I added a call to <a href="http://php.net/manual/en/function.ob-start.php" rel="nofollow noreferrer"><code>ob_start()</code></a> at the top of the file...same results.</p>
[ { "answer_id": 78174, "author": "djn", "author_id": 9673, "author_profile": "https://Stackoverflow.com/users/9673", "pm_score": 1, "selected": false, "text": "fb.php ob_start() fb($myErrorVariable, 'My brand new error', FirePHP::ERROR);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
68,907
<p>How can you measure the amount of time a function will take to execute? </p> <p>This is a relatively short function and the execution time would probably be in the millisecond range.</p> <p>This particular question relates to an embedded system, programmed in C or C++.</p>
[ { "answer_id": 68919, "author": "Galen", "author_id": 7894, "author_profile": "https://Stackoverflow.com/users/7894", "pm_score": 2, "selected": false, "text": "start_time = timer\nfunction()\nexec_time = timer - start_time\n" }, { "answer_id": 68925, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "// begin timing\nfor (int i = 0; i < 10000; i++) {\n invokeFunction();\n}\n// end time\n// divide by 10000 to get actual time.\n" }, { "answer_id": 68949, "author": "stalepretzel", "author_id": 1615, "author_profile": "https://Stackoverflow.com/users/1615", "pm_score": 1, "selected": false, "text": "time python function.py\n" }, { "answer_id": 68977, "author": "Joe Fontana", "author_id": 73, "author_profile": "https://Stackoverflow.com/users/73", "pm_score": 2, "selected": false, "text": "time [funtion_name]\n" }, { "answer_id": 68988, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 3, "selected": false, "text": "\n *io_pin = 1;\n myfunc();\n *io_pin = 0;\n" }, { "answer_id": 69166, "author": "Drew Frezell", "author_id": 10954, "author_profile": "https://Stackoverflow.com/users/10954", "pm_score": 2, "selected": false, "text": "#include <time.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define SEC_TO_NSEC(s) ((s) * 1000 * 1000 * 1000)\n\nint work_function(int c) {\n // do some work here\n int i, j;\n int foo = 0;\n for (i = 0; i < 1000; i++) {\n for (j = 0; j < 1000; j++) {\n for ^= i + j;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n struct timespec pre;\n struct timespec post;\n clock_gettime(CLOCK_THREAD_CPUTIME_ID, &pre);\n work_function(0);\n clock_gettime(CLOCK_THREAD_CPUTIME_ID, &post);\n\n printf(\"time %d\\n\",\n (SEC_TO_NSEC(post.tv_sec) + post.tv_nsec) -\n (SEC_TO_NSEC(pre.tv_sec) + pre.tv_nsec));\n return 0;\n}\n gcc -o test test.c -lrt\n clock_gettime sched_setaffinity() cpuset times(NULL) clock_gettime() CLOCK_THREAD_CPUTIME_ID CLOCK_MONOTONIC CLOCK_MONOTONIC" }, { "answer_id": 158220, "author": "selwyn", "author_id": 16314, "author_profile": "https://Stackoverflow.com/users/16314", "pm_score": 2, "selected": false, "text": "#define TICK_INTERVAL 1 // milliseconds between ticker interrupts\nstatic unsigned long tickCounter;\n\ninterrupt ticker (void) \n{\n tickCounter += TICK_INTERVAL;\n ...\n}\n\nunsigned in GetTickCount(void)\n{\n return tickCounter;\n}\n int function(void)\n{\n unsigned long time = GetTickCount();\n\n do something ...\n\n printf(\"Time is %ld\", GetTickCount() - ticks);\n}\n" }, { "answer_id": 158307, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "start = getTicks();\n\nrepeat n times {\n myFunction();\n myFunction();\n}\n\nlap = getTicks();\n\nrepeat n times {\n myFunction();\n}\n\nfinish = getTicks();\n\n// overhead + function + function\nelapsed1 = lap - start;\n\n// overhead + function\nelapsed2 = finish - lap;\n\n// overhead + function + function - overhead - function = function\nntimes = elapsed1 - elapsed2;\n\nonce = ntimes / n; // Average time it took for one function call, sans loop overhead\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
68,964
<p>So for e.g. 0110 has bits 1 and 2 set, 1000 has bit 3 set 1111 has bits 0,1,2,3 set</p>
[ { "answer_id": 69007, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 2, "selected": false, "text": "for( int i = 0; variable ; ++i, variable >>= 1 ) {\n if( variable & 1 )\n // store bit index - i\n}\n" }, { "answer_id": 69059, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 0, "selected": false, "text": "firstbit = (x & 0x00000001) \nsecondbit = (x & 0x00000002) \nthirdbit = (x & 0x00000004) //<-- I'm not saying to store these values, just giving an example. \n...\n" }, { "answer_id": 72286, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "[Flags]\npublic enum Int32Bits\n{\n // Lookup table but nicer\n None = 0,\n Bit1 = 1, Bit2 = 1 << 1, Bit3 = 1 << 2, Bit4 = 1 << 3, Bit5 = 1 << 4, Bit6 = 1 << 5, Bit7 = 1 << 6, Bit8 = 1 << 7,\n Bit9 = 1 << 8, Bit10 = 1 << 9, Bit11 = 1 << 10, Bit12 = 1 << 11, Bit13 = 1 << 12, Bit14 = 1 << 13, Bit15 = 1 << 14, Bit16 = 1 << 15,\n Bit17 = 1 << 16, Bit18 = 1 << 17, Bit19 = 1 << 18, Bit20 = 1 << 19, Bit21 = 1 << 20, Bit22 = 1 << 21, Bit23 = 1 << 22, Bit24 = 1 << 23,\n Bit25 = 1 << 24, Bit26 = 1 << 25, Bit27 = 1 << 26, Bit28 = 1 << 27, Bit29 = 1 << 28, Bit30 = 1 << 29, Bit31 = 1 << 30, Bit32 = 1 << 31,\n}\n\npublic static class BitTools\n{\n public static Boolean IsSet(Int32 value, Int32Bits bitToCheck)\n {\n return ((Int32Bits)value & bitToCheck) == bitToCheck;\n }\n\n public static Boolean IsSet(UInt32 value, Int32Bits bitToCheck)\n {\n return ((Int32Bits)value & bitToCheck) == bitToCheck;\n }\n\n public static Boolean IsBitSet(this Int32 value, Int32Bits bitToCheck)\n {\n return ((Int32Bits)value & bitToCheck) == bitToCheck;\n }\n public static Boolean IsBitSet(this UInt32 value, Int32Bits bitToCheck)\n {\n return ((Int32Bits)value & bitToCheck) == bitToCheck;\n }\n}\n static void Main(string[] args)\n{\n UInt32 testValue = 5557; //1010110110101;\n\n if (BitTools.IsSet(testValue, Int32Bits.Bit1))\n {\n Console.WriteLine(\"The first bit is set!\");\n }\n if (testValue.IsBitSet(Int32Bits.Bit5))\n {\n Console.WriteLine(\"The fifth bit is set!\");\n }\n if (!testValue.IsBitSet(Int32Bits.Bit2))\n {\n Console.WriteLine(\"The second bit is NOT set!\");\n }\n}\n" }, { "answer_id": 78373, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 0, "selected": false, "text": "set_bit= x & -x; x&= x - 1;" }, { "answer_id": 3082922, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import java.util.*;\npublic class bitSet {\n\n public static void main(String[]args) {\n Scanner scnr = new Scanner(System.in);\n int x = scnr.nextInt();\n int i = 0;\n while (i<32) {\n if ( ((x>>i)&1) == 1) {\n System.out.println(i);\n }\n i++;\n }\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8884/" ]
68,993
<p>Say I have a line in an emacs buffer that looks like this:</p> <pre><code>foo -option1 value1 -option2 value2 -option3 value3 \ -option4 value4 ... </code></pre> <p>I want it to look like this:</p> <pre><code>foo -option1 value1 \ -option2 value2 \ -option3 value3 \ -option4 value4 \ ... </code></pre> <p>I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region. </p> <p>Anybody know of an elisp function to do this? </p>
[ { "answer_id": 76888, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 3, "selected": true, "text": "(defun tcl-multiline-options ()\n \"spread option/value pairs across multiple lines with continuation characters\"\n (interactive)\n (save-excursion\n (tcl-join-continuations)\n (beginning-of-line)\n (while (re-search-forward \" -[^ ]+ +\" (line-end-position) t)\n (goto-char (match-beginning 0))\n (insert \" \\\\\\n\")\n (goto-char (+(match-end 0) 3))\n (indent-according-to-mode)\n (forward-sexp))))\n\n(defun tcl-join-continuations ()\n \"join multiple continuation lines into a single physical line\"\n (interactive)\n (while (progn (end-of-line) (char-equal (char-before) ?\\\\))\n (forward-line 1))\n (while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\\\))\n (end-of-line 0)\n (delete-char -1)\n (delete-char 1)\n (fixup-whitespace)))\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7432/" ]
68,999
<p>I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?</p> <p>I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. </p>
[ { "answer_id": 69105, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 4, "selected": false, "text": "time curl -I 'http://server:3000'\n" }, { "answer_id": 69195, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 3, "selected": false, "text": "import java.io.IOException;\n\nimport org.apache.commons.httpclient.HttpClient;\nimport org.apache.commons.httpclient.HttpMethod;\nimport org.apache.commons.httpclient.URIException;\nimport org.apache.commons.httpclient.methods.HeadMethod;\nimport org.apache.commons.lang.time.StopWatch;\n//import org.apache.commons.lang3.time.StopWatch\n\npublic class Main {\n\n public static void main(String[] args) throws URIException {\n StopWatch watch = new StopWatch();\n HttpClient client = new HttpClient();\n HttpMethod method = new HeadMethod(\"http://stackoverflow.com/\");\n \n try {\n watch.start();\n client.executeMethod(method);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n watch.stop();\n }\n \n System.out.println(String.format(\"%s %s %d: %s\", method.getName(), method.getURI(), method.getStatusCode(), watch.toString()));\n \n }\n}\n HEAD http://stackoverflow.com/ 200: 0:00:00.404\n" }, { "answer_id": 69210, "author": "Kevin Day", "author_id": 10973, "author_profile": "https://Stackoverflow.com/users/10973", "pm_score": 2, "selected": false, "text": "// open your connection\nlong start = System.currentTimeMillis();\n// send request, wait for response (the simple socket calls are all blocking)\nlong end = System.currentTimeMillis();\nSystem.out.println(\"Round trip response time = \" + (end-start) + \" millis\");\n" }, { "answer_id": 69223, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 5, "selected": true, "text": "public void sendHttpRequest(byte[] requestData, Socket connection) {\n long startTime = System.nanoTime();\n writeYourRequestData(connection.getOutputStream(), requestData);\n byte[] responseData = readYourResponseData(connection.getInputStream());\n long elapsedTime = System.nanoTime() - startTime;\n System.out.println(\"Total elapsed http request/response time in nanoseconds: \" + elapsedTime);\n}\n" }, { "answer_id": 12526594, "author": "A B", "author_id": 167362, "author_profile": "https://Stackoverflow.com/users/167362", "pm_score": 4, "selected": false, "text": "curl -s -w \"%{time_total}\\n\" -o /dev/null http://server:3000" }, { "answer_id": 54348183, "author": "Sudabe-Neirizi", "author_id": 9820210, "author_profile": "https://Stackoverflow.com/users/9820210", "pm_score": 0, "selected": false, "text": "@Aspect\n@Profile(\"performance\")\n@Component\npublic class MethodsExecutionPerformance {\n private final Logger logger = LoggerFactory.getLogger(getClass());\n\n @Pointcut(\"execution(* it.test.microservice.myService.service.*.*(..))\")\n public void serviceMethods() {\n }\n\n @Around(\"serviceMethods()\")\n public Object monitorPerformance(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {\n StopWatch stopWatch = new StopWatch(getClass().getName());\n stopWatch.start();\n Object output = proceedingJoinPoint.proceed();\n stopWatch.stop();\n logger.info(\"Method execution time\\n{}\", stopWatch.prettyPrint());\n return output;\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/68999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10889/" ]
69,000
<p>I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.</p> <p>Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.</p> <p>This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.</p> <p>At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!</p> <p>Also, the settings we need to manually change are:</p> <pre><code>&lt;security mode="TransportCredentialOnly"&gt; &lt;transport clientCredentialType="Ntlm" /&gt; &lt;/security&gt; </code></pre> <p>and:</p> <pre><code>&lt;binding maxBufferSize="655360" maxReceivedMessageSize="655360" /&gt; </code></pre> <p>We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed.</p>
[ { "answer_id": 69654, "author": "Wiren", "author_id": 2538222, "author_profile": "https://Stackoverflow.com/users/2538222", "pm_score": 3, "selected": true, "text": "REM generate meta data\ncall \"SVCUTIL.EXE\" /t:metadata \"MyProject.dll\" /reference:\"MyReference.dll\"\n\nREM making sure the file is writable\nattrib -r \"MyServiceProxy.cs\"\n\nREM create new proxy file\ncall \"SVCUTIL.EXE\" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:\"MyServiceProxy.cs\" /namespace:*,MY.Name.Space /reference:\"MyReference.dll\" \n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890/" ]
69,016
<p>I have an array of objects that when another object hits one of them, the object will be removed. I have removed it from the stage using removeChild() and removed from the array using splice(), but somehow the object is still calling some of its functions which is causing errors. How do I completely get rid of an object? There are no event listeners tied to it either.</p>
[ { "answer_id": 75679, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 2, "selected": false, "text": "stage.removeEventListener(...) stage.addEventListener(...) Event.ENTER_FRAME setInterval removeChild stop halt cleanup finalize null" }, { "answer_id": 117162, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 1, "selected": false, "text": "addEventListener(SomeEvent.EVENT_HAPPEND, onEventHappend);\n addEventListener(SomeEvent.EVENT_HAPPEND, onEventHappend, false, 0, true);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
69,030
<p>I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.</p> <p>Here is the script as it stands now:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 click helpMenuItem end tell end tell </code></pre> <p>And I'm thinking of something like this:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 set searchBox to menu item 1 of menu of helpMenuItem if (searchBox's focused) = true then key code 53 -- type esc else click helpMenuItem end if end tell end tell </code></pre> <p>... but I get this error:</p> <blockquote> <p>Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.</p> </blockquote> <p>So is there a way I can get my script to detect whether the search box is already focused?</p> <hr> <p>I solved my problem by <a href="https://stackoverflow.com/questions/69391/">working around it</a>. I still don't know how to check if a menu item is selected though, so I will leave this topic open.</p>
[ { "answer_id": 69404, "author": "tjw", "author_id": 11029, "author_profile": "https://Stackoverflow.com/users/11029", "pm_score": 3, "selected": true, "text": "focused menu item text field menu item selected tell application \"System Events\"\n tell (first process whose frontmost is true)\n set helpMenuItem to menu bar item \"Help\" of menu bar 1\n\n -- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact.\n set searchBox to a reference to menu item 1 of menu of helpMenuItem\n set searchField to a reference to text field 1 of searchBox\n\n if searchField's focused is true then\n key code 53 -- type esc\n else\n click helpMenuItem\n end if\n end tell\nend tell\n focused click" }, { "answer_id": 1545862, "author": "Steve Jones", "author_id": 187427, "author_profile": "https://Stackoverflow.com/users/187427", "pm_score": 2, "selected": false, "text": "tell application \"Adobe Illustrator\"\nactivate\ntell application \"System Events\"\n tell process \"Illustrator\"\n set frontmost to true\n set activeMenuItem to enabled of menu item \"Unlock All\" of menu \"Object\" of menu bar item \"Object\" of menu bar 1\n if activeMenuItem is true then\n tell me to beep 3\n else\n tell me to beep 2\n end if\n end tell\nend tell\nend tell\n" }, { "answer_id": 35948626, "author": "Chester Rieman", "author_id": 4821121, "author_profile": "https://Stackoverflow.com/users/4821121", "pm_score": 2, "selected": false, "text": "AXMenuItemMarkChar tell application \"System Events\"\n tell process \"Cisco Jabber\"\n set X to (value of attribute \"AXMenuItemMarkChar\" of menu item \"Available\" of menu \"Status\" of menu item \"Status\" of menu \"File\" of menu bar item \"File\" of menu bar 1) is \"✓\" -- check if Status is \"Availible\" \n end tell\nend tell\n ✓ missing value" }, { "answer_id": 65835776, "author": "Tao Starbow", "author_id": 1578589, "author_profile": "https://Stackoverflow.com/users/1578589", "pm_score": 0, "selected": false, "text": "tell application \"System Preferences\"\n reveal anchor \"keyboardTab\" of pane \"com.apple.preference.keyboard\"\nend tell\ntell application \"System Events\" to tell process \"System Preferences\"\n tell pop up button 2 of tab group 1 of window 1\n click\n delay 0.2\n set appControl to menu item \"App Controls\" of menu 1\n set fKeys to menu item \"F1, F2, etc. Keys\" of menu 1\n if selected of appControl is true then\n click fKeys\n else\n click appControl\n end if\n end tell\nend tell\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10906/" ]
69,063
<p>Most of our Eclipse projects have multiple source folders, for example:</p> <ul> <li>src/main/java</li> <li>src/test/java</li> </ul> <p>When you right-click on a class and choose New JUnit Test, the default source folder for the new test is "src/main/java" (presumably the first source folder listed in the project properties).</p> <p>Is there any way to change the default source folder for new JUnit tests, so that when I do the above action, the new test will be created in say the "src/test/java" folder by default?</p>
[ { "answer_id": 5400024, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 0, "selected": false, "text": "src/test/java" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10433/" ]
69,068
<p>How can I split long commands over multiple lines in a batch file?</p>
[ { "answer_id": 69079, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 11, "selected": true, "text": "^ copy file1.txt file2.txt\n copy file1.txt^\n file2.txt\n" }, { "answer_id": 4455750, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 8, "selected": false, "text": "echo Test1\necho one ^\ntwo ^\nthree ^\nfour^\n*\n--- Output ---\nTest1\none two three four*\n\necho Test2\necho one & echo two\n--- Output ---\nTest2\none\ntwo\n\necho Test3\necho one & ^\necho two\n--- Output ---\nTest3\none\ntwo\n\necho Test4\necho one ^\n& echo two\n--- Output ---\nTest4\none & echo two\n echo Test5\necho one <nul ^\n& echo two\n--- Output ---\nTest5\none\ntwo\n\n\necho Test6\necho one <nul ThisTokenIsLost^\n& echo two\n--- Output ---\nTest6\none\ntwo\n setlocal EnableDelayedExpansion\nset text=This creates ^\n\na line feed\necho Test7: %text%\necho Test8: !text!\n--- Output ---\nTest7: This creates\nTest8: This creates\na line feed\n" }, { "answer_id": 21000752, "author": "T.J. Crowder", "author_id": 157247, "author_profile": "https://Stackoverflow.com/users/157247", "pm_score": 7, "selected": false, "text": "^ ^ & | xcopy file1.txt file2.txt\n xcopy^\n file1.txt^\n file2.txt\n xcopy ^\nfile1.txt ^\nfile2.txt\n xc^\nopy ^\nfile1.txt ^\nfile2.txt\n xc ^ ^ xcopy ^ xcopy file1.txt file2.txt ^\n& echo copied successfully\n & xcopy" }, { "answer_id": 25471056, "author": "Mohammed Safwat", "author_id": 493119, "author_profile": "https://Stackoverflow.com/users/493119", "pm_score": 4, "selected": false, "text": "for %n in (hello\nbye) do echo %n\n" }, { "answer_id": 35371129, "author": "Todd Partridge", "author_id": 4515565, "author_profile": "https://Stackoverflow.com/users/4515565", "pm_score": 5, "selected": false, "text": "echo hi && echo hello ( echo hi\n echo hello )\n set AFILEPATH=\"C:\\SOME\\LONG\\PATH\\TO\\A\\FILE\"\nif exist %AFILEPATH% (\n start \"\" /b %AFILEPATH% -option C:\\PATH\\TO\\SETTING...\n) else (\n...\n ^ if if exist ^\n" }, { "answer_id": 64752041, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 3, "selected": false, "text": "@echo off\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset \"{{=setlocal enableDelayedExpansion&for %%a in (\" & set \"}}=\"::end::\" ) do if \"%%~a\" neq \"::end::\" (set command=!command! %%a) else (call !command! & endlocal)\"\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n%{{%\n echo\n \"command\"\n written\n on a\n few lines\n%}}%\n" }, { "answer_id": 68470236, "author": "Simon H", "author_id": 7071220, "author_profile": "https://Stackoverflow.com/users/7071220", "pm_score": 3, "selected": false, "text": "myprog \"needs this to be quoted\"\n myprog ^\"needs this ^\nto be quoted^\"\n echo ^\"^\nneeds this ^\nto be quoted^\n^\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
69,073
<p>When attempting to print using the SSRS Viewer Web Part in SharePoint I get the following error.</p> <blockquote> <p>An error occured during printing. (0x8007F303)</p> </blockquote> <p>The settings we are using in this box (production) are exactly the same as the settings in testing where this works perfectly fine. </p> <p>Anyone have any good ideas or faced this before?</p>
[ { "answer_id": 69731, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 1, "selected": false, "text": "[HKEY_CURRENT_USER\\Software\\Microsoft\\Microsoft SQL Server\\80\\Reporting Services] \"LogRSClientPrintInfo\"=dword:00000001" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
69,089
<p>We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this? </p> <p>BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate.</p>
[ { "answer_id": 127080, "author": "xnagyg", "author_id": 2622295, "author_profile": "https://Stackoverflow.com/users/2622295", "pm_score": 1, "selected": false, "text": " search_kiemeles=replace(lcase(search),\"\"\"\",\"\")\n do while not rs.eof 'The search result loop\n hirdetes=rs(\"hirdetes\")\n data=RegExpValueA(\"([A-Za-zöüóőúéáűíÖÜÓŐÚÉÁŰÍ0-9]+)\",search_kiemeles) 'Give back all the search words in an array, I need non-english characters also\n For i=0 to Ubound(data,1)\n hirdetes = RegExpReplace(hirdetes,\"(\"&NoAccentRE(data(i))&\")\",\"<em>$1</em>\")\n Next\n response.write hirdetes\n rs.movenext\n Loop\n ...\n 'All Match to Array\nFunction RegExpValueA(patrn, strng)\n Dim regEx\n Set regEx = New RegExp ' Create a regular expression.\n regEx.IgnoreCase = True ' Set case insensitivity.\n regEx.Global = True\n Dim Match, Matches, RetStr\n Dim data()\n Dim count\n count = 0\n Redim data(-1) 'VBSCript Ubound array bug workaround\n if isnull(strng) or strng=\"\" then\n RegExpValueA = data\n exit function\n end if\n regEx.Pattern = patrn ' Set pattern.\n Set Matches = regEx.Execute(strng) ' Execute search.\n For Each Match in Matches ' Iterate Matches collection.\n count = count + 1\n Redim Preserve data(count-1)\n data(count-1) = Match.Value\n Next\n set regEx = nothing\n RegExpValueA = data\nEnd Function\n\n'Replace non-english chars\nFunction NoAccentRE(accent_string)\n NoAccentRE=accent_string\n NoAccentRE=Replace(NoAccentRE,\"a\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"á\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[aá]\")\n NoAccentRE=Replace(NoAccentRE,\"e\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"é\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[eé]\")\n NoAccentRE=Replace(NoAccentRE,\"i\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"í\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[ií]\")\n NoAccentRE=Replace(NoAccentRE,\"o\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ó\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ö\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ő\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[oóöő]\")\n NoAccentRE=Replace(NoAccentRE,\"u\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ú\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ü\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ű\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[uúüű]\")\nend function\n" }, { "answer_id": 3338113, "author": "Shagglez", "author_id": 369166, "author_profile": "https://Stackoverflow.com/users/369166", "pm_score": 3, "selected": true, "text": "declare @SearchPattern nvarchar(1000) = 'FORMSOF (INFLECTIONAL, \" ' + @SearchString + ' \")' \ndeclare @SearchWords table (Word varchar(100), Expansion_type int)\ninsert into @SearchWords\nselect distinct display_term, expansion_type\nfrom sys.dm_fts_parser(@SearchPattern, 1033, 0, 0)\nwhere special_term = 'Exact Match'\n declare @FinalResults table \nwhile (select COUNT(*) from @PrelimResults) > 0\nbegin\n select top 1 @CurrID = [UID], @Text = Text from @PrelimResults\n declare @TextLength int = LEN(@Text )\n declare @IndexOfDot int = CHARINDEX('.', REVERSE(@Text ), @TextLength - dbo.RegExIndexOf(@Text, '\\b' + @FirstSearchWord + '\\b') + 1)\n set @Text = SUBSTRING(@Text, case @IndexOfDot when 0 then 0 else @TextLength - @IndexOfDot + 3 end, 300)\n\n while (select COUNT(*) from @TempSearchWords) > 0\n begin\n select top 1 @CurrWord = Word from @TempSearchWords\n set @Text = dbo.RegExReplace(@Text, '\\b' + @CurrWord + '\\b', '<b>' + SUBSTRING(@Text, dbo.RegExIndexOf(@Text, '\\b' + @CurrWord + '\\b'), LEN(@CurrWord) + 1) + '</b>')\n delete from @TempSearchWords where Word = @CurrWord\n end\n\n insert into @FinalResults\n select * from @PrelimResults where [UID] = @CurrID\n delete from @PrelimResults where [UID] = @CurrID\nend\n @FirstSearchWord" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1899/" ]
69,104
<p>A J2ME client is sending HTTP POST requests with chunked transfer encoding.</p> <p>When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.</p> <p>However, when I read the Request.InputStream to the end, it returns 0.</p> <p>Here's the code I'm using to read the input stream.</p> <pre><code>using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) { string readString = reader.ReadToEnd(); Console.WriteLine("CharSize:" + readString.Length); return BodyTextEncoding.GetBytes(readString); } </code></pre> <p>I can simulate the behaiviour of the client with Fiddler, e.g.</p> <p><strong>URL</strong> <a href="http://localhost:15148/page.aspx" rel="nofollow noreferrer">http://localhost:15148/page.aspx</a></p> <p><strong>Headers:</strong> User-Agent: Fiddler Transfer-Encoding: Chunked Host: somesite.com:15148</p> <p><strong>Body</strong> rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!</p> <p>My body reader from above will return a zero length byte array...lame...</p> <p>Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?</p> <p>I found <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;278998" rel="nofollow noreferrer">this script</a> for IIS but it isn't working.</p>
[ { "answer_id": 80576, "author": "Andrew", "author_id": 15127, "author_profile": "https://Stackoverflow.com/users/15127", "pm_score": 1, "selected": false, "text": "string responseText = null;\nWebRequest rabbits= WebRequest.Create(uri);\nusing (Stream resp = rabbits.GetResponse().GetResponseStream()) {\n MemoryStream memoryStream = new MemoryStream(0x10000);\n byte[] buffer = new byte[0x1000];\n int bytes;\n while ((bytes = resp.Read(buffer, 0, buffer.Length)) > 0) {\n memoryStream.Write(buffer, 0, bytes);\n }\n // use the encoding to match the data source.\n Encoding enc = Encoding.UTF8;\n reponseText = enc.GetString(memoryStream.ToArray());\n}\n" }, { "answer_id": 4294031, "author": "Anton Tykhyy", "author_id": 77724, "author_profile": "https://Stackoverflow.com/users/77724", "pm_score": 2, "selected": false, "text": "Transfer-Encoding: chunked" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
69,107
<p>What is the best way to refactor the attached code to accommodate multiple email addresses?</p> <p>The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script language="javascript"&gt; $(document).ready(function() { var validateUsername = $('#Email_Address_Status_Icon_1'); $('#Email_Address_1').keyup(function() { var t = this; if (this.value != this.lastValue) { if (this.timer) clearTimeout(this.timer); validateUsername.removeClass('error').html('Validating Email'); this.timer = setTimeout(function() { if (IsEmail(t.value)) { validateUsername.html('Valid Email'); } else { validateUsername.html('Not a valid Email'); }; }, 200); this.lastValue = this.value; } }); }); function IsEmail(email) { var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (regex.test(email)) return true; else return false; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;label for="Email_Address_1"&gt;Friend #1&lt;/label&gt;&lt;/div&gt; &lt;input type="text" ID="Email_Address_1"&gt; &lt;span id="Email_Address_Status_Icon_1"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="Email_Address_2"&gt;Friend #2&lt;/label&gt;&lt;/div&gt; &lt;input type="text" id="Email_Address_2"&gt; &lt;span id="Email_Address_Status_Icon_2"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="Email_Address_3"&gt;Friend #3&lt;/label&gt;&lt;/div&gt; &lt;input type="text" id="Email_Address_3"&gt; &lt;span id="Email_Address_Status_Icon_3"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 69148, "author": "Pandincus", "author_id": 2273, "author_profile": "https://Stackoverflow.com/users/2273", "pm_score": 3, "selected": true, "text": "<div>\n <label for=\"Email_Address_1\">Friend #1</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n<div>\n <label for=\"Email_Address_2\">Friend #2</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n<div>\n <label for=\"Email_Address_3\">Friend #3</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n $(this).next(\"span\").removeClass('error').html('Validating Email');\n" }, { "answer_id": 69241, "author": "Brian Boatright", "author_id": 3747, "author_profile": "https://Stackoverflow.com/users/3747", "pm_score": 0, "selected": false, "text": "<script language=\"javascript\">\n $(document).ready(function() {\n $('#Email_Address_1').keyup(function(){Update_Email_Validate_Status(this)});\n $('#Email_Address_2').keyup(function() { Update_Email_Validate_Status(this)});\n $('#Email_Address_3').keyup(function() { Update_Email_Validate_Status(this)}); \n });\n\n function Update_Email_Validate_Status(field) {\n var t = field;\n if (t.value != t.lastValue) {\n if (t.timer) clearTimeout(t.timer);\n $(t).next(\"span\").removeClass('error').html('Validating Email');\n\n t.timer = setTimeout(function() {\n if (IsEmail(t.value)) {\n $(t).next(\"span\").removeClass('error').html('Valid Email');\n } else {\n $(t).next(\"span\").removeClass('error').html('Not a valid Email');\n };\n }, 200);\n\n t.lastValue = t.value;\n }\n }\n\n function IsEmail(email) {\n var regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n if (regex.test(email)) return true;\n else return false;\n } \n </script>\n" }, { "answer_id": 69299, "author": "Geoff", "author_id": 10427, "author_profile": "https://Stackoverflow.com/users/10427", "pm_score": 0, "selected": false, "text": "$(document).ready(function() {\n $('.validateEmail').keyup(function(){Update_Email_Validate_Status(this)}); \n });\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
69,115
<p>Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?</p> <p>How can I make this faster?</p> <p>Compiled with -O3 in g++</p> <pre><code>static const char _hex2asciiU_value[256][2] = { {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} }; std::string char_to_hex( const unsigned char* _pArray, unsigned int _len ) { std::string str; str.resize(_len*2); char* pszHex = &amp;str[0]; const unsigned char* pEnd = _pArray + _len; clock_t stick, etick; stick = clock(); for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) { pszHex[0] = _hex2asciiU_value[*pChar][0]; pszHex[1] = _hex2asciiU_value[*pChar][1]; } etick = clock(); std::cout &lt;&lt; "ticks to hexify " &lt;&lt; etick - stick &lt;&lt; std::endl; return str; } </code></pre> <p><strong>Updates</strong></p> <p>Added timing code</p> <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126">Brian R. Bondy</a>: replace the std::string with a heap alloc'd buffer and change ofs*16 to ofs &lt;&lt; 4 - however the heap allocated buffer seems to slow it down? - result ~11ms</p> <p><a href="https://stackoverflow.com/questions/69115/#69305">Antti Sykäri</a>:replace inner loop with </p> <pre><code> int upper = *pChar &gt;&gt; 4; int lower = *pChar &amp; 0x0f; pszHex[0] = pHex[upper]; pszHex[1] = pHex[lower]; </code></pre> <p>result ~8ms</p> <p><a href="https://stackoverflow.com/questions/69115?sort=votes#69218">Robert</a>: replace <code>_hex2asciiU_value</code> with a full 256-entry table, sacrificing memory space but result ~7ms!</p> <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254">HoyHoy</a>: Noted it was producing incorrect results</p>
[ { "answer_id": 69126, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "16 bitshift << 4 std::string delete" }, { "answer_id": 69197, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "std::basic_string #include <string>\n\nusing std::string;\n\nstatic char const* digits(\"0123456789ABCDEF\");\n\nstring\ntohex(string const& data)\n{\n string result(data.size() * 2, 0);\n string::iterator ptr(result.begin());\n for (string::const_iterator cur(data.begin()), end(data.end()); cur != end; ++cur) {\n unsigned char c(*cur);\n *ptr++ = digits[c >> 4];\n *ptr++ = digits[c & 15];\n }\n return result;\n}\n" }, { "answer_id": 69218, "author": "Robert Groves", "author_id": 3534, "author_profile": "https://Stackoverflow.com/users/3534", "pm_score": 3, "selected": true, "text": "static const char _hex2asciiU_value[256][2] =\n { {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };\n const char *pHexVal = pHex[*pChar];\npszHex[0] = pHexVal[0];\npszHex[1] = pHexVal[1];\n" }, { "answer_id": 69305, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 1, "selected": false, "text": " ofs = *pChar >> 4;\n pszHex[0] = pHex[ofs];\n pszHex[1] = pHex[*pChar-(ofs*16)];\n int upper = *pChar >> 4;\n int lower = *pChar & 0x0f;\n pszHex[0] = pHex[upper];\n pszHex[1] = pHex[lower];\n _result.resize(_len*2);\nshort* pszHex = (short*) &_result[0];\nconst unsigned char* pEnd = _pArray + _len;\n\nconst char* pHex = _hex2asciiU_value;\nfor(const unsigned char* pChar = _pArray;\n pChar != pEnd;\n pChar++, ++pszHex )\n{\n *pszHex = bytes_to_chars[*pChar];\n}\n short short_table[256];\n\nfor (int i = 0; i < 256; ++i)\n{\n char* pc = (char*) &short_table[i];\n pc[0] = _hex2asciiU_value[i >> 4];\n pc[1] = _hex2asciiU_value[i & 0x0f];\n}\n gcc -O3" }, { "answer_id": 70254, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "#include <iostream>\n\nusing namespace std;\n\nstatic const size_t _h2alen = 256;\nstatic char _hex2asciiU_value[_h2alen][3];\n\nstring char_to_hex( const unsigned char* _pArray, unsigned int _len )\n{\n string str;\n str.resize(_len*2);\n char* pszHex = &str[0];\n const unsigned char* pEnd = _pArray + _len;\n const char* pHex = _hex2asciiU_value[0];\n for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {\n pszHex[0] = _hex2asciiU_value[*pChar][0];\n pszHex[1] = _hex2asciiU_value[*pChar][1];\n }\n return str;\n}\n\n\nint main() {\n for(int i=0; i<_h2alen; i++) {\n snprintf(_hex2asciiU_value[i], 3,\"%02X\", i);\n }\n size_t len = 200000000;\n char* a = new char[len];\n string t1;\n string t2;\n clock_t start;\n srand(time(NULL));\n for(int i=0; i<len; i++) a[i] = rand()&0xFF;\n start = clock();\n t1=char_to_hex((const unsigned char*)a, len);\n cout << \"char_to_hex conversion took ---> \" << (clock() - start)/(double)CLOCKS_PER_SEC << \" seconds\\n\";\n}\n" }, { "answer_id": 72055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++) {\n const char* pchars = _hex2asciiU_value[*pChar];\n *pszHex++ = *pchars++;\n *pszHex++ = *pchars;\n}\n" }, { "answer_id": 78611, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nchar* char_to_hex(const unsigned char* p_array, \n unsigned int p_array_len,\n char** hex2ascii)\n{\n unsigned char* str = malloc(p_array_len*2+1);\n const unsigned char* p_end = p_array + p_array_len;\n size_t pos=0;\n const unsigned char* p;\n for( p = p_array; p != p_end; p++, pos+=2 ) {\n str[pos] = hex2ascii[*p][0];\n str[pos+1] = hex2ascii[*p][1];\n }\n return (char*)str;\n}\n\nint main()\n{\n size_t hex2ascii_len = 256;\n char** hex2ascii;\n int i;\n hex2ascii = malloc(hex2ascii_len*sizeof(char*));\n for(i=0; i<hex2ascii_len; i++) {\n hex2ascii[i] = malloc(3*sizeof(char)); \n snprintf(hex2ascii[i], 3,\"%02X\", i);\n }\n size_t len = 8;\n const unsigned char a[] = \"DO NOT WANT\";\n printf(\"%s\\n\", char_to_hex((const unsigned char*)a, len, (char**)hex2ascii));\n}\n" }, { "answer_id": 78892, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 3, "selected": false, "text": "%include \"x86inc.asm\"\n\nSECTION_RODATA\npb_f0: times 16 db 0xf0\npb_0f: times 16 db 0x0f\npb_hex: db 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70\n\nSECTION .text\n\n; int convert_string_to_hex( char *input, char *output, int len )\n\ncglobal _convert_string_to_hex,3,3\n movdqa xmm6, [pb_f0 GLOBAL]\n movdqa xmm7, [pb_0f GLOBAL]\n.loop:\n movdqa xmm5, [pb_hex GLOBAL]\n movdqa xmm4, [pb_hex GLOBAL]\n movq xmm0, [r0+r2-8]\n movq xmm2, [r0+r2-16]\n movq xmm1, xmm0\n movq xmm3, xmm2\n pand xmm0, xmm6 ;high bits\n pand xmm2, xmm6\n psrlq xmm0, 4\n psrlq xmm2, 4\n pand xmm1, xmm7 ;low bits\n pand xmm3, xmm7\n punpcklbw xmm0, xmm1\n punpcklbw xmm2, xmm3\n pshufb xmm4, xmm0\n pshufb xmm5, xmm2\n movdqa [r1+r2*2-16], xmm4\n movdqa [r1+r2*2-32], xmm5\n sub r2, 16\n jg .loop\n REP_RET\n" }, { "answer_id": 4431837, "author": "Mihai Vrinceanu", "author_id": 540864, "author_profile": "https://Stackoverflow.com/users/540864", "pm_score": 1, "selected": false, "text": "short int hex_table[256] = {'0'*256+'0', '1'*256+'0', '2'*256+'0', ..., 'E'*256+'F', 'F'*256+'F'};\nunsigned short int* pszHex = &str[0];\n\nstick = clock();\n\nfor (const unsigned char* pChar = _pArray; pChar != pEnd; pChar++) \n *pszHex++ = hex_table[*pChar];\n\netick = clock();\n" }, { "answer_id": 8838619, "author": "Sergey Zhukov", "author_id": 1145960, "author_profile": "https://Stackoverflow.com/users/1145960", "pm_score": 2, "selected": false, "text": "unsigned char unsigned char c1 = byteVal >> 4;\nunsigned char c2 = byteVal & 0x0f;\n\nc1 += c1 <= 9 ? '0' : ('a' - 10);\nc2 += c2 <= 9 ? '0' : ('a' - 10);\n\nstd::string sHex(\" \");\nsHex[0] = c1 ;\nsHex[1] = c2 ;\n\n\n//sHex - contain what we need. For example \"0f\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716/" ]
69,159
<p>I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out: </p> <pre><code>"Too Many Connections" </code></pre> <p>I can't log in anywhere to close the connections manually. </p> <p><strong>Is that any way to close open connections using a script or other type of command?.</strong> </p> <p>Should I just wait?</p>
[ { "answer_id": 69179, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 0, "selected": false, "text": "max_connections=500\n show status show processlist" }, { "answer_id": 69244, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 0, "selected": false, "text": "require 'mysql'\n\nmysql = Mysql.new(ip, user, pass)\nprocesslist = mysql.query(\"show full processlist\")\nkilled = 0\nprocesslist.each { | process |\n mysql.query(\"KILL #{process[0].to_i}\")\n} \nputs \"#{Time.new} -- killed: #{killed} connections\"\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9803/" ]
69,188
<p><a href="http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx" rel="nofollow noreferrer">http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx</a></p> <p>This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated.</p>
[ { "answer_id": 69535, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": -1, "selected": false, "text": "function ReadCookie(cookieName) {\n var theCookie=\"\"+document.cookie;\n var ind=theCookie.indexOf(cookieName);\n if (ind==-1 || cookieName==\"\") return \"\"; \n var ind1=theCookie.indexOf(';',ind);\n if (ind1==-1) ind1=theCookie.length; \n return unescape(theCookie.substring(ind+cookieName.length+1,ind1));\n}\n" }, { "answer_id": 69563, "author": "White Dragon", "author_id": 11049, "author_profile": "https://Stackoverflow.com/users/11049", "pm_score": 3, "selected": false, "text": "var cookies = new HttpCookieCollection();\ncontroller.ControllerContext = new FakeControllerContext(controller, cookies);\nvar result = controller.TestCookie() as ViewResult;\nAssert.AreEqual(\"somevaluethatshouldbethere\", cookies[\"somecookieitem\"].Value);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438/" ]
69,192
<p>Suppose we have two stacks and no other temporary variable.</p> <p>Is to possible to "construct" a queue data structure using only the two stacks?</p>
[ { "answer_id": 69436, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 10, "selected": false, "text": "inbox outbox inbox outbox inbox outbox outbox public class Queue<E>\n{\n\n private Stack<E> inbox = new Stack<E>();\n private Stack<E> outbox = new Stack<E>();\n\n public void queue(E item) {\n inbox.push(item);\n }\n\n public E dequeue() {\n if (outbox.isEmpty()) {\n while (!inbox.isEmpty()) {\n outbox.push(inbox.pop());\n }\n }\n return outbox.pop();\n }\n\n}\n" }, { "answer_id": 77010, "author": "pythonquick", "author_id": 6225, "author_profile": "https://Stackoverflow.com/users/6225", "pm_score": 6, "selected": false, "text": "public class SimulatedQueue<E> {\n private java.util.Stack<E> stack = new java.util.Stack<E>();\n\n public void insert(E elem) {\n if (!stack.empty()) {\n E topElem = stack.pop();\n insert(elem);\n stack.push(topElem);\n }\n else\n stack.push(elem);\n }\n\n public E remove() {\n return stack.pop();\n }\n}\n" }, { "answer_id": 10111315, "author": "PradGar", "author_id": 1028292, "author_profile": "https://Stackoverflow.com/users/1028292", "pm_score": -1, "selected": false, "text": "public class QueueUsingStacks<T>\n{\n private LinkedListStack<T> stack1;\n private LinkedListStack<T> stack2;\n\n public QueueUsingStacks()\n {\n stack1=new LinkedListStack<T>();\n stack2 = new LinkedListStack<T>();\n\n }\n public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )\n {\n while(source.Head!=null)\n {\n dest.Push(source.Head.Data);\n source.Head = source.Head.Next;\n }\n }\n public void Enqueue(T entry)\n {\n\n stack1.Push(entry);\n }\n public T Dequeue()\n {\n T obj;\n if (stack2 != null)\n {\n Copy(stack1, stack2);\n obj = stack2.Pop();\n Copy(stack2, stack1);\n }\n else\n {\n throw new Exception(\"Stack is empty\");\n }\n return obj;\n }\n\n public void Display()\n {\n stack1.Display();\n }\n\n\n}\n" }, { "answer_id": 14078077, "author": "Harry He", "author_id": 1092195, "author_profile": "https://Stackoverflow.com/users/1092195", "pm_score": 2, "selected": false, "text": "template <typename T> class CQueue\n{\npublic:\n CQueue(void);\n ~CQueue(void);\n\n void appendTail(const T& node); \n T deleteHead(); \n\nprivate:\n stack<T> stack1;\n stack<T> stack2;\n};\n\ntemplate<typename T> void CQueue<T>::appendTail(const T& element) {\n stack1.push(element);\n} \n\ntemplate<typename T> T CQueue<T>::deleteHead() {\n if(stack2.size()<= 0) {\n while(stack1.size()>0) {\n T& data = stack1.top();\n stack1.pop();\n stack2.push(data);\n }\n }\n\n\n if(stack2.size() == 0)\n throw new exception(\"queue is empty\");\n\n\n T head = stack2.top();\n stack2.pop();\n\n\n return head;\n}\n" }, { "answer_id": 22750794, "author": "Rahul Gandhi", "author_id": 2860486, "author_profile": "https://Stackoverflow.com/users/2860486", "pm_score": 3, "selected": false, "text": "enQueue(q, x)\n1) While stack1 is not empty, push everything from stack1 to stack2.\n2) Push x to stack1 (assuming size of stacks is unlimited).\n3) Push everything back to stack1.\ndeQueue(q)\n1) If stack1 is empty then error\n2) Pop an item from stack1 and return it.\n enQueue(q, x)\n 1) Push x to stack1 (assuming size of stacks is unlimited).\n\ndeQueue(q)\n 1) If both stacks are empty then error.\n 2) If stack2 is empty\n While stack1 is not empty, push everything from stack1 to stack2.\n 3) Pop the element from stack2 and return it.\n" }, { "answer_id": 33095936, "author": "imvp", "author_id": 4092635, "author_profile": "https://Stackoverflow.com/users/4092635", "pm_score": 0, "selected": false, "text": "// Two stacks s1 Original and s2 as Temp one\n private Stack<Integer> s1 = new Stack<Integer>();\n private Stack<Integer> s2 = new Stack<Integer>();\n\n /*\n * Here we insert the data into the stack and if data all ready exist on\n * stack than we copy the entire stack s1 to s2 recursively and push the new\n * element data onto s1 and than again recursively call the s2 to pop on s1.\n * \n * Note here we can use either way ie We can keep pushing on s1 and than\n * while popping we can remove the first element from s2 by copying\n * recursively the data and removing the first index element.\n */\n public void insert( int data )\n {\n if( s1.size() == 0 )\n {\n s1.push( data );\n }\n else\n {\n while( !s1.isEmpty() )\n {\n s2.push( s1.pop() );\n }\n s1.push( data );\n while( !s2.isEmpty() )\n {\n s1.push( s2.pop() );\n }\n }\n }\n\n public void remove()\n {\n if( s1.isEmpty() )\n {\n System.out.println( \"Empty\" );\n }\n else\n {\n s1.pop();\n\n }\n }\n" }, { "answer_id": 37376579, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 0, "selected": false, "text": "type IntQueue struct {\n front []int\n back []int\n}\n\nfunc (q *IntQueue) PushFront(v int) {\n q.front = append(q.front, v)\n}\n\nfunc (q *IntQueue) Front() int {\n if len(q.front) > 0 {\n return q.front[len(q.front)-1]\n } else {\n return q.back[0]\n }\n}\n\nfunc (q *IntQueue) PopFront() {\n if len(q.front) > 0 {\n q.front = q.front[:len(q.front)-1]\n } else {\n q.back = q.back[1:]\n }\n}\n\nfunc (q *IntQueue) PushBack(v int) {\n q.back = append(q.back, v)\n}\n\nfunc (q *IntQueue) Back() int {\n if len(q.back) > 0 {\n return q.back[len(q.back)-1]\n } else {\n return q.front[0]\n }\n}\n\nfunc (q *IntQueue) PopBack() {\n if len(q.back) > 0 {\n q.back = q.back[:len(q.back)-1]\n } else {\n q.front = q.front[1:]\n }\n}\n type IntQueue struct {\n front []int\n frontOffset int\n back []int\n backOffset int\n}\n\nfunc (q *IntQueue) PushFront(v int) {\n if q.backOffset > 0 {\n i := q.backOffset - 1\n q.back[i] = v\n q.backOffset = i\n } else {\n q.front = append(q.front, v)\n }\n}\n\nfunc (q *IntQueue) Front() int {\n if len(q.front) > 0 {\n return q.front[len(q.front)-1]\n } else {\n return q.back[q.backOffset]\n }\n}\n\nfunc (q *IntQueue) PopFront() {\n if len(q.front) > 0 {\n q.front = q.front[:len(q.front)-1]\n } else {\n if len(q.back) > 0 {\n q.backOffset++\n } else {\n panic(\"Cannot pop front of empty queue.\")\n }\n }\n}\n\nfunc (q *IntQueue) PushBack(v int) {\n if q.frontOffset > 0 {\n i := q.frontOffset - 1\n q.front[i] = v\n q.frontOffset = i\n } else {\n q.back = append(q.back, v)\n }\n}\n\nfunc (q *IntQueue) Back() int {\n if len(q.back) > 0 {\n return q.back[len(q.back)-1]\n } else {\n return q.front[q.frontOffset]\n }\n}\n\nfunc (q *IntQueue) PopBack() {\n if len(q.back) > 0 {\n q.back = q.back[:len(q.back)-1]\n } else {\n if len(q.front) > 0 {\n q.frontOffset++\n } else {\n panic(\"Cannot pop back of empty queue.\")\n }\n }\n}\n" }, { "answer_id": 38801986, "author": "realPK", "author_id": 853001, "author_profile": "https://Stackoverflow.com/users/853001", "pm_score": -1, "selected": false, "text": "public final class QueueUsingStacks<E> {\n\n private final Stack<E> iStack = new Stack<>();\n private final Stack<E> oStack = new Stack<>();\n\n public void enqueue(E e) {\n iStack.push(e);\n }\n\n public E dequeue() {\n if (oStack.isEmpty()) {\n if (iStack.isEmpty()) {\n throw new NoSuchElementException(\"No elements present in Queue\");\n }\n while (!iStack.isEmpty()) {\n oStack.push(iStack.pop());\n }\n }\n return oStack.pop();\n }\n\n public boolean isEmpty() {\n if (oStack.isEmpty() && iStack.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public int size() {\n return iStack.size() + oStack.size();\n }\n\n}\n" }, { "answer_id": 39089983, "author": "Levent Divilioglu", "author_id": 3128926, "author_profile": "https://Stackoverflow.com/users/3128926", "pm_score": 8, "selected": false, "text": "{1, 2, 3, 4, 5} {5, 4, 3, 2, 1} {1, 2, 3, 4, 5} enqueue dequeue Push every input element to the Input Stack\n If ( Output Stack is Empty)\n pop every element in the Input Stack\n and push them to the Output Stack until Input Stack is Empty\n\npop from Output Stack\n {1, 2, 3} {1, 2} {4, 5} public class MyStack<T> {\n\n // inner generic Node class\n private class Node<T> {\n T data;\n Node<T> next;\n\n public Node(T data) {\n this.data = data;\n }\n }\n\n private Node<T> head;\n private int size;\n\n public void push(T e) {\n Node<T> newElem = new Node(e);\n\n if(head == null) {\n head = newElem;\n } else {\n newElem.next = head;\n head = newElem; // new elem on the top of the stack\n }\n\n size++;\n }\n\n public T pop() {\n if(head == null)\n return null;\n\n T elem = head.data;\n head = head.next; // top of the stack is head.next\n\n size--;\n\n return elem;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void printStack() {\n System.out.print(\"Stack: \");\n\n if(size == 0)\n System.out.print(\"Empty !\");\n else\n for(Node<T> temp = head; temp != null; temp = temp.next)\n System.out.printf(\"%s \", temp.data);\n\n System.out.printf(\"\\n\");\n }\n}\n public class MyQueue<T> {\n\n private MyStack<T> inputStack; // for enqueue\n private MyStack<T> outputStack; // for dequeue\n private int size;\n\n public MyQueue() {\n inputStack = new MyStack<>();\n outputStack = new MyStack<>();\n }\n\n public void enqueue(T e) {\n inputStack.push(e);\n size++;\n }\n\n public T dequeue() {\n // fill out all the Input if output stack is empty\n if(outputStack.isEmpty())\n while(!inputStack.isEmpty())\n outputStack.push(inputStack.pop());\n\n T temp = null;\n if(!outputStack.isEmpty()) {\n temp = outputStack.pop();\n size--;\n }\n\n return temp;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n}\n public class TestMyQueue {\n\n public static void main(String[] args) {\n MyQueue<Integer> queue = new MyQueue<>();\n\n // enqueue integers 1..3\n for(int i = 1; i <= 3; i++)\n queue.enqueue(i);\n\n // execute 2 dequeue operations \n for(int i = 0; i < 2; i++)\n System.out.println(\"Dequeued: \" + queue.dequeue());\n\n // enqueue integers 4..5\n for(int i = 4; i <= 5; i++)\n queue.enqueue(i);\n\n // dequeue the rest\n while(!queue.isEmpty())\n System.out.println(\"Dequeued: \" + queue.dequeue());\n }\n\n}\n Dequeued: 1\nDequeued: 2\nDequeued: 3\nDequeued: 4\nDequeued: 5\n" }, { "answer_id": 40602980, "author": "Jaydeep Shil", "author_id": 3428626, "author_profile": "https://Stackoverflow.com/users/3428626", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace QueueImplimentationUsingStack\n{\n class Program\n {\n public class Stack<T>\n {\n public int size;\n public Node<T> head;\n public void Push(T data)\n {\n Node<T> node = new Node<T>();\n node.data = data;\n if (head == null)\n head = node;\n else\n {\n node.link = head;\n head = node;\n }\n size++;\n Display();\n }\n public Node<T> Pop()\n {\n if (head == null)\n return null;\n else\n {\n Node<T> temp = head;\n //temp.link = null;\n head = head.link;\n size--;\n Display();\n return temp;\n }\n }\n public void Display()\n {\n if (size == 0)\n Console.WriteLine(\"Empty\");\n else\n {\n Console.Clear();\n Node<T> temp = head;\n while (temp!= null)\n {\n Console.WriteLine(temp.data);\n temp = temp.link;\n }\n }\n }\n }\n\n public class Queue<T>\n {\n public int size;\n public Stack<T> inbox;\n public Stack<T> outbox;\n public Queue()\n {\n inbox = new Stack<T>();\n outbox = new Stack<T>();\n }\n public void EnQueue(T data)\n {\n inbox.Push(data);\n size++;\n }\n public Node<T> DeQueue()\n {\n if (outbox.size == 0)\n {\n while (inbox.size != 0)\n {\n outbox.Push(inbox.Pop().data);\n }\n }\n Node<T> temp = new Node<T>();\n if (outbox.size != 0)\n {\n temp = outbox.Pop();\n size--;\n }\n return temp;\n }\n\n }\n public class Node<T>\n {\n public T data;\n public Node<T> link;\n }\n\n static void Main(string[] args)\n {\n Queue<int> q = new Queue<int>();\n for (int i = 1; i <= 3; i++)\n q.EnQueue(i);\n // q.Display();\n for (int i = 1; i < 3; i++)\n q.DeQueue();\n //q.Display();\n Console.ReadKey();\n }\n }\n}\n" }, { "answer_id": 44273758, "author": "Santhosh", "author_id": 6851131, "author_profile": "https://Stackoverflow.com/users/6851131", "pm_score": 2, "selected": false, "text": "public class Queue<T> where T : class\n{\n private Stack<T> input = new Stack<T>();\n private Stack<T> output = new Stack<T>();\n public void Enqueue(T t)\n {\n input.Push(t);\n }\n\n public T Dequeue()\n {\n if (output.Count == 0)\n {\n while (input.Count != 0)\n {\n output.Push(input.Pop());\n }\n }\n\n return output.Pop();\n }\n}\n" }, { "answer_id": 46390588, "author": "Irshad ck", "author_id": 8276943, "author_profile": "https://Stackoverflow.com/users/8276943", "pm_score": -1, "selected": false, "text": "class queue<T>{\n static class Node<T>{\n private T data;\n private Node<T> next;\n Node(T data){\n this.data = data;\n next = null;\n }\n }\n Node firstTop;\n Node secondTop;\n \n void push(T data){\n Node temp = new Node(data);\n temp.next = firstTop;\n firstTop = temp;\n }\n \n void pop(){\n if(firstTop == null){\n return;\n }\n Node temp = firstTop;\n while(temp != null){\n Node temp1 = new Node(temp.data);\n temp1.next = secondTop;\n secondTop = temp1;\n temp = temp.next;\n }\n secondTop = secondTop.next;\n firstTop = null;\n while(secondTop != null){\n Node temp3 = new Node(secondTop.data);\n temp3.next = firstTop;\n firstTop = temp3;\n secondTop = secondTop.next;\n }\n }\n \n}\n" }, { "answer_id": 46724770, "author": "hIpPy", "author_id": 58678, "author_profile": "https://Stackoverflow.com/users/58678", "pm_score": 0, "selected": false, "text": "O(1) dequeue() // time: O(n), space: O(n)\nenqueue(x):\n if stack.isEmpty():\n stack.push(x)\n return\n temp = stack.pop()\n enqueue(x)\n stack.push(temp)\n\n// time: O(1)\nx dequeue():\n return stack.pop()\n O(1) enqueue() // O(1)\nenqueue(x):\n stack.push(x)\n\n// time: O(n), space: O(n)\nx dequeue():\n temp = stack.pop()\n if stack.isEmpty():\n x = temp\n else:\n x = dequeue()\n stack.push(temp)\n return x\n" }, { "answer_id": 46796061, "author": "davejlin", "author_id": 5464788, "author_profile": "https://Stackoverflow.com/users/5464788", "pm_score": 1, "selected": false, "text": "struct Stack<Element> {\n var items = [Element]()\n\n var count : Int {\n return items.count\n }\n\n mutating func push(_ item: Element) {\n items.append(item)\n }\n\n mutating func pop() -> Element? {\n return items.removeLast()\n }\n\n func peek() -> Element? {\n return items.last\n }\n}\n\nstruct Queue<Element> {\n var inStack = Stack<Element>()\n var outStack = Stack<Element>()\n\n mutating func enqueue(_ item: Element) {\n inStack.push(item)\n }\n\n mutating func dequeue() -> Element? {\n fillOutStack() \n return outStack.pop()\n }\n\n mutating func peek() -> Element? {\n fillOutStack()\n return outStack.peek()\n }\n\n private mutating func fillOutStack() {\n if outStack.count == 0 {\n while inStack.count != 0 {\n outStack.push(inStack.pop()!)\n }\n }\n }\n}\n" }, { "answer_id": 50548677, "author": "Radioactive", "author_id": 5670939, "author_profile": "https://Stackoverflow.com/users/5670939", "pm_score": 1, "selected": false, "text": "if (s1.isEmpty())\nSystem.out.println(\"The Queue is empty\");\n else if (s1.size() == 1)\n return s1.pop();\n else {\n int x = s1.pop();\n int result = deQueue();\n s1.push(x);\n return result;\n" }, { "answer_id": 54274637, "author": "Jyoti Prasad Pal", "author_id": 3173123, "author_profile": "https://Stackoverflow.com/users/3173123", "pm_score": 1, "selected": false, "text": "//stack using array\nclass Stack {\n constructor() {\n this.data = [];\n }\n\n push(data) {\n this.data.push(data);\n }\n\n pop() {\n return this.data.pop();\n }\n\n peek() {\n return this.data[this.data.length - 1];\n }\n\n size(){\n return this.data.length;\n }\n}\n\nexport { Stack };\n import { Stack } from \"./Stack\";\n\nclass QueueUsingTwoStacks {\n constructor() {\n this.stack1 = new Stack();\n this.stack2 = new Stack();\n }\n\n enqueue(data) {\n this.stack1.push(data);\n }\n\n dequeue() {\n //if both stacks are empty, return undefined\n if (this.stack1.size() === 0 && this.stack2.size() === 0)\n return undefined;\n\n //if stack2 is empty, pop all elements from stack1 to stack2 till stack1 is empty\n if (this.stack2.size() === 0) {\n while (this.stack1.size() !== 0) {\n this.stack2.push(this.stack1.pop());\n }\n }\n\n //pop and return the element from stack 2\n return this.stack2.pop();\n }\n}\n\nexport { QueueUsingTwoStacks };\n import { StackUsingTwoQueues } from './StackUsingTwoQueues';\n\nlet que = new QueueUsingTwoStacks();\nque.enqueue(\"A\");\nque.enqueue(\"B\");\nque.enqueue(\"C\");\n\nconsole.log(que.dequeue()); //output: \"A\"\n" }, { "answer_id": 58008554, "author": "Girish Rathi", "author_id": 9785149, "author_profile": "https://Stackoverflow.com/users/9785149", "pm_score": 3, "selected": false, "text": "class MyQueue {\n\n Stack<Integer> input;\n Stack<Integer> output;\n\n /** Initialize your data structure here. */\n public MyQueue() {\n input = new Stack<Integer>();\n output = new Stack<Integer>();\n }\n\n /** Push element x to the back of queue. */\n public void push(int x) {\n input.push(x);\n }\n\n /** Removes the element from in front of queue and returns that element. */\n public int pop() {\n peek();\n return output.pop();\n }\n\n /** Get the front element. */\n public int peek() {\n if(output.isEmpty()) {\n while(!input.isEmpty()) {\n output.push(input.pop());\n }\n }\n return output.peek();\n }\n\n /** Returns whether the queue is empty. */\n public boolean empty() {\n return input.isEmpty() && output.isEmpty();\n }\n}\n" }, { "answer_id": 62305888, "author": "ASHISH R", "author_id": 4259659, "author_profile": "https://Stackoverflow.com/users/4259659", "pm_score": 1, "selected": false, "text": "/*\n\nenQueue(q, x)\n 1) Push x to stack1 (assuming size of stacks is unlimited).\n\ndeQueue(q)\n 1) If both stacks are empty then error.\n 2) If stack2 is empty\n While stack1 is not empty, push everything from stack1 to stack2.\n 3) Pop the element from stack2 and return it.\n\n*/\nclass myQueue {\n constructor() {\n this.stack1 = [];\n this.stack2 = [];\n }\n\n push(item) {\n this.stack1.push(item)\n }\n\n remove() {\n if (this.stack1.length == 0 && this.stack2.length == 0) {\n return \"Stack are empty\"\n }\n\n if (this.stack2.length == 0) {\n\n while (this.stack1.length != 0) {\n this.stack2.push(this.stack1.pop())\n }\n }\n return this.stack2.pop()\n }\n\n\n peek() {\n if (this.stack2.length == 0 && this.stack1.length == 0) {\n return 'Empty list'\n }\n\n if (this.stack2.length == 0) {\n while (this.stack1.length != 0) {\n this.stack2.push(this.stack1.pop())\n }\n }\n\n return this.stack2[0]\n }\n\n isEmpty() {\n return this.stack2.length === 0 && this.stack1.length === 0;\n }\n\n}\n\nconst q = new myQueue();\nq.push(1);\nq.push(2);\nq.push(3);\nq.remove()\n\nconsole.log(q)" }, { "answer_id": 67205990, "author": "Sarang", "author_id": 1278758, "author_profile": "https://Stackoverflow.com/users/1278758", "pm_score": 0, "selected": false, "text": "<?php\n$_fp = fopen(\"php://stdin\", \"r\");\n/* Enter your code here. Read input from STDIN. Print output to STDOUT */\n $queue = array();\n $count = 0;\n while($line = fgets($_fp)) {\n if($count == 0) {\n $noOfElement = $line;\n $count++;\n continue;\n }\n $action = explode(\" \",$line);\n $case = $action[0];\n switch($case) {\n case 1:\n $enqueueValue = $action[1];\n array_push($queue, $enqueueValue);\n break;\n case 2:\n array_shift($queue);\n break;\n case 3:\n $show = reset($queue);\n print_r($show);\n break;\n default:\n break;\n }\n }\n?>\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7086/" ]
69,209
<p>Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. </p>
[ { "answer_id": 69235, "author": "Eltariel", "author_id": 584, "author_profile": "https://Stackoverflow.com/users/584", "pm_score": 0, "selected": false, "text": "next previous->next current->next current" }, { "answer_id": 69306, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 5, "selected": false, "text": "tempList = B->next;\n*B = *tempList;\nfree(tempList);\n struct List { struct List *next; MyData *data; };\n struct HeavyList { struct HeavyList *next; char data[8192]; };\n" }, { "answer_id": 69321, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "prev = head\nnext = prev.link\n\nwhile(next != null)\n{\n if(next == del)\n {\n prev.link = next.link;\n free(del);\n del = null;\n return 0;\n }\n prev = next;\n next = next.link;\n}\n\nreturn 1;\n" }, { "answer_id": 69333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "void delete_node(Node* pNode)\n{\n pNode->Data = pNode->Next->Data; // Assume that SData::operator=(SData&) exists.\n Node* pTemp = pNode->Next->Next;\n delete(pNode->Next);\n pNode->Next = pTemp;\n}\n" }, { "answer_id": 1000807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "struct node \n{\n int data;\n struct node *link;\n };\n\nvoid populate(struct node **,int);\n\nvoid delete(struct node **);\n\nvoid printlist(struct node **);\n\nvoid populate(struct node **n,int num)\n{\n\n struct node *temp,*t;\n if(*n==NULL)\n {\n t=*n;\n t=malloc(sizeof(struct node));\n t->data=num;\n t->link=NULL;\n *n=t;\n }\n else\n {\n t=*n;\n temp=malloc(sizeof(struct node));\n while(t->link!=NULL)\n t=t->link;\n temp->data=num;\n temp->link=NULL;\n t->link=temp;\n }\n}\n\nvoid printlist(struct node **n)\n{\n struct node *t;\n t=*n;\n if(t==NULL)\n printf(\"\\nEmpty list\");\n\n while(t!=NULL)\n {\n printf(\"\\n%d\",t->data);\n printf(\"\\t%u address=\",t);\n t=t->link;\n }\n}\n\n\nvoid delete(struct node **n)\n{\n struct node *temp,*t;\n temp=*n;\n temp->data=temp->link->data;\n t=temp->link;\n temp->link=temp->link->link;\n free(t);\n} \n\nint main()\n{\n struct node *ty,*todelete;\n ty=NULL;\n populate(&ty,1);\n populate(&ty,2);\n populate(&ty,13);\n populate(&ty,14);\n populate(&ty,12);\n populate(&ty,19);\n\n printf(\"\\nlist b4 delete\\n\");\n printlist(&ty);\n\n printf(\"\\nEnter node pointer to delete the node====\");\n scanf(\"%u\",&todelete);\n delete(&todelete);\n\n printf(\"\\nlist after delete\\n\");\n printlist(&ty);\n\n return 0;\n}\n" }, { "answer_id": 2306642, "author": "Aneesh", "author_id": 278188, "author_profile": "https://Stackoverflow.com/users/278188", "pm_score": 0, "selected": false, "text": "void delself(list *list)\n{\n /*if we got a pointer to itself how to remove it...*/\n int n;\n\n printf(\"Enter the num:\");\n\n scanf(\"%d\",&n);\n\n while(list->next!=NULL)\n {\n if(list->number==n) /*now pointer in node itself*/\n {\n list->number=list->next->number;\n /*copy all(name,rollnum,mark..) data of next to current, disconect its next*/\n list->next=list->next->next;\n }\n list=list->next;\n }\n}\n" }, { "answer_id": 2306670, "author": "Aneesh", "author_id": 278188, "author_profile": "https://Stackoverflow.com/users/278188", "pm_score": 0, "selected": false, "text": "void delself(list *list)\n{\n /*if we got a pointer to itself how to remove it...*/\n int n;\n\n printf(\"Enter the num:\");\n scanf(\"%d\",&n);\n\n while(list->next!=NULL)\n {\n if(list->number==n) /*now pointer in node itself*/\n {\n list->number=list->next->number; /*copy all(name,rollnum,mark..)\n data of next to current, disconnect its next*/\n list->next=list->next->next;\n }\n list=list->next;\n }\n}\n" }, { "answer_id": 13522571, "author": "Vinay Kumar Baghel", "author_id": 685692, "author_profile": "https://Stackoverflow.com/users/685692", "pm_score": -1, "selected": false, "text": "Void deleteMidddle(Node* head)\n{\n Node* slow_ptr = head;\n Node* fast_ptr = head;\n Node* tmp = head;\n while(slow_ptr->next != NULL && fast_ptr->next != NULL)\n {\n tmp = slow_ptr;\n slow_ptr = slow_ptr->next;\n fast_ptr = fast_ptr->next->next;\n }\n tmp->next = slow_ptr->next;\n free(slow_ptr);\n enter code here\n\n}\n" }, { "answer_id": 15356392, "author": "Desyn8686", "author_id": 2159985, "author_profile": "https://Stackoverflow.com/users/2159985", "pm_score": 0, "selected": false, "text": "#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct node\n{\n int nodeID;\n node *next;\n};\n\nvoid printList(node* p_nodeList, int removeID);\nvoid removeNode(node* p_nodeList, int nodeID);\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode);\n\nnode* addNewNode(node* p_nodeList, int id)\n{\n node* p_node = new node;\n p_node->nodeID = id;\n p_node->next = p_nodeList;\n return p_node;\n}\n\nint main()\n{\n node* p_nodeList = NULL;\n int nodeID = 1;\n int removeID;\n int listLength;\n cout << \"Pick a list length: \";\n cin >> listLength;\n for (int i = 0; i < listLength; i++)\n {\n p_nodeList = addNewNode(p_nodeList, nodeID);\n nodeID++;\n }\n cout << \"Pick a node from 1 to \" << listLength << \" to remove: \";\n cin >> removeID;\n while (removeID <= 0 || removeID > listLength)\n {\n if (removeID == 0)\n {\n return 0;\n }\n cout << \"Please pick a number from 1 to \" << listLength << \": \";\n cin >> removeID;\n }\n removeNode(p_nodeList, removeID);\n printList(p_nodeList, removeID);\n}\n\nvoid printList(node* p_nodeList, int removeID)\n{\n node* p_currentNode = p_nodeList;\n if (p_currentNode != NULL)\n {\n p_currentNode = p_currentNode->next;\n printList(p_currentNode, removeID);\n if (removeID != 1)\n {\n if (p_nodeList->nodeID != 1)\n {\n cout << \", \";\n }\n\n cout << p_nodeList->nodeID;\n }\n else\n {\n if (p_nodeList->nodeID !=2)\n {\n cout << \", \";\n }\n cout << p_nodeList->nodeID;\n }\n }\n}\n\nvoid removeNode(node* p_nodeList, int nodeID)\n{\n node* p_currentNode = p_nodeList;\n if (p_currentNode->nodeID == nodeID)\n {\n if(p_currentNode->next != NULL)\n {\n p_currentNode->nodeID = p_currentNode->next->nodeID;\n node* p_temp = p_currentNode->next->next;\n delete(p_currentNode->next);\n p_currentNode->next = p_temp;\n }\n else\n {\n delete(p_currentNode);\n }\n }\n else if(p_currentNode->next->next == NULL)\n {\n removeLastNode(p_currentNode->next, nodeID, p_currentNode);\n }\n else\n {\n removeNode(p_currentNode->next, nodeID);\n }\n}\n\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode)\n{\n node* p_currentNode = p_nodeList;\n p_lastNode->next = NULL;\n delete (p_currentNode);\n}\n" }, { "answer_id": 58032707, "author": "Ankit Raj", "author_id": 5494644, "author_profile": "https://Stackoverflow.com/users/5494644", "pm_score": 1, "selected": false, "text": "struct node* temp = ptr->next;\nptr->data = temp->data;\nptr->next = temp->next;\nfree(temp);\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7086/" ]
69,250
<p>In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.<br> Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.<br> In "release" mode, you usually have all sorts of optimizations turned on.<br> Why the difference?</p>
[ { "answer_id": 69252, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "\nvoid foo() {\n1: int i;\n2: for(i = 0; i < 2; )\n3: i++;\n4: return;\n int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device\n *ptr = 0; // setup hardware device\n while(*ptr == 1) { // loop until hardware device is done\n // do something\n }\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
69,262
<p>I am wondering if there is a method or format string I'm missing in .NET to convert the following:</p> <pre><code> 1 to 1st 2 to 2nd 3 to 3rd 4 to 4th 11 to 11th 101 to 101st 111 to 111th </code></pre> <p><a href="http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx" rel="noreferrer">This link</a> has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.</p> <p><strong>Solution</strong></p> <p>Scott Hanselman's answer is the accepted one because it answers the question directly.</p> <p>For a solution however, see <a href="https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284">this great answer</a>.</p>
[ { "answer_id": 69284, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "function ordinal($num) {\n $ones = $num % 10;\n $tens = floor($num / 10) % 10;\n if ($tens == 1) {\n $suff = \"th\";\n } else {\n switch ($ones) {\n case 1 : $suff = \"st\"; break;\n case 2 : $suff = \"nd\"; break;\n case 3 : $suff = \"rd\"; break;\n default : $suff = \"th\";\n }\n }\n return $num . $suff;\n}\n" }, { "answer_id": 69287, "author": "mjallday", "author_id": 6084, "author_profile": "https://Stackoverflow.com/users/6084", "pm_score": 4, "selected": false, "text": " public static string Ordinal(this int number)\n {\n var ones = number % 10;\n var tens = Math.Floor (number / 10f) % 10;\n if (tens == 1)\n {\n return number + \"th\";\n }\n\n switch (ones)\n {\n case 1: return number + \"st\";\n case 2: return number + \"nd\";\n case 3: return number + \"rd\";\n default: return number + \"th\";\n }\n }\n" }, { "answer_id": 69328, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 6, "selected": false, "text": "public static string Ordinal(int number)\n{\n string suffix = String.Empty;\n\n int ones = number % 10;\n int tens = (int)Math.Floor(number / 10M) % 10;\n\n if (tens == 1)\n {\n suffix = \"th\";\n }\n else\n {\n switch (ones)\n {\n case 1:\n suffix = \"st\";\n break;\n\n case 2:\n suffix = \"nd\";\n break;\n\n case 3:\n suffix = \"rd\";\n break;\n\n default:\n suffix = \"th\";\n break;\n }\n }\n return String.Format(\"{0}{1}\", number, suffix);\n}\n" }, { "answer_id": 386318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "else if (choice=='q')\n{\n qtr++;\n\n switch (qtr)\n {\n case(2): strcpy(qtrs,\"nd\");break;\n case(3):\n {\n strcpy(qtrs,\"rd\");\n cout<<\"End of First Half!!!\";\n cout<<\" hteam \"<<\"[\"<<hteam<<\"] \"<<hs;\n cout<<\" vteam \"<<\" [\"<<vteam;\n cout<<\"] \";\n cout<<vs;dwn=1;yd=10;\n\n if (beginp=='H') team='V';\n else team='H';\n break;\n }\n case(4): strcpy(qtrs,\"th\");break;\n" }, { "answer_id": 611179, "author": "redcalx", "author_id": 15703, "author_profile": "https://Stackoverflow.com/users/15703", "pm_score": 3, "selected": false, "text": "CREATE FUNCTION [Internal].[GetNumberAsOrdinalString]\n(\n @num int\n)\nRETURNS nvarchar(max)\nAS\nBEGIN\n\n DECLARE @Suffix nvarchar(2);\n DECLARE @Ones int; \n DECLARE @Tens int;\n\n SET @Ones = @num % 10;\n SET @Tens = FLOOR(@num / 10) % 10;\n\n IF @Tens = 1\n BEGIN\n SET @Suffix = 'th';\n END\n ELSE\n BEGIN\n\n SET @Suffix = \n CASE @Ones\n WHEN 1 THEN 'st'\n WHEN 2 THEN 'nd'\n WHEN 3 THEN 'rd'\n ELSE 'th'\n END\n END\n\n RETURN CONVERT(nvarchar(max), @num) + @Suffix;\nEND\n" }, { "answer_id": 9290324, "author": "avenmore", "author_id": 37660, "author_profile": "https://Stackoverflow.com/users/37660", "pm_score": 2, "selected": false, "text": "function OrdinalNumberSuffix(const ANumber: integer): string;\nbegin\n Result := IntToStr(ANumber);\n if(((Abs(ANumber) div 10) mod 10) = 1) then // Tens = 1\n Result := Result + 'th'\n else\n case(Abs(ANumber) mod 10) of\n 1: Result := Result + 'st';\n 2: Result := Result + 'nd';\n 3: Result := Result + 'rd';\n else\n Result := Result + 'th';\n end;\nend;\n" }, { "answer_id": 19553611, "author": "Shahzad Qureshi", "author_id": 2719563, "author_profile": "https://Stackoverflow.com/users/2719563", "pm_score": 6, "selected": false, "text": " private static string GetOrdinalSuffix(int num)\n {\n string number = num.ToString();\n if (number.EndsWith(\"11\")) return \"th\";\n if (number.EndsWith(\"12\")) return \"th\";\n if (number.EndsWith(\"13\")) return \"th\";\n if (number.EndsWith(\"1\")) return \"st\";\n if (number.EndsWith(\"2\")) return \"nd\";\n if (number.EndsWith(\"3\")) return \"rd\";\n return \"th\";\n }\n public static class IntegerExtensions\n{\n public static string DisplayWithSuffix(this int num)\n {\n string number = num.ToString();\n if (number.EndsWith(\"11\")) return number + \"th\";\n if (number.EndsWith(\"12\")) return number + \"th\";\n if (number.EndsWith(\"13\")) return number + \"th\";\n if (number.EndsWith(\"1\")) return number + \"st\";\n if (number.EndsWith(\"2\")) return number + \"nd\";\n if (number.EndsWith(\"3\")) return number + \"rd\";\n return number + \"th\";\n }\n}\n int a = 1;\na.DisplayWithSuffix(); \n 1.DisplayWithSuffix();\n" }, { "answer_id": 20550095, "author": "Frank Hoffman", "author_id": 747173, "author_profile": "https://Stackoverflow.com/users/747173", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// Extension methods for numbers\n/// </summary>\npublic static class NumericExtensions\n{\n /// <summary>\n /// Adds the ordinal indicator to an integer\n /// </summary>\n /// <param name=\"number\">The number</param>\n /// <returns>The formatted number</returns>\n public static string ToOrdinalString(this int number)\n {\n // Numbers in the teens always end with \"th\"\n\n if((number % 100 > 10 && number % 100 < 20))\n return number + \"th\";\n else\n {\n // Check remainder\n\n switch(number % 10)\n {\n case 1:\n return number + \"st\";\n\n case 2:\n return number + \"nd\";\n\n case 3:\n return number + \"rd\";\n\n default:\n return number + \"th\";\n }\n }\n }\n}\n" }, { "answer_id": 20610293, "author": "Faust", "author_id": 613004, "author_profile": "https://Stackoverflow.com/users/613004", "pm_score": 0, "selected": false, "text": "public static string OrdinalSuffix(int ordinal)\n{\n //Because negatives won't work with modular division as expected:\n var abs = Math.Abs(ordinal); \n\n var lastdigit = abs % 10; \n\n return \n //Catch 60% of cases (to infinity) in the first conditional:\n lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? \"th\" \n : lastdigit == 1 ? \"st\" \n : lastdigit == 2 ? \"nd\" \n : \"rd\";\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
69,275
<p>I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one. </p> <p>The graph contains labeled nodes and unlabeled directional edges. The ideal output would be something like <a href="http://en.wikipedia.org/wiki/Image:6n-graf.svg" rel="noreferrer">this</a>. </p> <p>Anybody know of anything pre-built than can help?</p>
[ { "answer_id": 74815, "author": "wxs", "author_id": 12981, "author_profile": "https://Stackoverflow.com/users/12981", "pm_score": 4, "selected": true, "text": "graph untitled {\n graph[bgcolor=\"transparent\"];\n node [fontname=\"Bitstream Vera Sans\", fontsize=\"22.00\", shape=circle, style=\"bold,filled\" fillcolor=white];\n edge [style=bold];\n 1;2;3;4;5;6;\n 6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4;\n 2 -- 5;\n}\n neato -Tsvg input.dot > graph.svg\n" }, { "answer_id": 52329563, "author": "FGRibreau", "author_id": 745121, "author_profile": "https://Stackoverflow.com/users/745121", "pm_score": 0, "selected": false, "text": "https://image-charts.com/chart\n?cht=gv\n&chl=graph g{1;2;3;4;5;6; 6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4; 2 -- 5;)\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165305/" ]
69,277
<p>I have an Enumerable array</p> <pre><code>int meas[] = new double[] {3, 6, 9, 12, 15, 18}; </code></pre> <p>On each successive call to the mock's method that I'm testing I want to return a value from that array.</p> <pre><code>using(_mocks.Record()) { Expect.Call(mocked_class.GetValue()).Return(meas); } using(_mocks.Playback()) { foreach(var i in meas) Assert.AreEqual(i, mocked_class.GetValue(); } </code></pre> <p>Does anyone have an idea how I can do this?</p>
[ { "answer_id": 69382, "author": "vrdhn", "author_id": 414441, "author_profile": "https://Stackoverflow.com/users/414441", "pm_score": 0, "selected": false, "text": "get_next() {\n foreach( float x in meas ) {\n yield x;\n }\n}\n" }, { "answer_id": 69642, "author": "Darren", "author_id": 6065, "author_profile": "https://Stackoverflow.com/users/6065", "pm_score": 1, "selected": false, "text": "using(_mocks.Record()) {\n Expect.Call(mocked_class.GetValue()).Return(3); \n Expect.Call(mocked_class.GetValue()).Return(6); \n Expect.Call(mocked_class.GetValue()).Return(9); \n Expect.Call(mocked_class.GetValue()).Return(12); \n Expect.Call(mocked_class.GetValue()).Return(15); \n Expect.Call(mocked_class.GetValue()).Return(18); \n}\nusing(_mocks.Playback()) {\n foreach(var i in meas)\n Assert.AreEqual(i, mocked_class.GetValue(); \n}\n" }, { "answer_id": 69985, "author": "bahadorn", "author_id": 6476, "author_profile": "https://Stackoverflow.com/users/6476", "pm_score": 3, "selected": true, "text": "var meas = new int[] { 3, 6, 9, 12, 15, 18 };\nusing (mocks.Record())\n{\n int forMockMethod = 0;\n SetupResult.For(mocked_class.GetValue()).Do(\n new Func<int>(() => meas[forMockMethod++])\n );\n}\n\nusing(mocks.Playback())\n{\n foreach (var i in meas)\n Assert.AreEqual(i, mocked_class.GetValue());\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
69,281
<p>I've recently started using Eclipse Ganymede CDT for C development and I couldn't like it more. I'm aware the learning curve could be sort of pronounced, therefore and with your help, my goal is to flatten it as much as possible. I'm looking for the best hacks, hints, tips, tricks, and best practices to really unleash the full power of the IDE.</p>
[ { "answer_id": 69335, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": true, "text": ".h .cpp typedef struct class" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
69,296
<p>I have a a property defined as:</p> <pre><code>[XmlArray("delete", IsNullable = true)] [XmlArrayItem("contact", typeof(ContactEvent)), XmlArrayItem("sms", typeof(SmsEvent))] public List&lt;Event&gt; Delete { get; set; } </code></pre> <p>If the List&lt;> Delete has no items</p> <pre><code>&lt;delete /&gt; </code></pre> <p>is emitted. If the List&lt;> Delete is set to null</p> <pre><code>&lt;delete xsi:nil="true" /&gt; </code></pre> <p>is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?</p> <p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407">Greg</a> - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.</p> <p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518">Rob Cooper</a> - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.</p>
[ { "answer_id": 811038, "author": "theahuramazda", "author_id": 99290, "author_profile": "https://Stackoverflow.com/users/99290", "pm_score": 4, "selected": false, "text": "public List<Event> Delete { get; set; }\n[XMLIgnore]\npublic bool DeleteSpecified\n{\n get\n {\n bool isRendered = false;\n if (Delete != null)\n {\n isRendered = (Delete.Count > 0);\n } \n\n return isRendered;\n }\n set\n {\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
69,316
<p>What are the biggest pros and cons of <a href="http://incubator.apache.org/thrift/" rel="noreferrer">Apache Thrift</a> vs <a href="http://code.google.com/apis/protocolbuffers/" rel="noreferrer">Google's Protocol Buffers</a>?</p>
[ { "answer_id": 69374, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 7, "selected": false, "text": "Set" }, { "answer_id": 296349, "author": "eishay", "author_id": 16201, "author_profile": "https://Stackoverflow.com/users/16201", "pm_score": 6, "selected": false, "text": "option optimize_for = SPEED" }, { "answer_id": 46021476, "author": "Sinapse", "author_id": 1584435, "author_profile": "https://Stackoverflow.com/users/1584435", "pm_score": 1, "selected": false, "text": "thekvs YAS" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
69,332
<p>I suspect that one of my applications eats more CPU cycles than I want it to. The problem is - it happens in bursts, and just looking at the task manager doesn't help me as it shows immediate usage only.</p> <p>Is there a way (on Windows) to track the history of CPU &amp; Memory usage for some process. E.g. I will start tracking "firefox", and after an hour or so will see a graph of its CPU &amp; memory usage during that hour.</p> <p>I'm looking for either a ready-made tool or a programmatic way to achieve this.</p>
[ { "answer_id": 69416, "author": "Martin08", "author_id": 8203, "author_profile": "https://Stackoverflow.com/users/8203", "pm_score": 9, "selected": true, "text": "perfmon" }, { "answer_id": 10515335, "author": "Rich Kreider", "author_id": 1384476, "author_profile": "https://Stackoverflow.com/users/1384476", "pm_score": 4, "selected": false, "text": "@echo off\n: Rich Kreider <[email protected]>\n: report processor time for given process until process exits (could be expanded to use a PID to be more\n: precise)\n: Depends: typeperf\n: Usage: foo.cmd <processname>\n\nset process=%~1\necho Press CTRL-C To Stop...\n:begin\nfor /f \"tokens=2 delims=,\" %%c in ('typeperf \"\\Process(%process%)\\%% Processor Time\" -si 1 -sc 1 ^| find /V \"\\\\\"') do (\nif %%~c==-1 (\ngoto :end\n) else (\necho %%~c%%\ngoto begin\n)\n)\n\n:end\necho Process seems to have terminated.\n" }, { "answer_id": 50368360, "author": "Kaarthikeyan", "author_id": 2092251, "author_profile": "https://Stackoverflow.com/users/2092251", "pm_score": 2, "selected": false, "text": "select NumberOfLogicalProcessors from Win32_ComputerSystem\n select * from Win32_PerfRawData_PerfProc_Process where IDProcess=1234\n CPU%= ((p2-p1)/(t2-t1)*100)/NumberOfLogicalProcessors\n" }, { "answer_id": 58649113, "author": "Prosenjit Sen", "author_id": 11408288, "author_profile": "https://Stackoverflow.com/users/11408288", "pm_score": 2, "selected": false, "text": " $cpu = Get-WmiObject win32_processor\n $search = get-service \"WSearch\"\n if ($search.Status -eq 'Running')\n {\n $searchmem = Get-WmiObject Win32_Service -Filter \"Name = 'WSearch'\"\n $searchid = $searchmem.ProcessID\n $searchcpu1 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}\n Start-Sleep -Seconds 1\n $searchcpu2 = Get-WmiObject Win32_PerfRawData_PerfProc_Process | Where {$_.IDProcess -eq $searchid}\n $searchp2p1 = $searchcpu2.PercentProcessorTime - $searchcpu1.PercentProcessorTime\n $searcht2t1 = $searchcpu2.Timestamp_Sys100NS - $searchcpu1.Timestamp_Sys100NS\n $searchcpu = [Math]::Round(($searchp2p1 / $searcht2t1 * 100) /$cpu.NumberOfLogicalProcessors, 1)\n $searchmem = [Math]::Round($searchcpu1.WorkingSetPrivate / 1mb,1)\n Write-Host 'Service is' $search.Status', Memory consumed: '$searchmem' MB, CPU Usage: '$searchcpu' %'\n }\n\n else\n {\n Write-Host Service is $search.Status -BackgroundColor Red\n }\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
69,352
<p>What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.</p>
[ { "answer_id": 69359, "author": "JP Richardson", "author_id": 10333, "author_profile": "https://Stackoverflow.com/users/10333", "pm_score": 5, "selected": false, "text": "FormName.WindowState = FormWindowState.Minimized;\n" }, { "answer_id": 69362, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 4, "selected": false, "text": "<form>.WindowState = FormWindowState.Minimized;\n" }, { "answer_id": 69363, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "Form myForm;\nmyForm.WindowState = FormWindowState.Minimized;\n" }, { "answer_id": 69372, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if(e.KeyChar == 'm')\n this.WindowState = FormWindowState.Minimized;\n}\n" }, { "answer_id": 362666, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "this.WindowState = FormWindowState.Minimized\n" }, { "answer_id": 10916569, "author": "profnotime", "author_id": 1286381, "author_profile": "https://Stackoverflow.com/users/1286381", "pm_score": 2, "selected": false, "text": "if (form_Name.WindowState != FormWindowState.Minimized) form_Name.WindowState = FormWindowState.Minimized;\n" }, { "answer_id": 19263211, "author": "Tech Initiator", "author_id": 2861211, "author_profile": "https://Stackoverflow.com/users/2861211", "pm_score": -1, "selected": false, "text": "this.MdiParent.WindowState = FormWindowState.Minimized;\n" }, { "answer_id": 23004359, "author": "GoroundoVipa", "author_id": 3471643, "author_profile": "https://Stackoverflow.com/users/3471643", "pm_score": -1, "selected": false, "text": "Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\nMe.Hide()\n\nEnd Sub\n" }, { "answer_id": 56512081, "author": "Abdul Moiz", "author_id": 11519549, "author_profile": "https://Stackoverflow.com/users/11519549", "pm_score": 0, "selected": false, "text": "this.WindowState = FormWindowState.Minimized;" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7516/" ]
69,391
<p>In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script?</p>
[ { "answer_id": 69393, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 2, "selected": true, "text": "tell application \"System Events\"\n tell (first process whose frontmost is true)\n click menu \"Help\" of menu bar 1\n end tell\nend tell\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10906/" ]
69,411
<p>What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. </p>
[ { "answer_id": 69419, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 2, "selected": false, "text": "man scp man rsync scp file1 file2 dir3 user@remotehost:path\n" }, { "answer_id": 69421, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 3, "selected": false, "text": "scp -r <directory> <username>@<targethost>:<targetdir>\n" }, { "answer_id": 69422, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 1, "selected": false, "text": "tar cvf - | ssh server tar xf -\n" }, { "answer_id": 69433, "author": "Ycros", "author_id": 10495, "author_profile": "https://Stackoverflow.com/users/10495", "pm_score": 6, "selected": false, "text": "scp -r sourcedir/ [email protected]:/dest/dir/\n rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/\n" }, { "answer_id": 74328, "author": "Ram Prasad", "author_id": 6361, "author_profile": "https://Stackoverflow.com/users/6361", "pm_score": 1, "selected": false, "text": "rsync -azvu -e ssh user@host1:/directory/ user@host2:/directory2/\n ssh user@host1 \"/usr/bin/rsync -azvu -e ssh /directory/ user@host2:/directory2/\"\n" }, { "answer_id": 82302, "author": "Gunstick", "author_id": 15653, "author_profile": "https://Stackoverflow.com/users/15653", "pm_score": 2, "selected": false, "text": "rdiff-backup user1@host1::/source-dir user2@host2::/dest-dir\n sudo apt-get install rdiff-backup\n" }, { "answer_id": 82493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "cd /origin; find . -xdev -depth -not -path ./lost+found -print0 \\\n| tar --create --atime-preserve=system --null --files-from=- --format=posix \\\n--no-recursion --sparse | ssh targethost 'cd /target; tar --extract \\\n--overwrite --preserve-permissions --sparse'\n" }, { "answer_id": 104897, "author": "user19218", "author_id": 19218, "author_profile": "https://Stackoverflow.com/users/19218", "pm_score": 5, "selected": false, "text": "rsync -avlzp /path/to/sfolder [email protected]:/path/to/remote/dfolder\n rsync -aHvz /path/to/sfolder [email protected]:/path/to/remote/dfolder\n rsync -aHvz /path/to/sfolder/ [email protected]:/path/to/remote/dfolder\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
69,430
<p>I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.</p> <p>I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.</p>
[ { "answer_id": 69474, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 3, "selected": false, "text": "display:box" }, { "answer_id": 69494, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 5, "selected": false, "text": "<script type=\"text/javascript\">\n\n/***********************************************\n* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)\n* This notice MUST stay intact for legal use\n* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code\n\n***********************************************/\n\n\nfunction disableSelection(target){\n\n if (typeof target.onselectstart!=\"undefined\") //IE route\n target.onselectstart=function(){return false}\n\n else if (typeof target.style.MozUserSelect!=\"undefined\") //Firefox route\n target.style.MozUserSelect=\"none\"\n\n else //All other route (ie: Opera)\n target.onmousedown=function(){return false}\n\n target.style.cursor = \"default\"\n}\n\n\n\n//Sample usages\n//disableSelection(document.body) //Disable text selection on entire body\n//disableSelection(document.getElementById(\"mydiv\")) //Disable text selection on element with id=\"mydiv\"\n\n\n</script>\n" }, { "answer_id": 69500, "author": "Stephen M. Redd", "author_id": 10115, "author_profile": "https://Stackoverflow.com/users/10115", "pm_score": 4, "selected": false, "text": "<div onselectstart=\"return false\">some stuff</div>\n" }, { "answer_id": 541719, "author": "jlleblanc", "author_id": 586, "author_profile": "https://Stackoverflow.com/users/586", "pm_score": 3, "selected": false, "text": "::selection {\n background-color: transparent;\n}\n ul" }, { "answer_id": 668706, "author": "Alan Hensel", "author_id": 14532, "author_profile": "https://Stackoverflow.com/users/14532", "pm_score": 2, "selected": false, "text": "-khtml-user-select: none -moz-user-select target.style.KhtmlUserSelect=\"none\";" }, { "answer_id": 3320442, "author": "hbtdev", "author_id": 400478, "author_profile": "https://Stackoverflow.com/users/400478", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\ndocument.write(\".\");\ndocument.body.style.MozUserSelect='none';\n</script>\n" }, { "answer_id": 3320495, "author": "Taylor D. Edmiston", "author_id": 149428, "author_profile": "https://Stackoverflow.com/users/149428", "pm_score": 1, "selected": false, "text": "::selection" }, { "answer_id": 4448972, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 9, "selected": true, "text": "*.unselectable {\n -moz-user-select: -moz-none;\n -khtml-user-select: none;\n -webkit-user-select: none;\n\n /*\n Introduced in IE 10.\n See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/\n */\n -ms-user-select: none;\n user-select: none;\n}\n unselectable <div id=\"foo\" unselectable=\"on\" class=\"unselectable\">...</div>\n <div> function makeUnselectable(node) {\n if (node.nodeType == 1) {\n node.setAttribute(\"unselectable\", \"on\");\n }\n var child = node.firstChild;\n while (child) {\n makeUnselectable(child);\n child = child.nextSibling;\n }\n}\n\nmakeUnselectable(document.getElementById(\"foo\"));\n" }, { "answer_id": 6382503, "author": "Blowsie", "author_id": 370286, "author_profile": "https://Stackoverflow.com/users/370286", "pm_score": 5, "selected": false, "text": "-webkit-touch-callout: none;\n-webkit-user-select: none;\n-khtml-user-select: none;\n-moz-user-select: none;\n-ms-user-select: none;\nuser-select: none;\n" }, { "answer_id": 12577113, "author": "rgb", "author_id": 738957, "author_profile": "https://Stackoverflow.com/users/738957", "pm_score": 2, "selected": false, "text": "// @usage use within a rule\n// ex. img {@include user-select(none);}\n// @param assumed valid user-select value\n@mixin user-select($value)\n{\n & {\n -webkit-touch-callout: $value;\n -webkit-user-select: $value;\n -khtml-user-select: $value;\n -moz-user-select: $value;\n -ms-user-select: $value;\n user-select: $value;\n }\n}\n" } ]
2008/09/16
[ "https://Stackoverflow.com/questions/69430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561/" ]