qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
323,230
<p>We have a JavaEE server and servlets providing data to mobile clients (first JavaME, now soon iPhone). The servlet writes out data using the following code:</p> <pre><code>DataOutputStream dos = new DataOutputStream(out); dos.writeInt(someInt); dos.writeUTF(someString); </code></pre> <p>... and so on</p> <p>This data is returned to the client as bytes in the HTTP response body, to reduce the number of bytes transferred.</p> <p>In the iPhone app, the response payload is loaded into NSData object. Now, after spending hours and hours trying to figure out how to read the data out in the Objective-C application, I'm almost ready to give up, as I haven't found any good way to read the data into NSInteger and NSString (as corresponding to above protocol)</p> <p>Would anyone have any pointers how to read stuff out from a binary protocol written by a java app? Any help is greatly appreciated!</p> <p>Thanks!</p>
[ { "answer_id": 923499, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "DataOutputStream DataOutputStream NSString initWithBytes:length:encoding: NSData *data = ...; // this comes from the HTTP request\nint length = [data length];\nconst uint8_t *bytes = (const uint8_t *)[data bytes];\n\nif(length < 4)\n ; // oops, handle error\n\n// demarshall the big-endian integer from 4 bytes\nuint32_t myInt = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | (bytes[3]);\n// convert from (n)etwork endianness to (h)ost endianness (may be a no-op)\n// ntohl is defined in <arpa/inet.h>\nmyInt = ntohl(myInt);\n\n// advance to next datum\nbytes += 4;\nlength -= 4;\n\n// demarshall the string length\nif(length < 2)\n ; // oops, handle error\nuint16_t myStringLen = (bytes[0] << 8) | (bytes[1]);\n// convert from network to host endianness\nmyStringLen = ntohs(myStringLen);\nbytes += 2;\nlength -= 2;\n\n// make sure we actually have as much data as we say we have\nif(myStringLen > length)\n myStringLen = (uint16_t)length;\n\n// demarshall the string\nNSString *myString = [[NSString alloc] initWithBytes:bytes length:myStringLen encoding:NSUTF8StringEncoding];\nbytes += myStringLen;\nlength -= myStringLen;\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,260
<p>Please let me know how can I remove default banner of web server from response - Apache http1.1 coyote</p>
[ { "answer_id": 323364, "author": "Pierre-Yves Gillier", "author_id": 2692, "author_profile": "https://Stackoverflow.com/users/2692", "pm_score": 2, "selected": false, "text": "ServerSignature Off\n" }, { "answer_id": 8735831, "author": "Leif Wickland", "author_id": 175251, "author_profile": "https://Stackoverflow.com/users/175251", "pm_score": 0, "selected": false, "text": "<Connector> server <Connector executor=\"tomcatThreadPool\"\n port=\"80\" protocol=\"HTTP/1.1\"\n server=\" \"\n ...\n/>\n server server Server: \n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,264
<p>Is it possible (and if yes, how) to bypass DNS when doing a HTTP request ?</p> <p>I want to hit directly a front-end with an HTTP request, without getting through NLB but with the correct host header. As I have the IP of my server, I just need to bypass the DNS.</p> <p>I tried to use WebRequest, replacing the URL with the IP and setting the Host header, but this header is protected.</p> <p>How can I do that ? Do I need to create the HTTP request myself ?</p> <p>Note: editing host file is not an option</p>
[ { "answer_id": 323555, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 3, "selected": false, "text": "HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://127.0.0.1\");\nRequest.Host = \"www.example.com\"\n" }, { "answer_id": 359398, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 3, "selected": true, "text": "request.Proxy = new WebProxy(ip.ToString());\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22970/" ]
323,265
<p>I try <code>Request.Form.Set(k, v)</code> but it's throwing exception </p> <blockquote> <p>Collection is read-only</p> </blockquote>
[ { "answer_id": 323312, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 5, "selected": true, "text": "Request.Querystring NameValueCollection oQuery = Request.QueryString;\noQuery = (NameValueCollection)Request.GetType().GetField(\"_queryString\",BindingFlags.NonPublic | BindingFlags.Instance).GetValue(Request);\nPropertyInfo oReadable = oQuery .GetType().GetProperty(\"IsReadOnly\", BindingFlags.NonPublic | BindingFlags.Instance);\noReadable.SetValue(oQuery, false, null);\noQuery[\"foo\"] = \"bar\";\noReadable.SetValue(oQuery, true, null); \n NameValueCollection" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441493/" ]
323,271
<p>I have a HTML application, partially HTML, partially VBscript, disguised as a form. What it does is it opens a few local files, runs a DOS box containing GAWK and presents a text file as its result. I wish to expand upon it by letting it create a bitmap image with the results in a stacked bar graph, for instance as a .BMP file. But I'm stumped. I haven't the faintest idea where to start.</p>
[ { "answer_id": 323321, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<img>" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,284
<p>currently i am forcing my WPF app to use the luna theme no matter what, with this XAML code</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Styles.xaml" /&gt; &lt;ResourceDictionary Source="NavigationCommands.xaml" /&gt; &lt;ResourceDictionary Source="/RibbonControlsLibrary;component/Themes/Office2007Blue.xaml"/&gt; &lt;ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;;component/Themes/luna.normalcolor.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre> <p>and now i want to extend the style of every textbox with this validation trigger</p> <pre><code>&lt;Style TargetType="TextBox"&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="Validation.HasError" Value="true"&gt; &lt;Setter Property="Background" Value="#d3e1f3"&gt;&lt;/Setter&gt; &lt;Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>but this trigger does not work, because i forced the luna theme. (without the forced theme every thing works as it should, but doesn't look as it should :( ) is there some way to force the luna theme and extend it's style? probably over the BasedOn property?</p> <p>atm i defined a key for the style in question and added it to every textbox by hand, that works but isn't the prettiest way to go.</p> <p>tia</p>
[ { "answer_id": 324176, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 1, "selected": false, "text": "<Style x:Key=\"{x:Type TextBox}\" TargetType=\"{x:Type TextBox}\">\n" }, { "answer_id": 325322, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 1, "selected": false, "text": "<Style TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n" }, { "answer_id": 4662672, "author": "David", "author_id": 571800, "author_profile": "https://Stackoverflow.com/users/571800", "pm_score": 0, "selected": false, "text": "<Application.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;;component/Themes/luna.normalcolor.xaml\" />\n <ResourceDictionary Source=\"/RibbonControlsLibrary;component/Themes/Office2007Blue.xaml\"/> \n <ResourceDictionary Source=\"Styles.xaml\" />\n <ResourceDictionary Source=\"NavigationCommands.xaml\" />\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n</Application.Resources>\n" }, { "answer_id": 19809233, "author": "KadekM", "author_id": 872413, "author_profile": "https://Stackoverflow.com/users/872413", "pm_score": 0, "selected": false, "text": "<Style TargetType=\"TextBox\" BasedOn=\"{StaticResource {x:Type TextBox}}\">\n <Application.Resources>\n<ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"/RibbonControlsLibrary;component/Themes/Office2007Blue.xaml\"/>\n <ResourceDictionary Source=\"/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;;component/Themes/luna.normalcolor.xaml\" /> \n\n <ResourceDictionary Source=\"Styles.xaml\" />\n <ResourceDictionary Source=\"NavigationCommands.xaml\" />\n </ResourceDictionary.MergedDictionaries>\n</ResourceDictionary>\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12406/" ]
323,285
<p>I'm working with C and through a socket I will be receiving a message with one space in it, I need to split the string into parts at the space. How would I go about doing this?</p>
[ { "answer_id": 323290, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 5, "selected": true, "text": "strtok() strtok() strtok()" }, { "answer_id": 323305, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "strtok_r() char buffer[2048];\nchar *sp;\n\n/* read packet into buffer here, omitted */\n\n/* now find that space. */\nsp = strchr(buffer, ' ');\nif(sp != NULL)\n{\n /* 0-terminate the first part, by replacing the space with a '\\0'. */\n *sp++ = '\\0';\n /* at this point we have the first part in 'buffer', the second at 'sp'.\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
323,287
<p>Are there any guidelines/best practices for deciding what type of data should be stored in the database?</p> <p>For ex., is it ok to use database to store</p> <ol> <li>Application logs </li> <li>Configuration details (like server IP addresses etc.)</li> <li>System information (e.g., names of shell scripts, scheduling information for batch jobs, batch jobs status etc.)</li> </ol> <p>I have seen applications that use database for storing these. Is this acceptable? What are the pros and cons of such a design?</p>
[ { "answer_id": 553787, "author": "MattGrommes", "author_id": 3098, "author_profile": "https://Stackoverflow.com/users/3098", "pm_score": 0, "selected": false, "text": "app.properties config/" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24424/" ]
323,294
<p>I'm having a bit of a problem with converting the result of a MySQL query to a Java class when using SUM.</p> <p>When performing a simple SUM in MySQL</p> <pre><code>SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate'; </code></pre> <p>with <code>price</code> being an integer, it appears that the <code>SUM</code> sometimes returns a string and sometimes an integer, depending on the version of the JDBC driver.</p> <p>Apparently the server does tell the JDBC driver that the result of <code>SUM</code> is a string, and the JDBC driver sometimes 'conveniently' converts this to an integer. (see <a href="http://marc.info/?l=mysql-java&amp;m=116295785422117&amp;w=2" rel="nofollow noreferrer">Marc Matthews' explanation</a>).</p> <p>The Java code uses some <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/beans/BeanInfo.html" rel="nofollow noreferrer">BeanInfo</a> and <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/beans/Introspector.html" rel="nofollow noreferrer">Introspection</a> to automagically fill in a (list of) bean(s) with the result of a query. But this obviously can't work if the datatypes differ between servers where the application is deployed.</p> <p>I don't care wether I get a string or an integer, but I'd like to always have the same datatype, or at least know in advance which datatype I'll be getting. </p> <p>Is there some way to know which datatype will be returned by a MySQL <code>SUM</code> from within the Java code? Or does anyone know some better way to deal with this?</p>
[ { "answer_id": 323307, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "SELECT CAST(SUM(price) AS SIGNED) FROM cakes WHERE ingredient = 'marshmallows';\n" }, { "answer_id": 323410, "author": "gtRpr", "author_id": 41253, "author_profile": "https://Stackoverflow.com/users/41253", "pm_score": 2, "selected": false, "text": "ResultSet rs = statement.executeQuery(\"SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate'\");\nint sum = 0;\nif(rs.next())\nsize = Integer.parseInt(rs.getString(1));\n" }, { "answer_id": 1636739, "author": "Treffynnon", "author_id": 461813, "author_profile": "https://Stackoverflow.com/users/461813", "pm_score": -1, "selected": false, "text": "COALESCE(SUM(price),0)" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5822/" ]
323,314
<p>What is the best way to convert from Pascal Case (upper Camel Case) to a sentence.</p> <p>For example starting with</p> <pre><code>"AwaitingFeedback" </code></pre> <p>and converting that to</p> <pre><code>"Awaiting feedback" </code></pre> <p>C# preferable but I could convert it from Java or similar.</p>
[ { "answer_id": 323324, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 1, "selected": false, "text": "NewString = \"\";\nLoop through every char of the string (skip the first one)\n If char is upper-case ('A'-'Z')\n NewString = NewString + ' ' + lowercase(char)\n Else\n NewString = NewString + char\n" }, { "answer_id": 323329, "author": "Antoine", "author_id": 29568, "author_profile": "https://Stackoverflow.com/users/29568", "pm_score": 2, "selected": false, "text": " string spacedString = System.Text.RegularExpressions.Regex.Replace(yourString, \"\\B([A-Z])\", \" \\k\");\n spacedString = spacedString.ToLower();\n" }, { "answer_id": 323331, "author": "Sandeep Datta", "author_id": 39648, "author_profile": "https://Stackoverflow.com/users/39648", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace CamelCaseToString\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.WriteLine(CamelCaseToString(\"ThisIsYourMasterCallingYou\")); \n }\n\n private static string CamelCaseToString(string str)\n {\n if (str == null || str.Length == 0)\n return null;\n\n StringBuilder retVal = new StringBuilder(32);\n\n retVal.Append(char.ToUpper(str[0]));\n for (int i = 1; i < str.Length; i++ )\n {\n if (char.IsLower(str[i]))\n {\n retVal.Append(str[i]);\n }\n else\n {\n retVal.Append(\" \");\n retVal.Append(char.ToLower(str[i]));\n }\n }\n\n return retVal.ToString();\n }\n }\n}\n" }, { "answer_id": 323335, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "var camel = \"AwaitingFeedbackDearMaster\";\nvar sentence = camel.replace(/([A-Z].)/g, function (c) { return ' ' + c.toLowerCase(); });\nalert(sentence);\n String ToSentence(String camel)\n{\n if (camel == null) return \"\"; // Or null...\n String[] words = camel.split(\"(?=[A-Z])\");\n if (words == null) return \"\";\n if (words.length == 1) return words[0];\n StringBuilder sentence = new StringBuilder(camel.length());\n if (words[0].length() > 0) // Just in case of camelCase instead of CamelCase\n {\n sentence.append(words[0] + \" \" + words[1].toLowerCase());\n }\n else\n {\n sentence.append(words[1]);\n }\n for (int i = 2; i < words.length; i++)\n {\n sentence.append(\" \" + words[i].toLowerCase());\n }\n return sentence.toString();\n}\n\nSystem.out.println(ToSentence(\"AwaitingAFeedbackDearMaster\"));\nSystem.out.println(ToSentence(null));\nSystem.out.println(ToSentence(\"\"));\nSystem.out.println(ToSentence(\"A\"));\nSystem.out.println(ToSentence(\"Aaagh!\"));\nSystem.out.println(ToSentence(\"stackoverflow\"));\nSystem.out.println(ToSentence(\"disableGPS\"));\nSystem.out.println(ToSentence(\"Ahh89Boo\"));\nSystem.out.println(ToSentence(\"ABC\"));\n" }, { "answer_id": 323339, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 2, "selected": false, "text": "public static string CamelCaseToSentence(this string value)\n{\n var sb = new StringBuilder();\n var firstWord = true;\n\n foreach (var match in Regex.Matches(value, \"([A-Z][a-z]+)|[0-9]+\"))\n {\n if (firstWord)\n {\n sb.Append(match.ToString());\n firstWord = false;\n }\n else\n {\n sb.Append(\" \");\n sb.Append(match.ToString().ToLower());\n }\n }\n\n return sb.ToString();\n}\n" }, { "answer_id": 323362, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "string camel = \"MyCamelCaseString\";\nstring s = Regex.Replace(camel, \"([A-Z])\", \" $1\").ToLower().Trim();\nConsole.WriteLine(s.Substring(0,1).ToUpper() + s.Substring(1));\n \"^\\w\"\n \\U (i think)\n" }, { "answer_id": 323436, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 0, "selected": false, "text": "if (char.IsUpper(text[i])) \n newText.Append(' '); \nnewText.Append(text[i]);\n if (char.IsUpper(text[i])) \n{\n newText.Append(' '); \n newText.Append(char.ToLower(text[i]));\n}\nelse\n newText.Append(text[i]);\n" }, { "answer_id": 1211435, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "public static string ToSentenceCase(this string str)\n{\n return Regex.Replace(str, \"[a-z][A-Z]\", m => m.Value[0] + \" \" + char.ToLower(m.Value[1]));\n}\n public static string ToSentenceCase(this string str)\n{\n return Regex.Replace(str, \"[a-z][A-Z]\", m => $\"{m.Value[0]} {char.ToLower(m.Value[1])}\");\n}\n" }, { "answer_id": 1557647, "author": "Fraser", "author_id": 188761, "author_profile": "https://Stackoverflow.com/users/188761", "pm_score": 1, "selected": false, "text": "declare function content:sentenceCase($string)\n{\nlet $firstCharacter := substring($string, 1, 1)\nlet $remainingCharacters := substring-after($string, $firstCharacter)\nreturn\nconcat(upper-case($firstCharacter),lower-case(replace($remainingCharacters, '([A-Z])', ' $1')))\n};\n declare function content:titleCase($string)\n{\nlet $firstCharacter := substring($string, 1, 1)\nlet $remainingCharacters := substring-after($string, $firstCharacter)\nreturn\nconcat(upper-case($firstCharacter),replace($remainingCharacters, '([A-Z])', ' $1'))\n};\n" }, { "answer_id": 2926871, "author": "SSTA", "author_id": 352596, "author_profile": "https://Stackoverflow.com/users/352596", "pm_score": 4, "selected": false, "text": "Regex.Replace(strIn, \"([A-Z]{1,2}|[0-9]+)\", \" $1\").TrimStart()\n" }, { "answer_id": 10921428, "author": "Bryan Legend", "author_id": 52771, "author_profile": "https://Stackoverflow.com/users/52771", "pm_score": 4, "selected": false, "text": "Regex.Replace(\"ThisIsMyCapsDelimitedString\", \"(\\\\B[A-Z])\", \" $1\")\n" }, { "answer_id": 11432809, "author": "JefClaes", "author_id": 183229, "author_profile": "https://Stackoverflow.com/users/183229", "pm_score": 3, "selected": false, "text": "return Regex.Replace(input, \"([A-Z])\", \" $1\", RegexOptions.Compiled).Trim();\n" }, { "answer_id": 28520553, "author": "sscheider", "author_id": 1202146, "author_profile": "https://Stackoverflow.com/users/1202146", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n string piratese = \"avastTharMatey\";\n string ivyese = \"CheerioPipPip\";\n\n Console.WriteLine(\"{0}\\n{1}\\n\", piratese.CamelCaseToString(), ivyese.CamelCaseToString());\n Console.WriteLine(\"For Pete\\'s sake, man, hit ENTER!\");\n string strExit = Console.ReadLine();\n }\n\n }\n\n public static class StringExtension\n {\n public static string CamelCaseToString(this string str)\n {\n StringBuilder retVal = new StringBuilder(32);\n\n if (!string.IsNullOrEmpty(str))\n {\n string strTrimmed = str.Trim();\n\n if (!string.IsNullOrEmpty(strTrimmed))\n {\n retVal.Append(char.ToUpper(strTrimmed[0]));\n\n if (strTrimmed.Length > 1)\n {\n for (int i = 1; i < strTrimmed.Length; i++)\n {\n if (char.IsUpper(strTrimmed[i])) retVal.Append(\" \");\n\n retVal.Append(char.ToLower(strTrimmed[i]));\n }\n }\n }\n }\n return retVal.ToString();\n }\n }\n}\n" }, { "answer_id": 37501233, "author": "Banketeshvar Narayan", "author_id": 892214, "author_profile": "https://Stackoverflow.com/users/892214", "pm_score": 4, "selected": false, "text": "\"AwaitingFeedback\".Humanize() => Awaiting feedback\n \"PascalCaseInputStringIsTurnedIntoSentence\".Humanize() => \"Pascal case input string is turned into sentence\"\n\"Underscored_input_string_is_turned_into_sentence\".Humanize() => \"Underscored input string is turned into sentence\"\n\"Can_return_title_Case\".Humanize(LetterCasing.Title) => \"Can Return Title Case\"\n\"CanReturnLowerCase\".Humanize(LetterCasing.LowerCase) => \"can return lower case\"\n using Humanizer;\nusing static System.Console;\n\nnamespace HumanizerConsoleApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n WriteLine(\"AwaitingFeedback\".Humanize());\n WriteLine(\"PascalCaseInputStringIsTurnedIntoSentence\".Humanize());\n WriteLine(\"Underscored_input_string_is_turned_into_sentence\".Humanize());\n WriteLine(\"Can_return_title_Case\".Humanize(LetterCasing.Title));\n WriteLine(\"CanReturnLowerCase\".Humanize(LetterCasing.LowerCase));\n }\n }\n}\n" }, { "answer_id": 51310790, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 2, "selected": false, "text": "StringBuilder \"SomeBunchOfCamelCase2\".FromCamelCaseToSentence == \"Some Bunch Of Camel Case 2\"\n\npublic static string FromCamelCaseToSentence(this string input) {\n if(string.IsNullOrEmpty(input)) return input;\n\n var sb = new StringBuilder();\n // start with the first character -- consistent camelcase and pascal case\n sb.Append(char.ToUpper(input[0]));\n\n // march through the rest of it\n for(var i = 1; i < input.Length; i++) {\n // any time we hit an uppercase OR number, it's a new word\n if(char.IsUpper(input[i]) || char.IsDigit(input[i])) sb.Append(' ');\n // add regularly\n sb.Append(input[i]);\n }\n\n return sb.ToString();\n}\n" }, { "answer_id": 56728022, "author": "Ian Mercer", "author_id": 224370, "author_profile": "https://Stackoverflow.com/users/224370", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Add a space before any capitalized letter (but not for a run of capitals or numbers)\n /// </summary>\n internal static string FromCamelCaseToSentence(string input)\n {\n if (string.IsNullOrEmpty(input)) return String.Empty;\n\n var sb = new StringBuilder();\n bool upper = true;\n\n for (var i = 0; i < input.Length; i++)\n {\n bool isUpperOrDigit = char.IsUpper(input[i]) || char.IsDigit(input[i]);\n // any time we transition to upper or digits, it's a new word\n if (!upper && isUpperOrDigit)\n {\n sb.Append(' ');\n }\n sb.Append(input[i]);\n upper = isUpperOrDigit;\n }\n\n return sb.ToString();\n }\n [TestCase(null, ExpectedResult = \"\")]\n [TestCase(\"\", ExpectedResult = \"\")]\n [TestCase(\"ABC\", ExpectedResult = \"ABC\")]\n [TestCase(\"abc\", ExpectedResult = \"abc\")]\n [TestCase(\"camelCase\", ExpectedResult = \"camel Case\")]\n [TestCase(\"PascalCase\", ExpectedResult = \"Pascal Case\")]\n [TestCase(\"Pascal123\", ExpectedResult = \"Pascal 123\")]\n [TestCase(\"CustomerID\", ExpectedResult = \"Customer ID\")]\n [TestCase(\"CustomABC123\", ExpectedResult = \"Custom ABC123\")]\n public string CanSplitCamelCase(string input)\n {\n return FromCamelCaseToSentence(input);\n }\n" }, { "answer_id": 69802669, "author": "juanora", "author_id": 3375218, "author_profile": "https://Stackoverflow.com/users/3375218", "pm_score": 0, "selected": false, "text": "public static string PascalCaseToSentence(string input)\n {\n if (string.IsNullOrEmpty(input) || input.Length < 2)\n return input;\n\n var sb = new char[input.Length + ((input.Length + 1) / 2)];\n var len = 0;\n var lastIsLower = false;\n for (int i = 0; i < input.Length; i++)\n {\n var current = input[i];\n if (current < 97)\n {\n if (lastIsLower)\n {\n sb[len] = ' ';\n len++;\n }\n lastIsLower = false;\n }\n else\n {\n lastIsLower = true;\n }\n sb[len] = current;\n\n len++;\n }\n\n return new string(sb, 0, len);\n }\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6369/" ]
323,323
<p>Can someone tell me what Strong typing and weak typing means and which one is better?</p>
[ { "answer_id": 323472, "author": "JoeBloggs", "author_id": 34097, "author_profile": "https://Stackoverflow.com/users/34097", "pm_score": 6, "selected": false, "text": "$message = \"You are visitor number \".$count;\n $message = \"you are visitor number \".(string)$count;\n $message = \"you are visitor number \".strval($count);\n" }, { "answer_id": 28394605, "author": "miksiii", "author_id": 2923111, "author_profile": "https://Stackoverflow.com/users/2923111", "pm_score": 2, "selected": false, "text": "String foo = \"Hello, world!\";\nObject obj = foo;\n\nString bar = (String) obj;\nDate baz = (Date) obj; // This line will throw an error\n $a = 10;\n$b = \"a\";\n$c = $a . $b;\nprint $c; # returns 10a\n" }, { "answer_id": 34004885, "author": "mehmet", "author_id": 2863603, "author_profile": "https://Stackoverflow.com/users/2863603", "pm_score": 1, "selected": false, "text": "str = 5 + 'a' \n# would throw an error since it does not want to cast one type to the other implicitly.\n int a = 5;\na = 5 + 'c';\n/* is fine, because C treats 'c' as an integer in this case */\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30234/" ]
323,342
<p>I'd like to sort on a column in the result of a stored procedure without having to add the Order By clause in the stored procedure. I don't want the data to be sorted after I have executed the query, sorting should be part of the query if possible. I have the following code:</p> <pre><code>public static DataTable RunReport(ReportQuery query) { OffertaDataContext db = new OffertaDataContext(); Report report = (from r in db.Reports where r.Id == (int)query.ReportId select r).Single(); //???: check security clearance. DataSet dataSet = new DataSet(); /* doesn't work, I guess the "Result" table hasn't been created yet; if(!string.IsNullOrEmpty(query.SortField)) { dataSet.DefaultViewManager.DataViewSettings["Result"].Sort = query.SortField + " " + (query.SortAscending ? "ASC" : "DESC"); } */ using (SqlConnection conn = new SqlConnection(Config.ConnectionString)) { conn.Open(); using (SqlCommand exec = conn.CreateCommand()) { using (SqlDataAdapter adapter = new SqlDataAdapter()) { exec.Connection = conn; exec.CommandType = CommandType.StoredProcedure; exec.CommandText = report.ReportProc; adapter.SelectCommand = exec; try { adapter.Fill(dataSet, query.Skip, query.Take, "Result"); } catch (Exception e) { throw e; } finally { conn.Close(); } return dataSet.Tables["Result"]; } } } } </code></pre> <p>How do I add sorting? </p>
[ { "answer_id": 323374, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "var qry = from row in ctx.SomeMethod(args)\n order by row.Name, row.Key\n select row;\n SELECT blah FROM theudf(args) ORDER BY blah\n Skip() Take()" }, { "answer_id": 323377, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 3, "selected": true, "text": "myTable.DefaultView.Sort = \"myColumn DESC\";\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40939/" ]
323,363
<pre><code>&gt;rails -v Rails 1.2.6 &gt;ruby -v ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] </code></pre> <p>When I run a test fixture (that tests a rails model class) like this, it takes 20-30 secs to start executing these tests (show the "Loaded suite..."). What gives?</p> <pre><code>&gt;ruby test\unit\category_test.rb require File.dirname(__FILE__) + '/../test_helper' class CategoryTest &lt; Test::Unit::TestCase def setup Category.delete_all end def test_create obCategoryEntry = Category.new({:name=&gt;'Apparel'}) assert obCategoryEntry.save, obCategoryEntry.errors.full_messages.join(', ') assert_equal 1, Category.count assert_not_nil Category.find(:all, :conditions=&gt;"name='Apparel'") end #.. 1 more test here end </code></pre> <p>This one is Rails using a MySql DB with no fixtures. This time it clocked 30secs+ to startup. </p>
[ { "answer_id": 323442, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "(11:39) ~/tmp $ cat test_unit.rb \nrequire 'test/unit'\nclass MyTest < Test::Unit::TestCase\n def test_test\n assert_equal(\"this\", \"that\")\n end\nend\n\n(11:39) ~/tmp $ time ruby test_unit.rb \nLoaded suite test_unit\nStarted\nF\nFinished in 0.007338 seconds.\n\n 1) Failure:\ntest_test(MyTest) [test_unit.rb:4]:\n<\"this\"> expected but was\n<\"that\">.\n\n1 tests, 1 assertions, 1 failures, 0 errors\n\nreal 0m0.041s\nuser 0m0.027s\nsys 0m0.012s\n" }, { "answer_id": 323840, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 0, "selected": false, "text": "self.use_instantiated_fixtures = true\n" }, { "answer_id": 324357, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 0, "selected": false, "text": "require 'socket'\nSocket.do_not_reverse_lookup = true\n require" }, { "answer_id": 368738, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 1, "selected": false, "text": "ruby -v require require require" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
323,367
<p>I'm trying to make a BEA Portal website XHTML compliant, because this has been written in the contract with the client, and I'm stuck on this problem: BEA renders <code>&lt;meta&gt;</code> and <code>&lt;link&gt;</code> tags without the closing slash, i.e. <code>&lt;link/&gt;</code> and <code>&lt;meta/&gt;</code> as it is required by XHTML.</p> <p>When I look at the documentation from BEA it seems that it should be possible to make it render the tags with a closing slash: <a href="http://edocs.bea.com/wlp/docs81/lookandfeel/lookandfeel.html#999045" rel="nofollow noreferrer">The skin.properties file (edocs.bea.com)</a>.</p> <p>Is it possible to change the redering with a configuration directive? Or perhaps, to hook into the underlying redering method so that I can fix it?</p>
[ { "answer_id": 323442, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "(11:39) ~/tmp $ cat test_unit.rb \nrequire 'test/unit'\nclass MyTest < Test::Unit::TestCase\n def test_test\n assert_equal(\"this\", \"that\")\n end\nend\n\n(11:39) ~/tmp $ time ruby test_unit.rb \nLoaded suite test_unit\nStarted\nF\nFinished in 0.007338 seconds.\n\n 1) Failure:\ntest_test(MyTest) [test_unit.rb:4]:\n<\"this\"> expected but was\n<\"that\">.\n\n1 tests, 1 assertions, 1 failures, 0 errors\n\nreal 0m0.041s\nuser 0m0.027s\nsys 0m0.012s\n" }, { "answer_id": 323840, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 0, "selected": false, "text": "self.use_instantiated_fixtures = true\n" }, { "answer_id": 324357, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 0, "selected": false, "text": "require 'socket'\nSocket.do_not_reverse_lookup = true\n require" }, { "answer_id": 368738, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 1, "selected": false, "text": "ruby -v require require require" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37147/" ]
323,371
<p>A friend of mine asked me today if there is any open-source or commercially available Webmail/Email "engine". When I asked her what she meant by engine, I got a list of features her boss asked for - </p> <ul> <li>Web interface to login &amp; access e-mails</li> <li>Ability to send/receive/forward e-mails using the web interface </li> <li>Ability to compose and save drafts using the web interface</li> <li>Ability to delete emails, empty deleted items folder using the web interface</li> <li>Ability to search e-mails (by Sender's e-mail, Subject, Content)</li> <li>Maintain and manage a contacts list (of e-mail addresses) using the web interface</li> <li>Allow users to synchronise their e-mails with iPhone/Windows Mobile smartphones</li> </ul> <p>I found <a href="http://anmar.eu.org/projects/sharpwebmail/" rel="nofollow noreferrer">SharpWebMail</a> to have some of the features, although it has not had updates in recent times, last update was in April 2006. I am inclined towards using ASP.NET, the proposal is to primarily use the e-mail in conjunction with an intranet (developed in ASP.NET). If you have any suggestions, please let me know.</p> <p>indy</p>
[ { "answer_id": 323442, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "(11:39) ~/tmp $ cat test_unit.rb \nrequire 'test/unit'\nclass MyTest < Test::Unit::TestCase\n def test_test\n assert_equal(\"this\", \"that\")\n end\nend\n\n(11:39) ~/tmp $ time ruby test_unit.rb \nLoaded suite test_unit\nStarted\nF\nFinished in 0.007338 seconds.\n\n 1) Failure:\ntest_test(MyTest) [test_unit.rb:4]:\n<\"this\"> expected but was\n<\"that\">.\n\n1 tests, 1 assertions, 1 failures, 0 errors\n\nreal 0m0.041s\nuser 0m0.027s\nsys 0m0.012s\n" }, { "answer_id": 323840, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 0, "selected": false, "text": "self.use_instantiated_fixtures = true\n" }, { "answer_id": 324357, "author": "Aaron Hinni", "author_id": 12086, "author_profile": "https://Stackoverflow.com/users/12086", "pm_score": 0, "selected": false, "text": "require 'socket'\nSocket.do_not_reverse_lookup = true\n require" }, { "answer_id": 368738, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 1, "selected": false, "text": "ruby -v require require require" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32649/" ]
323,397
<p>Part of my application maps resources stored in a number of locations onto web URLs like this:</p> <pre><code>http://servername/files/path/to/my/resource/ </code></pre> <p>The resources location is modelled after file paths and as a result there can be an unlimited level of nesting. Is it possible to construct an MVC route that matches this so that I get the path in its entirety passed into my controller? Either as a single string or possibly as an params style array of strings.</p> <p>I guess this requires a match on the files keyword, followed by some sort of wildcard. Though I have no idea if MVC supports this. </p>
[ { "answer_id": 323460, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 6, "selected": true, "text": "\"Files/{*path}\"\n * \"Files/\"" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28882/" ]
323,403
<p>Is there a way to mount a folder on the hard disk as a device in Finder. The intend here is to provide the user with an easy way to get to a folder that my application uses to store data. I don't want my user to go searching for data in Application Data. I would rather allow them to make this data available as a mounted volume or device in Finder. I would also like this volume or device to be read/write, so that if the user makes any changes to the data files, the changes will get reflected in the original folder.</p> <p>Is there a way to do this in cocoa, carbon or applescript.</p>
[ { "answer_id": 323663, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "~/Documents/ ln -s '~/Application Data/Yourapp' '~/Desktop/Yourapp Data'\n" }, { "answer_id": 32356645, "author": "Kiko Albiol Colomer", "author_id": 5190397, "author_profile": "https://Stackoverflow.com/users/5190397", "pm_score": 0, "selected": false, "text": " NSURL *path=[NSURL URLWithString:@\"smb://server.resource/KEYS_DB\"];\n if(NO==[self isMountedPath:[path absoluteString]])\n {\n NSWorkspace *ws=[NSWorkspace sharedWorkspace];\n [ws openURL:path];\n }\n -(BOOL)isMountedPath:(NSString *)share\n{\n NSArray * keys = @[NSURLVolumeURLForRemountingKey];\n NSArray * mountPaths = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:keys options:0];\n\n NSError * error;\n NSURL * remount;\n\n for (NSURL * mountPath in mountPaths) {\n [mountPath getResourceValue:&remount forKey:NSURLVolumeURLForRemountingKey error:&error];\n if(remount){\n if ([[[NSURL URLWithString:share] host] isEqualToString:[remount host]] && [[[NSURL URLWithString:share] path] isEqualToString:[remount path]])\n {\n printf(\"Already mounted at %s\\n\", [[mountPath path] UTF8String]);\n return YES;\n }\n }\n }\n return NO;\n}\n -(NSString *)mountedPath:(NSString *)share\n{\n NSArray * keys = @[NSURLVolumeURLForRemountingKey];\n NSArray * mountPaths = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:keys options:0];\n\n NSError * error;\n NSURL * remount;\n\n for (NSURL * mountPath in mountPaths) {\n [mountPath getResourceValue:&remount forKey:NSURLVolumeURLForRemountingKey error:&error];\n if(remount){\n if ([[[NSURL URLWithString:share] host] isEqualToString:[remount host]] && [[[NSURL URLWithString:share] path] isEqualToString:[remount path]])\n {\n printf(\"Already mounted at %s\\n\", [[mountPath path] UTF8String]);\n return [mountPath path];\n }\n }\n }\n return nil;\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,405
<p>I try to migrate a Windows SVN Server to Linux.<br> I have configured Apache to validate against AD for Useraccess so only AD Users can logon.<br> Now i have to set permissions for repositories with authz files.<br> When i set permission with AD username it works, but AD groups it doesn't.</p> <p>The authz file looks like the following:</p> <pre><code>[test:/] user1=rw #That works [test2:/] @usergroup=rw #No access for the groupmembers </code></pre> <p>When I create groups inside the authz file and asign AD users, that internal group works fine, but i can't administer groups in 2 locations, there just to much changes made every day.</p> <p>Has anyone an idea, how to use AD groups inside authz files?</p>
[ { "answer_id": 323431, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 2, "selected": false, "text": "[groups]\nusergroup = user1, user2, user3\n\n[test:/]\nuser1 = rw\n\n[test2:/]\nusergroup = rw\n" }, { "answer_id": 13512129, "author": "Johan Sörell", "author_id": 769035, "author_profile": "https://Stackoverflow.com/users/769035", "pm_score": 2, "selected": false, "text": " python ./sync_ldap_groups_to_svn_authz.py \\\n-d \"CN=access-TO-AD-user,OU=Users,OU=SiteName,OU=Europe,OU=St,DC=domainname,DC=com\" \\\n -l \"ldap://adserver.domainname.com:389\" \\ \n-b \"OU=Groups,OU=SiiteName,OU=Europe,OU=St,DC=domainname,DC=com\" \\\n-u \"objectClass=person\" -g \"(&(objectClass=group)(cn=UniqueStringBeforSVN*))\" \\ \n-i \"sAMAccountName\" > ldaptest.txt\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,407
<p>How does the C/C++ compiler manipulate the escape character ["\"] in source code? How is compiler grammar written for processing that character? What does the compiler do after encountering that character?</p>
[ { "answer_id": 323454, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 1, "selected": false, "text": "\\n" }, { "answer_id": 323486, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "\\a \\n \\xNUM" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38038/" ]
323,413
<p>I have an app that needs to handle very large strings between a SQL Server database and .NET code. I have a LINQ query that generates the strings when saving them <i>to</i> the database, but when trying to create the strings <i>from</i> the database, the app crashes with an OutOfMemoryException because of the size of the strings.</p> <p>Do I have to do something to make the LINQ generated code avoid that? Using some kind of compression might be an option, but would like to avoid that for performance reasons.</p>
[ { "answer_id": 323425, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "ExecuteReader() IDataReader using (var reader = cmd.ExecuteReader(\n CommandBehavior.SequentialAccess)) {\n char[] buffer = new char[8040]; // or some multiple (sql server page size)\n while (reader.Read()) {\n long dataOffset = 0, read;\n while((read = reader.GetChars(colIndex, dataOffset, buffer, 0, buffer.Length)) > 0) {\n // process \"read\"-many chars from \"buffer\"\n dataOffset += read;\n }\n }\n }\n XmlReader cmd.ExecuteXmlReader() IDataReader ctx.GetCommand() ExecuteReader ExecuteXmlReader" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41304/" ]
323,419
<p>Do you know a simple script to count NLOCs (netto lines of code). The script should count lines of C Code. It should not count empty lines or lines with just braces. But it doesn't need to be overly exact either.</p>
[ { "answer_id": 323531, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "perl -pe \"s/^\\s*[{}]?\\s*\\n//\" Dialog.java | wc -l\n perl -pe \"s#^\\s*[{}]?\\s*\\n|^\\s*//.*\\n##\" Dialog.java | wc -l\n perl -pe \"s#^\\s*(?:[{}]?\\s*|//.*)\\n##\" Dialog.java | wc -l\n perl -e \"$x = join('', <>); $x =~ s#/\\*.*?\\*/##gs; print $x\" Dialog.java | perl -pe \"s#^\\s*(?:[{}]?\\s*|//.*)\\n##\" | wc -l\n" }, { "answer_id": 324732, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "scc Black JL: co -q -p scc.c | scc | sed '/^[ ]*$/d' | wc -l\n 208\nBlack JL: co -q -p scc.c | scc | sed '/^[ {}]*$/d' | wc -l\n 144\nBlack JL: co -p -q scc.c | wc -l\n 271\nBlack JL:\n scc cpp -fpreprocessed -P file SCC has been trained to handle 'q' single quotes in most of\nthe aberrant forms that can be used. '\\0', '\\', '\\'', '\\\\\nn' (a valid variant on '\\n'), because the backslash followed\nby newline is elided by the token scanning code in CPP before\nany other processing occurs.\n SCC has been trained to handle 'q' single quotes in most of\n<stdin>:2:56: warning: missing terminating ' character\nthe aberrant forms that can be used. '\\0', '\\', '\\'', '\\\\\n<stdin>:3:27: warning: missing terminating ' character\nn' (a valid variant on '\\n'), because the backslash followed\nby newline is elided by the token scanning code in CPP before\nany other processing occurs.\n cpp -fpreprocessed -P -P #line" }, { "answer_id": 365685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " # Increment file count.<br>\nset $fileCount = $fileCount+1<br>\n\n# Collect the content of $file in $content<br>\nvar str content # Content of one file at a time<br>\nrepro $file >$content<br>\n\n# Get count and non-blank count.<br>\nset $c={len -e $content}<br>\nset $nb={len $content}<br>\n\necho -e \"File: \" $file \", Total Count: \" $c \", Non-blank Count: \" $nb<br>\n\n# Update total counts.<br>\nset $totalc = $totalc + $c<br>\nset $totalnb = $totalnb + $nb<br>\n" }, { "answer_id": 365722, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 1, "selected": false, "text": "grep -x -v \"[[:space:]}{]*\" files.c | wc\n" }, { "answer_id": 365749, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 1, "selected": false, "text": "grep -vc '^$' (my files)\n" }, { "answer_id": 365787, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "find . -name \\*.cpp -o -name \\*.h | xargs -n1 cpp -fpreprocessed -P | \n awk '!/^[{[:space:]}]*$/' | wc -l\n find . -name \\*.cpp -o -name \\*.h | xargs awk '!/^[{[:space:]}]*$/' | wc -l\n" }, { "answer_id": 365856, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl -w\n# eLOC - Effective Lines of Code Counter\n# JFS (2005)\n#\n# $ perl eLOC.pl --help\n#\nuse strict;\nuse warnings;\nuse sigtrap;\nuse diagnostics;\n\nuse warnings::register;\nno warnings __PACKAGE__;\nsub DEBUG { 0 }\n\nuse English qw( -no_match_vars ) ; # Avoids regex performance penalty\nuse Getopt::Long qw(:config gnu_getopt);\nuse File::DosGlob 'glob';\nuse Pod::Usage;\n\n\nour $VERSION = '0.01';\n\n# globals\nuse constant NOTFILENAME => undef;\nmy %counter = ( \n 'PHYS' => 0, \n 'ELOC' => 0, \n 'PURE_COMMENT' => 0,\n 'BLANK' => 0,\n 'LLOC' => 0,\n 'INLINE_COMMENT'=> 0,\n 'LOC' => 0,\n);\nmy %header = (\n \"eloc\" => \"eloc\",\n \"lloc\" => \"lloc\",\n \"loc\" => \"loc\",\n \"comment\" => \"comment\",\n \"blank\" => \"blank\",\n \"newline\" => \"newline\",\n \"logicline\" => \"lgcline\",\n);\nmy %total = %counter; # copy\nmy $c = \\%counter; # see format below\nmy $h = \\%header; # see top format below\nmy $inside_multiline_comment = 0;\nmy $filename = NOTFILENAME;\nmy $filecount = 0;\nmy $filename_header = \"file name\";\n\n# process input args\nmy $version = '';\nmy $help = '';\nmy $man = '';\nmy $is_deterministic = '';\nmy $has_header = '';\n\nprint STDERR \"Input args:'\" if DEBUG;\nprint STDERR (join(\"|\",@ARGV),\"'\\n\") if DEBUG;\n\nmy %option = ('version' => \\$version,\n 'help' => \\$help, \n 'man' => \\$man,\n 'deterministic' => \\$is_deterministic,\n 'header' => \\$has_header\n);\nGetOptions( \\%option, 'version', 'help', 'man',\n 'eloc|e', # print the eLOC counts\n 'lloc|s', # print the lLOC counts (code statements)\n 'loc|l' , # print the LOC counts (eLOC + lines of a single brace or parenthesis)\n 'comment|c' , # print the comments counts (count lines which contains a comment)\n 'blank|b' , # print the blank counts\n 'newline|n' , # print the newline count\n 'logicline|g' , # print the logical line count (= LOC + Comment Lines + Blank Lines) \n 'deterministic', # print the LOC determination for every line in the source file\n 'header', # print header line\n) or invalid_options(\"$0: invalid options\\nTry `$0 --help' for more information.\");\n\nversion() if $version;\npod2usage(-exitstatus => 0, -verbose => 1) if $help ;\npod2usage(-exitstatus => 0, -verbose => 2) if $man;\n\n#\n$has_header = 1 if $is_deterministic && $has_header eq '';\n\n#format for print_loc_metric()\nmy ($format, $format_top) = make_format(); \nprint STDERR \"format:\\n\" if DEBUG > 10;\nprint STDERR $format if DEBUG > 10;\neval $format;\ndie $@ if $@; # $EVAL_ERROR\n\nif(DEBUG>10) {\n print STDERR (\"format_top:\\n\", $format_top);\n}\nif( $has_header) {\n eval $format_top;\n die $@ if $@; # $EVAL_ERROR \n}\n\n# process files\nprint STDERR (\"Input args after Getopts():\\n\",\n join(\"|\",@ARGV),\"\\n\") if DEBUG > 10;\n\nexpand_wildcards();\n@ARGV = '-' unless @ARGV;\nforeach my $fn (@ARGV) {\n $filename = $fn;\n unless (open(IN, \"<$filename\")) {\n warn \"$0: Unable to read from '$filename': $!\\n\";\n next;\n }\n print STDERR \"Scanning $filename...\\n\" if DEBUG;\n\n clear_counters();\n generate_loc_metric(); \n\n $filecount++;\n\n print_loc_metric(); \n\n close(IN)\n or warn \"$0: Could not close $filename: $!\\n\"; \n}\n\n# print total\nif($filecount > 1) {\n $filename = \"total\";\n $c = \\%total;\n print_loc_metric();\n}\nexit 0;\n\n#-------------------------------------------------\nsub wsglob {\n my @list = glob;\n @list ? @list : @_; #HACK: defence from emtpy list from glob()\n}\nsub expand_wildcards {\n print STDERR (\"Input args before expand_wildcards():\\n\",\n join(\"|\",@ARGV),\"\\n\") if DEBUG;\n\n { \n @ARGV = map( /['*?']/o ? wsglob($_) : $_ , @ARGV);\n } \n print STDERR (\"Input args after expand_wildcards():\\n\",\n join(\"|\",@ARGV),\"\\n\") if DEBUG; \n}\nsub clear_counters {\n for my $name ( keys %counter) {\n $counter{$name} = 0;\n } \n}\nsub make_format {\n my $f = 'format STDOUT =' . \"\\n\";\n $f .= '# LOC, eLOC, lLOC, comment, blank, newline, logicline and filename' . \"\\n\";\n my $f_top = 'format STDOUT_TOP =' . \"\\n\"; \n my $console_screen_width = (get_terminal_size())[0];\n print STDERR '$console_screen_width=' . $console_screen_width .\"\\n\" if DEBUG>10;\n $console_screen_width = 100 if $console_screen_width < 0;\n my $is_print_specifiers_set = \n ($option{\"eloc\"} or\n $option{\"lloc\"} or\n $option{\"loc\"} or\n $option{\"comment\"} or\n $option{\"blank\"} or\n $option{\"newline\"} or\n $option{\"logicline\"});\n\n my %o = %option;\n my $fc = 0;\n if( $is_print_specifiers_set ) {\n\n $fc++ if $o{\"eloc\"};\n $fc++ if $o{\"lloc\"};\n $fc++ if $o{\"loc\"};\n $fc++ if $o{\"comment\"};\n $fc++ if $o{\"blank\"};\n $fc++ if $o{\"newline\"};\n $fc++ if $o{\"logicline\"};\n if( $fc == 0 ) { die \"$0: assertion failed: field count is zero\" }\n }\n else {\n # default\n $fc = 7;\n $o{\"loc\"} = 1; \n $o{\"eloc\"} = 1; \n $o{\"lloc\"} = 1; \n $o{\"comment\"} = 1; \n $o{\"blank\"} = 1; \n $o{\"newline\"} = 1; \n $o{\"logicline\"} = 1; \n }\n if (DEBUG > 10) {\n while( (my ($name, $value) = each %{o}) ) {\n print STDERR \"name=$name, value=$value\\n\";\n } \n }\n\n\n # picture line \n my $field_format = '@>>>>>> ';\n my $field_width = length $field_format;\n my $picture_line = $field_format x $fc; \n # place for filename\n $picture_line .= '^'; \n $picture_line .= '<' x ($console_screen_width - $field_width * $fc - 2);\n $picture_line .= \"\\n\"; \n $f .= $picture_line;\n $f_top .= $picture_line;\n # argument line\n $f .= '$$c{\"LOC\"}, ' ,$f_top .= '$$h{\"loc\"}, ' if $o{\"loc\"};\n $f .= '$$c{\"ELOC\"}, ' ,$f_top .= '$$h{\"eloc\"}, ' if $o{\"eloc\"}; \n $f .= '$$c{\"LLOC\"}, ' ,$f_top .= '$$h{\"lloc\"}, ' if $o{\"lloc\"};\n $f .= '$$c{\"comment\"}, ' ,$f_top .= '$$h{\"comment\"}, ' if $o{\"comment\"};\n $f .= '$$c{\"BLANK\"}, ' ,$f_top .= '$$h{\"blank\"}, ' if $o{\"blank\"};\n $f .= '$$c{\"PHYS\"}, ' ,$f_top .= '$$h{\"newline\"}, ' if $o{\"newline\"};\n $f .= '$$c{\"logicline\"}, ',$f_top .= '$$h{\"logicline\"}, ' if $o{\"logicline\"};\n $f .= '$filename' . \"\\n\";\n $f_top .= '$filename_header' . \"\\n\"; \n\n # 2nd argument line for long file names\n $f .= '^'; \n $f .= '<' x ($console_screen_width-2);\n $f .= '~~' . \"\\n\"\n .' $filename' . \"\\n\";\n $f .='.' . \"\\n\";\n $f_top .='.' . \"\\n\";\n return ($f, $f_top);\n}\nsub generate_loc_metric {\n my $is_concatinated = 0;\n LINE: while(<IN>)\n {\n chomp; \n print if $is_deterministic && !$is_concatinated; \n\n # handle multiline code statements\n if ($is_concatinated = s/\\\\$//) {\n warnings::warnif(\"$0: '\\\\'-ending line concantinated\");\n increment('PHYS');\n print \"\\n\" if $is_deterministic;\n my $line = <IN>;\n $_ .= $line;\n chomp($line);\n print $line if $is_deterministic;\n redo unless eof(IN); \n } \n\n # blank lines, including inside comments, don't move to next line here\n increment('BLANK') if( /^\\s*$/ ); \n\n # check whether multiline comments finished\n if( $inside_multiline_comment && m~\\*/\\s*(\\S*)\\s*$~ ) {\n $inside_multiline_comment = 0;\n # check the rest of the line if it contains non-whitespace characters\n #debug $_ = $REDO_LINE . $1, redo LINE if($1);\n warnings::warnif(\"$0: expression '$1' after '*/' discarded\") if($1);\n # else mark as pure comment\n increment('PURE_COMMENT');\n next LINE;\n }\n # inside multiline comments\n increment('PURE_COMMENT'), next LINE if( $inside_multiline_comment );\n\n # C++ style comment at the begining of line (except whitespaces)\n increment('PURE_COMMENT'), next LINE if( m~^\\s*//~ ); \n\n # C style comment at the begining of line (except whitespaces)\n if ( m~^\\s*/\\*~ ) {\n $inside_multiline_comment = 1 unless( m~\\*/~ );\n increment('PURE_COMMENT'), next LINE;\n }\n # inline comment, don't move to next line here\n increment('INLINE_COMMENT') if ( is_inline_comment($_) );\n\n # lLOC implicitly incremented inside is_inline_comment($)\n\n #\n increment('LOC') unless( /^\\s*$/ );\n\n # standalone braces or parenthesis \n next LINE if( /^\\s*(?:\\{|\\}|\\(|\\))+\\s*$/ ); \n\n # eLOC is not comments, blanks or standalone braces or parenthesis\n # therefore just increment eLOC counter here\n increment('ELOC'), next LINE unless( /^\\s*$/ );\n }\n continue {\n increment('PHYS');\n print \" [$.]\\n\" if $is_deterministic; # $INPUT_LINE_NUMBER\n }\n}\n\nsub print_loc_metric {\n $$c{'comment'} = $$c{'PURE_COMMENT'} + $$c{'INLINE_COMMENT'}; \n # LOC + Comment Lines + Blank Lines \n $$c{'logicline'} = $$c{'LOC'} + $$c{'comment'} + $$c{'BLANK'};\n unless (defined $filename) { \n die \"print_loc_metric(): filename is not defined\";\n } \n\n my $fn = $filename;\n $filename = \"\", $filename_header = \"\" \n unless($#ARGV);\n print STDERR (\"ARGV in print_loc_metric:\" , join('|',@ARGV), \"\\n\") \n if DEBUG;\n write STDOUT; # replace with printf\n $filename = $fn;\n}\nsub increment {\n my $loc_type = shift;\n defined $loc_type\n or die 'increment(\\$): input argument is undefined'; \n\n $counter{$loc_type}++;\n $total{$loc_type}++;\n print \"\\t#\". $loc_type .\"#\" if $is_deterministic; \n}\n\nsub is_inline_comment {\n my $line = shift;\n defined $line \n or die 'is_inline_comment($): $line is not defined';\n\n print \"\\n$line\" if DEBUG > 10; \n\n# here: line is not empty, not begining both C and C++ comments signs,\n# not standalone '{}()', not inside multiline comment,\n# ending '\\' removed (joined line created if needed)\n\n# Possible cases: \n# - no C\\C++ comment signs => is_inline_comment = 0\n# - C++ comment (no C comment sign)\n# * no quote characters => is_inline_comment = 1\n# * at least one comment sign is not quoted => is_inline_comment = 1\n# * all comment signs are quoted => is_inline_comment = 0\n# - C comment (no C++ comment sign)\n# * no quote characters => is_inline_comment = 1,\n# ~ odd number of '/*' and '*/' => $inside_multiple_comment = 1 \n# ~ even number => $inside_multiple_comment = 0\n# * etc...\n# - ...\n# algorithm: move along the line from left to right\n# rule: quoted comments are not counted\n# rule: quoted by distinct style quotes are not counted\n# rule: commented quotes are not counted\n# rule: commented distinct style comments are not counted\n# rule: increment('LLOC') if not-quoted, not-commented\n# semi-colon presents in the line except that two \n# semi-colon in for() counted as one.\n\n# \n$_ = $line; #hack: $_ = $line inside sub\n# state\nmy %s = (\n 'c' => 0, # c slash star - inside c style comments\n 'cpp' => 0, # c++ slash slash - inside C++ style comment\n 'qm' => 0, # quoted mark - inside quoted string\n 'qqm' => 0, # double quoted - inside double quoted string\n);\nmy $has_comment = 0;\n# find state\nLOOP:\n {\n /\\G\\\"/gc && do { # match double quote\n unless( $s{'qm'} || $s{'c'} || $s{'cpp'} ) {\n # toggle \n $s{'qqm'} = $s{'qqm'} ? 0 : 1; \n }\n redo LOOP;\n };\n /\\G\\'/gc && do { # match single quote\n unless( $s{'qqm'} || $s{'c'} || $s{'cpp'} ) {\n # toggle \n $s{'qm'} = $s{'qm'} ? 0 : 1; \n }\n redo LOOP;\n };\n m~\\G//~gc && do { # match C++ comment sign\n unless( $s{'qm'} || $s{'qqm'} || $s{'c'} ) {\n # on\n $has_comment = 1;\n $s{'cpp'} = 1; \n } \n redo LOOP;\n };\n m~\\G/\\*~gc && do { # match begining C comment sign\n unless( $s{'qm'} || $s{'qqm'} || $s{'cpp'} ) {\n # on\n $has_comment = 1;\n $s{'c'} = $s{'c'} ? 1 : 1; \n } \n redo LOOP;\n };\n m~\\G\\*/~gc && do { # match ending C comment sign\n unless( $s{'qm'} || $s{'qqm'} || $s{'cpp'} ) {\n # off \n if( $s{'c'} ) { \n $s{'c'} = 0;\n }\n else {\n die 'is_inline_comment($): unexpected c style ending comment sign'.\n \"\\n'$line'\";\n }\n } \n redo LOOP;\n };\n /\\Gfor\\s*\\(.*\\;.*\\;.*\\)/gc && do { # match for loop\n unless( $s{'qm'} || $s{'qqm'} || $s{'cpp'} || $s{'c'} ) {\n # not-commented, not-quoted semi-colon \n increment('LLOC');\n }\n redo LOOP;\n }; \n /\\G\\;/gc && do { # match semi-colon\n unless( $s{'qm'} || $s{'qqm'} || $s{'cpp'} || $s{'c'} ) {\n # not-commented, not-quoted semi-colon\n # not inside for() loop\n increment('LLOC');\n }\n redo LOOP;\n }; \n /\\G./gc && do { # match any other character\n # skip 1 character\n redo LOOP;\n };\n /\\G$/gc && do { # match end of the line\n last LOOP;\n }; \n #default\n die 'is_inline_comment($): unexpected character in the line:' .\n \"\\n'$line'\";\n }\n# apply state\n $inside_multiline_comment = $s{'c'};\n return $has_comment;\n}\n\nsub version {\n# TODO: version implementation\n print <<\"VERSION\";\nNAME v$VERSION\nWritten by AUTHOR\n\nCOPYRIGHT AND LICENSE\nVERSION\n\nexit 0;\n}\n\nsub invalid_options {\n print STDERR (@_ ,\"\\n\");\n exit 2;\n}\n\nsub get_terminal_size {\n my ($wchar, $hchar) = ( -1, -1); \n my $win32console = <<'WIN32_CONSOLE'; \n use Win32::Console; \n my $CONSOLE = new Win32::Console(); \n ($wchar, $hchar) = $CONSOLE->MaxWindow();\nWIN32_CONSOLE\n\n eval($win32console); \n return ($wchar, $hchar) unless( $@ );\n warnings::warnif($@); # $EVAL_ERROR\n\n my $term_readkey = <<'TERM_READKEY';\n use Term::ReadKey; \n ($wchar,$hchar, $wpixels, $hpixels) = GetTerminalSize(); \nTERM_READKEY\n\n eval($term_readkey); \n return ($wchar, $hchar) unless( $@ );\n\n warnings::warnif($@); # $EVAL_ERROR \n my $ioctl = <<'IOCTL'; \n require 'sys/ioctl.ph'; \n die \"no TIOCGWINSZ \" unless defined &TIOCGWINSZ; \n open(TTY, \"+</dev/tty\") \n or die \"No tty: $!\"; \n unless (ioctl(TTY, &TIOCGWINSZ, $winsize='')) { \n die sprintf \"$0: ioctl TIOCGWINSZ (%08x: $!)\\n\", \n &TIOCGWINSZ; \n } \n ($hchar, $wchar, $xpixel, $ypixel) = \n unpack('S4', $winsize); # probably $hchar & $wchar should be swapped here \nIOCTL\n\n eval($ioctl); \n warnings::warnif($@) if $@ ; # $EVAL_ERROR \n\n return ($wchar, $hchar); \n}\n\n1;\n__END__ \n\n=head1 NAME\n\neLOC - Effective Lines of Code Counter\n\n=head1 SYNOPSIS\n\nB<eloc> B<[>OPTIONB<]...> B<[>FILEB<]...>\n\nPrint LOC, eLOC, lLOC, comment, blank, newline and logicline counts \nfor each FILE, and a total line if more than one FILE is specified.\nSee L</\"LOC Specification\"> for more info, use `eloc --man'.\n\n -e, --eloc print the {E}LOC counts\n -s, --lloc print the lLOC counts (code {S}tatements)\n -l, --loc print the {L}OC counts (eLOC + lines of a single brace or parenthesis)\n -c, --comment print the {C}omments counts (count lines which contains a comment)\n -b, --blank print the {B}lank counts\n -n, --newline print the {N}ewline count\n -g, --logicline print the lo{G}ical line count (= LOC + Comment Lines + Blank Lines)\n --deterministic print the LOC determination for every line in the source file\n --header print header line\n --help display this help and exit\n --man display full help and exit\n --version output version information and exit\n\nWith no FILE, or when FILE is -, read standard input. \n\nMetrics counted by the program are based on narration from \nhttp://msquaredtechnologies.com/m2rsm/docs/rsm_metrics_narration.htm\n\n=for TODO: Comment Percent = Comment Line Count / Logical Line Count ) x 100 \n\n=for TODO: White Space Percentage = (Number of spaces / Number of spaces and characters) * 100 \n\n=head1 DESCRIPTION\n\neLOC is a simple LOC counter. See L</\"LOC Specification\">. \n\n=head2 LOC Specification\n\n=over 1\n\n=item LOC\n\nLines Of Code = eLOC + lines of a single brace or parenthesis\n\n=item eLOC\n\nAn effective line of code or eLOC is the measurement of all lines that are \nnot comments, blanks or standalone braces or parenthesis. \nThis metric more closely represents the quantity of work performed. \nRSM introduces eLOC as a metrics standard.\nSee http://msquaredtechnologies.com/m2rsm/docs/rsm_metrics_narration.htm\n\n=item lLOC\n\nLogical lines of code represent a metrics for those line of code which form \ncode statements. These statements are terminated with a semi-colon. \n\nThe control line for the \"for\" loop contain two semi-colons but accounts \nfor only one semi colon.\nSee http://msquaredtechnologies.com/m2rsm/docs/rsm_metrics_narration.htm\n\n=item comment\n\ncomment = pure comment + inline comment\n\n\n\n=over\n\n=item pure comment\n\nComment lines represent a metrics for pure comment line without any code in it.\nSee L</\"inline comment\">.\n\n=item inline comment\n\nInline comment line is a line which contains both LOC line and pure comment.\n\nInline comment line and pure comment line (see L</\"pure comment\">)\nare mutually exclusive, that is a given physical line cannot be an inline comment\nline and a pure comment line simultaneously.\n\n=over\n\n=item Example:\n\n static const int defaultWidth = 400; // value provided in declaration\n\n=back\n\n=back\n\n=item blank\n\nBlank line is a line which contains at most whitespaces.\nBlank lines are counted inside comments too.\n\n=item logicline\n\nThe logical line count = LOC + Comment Lines + Blank Lines\n\n=back\n\n=head1 KNOWN BUGS AND LIMITATIONS\n\n=over\n\n=item\n\nIt supports only C/C++ source files.\n\n=item\n\nComments inside for(;;) statements are not counted\n\n=over\n\n=item Example:\n\n for(int i = 0; i < N /*comment*/; i++ ); #LLOC# #LLOC# #LOC# #ELOC# #PHYS# [1]\n\n=back\n\n=item\n\n'\\'-ending lines are concatinated ( though newline count is valid)\n\n=item\n\nInput from stdin is not supported in the case \nthe script is envoked solely by name without explicit perl executable.\n\n=item\n\nWildcards in path with spaces are not supported (like GNU utilities).\n\n=back\n\n=over\n\n=begin fixed\n=item Limitation: single source file\n\n Only one source file at time supported\n\n=item Limitation: LLOC is unsupported\n\n The logical lines of code metric is unsupported. \n\n=item missed inline comment for C style comment\n\n #include <math.h> /* comment */ #ELOC# #PHYS# [2]\n\nBut must be\n #include <math.h> /* comment */ #INLINE_COMMENT# #ELOC# #PHYS# [2]\n\n=item wrong LOC type for the code after '*/'\n\n /* another #PURE_COMMENT# #PHYS# [36]\n trick #PURE_COMMENT# #PHYS# [37]\n */ i++; #PURE_COMMENT# #PHYS# [38]\n\nIn the last line must be \n\n #INLINE_COMMENT# #PHYS# [38]\n\n=end fixed\n\n=back\n\n=head1 SEE ALSO\n\nMetrics counted by the program are based on narration from L<http://msquaredtechnologies.com/m2rsm/docs/rsm_metrics_narration.htm>\n\n=cut\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668/" ]
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre class="lang-py prettyprint-override"><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
[ { "answer_id": 325456, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 6, "selected": true, "text": "*** finding dlls needed ***\nerror: MSVCP90.dll: No such file or directory\n" }, { "answer_id": 774715, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "distutils.core.setup(\n options = {\n \"py2exe\": {\n \"dll_excludes\": [\"MSVCP90.dll\"]\n }\n },\n ...\n)\n" }, { "answer_id": 1433894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "import sys\n\nsys.path.append('c:/Program Files/Microsoft Visual Studio 9.0/VC/redist/x86/Microsoft.VC90.CRT')\n" }, { "answer_id": 12577412, "author": "Egor", "author_id": 1696397, "author_profile": "https://Stackoverflow.com/users/1696397", "pm_score": 3, "selected": false, "text": "import sys\n\nsys.path.append('C:\\\\WINDOWS\\\\WinSxS\\\\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4148_none_5090ab56bcba71c2')\n MSVCP90.dll C:\\\\WINDOWS\\\\WinSxS\\\\ x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4148_none_5090ab56bcba71c2 C:\\\\WINDOWS\\\\WinSxS\\\\ MSVCP90.dll" }, { "answer_id": 28651480, "author": "petitchamp", "author_id": 1553020, "author_profile": "https://Stackoverflow.com/users/1553020", "pm_score": -1, "selected": false, "text": "import sys\nsys.path.append('C:/WINDOWS/WinSxS/x86_Microsoft.VC90.CRT_XXXXXXX')\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
323,426
<p>I would like to provide the raw text referring to an environment variable to a command instead of evaluating the environment variable.</p> <p>I need this to configure BizTalk from the command line, for example:</p> <p>BTSTask.exe AddResource -ApplicationName:App1 -Type:System.BizTalk:BizTalkAssembly -Overwrite -Source:..\Schemas\bin\development\App1.Schemas.dll -Destination:%BTAD_InstallDir%\App1.Schemas.dll</p> <p>This command adds a resource to a BizTalk application. I want the destination to be %BTAD_InstallDir%\App1.Schemas.dll, however at present it is evaluating the environment variable (to nothing) and using \App1.Schemas.dll.</p> <p>Is it possible to escape or disable the evaluation of this environment variable while parsing\executing this command?</p> <p>I have tried escaping the first and both percentage characters with a carrot (^), however this did not stop the evaluation.</p> <p><b>[EDIT]</b> When I execute this at the command prompt it doesn't replace the environment variable, however it does when I run it as a script, any thoughts as to why this is different?</p>
[ { "answer_id": 323466, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "C:\\PrgCmdLine\\Unix\\echo.exe \"%\"JAVA_HOME\"%\"\n %JAVA_HOME%\n C:\\PrgCmdLine\\Unix\\echo.exe ^%JAVA_HOME^%" }, { "answer_id": 323516, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "%%BTAD_InstallDir%%\n %BTAD_InstallDir%" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23940/" ]
323,462
<p>This is driving me nuts so any advice from fellow users would be welcome. I am using Subversion, with a copy of VisualSVN 1.6.1 installed on a Windows server. On my PC I am using a combination of TortoiseSVN and the wonderful AnkhSVN Visual Studio plugin. Everything works like a dream, but now I am trying use the <code>svn:keywords</code> feature so I can include <code>$Id$</code> at the top of all my source files. Now, for existing files I can edit the SVN properties and add this keyword and it all works fine, but I want this done automatically for new files - and I cannot make it work.</p> <p>According to the documentation you need to edit a special Subversion Config file located in your <code>C:\Documents and Settings\&lt;user&gt;\Application Data\Subversion</code> folder. My PC already had a copy of this file, so I changed it to look like this:</p> <pre><code>[miscellany] enable-auto-props = yes [auto-props] *.cpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.hpp = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rc = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.rc2 = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.cc = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.c = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.h = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.wsf = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.js = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.htm = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.html = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision *.css = svn:eol-style=native;svn:keywords=Author Date Id HeadURL Revision </code></pre> <p>I then added a new file to an existing Visual Studio project (from within Visual Studio), added <code>$Id$</code> to the top and committed it - but, alas, the <code>svn:keywords</code> property is not being set.</p> <p>Does anyone know how to get this working? I even tried adding settings to the registry (in <code>HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config</code>) but still no joy. I then tried messing with Config files on the SVN server itself, but nothing seems to work.</p> <p>I have obviously missed something blindingly obvious!</p>
[ { "answer_id": 323489, "author": "LenW", "author_id": 41292, "author_profile": "https://Stackoverflow.com/users/41292", "pm_score": 3, "selected": false, "text": "[auto-props]\n*.cpp = svn:eol-style=native;svn:keywords=\"Author Date Id HeadURL Revision\"\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
323,503
<p>I've got a DataTable containing a sitemap hierarchy with the following columns:</p> <ul> <li>ItemId</li> <li>ParentId</li> <li>Name</li> <li>Url</li> </ul> <p>I need to generate a set of nested lists in HTML (left the anchor elements out for clarity):</p> <pre><code>&lt;ul&gt; &lt;li&gt;Item 1&lt;/li&gt; &lt;li&gt;Item 2&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Sub Item 1&lt;/li&gt; &lt;li class="current"&gt;Sub Item 2&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;Item 3&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The tree should only contain branches that lead to the 'current' node/page (so using the above example any child items that Item '1' or '3' have are not displayed. Can anyone help out with some pseudo code / code example that can traverse the tree from the leaf to root building the HTML as it goes? Thanks.</p>
[ { "answer_id": 323602, "author": "Bork Blatt", "author_id": 5381, "author_profile": "https://Stackoverflow.com/users/5381", "pm_score": 0, "selected": false, "text": "'# OMITTED: Code to retrieve the record for the current node, and read all info about it.\n'# Note: field values are read into variables with the same names.\n\nDim RootFound\nDim ListHTML\nRootFound = false\nListHTML = \"\"\n\nif ParentID = Null then RootFound = true\nListHTML = \"<ul><li>\" & Name & \"</li></ul>\"\n\nwhile not RootFound\n SQL = \"SELECT * FROM DataTable WHERE ItemID = \" & ParentID\n '# OMITTED: Code to open dataset using the SQL statement above and \n 'fetch all field values into identically named variables\n\n ListHTML = \"<ul><li>\" & Name & \"</li>\" & ListHTML & \"</ul>\"\n if ParentID = Null then RootFound = true\nwend\n" }, { "answer_id": 324025, "author": "ShreevatsaR", "author_id": 4958, "author_profile": "https://Stackoverflow.com/users/4958", "pm_score": 2, "selected": false, "text": "for all n: mark[n]=False\nn=current\nwhile n!=root:\n n=parent[n]\n mark[n]=True\n\ndef print_tree(n):\n print_node(n)\n if mark[v]==True:\n print '<ul>'\n for each child c of n: print_tree(c)\n print '</ul>'\n\ndef print_node(n):\n if n==current: print '<li class=\"current\">' else: print '<li>'\n print name[n]\n print \"</li>\"\n\nprint_tree(root)\n parent[n] name[n] n.parent n.name" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14072/" ]
323,506
<p>The developer environment db server is SqlServer 2005 (developer edition)</p> <p>Is there any way to make sure my SQL Queries will run in SqlServer 2000?</p> <p>This database is set to Compatibility level "SQL Server 2000 (80)" but some queries that run without problems in the development system can not run in the Test Server (SqlServer).</p> <p>(The problems seems to be in subqueries)</p>
[ { "answer_id": 325179, "author": "Kaniu", "author_id": 3236, "author_profile": "https://Stackoverflow.com/users/3236", "pm_score": 0, "selected": false, "text": "SELECT * FROM Loans WHERE EXISTS (SELECT * FROM Collaterals WHERE LOAN_NUMBER=Loans.LOAN_NUMBER)\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28207/" ]
323,515
<p>I'm trying to store in a variable the name of the current file that I've opened from a folder.</p> <p>How can I do that? I've tried <code>cwd = os.getcwd()</code> but this only gives me the path of the folder, and I need to store the name of the opened file.</p> <p>Can you please help me?</p>
[ { "answer_id": 323522, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": false, "text": "Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)\n[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> f = open('generic.png','r')\n>>> f.name\n'generic.png'\n" }, { "answer_id": 324326, "author": "Rudiger Wolf", "author_id": 41431, "author_profile": "https://Stackoverflow.com/users/41431", "pm_score": 3, "selected": false, "text": "import sys, os\nprint sys.argv[0]\nprint os.path.basename(sys.argv[0])\n D:\\UserData\\workspace\\temp\\Script1.py\nScript1.py\n" }, { "answer_id": 24144992, "author": "James Errico", "author_id": 832005, "author_profile": "https://Stackoverflow.com/users/832005", "pm_score": 6, "selected": false, "text": ">>> f = open('/tmp/generic.png','r')\n>>> f.name\n'/tmp/generic.png'\n>>> import os\n>>> os.path.basename(f.name)\n'generic.png'\n" }, { "answer_id": 60945006, "author": "ROHIT TEJA", "author_id": 13163042, "author_profile": "https://Stackoverflow.com/users/13163042", "pm_score": 0, "selected": false, "text": ".py target_file = inspect.currentframe().f_code.co_filename\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,517
<p>We need to see what methods/fields an object has in Javascript.</p>
[ { "answer_id": 323529, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 7, "selected": false, "text": "console.debug(myObject);\n for (property in object) {\n // do what you want with property, object[property].value\n}\n" }, { "answer_id": 323809, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 9, "selected": true, "text": "function dump(obj) {\n var out = '';\n for (var i in obj) {\n out += i + \": \" + obj[i] + \"\\n\";\n }\n\n alert(out);\n\n // or, if you wanted to avoid alerts...\n\n var pre = document.createElement('pre');\n pre.innerHTML = out;\n document.body.appendChild(pre)\n}\n" }, { "answer_id": 7034412, "author": "PPrice", "author_id": 190219, "author_profile": "https://Stackoverflow.com/users/190219", "pm_score": 6, "selected": false, "text": "JSON.stringify(myVar);\n" }, { "answer_id": 14845499, "author": "naterudd", "author_id": 1975290, "author_profile": "https://Stackoverflow.com/users/1975290", "pm_score": 2, "selected": false, "text": "function dump(v) {\n switch (typeof v) {\n case \"object\":\n for (var i in v) {\n console.log(i+\":\"+v[i]);\n }\n break;\n default: //number, string, boolean, null, undefined \n console.log(typeof v+\":\"+v);\n break;\n }\n}\n" }, { "answer_id": 20260831, "author": "Stan", "author_id": 2298902, "author_profile": "https://Stackoverflow.com/users/2298902", "pm_score": 2, "selected": false, "text": "function var_dump(obj, element)\n{\n var logMsg = objToString(obj, 0);\n if (element) // set innerHTML to logMsg\n {\n var pre = document.createElement('pre');\n pre.innerHTML = logMsg;\n element.innerHTML = '';\n element.appendChild(pre);\n }\n else // write logMsg to the console\n {\n console.log(logMsg);\n }\n}\n\nfunction objToString(obj, level)\n{\n var out = '';\n for (var i in obj)\n {\n for (loop = level; loop > 0; loop--)\n {\n out += \" \";\n }\n if (obj[i] instanceof Object)\n {\n out += i + \" (Object):\\n\";\n out += objToString(obj[i], level + 1);\n }\n else\n {\n out += i + \": \" + obj[i] + \"\\n\";\n }\n }\n return out;\n}\n" }, { "answer_id": 25962952, "author": "ReverseEMF", "author_id": 2755918, "author_profile": "https://Stackoverflow.com/users/2755918", "pm_score": 3, "selected": false, "text": "/**\n * Does a PHP var_dump'ish behavior. It only dumps one variable per call. The\n * first parameter is the variable, and the second parameter is an optional\n * name. This can be the variable name [makes it easier to distinguish between\n * numerious calls to this function], but any string value can be passed.\n * \n * @param mixed var_value - the variable to be dumped\n * @param string var_name - ideally the name of the variable, which will be used \n * to label the dump. If this argumment is omitted, then the dump will\n * display without a label.\n * @param boolean - annonymous third parameter. \n * On TRUE publishes the result to the DOM document body.\n * On FALSE a string is returned.\n * Default is TRUE.\n * @returns string|inserts Dom Object in the BODY element.\n */\nfunction my_dump (var_value, var_name)\n{\n // Check for a third argument and if one exists, capture it's value, else\n // default to TRUE. When the third argument is true, this function\n // publishes the result to the document body, else, it outputs a string.\n // The third argument is intend for use by recursive calls within this\n // function, but there is no reason why it couldn't be used in other ways.\n var is_publish_to_body = typeof arguments[2] === 'undefined' ? true:arguments[2];\n\n // Check for a fourth argument and if one exists, add three to it and\n // use it to indent the out block by that many characters. This argument is\n // not intended to be used by any other than the recursive call.\n var indent_by = typeof arguments[3] === 'undefined' ? 0:arguments[3]+3;\n\n var do_boolean = function (v)\n {\n return 'Boolean(1) '+(v?'TRUE':'FALSE');\n };\n\n var do_number = function(v)\n {\n var num_digits = (''+v).length;\n return 'Number('+num_digits+') '+v;\n };\n\n var do_string = function(v)\n {\n var num_chars = v.length;\n return 'String('+num_chars+') \"'+v+'\"';\n };\n\n var do_object = function(v)\n {\n if (v === null)\n {\n return \"NULL(0)\";\n }\n\n var out = '';\n var num_elem = 0;\n var indent = '';\n\n if (v instanceof Array)\n {\n num_elem = v.length;\n for (var d=0; d<indent_by; ++d)\n {\n indent += ' ';\n }\n out = \"Array(\"+num_elem+\") \\n\"+(indent.length === 0?'':'|'+indent+'')+\"(\";\n for (var i=0; i<num_elem; ++i)\n {\n out += \"\\n\"+(indent.length === 0?'':'|'+indent)+\"| [\"+i+\"] = \"+my_dump(v[i],'',false,indent_by);\n }\n out += \"\\n\"+(indent.length === 0?'':'|'+indent+'')+\")\";\n return out;\n }\n else if (v instanceof Object)\n {\n for (var d=0; d<indent_by; ++d)\n {\n indent += ' ';\n }\n out = \"Object \\n\"+(indent.length === 0?'':'|'+indent+'')+\"(\";\n for (var p in v)\n {\n out += \"\\n\"+(indent.length === 0?'':'|'+indent)+\"| [\"+p+\"] = \"+my_dump(v[p],'',false,indent_by);\n }\n out += \"\\n\"+(indent.length === 0?'':'|'+indent+'')+\")\";\n return out;\n }\n else\n {\n return 'Unknown Object Type!';\n }\n };\n\n // Makes it easier, later on, to switch behaviors based on existance or\n // absence of a var_name parameter. By converting 'undefined' to 'empty \n // string', the length greater than zero test can be applied in all cases.\n var_name = typeof var_name === 'undefined' ? '':var_name;\n var out = '';\n var v_name = '';\n switch (typeof var_value)\n {\n case \"boolean\":\n v_name = var_name.length > 0 ? var_name + ' = ':''; // Turns labeling on if var_name present, else no label\n out += v_name + do_boolean(var_value);\n break;\n case \"number\":\n v_name = var_name.length > 0 ? var_name + ' = ':'';\n out += v_name + do_number(var_value);\n break;\n case \"string\":\n v_name = var_name.length > 0 ? var_name + ' = ':'';\n out += v_name + do_string(var_value);\n break;\n case \"object\":\n v_name = var_name.length > 0 ? var_name + ' => ':'';\n out += v_name + do_object(var_value);\n break;\n case \"function\":\n v_name = var_name.length > 0 ? var_name + ' = ':'';\n out += v_name + \"Function\";\n break;\n case \"undefined\":\n v_name = var_name.length > 0 ? var_name + ' = ':'';\n out += v_name + \"Undefined\";\n break;\n default:\n out += v_name + ' is unknown type!';\n }\n\n // Using indent_by to filter out recursive calls, so this only happens on the \n // primary call [i.e. at the end of the algorithm]\n if (is_publish_to_body && indent_by === 0)\n {\n var div_dump = document.getElementById('div_dump');\n if (!div_dump)\n {\n div_dump = document.createElement('div');\n div_dump.id = 'div_dump';\n\n var style_dump = document.getElementsByTagName(\"style\")[0];\n if (!style_dump)\n {\n var head = document.getElementsByTagName(\"head\")[0];\n style_dump = document.createElement(\"style\");\n head.appendChild(style_dump);\n }\n // Thank you Tim Down [http://stackoverflow.com/users/96100/tim-down] \n // for the following addRule function\n var addRule;\n if (typeof document.styleSheets != \"undefined\" && document.styleSheets) {\n addRule = function(selector, rule) {\n var styleSheets = document.styleSheets, styleSheet;\n if (styleSheets && styleSheets.length) {\n styleSheet = styleSheets[styleSheets.length - 1];\n if (styleSheet.addRule) {\n styleSheet.addRule(selector, rule)\n } else if (typeof styleSheet.cssText == \"string\") {\n styleSheet.cssText = selector + \" {\" + rule + \"}\";\n } else if (styleSheet.insertRule && styleSheet.cssRules) {\n styleSheet.insertRule(selector + \" {\" + rule + \"}\", styleSheet.cssRules.length);\n }\n }\n };\n } else {\n addRule = function(selector, rule, el, doc) {\n el.appendChild(doc.createTextNode(selector + \" {\" + rule + \"}\"));\n };\n }\n\n // Ensure the dump text will be visible under all conditions [i.e. always\n // black text against a white background].\n addRule('#div_dump', 'background-color:white', style_dump, document);\n addRule('#div_dump', 'color:black', style_dump, document);\n addRule('#div_dump', 'padding:15px', style_dump, document);\n\n style_dump = null;\n }\n\n var pre_dump = document.getElementById('pre_dump');\n if (!pre_dump)\n {\n pre_dump = document.createElement('pre');\n pre_dump.id = 'pre_dump';\n pre_dump.innerHTML = out+\"\\n\";\n div_dump.appendChild(pre_dump);\n document.body.appendChild(div_dump);\n } \n else\n {\n pre_dump.innerHTML += out+\"\\n\";\n }\n }\n else\n {\n return out;\n }\n}\n" }, { "answer_id": 26463747, "author": "Halayem Anis", "author_id": 4098311, "author_profile": "https://Stackoverflow.com/users/4098311", "pm_score": 2, "selected": false, "text": "console.log(OBJECT|ARRAY|STRING|...);\nconsole.info(OBJECT|ARRAY|STRING|...);\nconsole.debug(OBJECT|ARRAY|STRING|...);\nconsole.warn(OBJECT|ARRAY|STRING|...);\nconsole.assert(Condition, 'Message if false');\n" }, { "answer_id": 28306216, "author": "Doglas", "author_id": 3620727, "author_profile": "https://Stackoverflow.com/users/3620727", "pm_score": 2, "selected": false, "text": "function dump(obj) {\n var out = '';\n for (var i in obj) {\n if(typeof obj[i] === 'object'){\n dump(obj[i]);\n }else{\n out += i + \": \" + obj[i] + \"\\n\";\n }\n }\n\n var pre = document.createElement('pre');\n pre.innerHTML = out;\n document.body.appendChild(pre);\n}\n" }, { "answer_id": 31813321, "author": "Daweb", "author_id": 3779294, "author_profile": "https://Stackoverflow.com/users/3779294", "pm_score": 2, "selected": false, "text": "function dump(v, s) {\n s = s || 1;\n var t = '';\n switch (typeof v) {\n case \"object\":\n t += \"\\n\";\n for (var i in v) {\n t += Array(s).join(\" \")+i+\": \";\n t += dump(v[i], s+3);\n }\n break;\n default: //number, string, boolean, null, undefined \n t += v+\" (\"+typeof v+\")\\n\";\n break;\n }\n return t;\n}\n var a = {\n b: 1,\n c: {\n d:1,\n e:2,\n d:3,\n c: {\n d:1,\n e:2,\n d:3\n }\n }\n};\n\nvar d = dump(a);\nconsole.log(d);\ndocument.getElementById(\"#dump\").innerHTML = \"<pre>\" + d + \"</pre>\";\n b: 1 (number)\nc: \n d: 3 (number)\n e: 2 (number)\n c: \n d: 3 (number)\n e: 2 (number)\n" }, { "answer_id": 32289805, "author": "user5280460", "author_id": 5280460, "author_profile": "https://Stackoverflow.com/users/5280460", "pm_score": 3, "selected": false, "text": "var_dump var objectInStringFormat = JSON.stringify(someObject);\nalert(objectInStringFormat);\n" }, { "answer_id": 41540288, "author": "Blackbam", "author_id": 576746, "author_profile": "https://Stackoverflow.com/users/576746", "pm_score": 0, "selected": false, "text": "var_dump function dump(arr,level) {\n var dumped_text = \"\";\n if(!level) level = 0;\n \n //The padding given at the beginning of the line.\n var level_padding = \"\";\n for(var j=0;j<level+1;j++) level_padding += \" \";\n \n if(typeof(arr) == 'object') { //Array/Hashes/Objects \n for(var item in arr) {\n var value = arr[item];\n if(typeof(value) == 'object') { //If it is an array,\n dumped_text += level_padding + \"'\" + item + \"' ...\\n\";\n dumped_text += dump(value,level+1);\n } else {\n dumped_text += level_padding + \"'\" + item + \"' => \\\"\" + value + \"\\\"\\n\";\n }\n }\n } else { //Stings/Chars/Numbers etc.\n dumped_text = \"===>\"+arr+\"<===(\"+typeof(arr)+\")\";\n }\n return dumped_text;\n}\n" }, { "answer_id": 51539138, "author": "Chris Sprague", "author_id": 2979955, "author_profile": "https://Stackoverflow.com/users/2979955", "pm_score": 0, "selected": false, "text": "/*\n* Brief: Print to console.log() from PHP\n* Description: Print as many strings,arrays, objects, and other data types to console.log from PHP.\n* To use, just call consoleLog($data1, $data2, ... $dataN) and each dataI will be sent to console.log - note that\n* you can pass as many data as you want an this will still work.\n*\n* This is very powerful as it shows the entire contents of objects and arrays that can be read inside of the browser console log.\n* \n* A tag can be set by passing a string that has the prefix TAG- as one of the arguments. Everytime a string with the TAG- prefix is\n* detected, the tag is updated. This allows you to pass a tag that is applied to all data until it reaches another tag, which can then\n* be applied to all data after it.\n*\n* Example:\n* consoleLog('TAG-FirstTag',$data,$data2,'TAG-SecTag,$data3); \n* Result:\n* FirstTag '...data...'\n* FirstTag '...data2...'\n* SecTag '...data3...' \n*/\nfunction consoleLog(){\n if(func_num_args() == 0){\n return;\n }\n\n $tag = '';\n for ($i = 0; $i < func_num_args(); $i++) {\n $arg = func_get_arg($i);\n if(!empty($arg)){ \n if(is_string($arg)&& strtolower(substr($arg,0,4)) === 'tag-'){\n $tag = substr($arg,4);\n }else{ \n $arg = json_encode($arg, JSON_HEX_TAG | JSON_HEX_AMP );\n echo \"<script>console.log('\".$tag.\" \".$arg.\"');</script>\";\n } \n }\n }\n}\n" }, { "answer_id": 54997805, "author": "ankurnarkhede", "author_id": 8001821, "author_profile": "https://Stackoverflow.com/users/8001821", "pm_score": 2, "selected": false, "text": "npm install var_dump --save-dev\n const var_dump = require('var_dump')\n\nvar variable = {\n 'data': {\n 'users': {\n 'id': 12,\n 'friends': [{\n 'id': 1,\n 'name': 'John Doe'\n }]\n }\n }\n}\n\n// print the variable using var_dump\nvar_dump(variable)\n object(1) {\n [\"data\"] => object(1) {\n [\"users\"] => object(2) {\n [\"id\"] => number(12)\n [\"friends\"] => array(1) {\n [0] => object(2) {\n [\"id\"] => number(1)\n [\"name\"] => string(8) \"John Doe\"\n }\n }\n }\n }\n}\n" }, { "answer_id": 63767040, "author": "Nate Levin", "author_id": 13608595, "author_profile": "https://Stackoverflow.com/users/13608595", "pm_score": 2, "selected": false, "text": "var_dump function var_dump(variable) {\n let out = \"\";\n \n let type = typeof variable;\n if(type == \"object\") {\n var realType;\n var length;\n if(variable instanceof Array) {\n realType = \"array\";\n length = variable.length;\n } else {\n realType = \"object\";\n length = Object.keys(variable).length;\n }\n out = `${realType}(${length}) {`;\n for (const [key, value] of Object.entries(variable)) {\n out += `\\n [${key}]=>\\n ${var_dump(value).replace(/\\n/g, \"\\n \")}\\n`;\n }\n out += \"}\";\n } else if(type == \"string\") {\n out = `${type}(${type.length}) \"${variable}\"`;\n } else {\n out = `${type}(${variable.toString()})`;\n }\n return out;\n}\nconsole.log(var_dump(1.5));\nconsole.log(var_dump(\"Hello!\"));\nconsole.log(var_dump([]));\nconsole.log(var_dump([1,2,3,[1,2]]));\n\nconsole.log(var_dump({\"a\":\"b\"}));" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30759/" ]
323,521
<p>in windows I am able to use winmerge as the external diff tool for hg using <i>mercurial.ini</i>,etc. <br> Using some options switch that you can find in web(I think it's a japanese website) Anyway, here for example:</p> <pre>hg winmerge -r1 -r2</pre> <p>will list file(s) change(s) between rev1 and rev2 in winmerge. I can just click which file to diff </p> <p>but for bc3:</p> <pre>hg bcomp -r1 -r2</pre> <p>will make bc3 open a dialog which stated that a temp dir can't be found.</p> <p>The most I can do using bc3 and hg is</p> <pre> hg bcomp -r1 -r2 myfile.cpp </pre> <p>which will open diff between rev1 and rev2 of myfile.cpp</p> <p>So,it seems that hg+bc3 can't successfully acknowledge of all files change between revision. Only able to diff 1 file at a time. <br> Anyone can use bc3 + hg better ? <br></p> <p>edit: Problem Solved ! <br></p> <p>Got the solution from http://www.scootersoftware.com/support.php?zz=kb_vcs.php>scooter support page. I have to use <i>bcompare</i> instead of <i>bcomp</i> Here's a snippet of my mercurial.ini</p> <pre> [extensions] hgext.win32text = ;mhd adds hgext.extdiff = ;mhd adds for bc [extdiff] cmd.bc3 = bcompare opts.bc3 = /ro ;mhd adds for winmerge ;[extdiff] ;cmd.winmerge = WinMergeU ;opts.winmerge = /r /e /x /ub </pre>
[ { "answer_id": 499666, "author": "mrrage", "author_id": 8631, "author_profile": "https://Stackoverflow.com/users/8631", "pm_score": 2, "selected": false, "text": "[extensions]\nextdiff =\n\n[extdiff]\ncmd.bc3 = C:\\Program Files\\Beyond Compare 3\\BCompare.exe\nopts.bc3 = /ro\n" }, { "answer_id": 1023463, "author": "Refael Ackermann", "author_id": 27955, "author_profile": "https://Stackoverflow.com/users/27955", "pm_score": 5, "selected": false, "text": "[extensions]\nextdiff =\n\n[extdiff]\ncmd.bcomp = C:\\Program Files\\Beyond Compare 3\\BCompare.exe\nopts.bcomp = /leftreadonly\n\n[merge-tools]\nbcomp.executable = C:\\Program Files\\Beyond Compare 3\\BComp\nbcomp.args = /leftreadonly /centerreadonly $local $other $base $output\nbcomp.priority = 1\n\n[ui]\nmerge = bcomp\n\n[tortoisehg]\nauthorcolor = True\nvdiff = bcomp\n" }, { "answer_id": 2681676, "author": "user87362", "author_id": 87362, "author_profile": "https://Stackoverflow.com/users/87362", "pm_score": 2, "selected": false, "text": "/solo [extdiff]\ncmd.bcomp = C:\\Program Files\\Beyond Compare 3\\BCompare.exe\nopts.bcomp = /leftreadonly /solo\n" }, { "answer_id": 3158713, "author": "MPritchard", "author_id": 83083, "author_profile": "https://Stackoverflow.com/users/83083", "pm_score": 2, "selected": false, "text": "[extensions] extdiff =\n\n[extdiff] \ncmd.bcomp = C:\\Program Files\\Beyond Compare 3\\BCompare.exe\nopts.bcomp = /ro\n\n[tortoisehg] vdiff = bcomp \n hg bcomp -r <rev1> [-r <rev2>] [<filename>]\n [merge-tools] \nbcomp.executable = C:\\Program Files\\Beyond Compare 3\\BComp \nbcomp.args = $local $other\n$base $output bcomp.priority = 1\nbcomp.premerge = True bcomp.gui = True\n\n[ui] merge = bcomp\n" }, { "answer_id": 3347318, "author": "Oliver", "author_id": 67494, "author_profile": "https://Stackoverflow.com/users/67494", "pm_score": 1, "selected": false, "text": "path bcompare" }, { "answer_id": 3893482, "author": "Regent", "author_id": 107718, "author_profile": "https://Stackoverflow.com/users/107718", "pm_score": 4, "selected": false, "text": "mergetools.rc file [merge-tools]\n....\n; Windows version of Beyond Compare\nbeyondcompare3.args=$local $other $base $output /ro /lefttitle=local /centertitle=base /righttitle=other /automerge /reviewconflicts /solo\nbeyondcompare3.regkey=Software\\Scooter Software\\Beyond Compare 3\nbeyondcompare3.regname=ExePath\nbeyondcompare3.gui=True\nbeyondcompare3.priority=-2\nbeyondcompare3.diffargs=/lro /lefttitle='$plabel1' /righttitle='$clabel' /solo /expandall $parent $child\n extdiff beyondcompare3 merge-tools diffargs beyondcompare3 ui.merge tortoisehg.vdiff" }, { "answer_id": 5759148, "author": "tamakisquare", "author_id": 338961, "author_profile": "https://Stackoverflow.com/users/338961", "pm_score": 1, "selected": false, "text": "[extensions]\nextdiff =\n\n[extdiff]\ncmd.bcomp = bcompare\nopts.bcomp = -ro1\n [merge-tools]\nbcomp.executable = bcompare\nbcomp.args = -title1='First Parent' -title2='Second Parent' -title3='Common Ancestor' -title4='Output' -ro1 -ro2 -ro3 $local $other $base $output\nbcomp.premerge = True\nbcomp.gui = True\n -ro# -title#=<title> # bcompare bcompare -help" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38515/" ]
323,536
<p>How can I get a full list of Groups in my Active Directory?</p>
[ { "answer_id": 323578, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 6, "selected": true, "text": "using System.DirectoryServices; \n\npublic class test\n{\n\n private void main()\n {\n foreach (string @group in GetGroups())\n {\n Debug.Print(@group);\n }\n }\n\n public List<string> GetGroups()\n {\n DirectoryEntry objADAM = default(DirectoryEntry);\n // Binding object. \n DirectoryEntry objGroupEntry = default(DirectoryEntry);\n // Group Results. \n DirectorySearcher objSearchADAM = default(DirectorySearcher);\n // Search object. \n SearchResultCollection objSearchResults = default(SearchResultCollection);\n // Results collection. \n string strPath = null;\n // Binding path. \n List<string> result = new List<string>();\n\n // Construct the binding string. \n strPath = \"LDAP://stefanserver.stefannet.local\";\n //Change to your ADserver \n\n // Get the AD LDS object. \n try\n {\n objADAM = new DirectoryEntry(strPath);\n objADAM.RefreshCache();\n }\n catch (Exception e)\n {\n throw e;\n }\n\n // Get search object, specify filter and scope, \n // perform search. \n try\n {\n objSearchADAM = new DirectorySearcher(objADAM);\n objSearchADAM.Filter = \"(&(objectClass=group))\";\n objSearchADAM.SearchScope = SearchScope.Subtree;\n objSearchResults = objSearchADAM.FindAll();\n }\n catch (Exception e)\n {\n throw e;\n }\n\n // Enumerate groups \n try\n {\n if (objSearchResults.Count != 0)\n {\n foreach (SearchResult objResult in objSearchResults)\n {\n objGroupEntry = objResult.GetDirectoryEntry();\n result.Add(objGroupEntry.Name);\n }\n }\n else\n {\n throw new Exception(\"No groups found\");\n }\n }\n catch (Exception e)\n {\n throw new Exception(e.Message);\n }\n\n return result;\n }\n\n}\n Imports System.DirectoryServices\n\nPublic Class Form1\n\nPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n For Each group As String In GetGroups()\n Debug.Print(group)\n Next\nEnd Sub\n\nPublic Function GetGroups() As List(Of String)\n Dim objADAM As DirectoryEntry ' Binding object.\n Dim objGroupEntry As DirectoryEntry ' Group Results.\n Dim objSearchADAM As DirectorySearcher ' Search object.\n Dim objSearchResults As SearchResultCollection ' Results collection.\n Dim strPath As String ' Binding path.\n Dim result As New List(Of String)\n\n ' Construct the binding string. \n strPath = \"LDAP://stefanserver.stefannet.local\" 'Change to your ADserver\n\n ' Get the AD LDS object.\n Try\n objADAM = New DirectoryEntry(strPath)\n objADAM.RefreshCache()\n Catch e As Exception\n Throw e\n End Try\n\n ' Get search object, specify filter and scope,\n ' perform search.\n Try\n objSearchADAM = New DirectorySearcher(objADAM)\n objSearchADAM.Filter = \"(&(objectClass=group))\"\n objSearchADAM.SearchScope = SearchScope.Subtree\n objSearchResults = objSearchADAM.FindAll()\n Catch e As Exception\n Throw e\n End Try\n\n ' Enumerate groups\n Try\n If objSearchResults.Count <> 0 Then\n Dim objResult As SearchResult\n For Each objResult In objSearchResults\n objGroupEntry = objResult.GetDirectoryEntry\n result.Add(objGroupEntry.Name)\n Next objResult\n Else\n Throw New Exception(\"No groups found\")\n End If\n Catch e As Exception\n Throw New Exception(e.Message)\n End Try\n\n Return result\nEnd Function\nEnd Class\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36026/" ]
323,551
<p>I have a WCF service with the following configuration:</p> <pre><code>&lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MetadataEnabled"&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service behaviorConfiguration="MetadataEnabled" name="MyNamespace.MyService"&gt; &lt;endpoint name="BasicHttp" address="" binding="basicHttpBinding" contract="MyNamespace.IMyServiceContract" /&gt; &lt;endpoint name="MetadataHttp" address="contract" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost/myservice" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; &lt;/system.serviceModel&gt; </code></pre> <p>When hosting the service in the <strong>WcfSvcHost.exe</strong> process, if I browse to the URL:</p> <blockquote> <p><a href="http://localhost/myservice/contract" rel="noreferrer">http://localhost/myservice/contract</a></p> </blockquote> <p>where the service metadata is available I get an <strong>HTTP 400 Bad Request</strong> error.<br/><br/> By inspecting the WCF logs I found out that an <strong>System.Xml.XmlException</strong> exception is being thrown with the message: "<em>The body of the message cannot be read because it is empty.</em>"<br/>Here is an extract of the log file:</p> <pre><code>&lt;Exception&gt; &lt;ExceptionType&gt; System.ServiceModel.ProtocolException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 &lt;/ExceptionType&gt; &lt;Message&gt;There is a problem with the XML that was received from the network. See inner exception for more details.&lt;/Message&gt; &lt;StackTrace&gt; at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, ItemDequeuedCallback callback) at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult result) at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result) at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Net.LazyAsyncResult.Complete(IntPtr userToken) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken) at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) &lt;/StackTrace&gt; &lt;InnerException&gt; &lt;ExceptionType&gt;System.Xml.XmlException, System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&lt;/ExceptionType&gt; &lt;Message&gt;The body of the message cannot be read because it is empty.&lt;/Message&gt; &lt;StackTrace&gt; at System.ServiceModel.Channels.HttpRequestContext.CreateMessage() at System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, ItemDequeuedCallback callback) at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult result) at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result) at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) at System.Net.LazyAsyncResult.Complete(IntPtr userToken) at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken) at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) &lt;/StackTrace&gt; &lt;/InnerException&gt; &lt;/Exception&gt; </code></pre> <p>If I instead browse to the URL:</p> <blockquote> <p><a href="http://localhost/myservice?wsdl" rel="noreferrer">http://localhost/myservice?wsdl</a></p> </blockquote> <p>everything works just fine and I get the WSDL contract. At this point, I can also remove the <em>"MetadataHttp"</em> metadata endpoint completely, and it wouldn't make any difference.</p> <p>I'm using .NET 3.5 SP1. Does anyone have an idea of what could be wrong here?</p>
[ { "answer_id": 323574, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 5, "selected": true, "text": "<serviceBehaviors>\n <behavior name=\"MetadataEnabled\">\n <serviceMetadata httpGetEnabled=\"true\" />\n </behavior>\n</serviceBehaviors>\n" }, { "answer_id": 22668863, "author": "Boris B.", "author_id": 382783, "author_profile": "https://Stackoverflow.com/users/382783", "pm_score": 2, "selected": false, "text": "httpsGetEnabled true" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26396/" ]
323,556
<pre><code>A.Event1 := nil; A.Event2 := nil; try ... finally A.Event1 := MyEvent1; A.Event2 := MyEvent2; end; </code></pre> <p>Can something go wrong with it?</p> <p><strong>EDIT:</strong></p> <p>I've accepted Barry's answer because it answered exactly what I asked, but Vegar's answer is also correct depending on the scenario, sadly I can't accept both.</p>
[ { "answer_id": 323781, "author": "Vegar", "author_id": 11956, "author_profile": "https://Stackoverflow.com/users/11956", "pm_score": 3, "selected": false, "text": "procedure TMyObject.Traverse;\nbegin\n inc(FTraverseFlag);\n try\n ...\n finally\n dec(FTracerseFlag);\n end;\nend;\n\nprocedure TMyObject.OnBefore( ... );\nbegin\n if FTraverseFlag > 0 then \n exit;\n ...\nend;\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
323,558
<p>Here's a relatively common task for me, and, I think, for many a .NET programmer:<br> I want to use the .NET ThreadPool for scheduling worker threads that need to process a given type of tasks.</p> <p>As a refresher, the signatures for the queueing method of the ThreadPool and its associated delegate are:</p> <pre><code>public static bool QueueUserWorkItem ( WaitCallback callBack, Object state ) public delegate void WaitCallback (Object state) </code></pre> <p>Therefore, a typical generic worker thread class would look something like:</p> <pre><code>public class Worker&lt;T&gt; { public void schedule(T i_task) { ThreadPool.QueueUserWorkItem(execute, i_task) } private void execute(Object o){ T task = (T)o; //What happened to the type safety? executeTask(task); } private void executeTask(T i_task){ //process i_task } } </code></pre> <p>Notice the type of the <code>state</code> parameter? It's <em><code>Object</code></em> !</p> <p>What's the compelling reason why the .NET team chose not to make the <code>QueueUserWorkItem</code> method (or the whole <code>ThreadPool</code> class) generic? I can't believe they just overlooked it.</p> <p>Here's how I'd like to see it:</p> <pre><code>//in the ThreadPool class: public static bool QueueUserWorkItem&lt;T&gt; ( WaitCallback&lt;T&gt; callBack, T state ) public delegate void WaitCallback&lt;T&gt; (T state) </code></pre> <p>This would make the worker class type-safe (and a lot clearer, IMHO):</p> <pre><code>public class Worker&lt;T&gt; { public void schedule(T i_task) { ThreadPool.QueueUserWorkItem&lt;T&gt;(execute, i_task) } private void execute(T i_task){ //process i_task } } </code></pre> <p>I must be missing something.</p>
[ { "answer_id": 323565, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 3, "selected": false, "text": "static void QueueItem<T>(Action<T> action, T state)\n{\n ThreadPool.QueueUserWorkItem(delegate { action(state); });\n}\n" }, { "answer_id": 323575, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "Thread ThreadPool Control.Invoke Thread t = new Thread(() => SomeMethod(arg));\n t.IsBackground = true;\n t.Name = \"Worker n\";\n t.Start();\n ThreadPool" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11545/" ]
323,561
<p>I know how to disable <a href="https://stackoverflow.com/questions/303488/in-php-how-can-you-clear-a-wsdl-cache">WSDL-cache</a> in PHP, but what about force a re-caching of the WSDL? </p> <p>This is what i tried: I run my code with caching set to disabled, and the new methods showed up as espected. Then I activated caching, but of some reason my old non-working wsdl showed up again. So: how can I force my new WSDL to overwrite my old cache?</p>
[ { "answer_id": 323582, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "$limit = ini_get('soap.wsdl_cache_limit');\nini_set('soap.wsdl_cache_limit', 0);\nini_set('soap.wsdl_cache_limit', $limit);\n soap.wsdl_cache_ttl" }, { "answer_id": 323600, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 6, "selected": true, "text": "ini_set('soap.wsdl_cache_ttl', 1);\n" }, { "answer_id": 881939, "author": "G Mawr", "author_id": 109282, "author_profile": "https://Stackoverflow.com/users/109282", "pm_score": 4, "selected": false, "text": "soap.wsdl_cache_dir=\"/tmp\"\n rm /tmp/wsdl-*\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36975/" ]
323,562
<p>I have the following code in Visual Studio 2005.</p> <pre><code> Dim OutFile As System.IO.StreamWriter Try OutFile = New System.IO.StreamWriter(Filename) // Do stuff with OutFile Catch Ex As Exception // Handle Exception Finally If OutFile IsNot Nothing Then OutFile.Close() End Try </code></pre> <p>But VS2005 brings up the warning for the line "If OutFile IsNot.." that </p> <blockquote> <p>Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.</p> </blockquote> <p>Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?</p> <p>Thanks</p> <p>Rob</p>
[ { "answer_id": 323566, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": "Dim OutFile As System.IO.StreamWriter\nOutFile = Nothing\nTry\n OutFile = New System.IO.StreamWriter(Filename)\n // Do stuff with OutFile\nCatch Ex As Exception\n // Handle Exception\nFinally\n If OutFile IsNot Nothing Then OutFile.Close()\nEnd Try\n" }, { "answer_id": 31727458, "author": "Arin", "author_id": 2391294, "author_profile": "https://Stackoverflow.com/users/2391294", "pm_score": 1, "selected": false, "text": "0 Nothing Sub Main()\n For i As Integer = 1 To 5\n Dim number As Integer\n If i = 3 Then number = 3\n\n Console.Write(number)\n Next\nEnd Sub\n number 0 3 0 00300 number 0 Dim number As Integer = 0\n Dim 0 Nothing" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41338/" ]
323,567
<p>From index.jsp code, </p> <pre><code>statement.executeQuery("select * from fus where tester_num like 'hf60' ") ; </code></pre> <p>Example I want "hf60" to be a variable(userinput), wherein USER must input/write data from input text then submit and get the data so that the result will be </p> <pre><code>("select * from fus where tester_num like 'userinput' ") </code></pre> <p>Where should I insert that code, Is it in InsertServlet .java or in Index.jsp.? or make another filename.java code? Please help. Thanks;)</p> <p><strong>Index.jsp</strong></p> <pre><code>&lt;%@ page import="java.sql.*" %&gt; &lt;% Class.forName("oracle.jdbc.driver.OracleDriver"); %&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;SHIFT REPORT &lt;/TITLE&gt; &lt;/HEAD&gt; &lt;BODY BGCOLOR=##342D7E&gt; &lt;CENTER&gt; &lt;H2&gt;&lt;FONT COLOR="#ECD672" FACE="Verdana" &gt;SHIFT REPORT&lt;/FONT&gt;&lt;/H2&gt;&lt;/CENTER&gt; &lt;hr&gt; &lt;% Connection connection=DriverManager.getConnection ("jdbc:oracle:thin:@oradev2.*****.com:1521:RPADB","shift_admin", // "shift_admin" ); Statement statement = connection.createStatement() ; //**Should I input the codes here?** ResultSet resultset = statement.executeQuery("select * from fus where tester_num like 'hf60") ; %&gt; &lt;TABLE BORDER="1" BGCOLOR="CCFFFF" width='200%' cellspacing='1' cellpadding='0' bordercolor="black" border='1'&gt; &lt;TR&gt; &lt;TH bgcolor='#DAA520'&gt; &lt;font size='2'&gt;RECORD NUMBER&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;TESTER NUMBER&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;DATE&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;TIME&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;SYSTEM TYPE&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;PACKAGE&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;SOCKETS&lt;/TH&gt; &lt;TH bgcolor='#DAA520'&gt;&lt;font size='2'&gt;VALIDATED BY&lt;/TH&gt; &lt;/TR&gt; &lt;% while(resultset.next()){ %&gt; &lt;TR&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getLong(1) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(2) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getDate(3) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(4) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(5) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(6) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(7) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;TD&gt; &lt;font size='2'&gt;&lt;center&gt;&lt;%= resultset.getString(8) %&gt;&lt;/center&gt;&lt;/TD&gt; &lt;/TR&gt; &lt;% } %&gt; &lt;/TABLE&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p><strong>InsertServlet.java</strong></p> <pre><code>package fusion.shift.servlets.db; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class InsertServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); } public void destroy() { } public boolean processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String rec_num = request.getParameter("rec_num"); String tester_num = request.getParameter("tester_num"); String t_date = request.getParameter("t_date"); String t_time = request.getParameter("t_time"); String sys_type = request.getParameter("sys_type"); String packages = request.getParameter("package"); String sockets = request.getParameter("sockets"); String sockets = request.getParameter("val"); Connection con = null; Statement stmt = null; ResultSet rs = null; PreparedStatement ps = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@oradev2.*****.com:1521:RPADB","shift_admin", // "shift_admin" ); String sql; sql = "INSERT INTO fusion_shiftrpt(RECORD_NUM, TESTER_NUM, T_DATE, T_TIME, SYSTEM_TYPE, PACKAGE, SOCKETS,VAL) VALUES (?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); stmt = con.createStatement(); ps.setString(1, rec_num); .0+ ps.setString(2, tester_num); ps.setString(3, t_date); ps.setString(4, t_time); ps.setString(5, sys_type); ps.setString(6, packages); ps.setString(7, sockets); ps.setString(8, val); ps.executeUpdate(); } catch (SQLException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } finally { try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(ps != null) ps.close(); if(con != null) con.close(); } catch (SQLException e) {} } return(true); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request,response); //String url = request.getRequestURI(); //System.out.println(url); } } </code></pre>
[ { "answer_id": 323587, "author": "carson", "author_id": 25343, "author_profile": "https://Stackoverflow.com/users/25343", "pm_score": 2, "selected": false, "text": "JSP JSP test.jsp?q=userinput\n JSP request.getParameter('userinput');\n JSP preparedStatement PreparedStatement ps = connection.prepareStatement(\"select * from fus where tester_num like ?\");\nps.setString(1, \"%\" + request.getParameter('userinput') + \"%\");\nResultSet resultSet = ps.executeQuery();\n" }, { "answer_id": 334636, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<sql:query var=\"rows\" >\n select * from fus where tester_num like ?\n <sql:param value=\"${param.user_input}\" />\n</sql:query>\n\n<table>\n <c:forEach var=\"row\" items=\"${rows}\">\n <tr>\n <td>${row.column1name}</td>\n <td>${row.column2name}</td>\n <td>${row.column3name}</td>\n </tr>\n </c:forEach>\n</table>\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
323,572
<p>I have the following route defined</p> <pre><code> routes.MapRoute( "ItemName", "{controller}/{action}/{projectName}/{name}", new { controller = "Home", action = "Index", name = "", projectName = "" } ); </code></pre> <p>This route actually works, so if I type in the browser</p> <pre><code>/Milestone/Edit/Co-Driver/Feature complete </code></pre> <p>It correctly goes to the Milestone controller, the edit action and passes the values.</p> <p>However, if I try and construct the link in the view with a url.action - </p> <pre><code>&lt;%=Url.Action("Edit", "Milestone", new {name=m.name, projectName=m.Project.title})%&gt; </code></pre> <p>I get the following url</p> <pre><code>Milestone/Edit?name=Feature complete&amp;projectName=Co-Driver </code></pre> <p>It still works, but isn't very clean. Any ideas?</p>
[ { "answer_id": 324537, "author": "idursun", "author_id": 5984, "author_profile": "https://Stackoverflow.com/users/5984", "pm_score": 0, "selected": false, "text": "Html.RouteLink(\"Edit\",\"ItemName\", new {name=m.name, projectName=m.Project.title});\n" }, { "answer_id": 324557, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 4, "selected": true, "text": "\"{controller}/{action}/{id}\"\n\"{controller}/{action}/{projectName}/{name}\"\n routes.MapRoute(\n \"ItemName\",\n \"Home/{action}/{projectName}/{name}\",\n new { controller = \"Home\", action = \"Index\", name = \"\", projectName = \"\" }\n);\n" }, { "answer_id": 325437, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 1, "selected": false, "text": "<%=Html.RouteLink(\"Edit\", \"ItemName\", new { projectName=m.Project.title, name=m.name, controller=\"Milestone\", action=\"Edit\"})%>\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193/" ]
323,585
<p>I'm using WCF and want to upload a large file from the client to the server. I have investigated and decided to follow the chunking approach outlined at <a href="http://msdn.microsoft.com/en-us/library/aa717050.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa717050.aspx</a></p> <p>However, this approach (just like streaming) restricts the contract to limited method signitures:</p> <pre><code>[OperationContract(IsOneWay=true)] [ChunkingBehavior(ChunkingAppliesTo.InMessage)] void UploadStream(Stream stream); </code></pre> <p>The sample uses the rather convenient example of uploading a file from a fixed path and saving it to a fixed path on the server. Therefore, my question is how do I pass additional parameters to specify things like filename, filepath etc.</p> <p>eg. I would like something like:</p> <pre><code>[OperationContract(IsOneWay=true)] [ChunkingBehavior(ChunkingAppliesTo.InMessage)] void UploadStream(Stream stream, String filePath); </code></pre> <p>Thanks in advance, Mark.</p>
[ { "answer_id": 323666, "author": "JacobE", "author_id": 30056, "author_profile": "https://Stackoverflow.com/users/30056", "pm_score": 2, "selected": false, "text": "[OperationContract(IsInitiating = true)]\nvoid InitializeUploadService(string filename);\n\n[OperationContract(IsOneWay = true, IsInitiating = false)]\n[ChunkingBehavior(ChunkingAppliesTo.InMessage)]\nvoid UploadStream(Stream stream);\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,599
<p>I haven't played with CSS for too long a time and am without references at the moment. My question should be fairly easy but googling isn't bringing up a sufficient answer. So, adding to the collective knowledge...</p> <pre><code>|#header---------------------------------------------------------------| | TITLE | |#sub-title------------------------------------------------------------| |bread &gt; crumb | username logout | |#sub-left | #sub-right| |---------------------------------|------------------------------------| </code></pre> <p>That's what I'm wanting my layout to be. The heading anyways. I wanted sub-title to contain sub-left AND sub-right. What css rules do I use to ensure a div is bound by the attributes of another div. In this case, how do I ensure that sub-left and sub-right stay within sub-title? </p>
[ { "answer_id": 323617, "author": "Jack Ryan", "author_id": 28882, "author_profile": "https://Stackoverflow.com/users/28882", "pm_score": -1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n <head>\n <style>\n #container\n {\n width:600px;\n }\n\n #head, #sub-title\n {\n width:100%;\n }\n\n #sub-left, #sub-right\n {\n width:50%;\n float:left;\n }\n\n </style>\n </head>\n\n <body>\n <div id=\"container\">\n <div id=\"head\">\n #head\n </div>\n <div id=\"sub-title\">\n #sub-title\n <div id=\"sub-left\">\n #sub-left\n </div>\n\n <div id=\"sub-right\">\n #sub-right\n </div>\n </div>\n </div>\n </body>\n</html>\n" }, { "answer_id": 323639, "author": "csexton", "author_id": 19839, "author_profile": "https://Stackoverflow.com/users/19839", "pm_score": 3, "selected": false, "text": "<html>\n <head>\n <style type=\"text/css\">\n #header {\n text-align: center;\n }\n #wrapper {\n margin:0 auto;\n width:600px;\n }\n #submain {\n margin:0 auto;\n width:600px;\n }\n #sub-left {\n float:left;\n width:300px;\n }\n #sub-right {\n float:right;\n width:240px;\n text-align: right;\n }\n </style>\n\n </head>\n <body>\n <div id=\"wrapper\">\n <div id=\"header\"><h1>Head</h1></div>\n <div id=\"sub-main\">\n <div id=\"sub-left\">\n Right\n </div>\n <div id=\"sub-right\">\n Left\n </div>\n </div>\n </div>\n </body>\n</html>\n" }, { "answer_id": 323659, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 5, "selected": false, "text": "sub-left sub-right sub-title style = \"clear: both\" <div id=\"sub-title\">\n <div id=\"sub-left\">\n sub-left\n </div>\n <div id=\"sub-right\">\n sub-right\n </div>\n <div class=\"clear-both\"></div>\n</div>\n #sub-left {\n float: left;\n}\n#sub-right {\n float: right;\n}\n.clear-both {\n clear: both;\n}\n" }, { "answer_id": 323694, "author": "James Piggot", "author_id": 28213, "author_profile": "https://Stackoverflow.com/users/28213", "pm_score": 3, "selected": false, "text": "#sub_close {clear:both;}\n <div id=\"sub-title\">\n<div id=\"sub-left\">Right</div>\n<div id=\"sub-right\">Left</div>\n<div id=\"sub-close\"></div>\n</div>\n" }, { "answer_id": 324553, "author": "Darko", "author_id": 32943, "author_profile": "https://Stackoverflow.com/users/32943", "pm_score": 7, "selected": true, "text": "clear:both overflow:hidden #sub-title { overflow:hidden; }\n" }, { "answer_id": 326920, "author": "Justin Lucente", "author_id": 35773, "author_profile": "https://Stackoverflow.com/users/35773", "pm_score": 3, "selected": false, "text": "#sub-title { overflow:hidden; zoom: 1; }\n" }, { "answer_id": 4281377, "author": "Tim Black", "author_id": 520270, "author_profile": "https://Stackoverflow.com/users/520270", "pm_score": -1, "selected": false, "text": "<table>\n <tr>\n <td colspan=\"2\">TITLE</td>\n </tr>\n <tr>\n <td>subleft</td><td>subright</td>\n </tr>\n</table>\n" }, { "answer_id": 12225734, "author": "kongaraju", "author_id": 1307915, "author_profile": "https://Stackoverflow.com/users/1307915", "pm_score": 0, "selected": false, "text": "#subtitle{\n/*for webkit browsers*/\n display:-webkit-box;\n -webkit-box-align:center;\n -webkit-box-pack: center;\n width:100%;\n}\n\n#subleft,#subright{\n width:50%;\n}\n" }, { "answer_id": 22029092, "author": "Kevin", "author_id": 1144724, "author_profile": "https://Stackoverflow.com/users/1144724", "pm_score": -1, "selected": false, "text": "#sub-left, #sub-right\n{\n display: inline-block;\n}\n" }, { "answer_id": 28447114, "author": "Razan Paul", "author_id": 1037073, "author_profile": "https://Stackoverflow.com/users/1037073", "pm_score": -1, "selected": false, "text": "<div class=\"container\"> \n <div class=\"row\">\n <div class=\"col-sm-6\" style=\"background-color:lavender;\">\n Div1 \n </div>\n <div class=\"col-sm-6\" style=\"background-color:lavenderblush;\">\n Div2\n </div>\n </div>\n</div>\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
323,604
<p>When designing a file format for recording binary data, what attributes would you think the format should have? So far, I've come up with the following important points:</p> <ul> <li>have some "magic bytes" at the beginning, to be able to recognize the files (in my specific case, this should also help to distinguish the files from "legacy" files)</li> <li>have a file version number at the beginning, so that the file format can be changed later without breaking compatibility</li> <li>specify the endianness and size of all data items; or: include some space to describe endianness/size of data (I would tend towards the former)</li> <li>possibly reserve some space for further per-file attributes that might be necessary in the future?</li> </ul> <p>What else would be useful to make the format more future-proof and minimize headache in the future?</p>
[ { "answer_id": 323660, "author": "atzz", "author_id": 23252, "author_profile": "https://Stackoverflow.com/users/23252", "pm_score": 4, "selected": false, "text": "1 byte = record type\n3 bytes = record length\nfollowed by record content\n" }, { "answer_id": 323785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "magic number/file id\nversion\ntag for first data entry\npointer to first data entry --------+\ntag for second data entry |\npointer to second data entry |\n... |\nlength of first data entry <--------+\nvalue for first data entry\n...\n" }, { "answer_id": 19759949, "author": "Kevin Cox", "author_id": 1166181, "author_profile": "https://Stackoverflow.com/users/1166181", "pm_score": 3, "selected": false, "text": "zcat | strings zcat" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ]
323,608
<p>Can anyone please help me to get all the domains in Active Directory. I have tried many times, but all the programs are listing only the current working domain. </p> <p>How can I do this?</p>
[ { "answer_id": 324416, "author": "LeeMobile", "author_id": 26861, "author_profile": "https://Stackoverflow.com/users/26861", "pm_score": 3, "selected": false, "text": "Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, \"yourDomain\", \"username\", \"password\"));\n\nForest forest = domain.Forest;\n\nDomainCollection domains = forest.Domains;\n" }, { "answer_id": 6146659, "author": "Paul", "author_id": 454600, "author_profile": "https://Stackoverflow.com/users/454600", "pm_score": 3, "selected": false, "text": "Forest forest = Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest, \"yourForestDomain\", \"username\", \"password\"));\nDomainCollection domains = forest.Domains;\n" }, { "answer_id": 38088376, "author": "kotpal", "author_id": 2183503, "author_profile": "https://Stackoverflow.com/users/2183503", "pm_score": 0, "selected": false, "text": "var domains = Forest.GetCurrentForest().Domains.Cast<Domain>();\nforeach (var domain in domains)\n{\n Console.WriteLine(domain.Name);\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/201406/" ]
323,613
<p>This is more of an academic inquiry than a practical question. Are there any language or framework features that can, or will in future, allow a heterogeneous typed dcitionary, e.g. </p> <pre><code>myDict.Add("Name", "Bill"); myDict.Add("Height", 1.2); </code></pre> <p>where myDict now contains not two <code>object</code> types as values, but one <code>string</code> and one <code>double</code>? I could then retrieve my <code>double</code> with </p> <pre><code>double dbl = myDict["Height"]; </code></pre> <p>and expect a double or an exception to be thrown?</p> <p>Please note: The Name and Height values are not necessarily of the same object.</p>
[ { "answer_id": 323628, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 1, "selected": false, "text": "Dictionary<object, object>" }, { "answer_id": 323661, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "Dictionary<string,object> object double dbl = (double)myDict[\"Height\"];\nobject height = myDict[\"Height\"];\n" }, { "answer_id": 323712, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 1, "selected": false, "text": "public class CustomDictionary : Dictionary<string,object>\n{\n public T GetTyped<T>(string key) where T : IConvertible\n {\n return (T)Convert.ChangeType(base[key], typeof (T));\n }\n}\n CustomDictionary dictionary = new CustomDictionary();\n\ndictionary.Add(\"Test\",1.2);\n\nvar d = dictionary.GetTyped<double>(\"Test\");\n" }, { "answer_id": 323714, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 5, "selected": true, "text": "sealed class MyDictionaryKey<T>\n{\n}\n\nclass MyDictionary\n{\n private Dictionary<object, object> dictionary = new Dictionary<object, object>();\n\n public void Add<T>(MyDictionaryKey<T> key, T value)\n {\n dictionary.Add(key, value);\n }\n\n public bool TryGetValue<T>(MyDictionaryKey<T> key, out T value)\n {\n object objValue;\n if (dictionary.TryGetValue(key, out objValue))\n {\n value = (T)objValue;\n return true;\n }\n value = default(T);\n return false;\n }\n\n public T Get<T>(MyDictionaryKey<T> key)\n {\n T value;\n if (!TryGetValue(key, out value))\n throw new KeyNotFoundException();\n return value;\n }\n}\n static readonly MyDictionaryKey<string> NameKey = new MyDictionaryKey<string>();\nstatic readonly MyDictionaryKey<double> HeightKey = new MyDictionaryKey<double>();\n var myDict = new MyDictionary();\nmyDict.Add(NameKey, \"Bill\"); // this will take a string\nmyDict.Add(HeightKey , 1.2); // this will take a double\n\nstring name = myDict.Get(NameKey); // will return a string\ndouble height = myDict.Get(HeightKey); // will return a double\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
323,640
<p>In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.</p> <p>If this code:</p> <pre><code>Console.WriteLine(someString); </code></pre> <p>produces:</p> <pre><code>Hello World! </code></pre> <p>I want this code:</p> <pre><code>Console.WriteLine(ToLiteral(someString)); </code></pre> <p>to produce:</p> <pre><code>\tHello\r\n\tWorld!\r\n </code></pre>
[ { "answer_id": 323670, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 5, "selected": false, "text": "string char public class ReplaceString\n{\n static readonly IDictionary<string, string> m_replaceDict\n = new Dictionary<string, string>();\n\n const string ms_regexEscapes = @\"[\\a\\b\\f\\n\\r\\t\\v\\\\\"\"]\";\n\n public static string StringLiteral(string i_string)\n {\n return Regex.Replace(i_string, ms_regexEscapes, match);\n }\n\n public static string CharLiteral(char c)\n {\n return c == '\\'' ? @\"'\\''\" : string.Format(\"'{0}'\", c);\n }\n\n private static string match(Match m)\n {\n string match = m.ToString();\n if (m_replaceDict.ContainsKey(match))\n {\n return m_replaceDict[match];\n }\n\n throw new NotSupportedException();\n }\n\n static ReplaceString()\n {\n m_replaceDict.Add(\"\\a\", @\"\\a\");\n m_replaceDict.Add(\"\\b\", @\"\\b\");\n m_replaceDict.Add(\"\\f\", @\"\\f\");\n m_replaceDict.Add(\"\\n\", @\"\\n\");\n m_replaceDict.Add(\"\\r\", @\"\\r\");\n m_replaceDict.Add(\"\\t\", @\"\\t\");\n m_replaceDict.Add(\"\\v\", @\"\\v\");\n\n m_replaceDict.Add(\"\\\\\", @\"\\\\\");\n m_replaceDict.Add(\"\\0\", @\"\\0\");\n\n //The SO parser gets fooled by the verbatim version\n //of the string to replace - @\"\\\"\"\"\n //so use the 'regular' version\n m_replaceDict.Add(\"\\\"\", \"\\\\\\\"\");\n }\n\n static void Main(string[] args){\n\n string s = \"here's a \\\"\\n\\tstring\\\" to test\";\n Console.WriteLine(ReplaceString.StringLiteral(s));\n Console.WriteLine(ReplaceString.CharLiteral('c'));\n Console.WriteLine(ReplaceString.CharLiteral('\\''));\n\n }\n}\n" }, { "answer_id": 323927, "author": "rfgamaral", "author_id": 40480, "author_profile": "https://Stackoverflow.com/users/40480", "pm_score": -1, "selected": false, "text": "string someString1 = \"\\tHello\\r\\n\\tWorld!\\r\\n\";\nstring someString2 = @\"\\tHello\\r\\n\\tWorld!\\r\\n\";\n\nConsole.WriteLine(someString1);\nConsole.WriteLine(someString2);\n Hello\n World!\n\n\\tHello\\r\\n\\tWorld!\\r\\n\n" }, { "answer_id": 324109, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 4, "selected": false, "text": "public static class StringHelpers\n{\n private static Dictionary<string, string> escapeMapping = new Dictionary<string, string>()\n {\n {\"\\\"\", @\"\\\\\\\"\"\"},\n {\"\\\\\\\\\", @\"\\\\\"},\n {\"\\a\", @\"\\a\"},\n {\"\\b\", @\"\\b\"},\n {\"\\f\", @\"\\f\"},\n {\"\\n\", @\"\\n\"},\n {\"\\r\", @\"\\r\"},\n {\"\\t\", @\"\\t\"},\n {\"\\v\", @\"\\v\"},\n {\"\\0\", @\"\\0\"},\n };\n\n private static Regex escapeRegex = new Regex(string.Join(\"|\", escapeMapping.Keys.ToArray()));\n\n public static string Escape(this string s)\n {\n return escapeRegex.Replace(s, EscapeMatchEval);\n }\n\n private static string EscapeMatchEval(Match m)\n {\n if (escapeMapping.ContainsKey(m.Value))\n {\n return escapeMapping[m.Value];\n }\n return escapeMapping[Regex.Escape(m.Value)];\n }\n}\n" }, { "answer_id": 324812, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 8, "selected": false, "text": "private static string ToLiteral(string input)\n{\n using (var writer = new StringWriter())\n {\n using (var provider = CodeDomProvider.CreateProvider(\"CSharp\"))\n {\n provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);\n return writer.ToString();\n }\n }\n}\n var input = \"\\tHello\\r\\n\\tWorld!\";\nConsole.WriteLine(input);\nConsole.WriteLine(ToLiteral(input));\n Hello\n World!\n\"\\tHello\\r\\n\\tWorld!\"\n private static string ToLiteral(string valueTextForCompiler)\n{\n return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);\n}\n" }, { "answer_id": 9532232, "author": "Arsen Zahray", "author_id": 847200, "author_profile": "https://Stackoverflow.com/users/847200", "pm_score": 4, "selected": false, "text": "var t = HttpUtility.JavaScriptStringEncode(s);\n" }, { "answer_id": 14087738, "author": "Smilediver", "author_id": 254101, "author_profile": "https://Stackoverflow.com/users/254101", "pm_score": 5, "selected": false, "text": "static string ToLiteral(string input) {\n StringBuilder literal = new StringBuilder(input.Length + 2);\n literal.Append(\"\\\"\");\n foreach (var c in input) {\n switch (c) {\n case '\\\"': literal.Append(\"\\\\\\\"\"); break;\n case '\\\\': literal.Append(@\"\\\\\"); break;\n case '\\0': literal.Append(@\"\\0\"); break;\n case '\\a': literal.Append(@\"\\a\"); break;\n case '\\b': literal.Append(@\"\\b\"); break;\n case '\\f': literal.Append(@\"\\f\"); break;\n case '\\n': literal.Append(@\"\\n\"); break;\n case '\\r': literal.Append(@\"\\r\"); break;\n case '\\t': literal.Append(@\"\\t\"); break;\n case '\\v': literal.Append(@\"\\v\"); break;\n default:\n // ASCII printable character\n if (c >= 0x20 && c <= 0x7e) {\n literal.Append(c);\n // As UTF16 escaped character\n } else {\n literal.Append(@\"\\u\");\n literal.Append(((int)c).ToString(\"x4\"));\n }\n break;\n }\n }\n literal.Append(\"\\\"\");\n return literal.ToString();\n}\n // UTF16 control characters\n} else if (Char.GetUnicodeCategory(c) == UnicodeCategory.Control) {\n literal.Append(@\"\\u\");\n literal.Append(((int)c).ToString(\"x4\"));\n} else {\n literal.Append(c);\n}\n" }, { "answer_id": 14502246, "author": "deerchao", "author_id": 119561, "author_profile": "https://Stackoverflow.com/users/119561", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Globalization;\nusing System.Text;\n\npublic static class CodeHelper\n{\n public static string ToLiteral(this string input)\n {\n var literal = new StringBuilder(input.Length + 2);\n literal.Append(\"\\\"\");\n foreach (var c in input)\n {\n switch (c)\n {\n case '\\'': literal.Append(@\"\\'\"); break;\n case '\\\"': literal.Append(\"\\\\\\\"\"); break;\n case '\\\\': literal.Append(@\"\\\\\"); break;\n case '\\0': literal.Append(@\"\\0\"); break;\n case '\\a': literal.Append(@\"\\a\"); break;\n case '\\b': literal.Append(@\"\\b\"); break;\n case '\\f': literal.Append(@\"\\f\"); break;\n case '\\n': literal.Append(@\"\\n\"); break;\n case '\\r': literal.Append(@\"\\r\"); break;\n case '\\t': literal.Append(@\"\\t\"); break;\n case '\\v': literal.Append(@\"\\v\"); break;\n default:\n if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)\n {\n literal.Append(c);\n }\n else\n {\n literal.Append(@\"\\u\");\n literal.Append(((ushort)c).ToString(\"x4\"));\n }\n break;\n }\n }\n literal.Append(\"\\\"\");\n return literal.ToString();\n }\n}\n" }, { "answer_id": 14719643, "author": "lesur", "author_id": 1775993, "author_profile": "https://Stackoverflow.com/users/1775993", "pm_score": 4, "selected": false, "text": "private static string ToLiteral(string input)\n{\n using (var writer = new StringWriter())\n {\n using (var provider = CodeDomProvider.CreateProvider(\"CSharp\"))\n {\n provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions {IndentString = \"\\t\"});\n var literal = writer.ToString();\n literal = literal.Replace(string.Format(\"\\\" +{0}\\t\\\"\", Environment.NewLine), \"\");\n return literal;\n }\n }\n}\n" }, { "answer_id": 16906723, "author": "J Cracknell", "author_id": 927318, "author_profile": "https://Stackoverflow.com/users/927318", "pm_score": -1, "selected": false, "text": "null switch using System;\nusing System.Text;\nusing System.Linq;\n\npublic static class StringLiteralEncoding {\n private static readonly char[] HEX_DIGIT_LOWER = \"0123456789abcdef\".ToCharArray();\n private static readonly char[] LITERALENCODE_ESCAPE_CHARS;\n\n static StringLiteralEncoding() {\n // Per http://msdn.microsoft.com/en-us/library/h21280bw.aspx\n var escapes = new string[] { \"\\aa\", \"\\bb\", \"\\ff\", \"\\nn\", \"\\rr\", \"\\tt\", \"\\vv\", \"\\\"\\\"\", \"\\\\\\\\\", \"??\", \"\\00\" };\n LITERALENCODE_ESCAPE_CHARS = new char[escapes.Max(e => e[0]) + 1];\n foreach(var escape in escapes)\n LITERALENCODE_ESCAPE_CHARS[escape[0]] = escape[1];\n }\n\n /// <summary>\n /// Convert the string to the equivalent C# string literal, enclosing the string in double quotes and inserting\n /// escape sequences as necessary.\n /// </summary>\n /// <param name=\"s\">The string to be converted to a C# string literal.</param>\n /// <returns><paramref name=\"s\"/> represented as a C# string literal.</returns>\n public static string Encode(string s) {\n if(null == s) return \"null\";\n\n var sb = new StringBuilder(s.Length + 2).Append('\"');\n for(var rp = 0; rp < s.Length; rp++) {\n var c = s[rp];\n if(c < LITERALENCODE_ESCAPE_CHARS.Length && '\\0' != LITERALENCODE_ESCAPE_CHARS[c])\n sb.Append('\\\\').Append(LITERALENCODE_ESCAPE_CHARS[c]);\n else if('~' >= c && c >= ' ')\n sb.Append(c);\n else\n sb.Append(@\"\\x\")\n .Append(HEX_DIGIT_LOWER[c >> 12 & 0x0F])\n .Append(HEX_DIGIT_LOWER[c >> 8 & 0x0F])\n .Append(HEX_DIGIT_LOWER[c >> 4 & 0x0F])\n .Append(HEX_DIGIT_LOWER[c & 0x0F]);\n }\n\n return sb.Append('\"').ToString();\n }\n}\n" }, { "answer_id": 41934438, "author": "Serge N", "author_id": 6831114, "author_profile": "https://Stackoverflow.com/users/6831114", "pm_score": 2, "selected": false, "text": "public static class StringEscape\n{\n static char[] toEscape = \"\\0\\x1\\x2\\x3\\x4\\x5\\x6\\a\\b\\t\\n\\v\\f\\r\\xe\\xf\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\\"\\\\\".ToCharArray();\n static string[] literals = @\"\\0,\\x0001,\\x0002,\\x0003,\\x0004,\\x0005,\\x0006,\\a,\\b,\\t,\\n,\\v,\\f,\\r,\\x000e,\\x000f,\\x0010,\\x0011,\\x0012,\\x0013,\\x0014,\\x0015,\\x0016,\\x0017,\\x0018,\\x0019,\\x001a,\\x001b,\\x001c,\\x001d,\\x001e,\\x001f\".Split(new char[] { ',' });\n\n public static string Escape(this string input)\n {\n int i = input.IndexOfAny(toEscape);\n if (i < 0) return input;\n\n var sb = new System.Text.StringBuilder(input.Length + 5);\n int j = 0;\n do\n {\n sb.Append(input, j, i - j);\n var c = input[i];\n if (c < 0x20) sb.Append(literals[c]); else sb.Append(@\"\\\").Append(c);\n } while ((i = input.IndexOfAny(toEscape, j = ++i)) > 0);\n\n return sb.Append(input, j, input.Length - j).ToString();\n }\n}\n" }, { "answer_id": 47073944, "author": "Derek", "author_id": 635195, "author_profile": "https://Stackoverflow.com/users/635195", "pm_score": 2, "selected": false, "text": "private static string ToLiteral(string input)\n{\n using (var writer = new StringWriter())\n {\n using (var provider = CodeDomProvider.CreateProvider(\"CSharp\"))\n {\n provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions { IndentString = \"\\t\" });\n var literal = writer.ToString();\n literal = literal.Replace(string.Format(\"\\\" +{0}\\t\\\"\", Environment.NewLine), \"\");\n return literal;\n }\n }\n}\n\nprivate static string ToVerbatim(string input)\n{\n string literal = ToLiteral(input);\n string verbatim = \"@\" + literal.Replace(@\"\\r\\n\", Environment.NewLine);\n return verbatim;\n}\n" }, { "answer_id": 54512065, "author": "Ehsan88", "author_id": 2571422, "author_profile": "https://Stackoverflow.com/users/2571422", "pm_score": 2, "selected": false, "text": "Newtonsoft.Json using System;\nusing Newtonsoft.Json;\n\npublic class Program\n{\n public static void Main()\n {\n Console.WriteLine(ToLiteral(@\"abc\\n123\"));\n }\n\n private static string ToLiteral(string input)\n {\n return JsonConvert.DeserializeObject<string>(\"\\\"\" + input + \"\\\"\");\n }\n}\n" }, { "answer_id": 54753974, "author": "Alexander Yoshi", "author_id": 498805, "author_profile": "https://Stackoverflow.com/users/498805", "pm_score": 1, "selected": false, "text": " provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);\n var literal = writer.ToString();\n var r2 = new Regex(@\"\\\"\" \\+.\\n[\\s]+\\\"\"\", RegexOptions.ECMAScript);\n literal = r2.Replace(literal, \"\");\n return literal;\n" }, { "answer_id": 58825732, "author": "Graham", "author_id": 1128762, "author_profile": "https://Stackoverflow.com/users/1128762", "pm_score": 6, "selected": true, "text": "private static string ToLiteral(string valueTextForCompiler)\n{\n return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15454/" ]
323,650
<p>I have this code</p> <pre><code>while($row = mysql_fetch_row($result)) { echo '&lt;tr&gt;'; $pk = $row[0]['ARTICLE_NO']; foreach($row as $key =&gt; $value) { echo '&lt;td&gt;&lt;a href="#" onclick="GetAuctionData(\''.$pk.'\')"&gt;' . $value . '&lt;/a&gt;&lt;/td&gt;'; } </code></pre> <p>which gets pk. pk is then passed on to the axjax part with this:</p> <pre><code>function GetAuctionData(pk) { ..... var url="get_auction.php?" url=url+"cmd=GetAuctionData&amp;pk="+pk; </code></pre> <p>And finally used in a separate php file with:</p> <pre><code>$pk = $_GET["pk"]; $sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'"; </code></pre> <p>the second php file works fine when using it by itself and passing parameters. Likewise there are no errors anywhere. The problem seems to be with passing or generating $pk, as the links in the output file result in $pk being incremednted by 2, eg 4, 6, 8 etc</p> <p>I can not understand why this is happening.</p>
[ { "answer_id": 323676, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "$pk = $row[0]['ARTICLE_NO'];\n $pk = $row['ARTICLE_NO'];\n" }, { "answer_id": 323688, "author": "benlumley", "author_id": 39161, "author_profile": "https://Stackoverflow.com/users/39161", "pm_score": 1, "selected": false, "text": "mysql_fetch_assoc // return $article['ARTICLE_NO'], $article['otherfield'] etc\n\nmysql_fetch_array // returns an array that is effectively the above two array_merge'd\nmysql_fetch_object // returns a stdclass object, as if mysql_fetch_assoc had been passed to get_object_vars()\n" }, { "answer_id": 323695, "author": "OIS", "author_id": 36175, "author_profile": "https://Stackoverflow.com/users/36175", "pm_score": 4, "selected": true, "text": "$pk = $row[0];\n while($row = mysql_fetch_assoc($result))\n$pk = $row['ARTICLE_NO'];\n while($row = mysql_fetch_array($result, MYSQL_BOTH))\n$pk = $row['ARTICLE_NO'];\n $result = mysql_query(\"SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}\");\n $result = mysql_query(\"ARTICLE_NO, SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}\");\n while($row = mysql_fetch_assoc($result))\n{\n $pk = $row['ARTICLE_NO'];\n echo '<td><a href=\"#\" onclick=\"GetAuctionData(\\''.$pk.'\\')\">' . $row['ARTICLE_NAME'] . '</a></td>';\n}\n" }, { "answer_id": 323835, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "while($row = mysql_fetch_row($result))\n{\n echo '<tr>';\n $pk = $row[0]['ARTICLE_NO'];\n\n foreach($row as $key => $value)\n {\n echo '<td><a href=\"#\" onclick=\"GetAuctionData(\\''.$pk.'\\')\">' . $value . '</a></td>';\n }\n}\n $pk = $row[0]['ARTICLE_NO'];\nvar_dump($pk);\n $pk = $row[0]['ARTICLE_NO'];\nvar_dump($row);\n array(2) {\n [0]=> string(2) \"12\"\n [1]=> string(7) \"myValue\"\n}\n $pk = $row[0];\n var_dump() print_r()" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
323,653
<p>I need to monitor number of the facebook group users and display it on the website. I know that it is possible to get User IDs using their API, but they are limited to 500 only (if the total number of members is 500+). </p> <p>What would be the easiest way to get total number of members that signed up to a Facebook Group that I'd set up? Is this at all possible?</p>
[ { "answer_id": 488092, "author": "rfunduk", "author_id": 210, "author_profile": "https://Stackoverflow.com/users/210", "pm_score": 0, "selected": false, "text": "Groups.getMembers" }, { "answer_id": 8371927, "author": "Madarco", "author_id": 108117, "author_profile": "https://Stackoverflow.com/users/108117", "pm_score": 2, "selected": false, "text": "SELECT uid FROM group_member WHERE gid = <group_id> limit 500\nSELECT uid FROM group_member WHERE gid = <group_id> limit 500 offset 500\nSELECT uid FROM group_member WHERE gid = <group_id> limit 500 offset 1000\n...\n perPage = 500\n for count in range(100):\n res = fql('SELECT uid FROM group_member WHERE gid = %s limit %d offset %d' % (fbUserId, perPage, perPage * count))\n if len(res) == 0:\n break\n friends += len(res)\n SELECT uid, name, pic_square FROM user WHERE uid IN ( \n SELECT uid FROM group_member WHERE gid = <group_id> limit 500 offset %d )\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,668
<p>The title is a bit abstract so maybe it is easier to explain with a specific example:</p> <p>I find it useful to have my exception classes take an enum parameter instead of a string message. </p> <pre><code>throw new SpecificException(SpecificExceptionCode.ThisThingWentWrong); </code></pre> <p>There are few reasons for this, including:</p> <ul> <li>I can encapulate all the logic for accessing localized string resources in one place</li> <li>I can easily make sure I have string resources for all my exception messages</li> <li>Checking for correct exception messages in unit tests is simpler</li> </ul> <p>I would like to write a base class for this type of exception. Derived exception classes generally just want to provide their own System.Resources.ResourceManager but may also provide additional constructors. The trouble comes because I can only call static methods in calls to base class constructors. This leads me to something like:</p> <pre><code>public abstract class BaseException : ApplicationException { protected static ResourceManager m_resources; public BaseException(System.Enum errorCode, params object[] messageArgs) : base(ProcessError(errorCode, messageArgs)) {} private static string ProcessError(Enum errorCode, params object[] messageArgs) { string errorMessage = m_resources.GetString(errorCode.ToString()); // Handling of messageArgs and trace logging // .... return finalError; } } </code></pre> <p>and </p> <pre><code>public class SpecificException : BaseException { static SpecificException() { m_resources = //.. Get an appropriate resource manager instance } public SpecificException(SpecificExceptionCode errorCode, params object[] messageArgs) : base(errorCode, messageArgs) {} } </code></pre> <p>This works, but I am unhappy with it as there is no compile time hint that the derived class must provide its own <code>System.ResourceManager</code>. I would like to have a base class such as:</p> <pre><code>public abstract class BaseException : ApplicationException { protected abstract static ResourceManager Resources{get;} public BaseException(System.Enum errorCode, params object[] messageArgs) : base(ProcessError(errorCode, messageArgs)) {} private static string ProcessError(Enum errorCode, params object[] messageArgs) { string errorMessage = Resources.GetString(errorCode.ToString()); // Handling of messageArgs and trace logging // .... return finalError; } } </code></pre> <p>...but I cannot have an abstract static method. Is there a better way?</p>
[ { "answer_id": 323687, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 0, "selected": false, "text": "protected abstract static ResourceManager Resources{get;}\n private static ResourceManager resources = ....\n\nprotected override static ResourceManager Resources{get {return resources; }}\n" }, { "answer_id": 323692, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "public abstract class BaseException : ApplicationException\n{\n static ResourceManager defaultManager;\n static ResourceManager DefaultManager\n {\n get\n {\n if (defaultManager == null) defaultManager = TODO; // sensible default\n return defaultManager;\n }\n }\n\n public BaseException(System.Enum errorCode, params object[] messageArgs)\n : this(DefaultManager, errorCode, messageArgs) {}\n public BaseException(ResourceManager resourceManager, System.Enum errorCode, params object[] messageArgs)\n : base(ProcessError(resourceManager, errorCode, messageArgs))\n { }\n\n private static string ProcessError(ResourceManager resourceManager, Enum errorCode, params object[] messageArgs)\n {\n if (resourceManager == null) throw new ArgumentNullException(\"resourceManager\");\n string errorMessage = resourceManager.GetString(errorCode.ToString());\n // Handling of messageArgs and trace logging\n // ....\n return finalString;\n }\n}\n public class SpecificException : BaseException\n{\n static ResourceManager customManager;\n static SpecificException()\n {\n customManager = //TODO - init manager\n }\n public SpecificException(SomeEnum errorCode, params object[] messageArgs)\n : base(customManager, errorCode, messageArgs)\n { }\n}\n : base(errorCode, messageArgs)\n" }, { "answer_id": 323747, "author": "jageall", "author_id": 27036, "author_profile": "https://Stackoverflow.com/users/27036", "pm_score": 0, "selected": false, "text": "public static SpecificException SpecificExceptionCodeName()\n{\n //Do resource lookup and create Exception\n}\n throw ExceptionBuilder.SpecificExceptionCodeName();\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24770/" ]
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
[ { "answer_id": 323698, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 6, "selected": false, "text": "[:] # ================================================================\n# === ShallowCopy.py =============================================\n# ================================================================\n#\nclass Foo:\n def __init__(self, data):\n self._data = data\n\naa = Foo ('aaa')\nbb = Foo ('bbb')\n\n# The initial list has two elements containing 'aaa' and 'bbb'\nOldList = [aa,bb]\nprint OldList[0]._data\n\n# The shallow copy makes a new list pointing to the old elements\nNewList = OldList[:]\nprint NewList[0]._data\n\n# Updating one of the elements through the new list sees the\n# change reflected when you access that element through the\n# old list.\nNewList[0]._data = 'xxx'\nprint OldList[0]._data\n\n# Updating the new list to point to something new is not reflected\n# in the old list.\nNewList[0] = Foo ('ccc')\nprint NewList[0]._data\nprint OldList[0]._data\n >>> # ================================================================\n... # === ShallowCopy.py =============================================\n... # ================================================================\n... #\n... class Foo:\n... def __init__(self, data):\n... self._data = data\n...\n>>> aa = Foo ('aaa')\n>>> bb = Foo ('bbb')\n>>>\n>>> # The initial list has two elements containing 'aaa' and 'bbb'\n... OldList = [aa,bb]\n>>> print OldList[0]._data\naaa\n>>>\n>>> # The shallow copy makes a new list pointing to the old elements\n... NewList = OldList[:]\n>>> print NewList[0]._data\naaa\n>>>\n>>> # Updating one of the elements through the new list sees the\n... # change reflected when you access that element through the\n... # old list.\n... NewList[0]._data = 'xxx'\n>>> print OldList[0]._data\nxxx\n>>>\n>>> # Updating the new list to point to something new is not reflected\n... # in the old list.\n... NewList[0] = Foo ('ccc')\n>>> print NewList[0]._data\nccc\n>>> print OldList[0]._data\nxxx\n" }, { "answer_id": 323733, "author": "Deinumite", "author_id": 5219, "author_profile": "https://Stackoverflow.com/users/5219", "pm_score": 7, "selected": true, "text": "newList = oldList oldList newList newList = oldList[:] [:]" }, { "answer_id": 323800, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": ">>> a = [1, 2, 3, 4]\n>>> b = a\n>>> c = a[:]\n>>> b[2] = 10\n>>> c[3] = 20\n>>> a\n[1, 2, 10, 4]\n>>> b\n[1, 2, 10, 4]\n>>> c\n[1, 2, 3, 20]\n" }, { "answer_id": 323810, "author": "kaleissin", "author_id": 30368, "author_profile": "https://Stackoverflow.com/users/30368", "pm_score": 2, "selected": false, "text": "def myfunction(mylist=[]): \n pass\n" }, { "answer_id": 2220902, "author": "abhiomkar", "author_id": 235453, "author_profile": "https://Stackoverflow.com/users/235453", "pm_score": -1, "selected": false, "text": "a = ['one','two','three']\n\nb = a[:]\n\nb[1] = 2\n\nprint id(a), a #Output: 1077248300 ['one', 'two', 'three']\nprint id(b), b #Output: 1077248908 ['one', 2, 'three']\n a = ['one','two','three']\n\nb = a\n\nb[1] = 2\n\n\nprint id(a), a #Output: 1077248300 ['one', 2, 'three']\nprint id(b), b #Output: 1077248300 ['one', 2, 'three']\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
323,697
<p>I need to test a url that it <strong>does not</strong> end with <code>.asp</code></p> <p>So <code>test</code>, <code>test.html</code> and <code>test.aspx</code> should match, but <code>test.asp</code> should not match.</p> <p>Normally you'd test if the url <strong>does</strong> end with .asp and negate the fact that it matched using the NOT operator in code:</p> <pre><code>if(!regex.IsMatch(url)) { // Do something } </code></pre> <p>In that case the regular expression would be <code>\.asp$</code> but in this case I need the regular expression to result in a match. </p> <hr> <p>Background: I need to use the regular expression as a route contraint in the ASP.NET MVC <code>RouteCollection.MapRoute</code> extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp</p>
[ { "answer_id": 323723, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 2, "selected": false, "text": "^((?!\\.asp$).)*$\n" }, { "answer_id": 323756, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 6, "selected": true, "text": "(?<!\\.asp)$\n ^.*(?<!\\.asp)$\n ^[^#?]+(?<!\\.asp)([#?]|$)\n ^[^#?]+(?<!\\.asp)([#?].+|$)\n" }, { "answer_id": 323799, "author": "Ian G", "author_id": 31765, "author_profile": "https://Stackoverflow.com/users/31765", "pm_score": 2, "selected": false, "text": "string test1 = \"me.asp\" ;\nstring test2 = \"me.aspx\" ;\n\ntest1.EndsWith(\".asp\") // true;\ntest2.EndsWith(\".asp\") // false ;\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4830/" ]
323,704
<p>Does anyone know of a definitive list of LINQ to SQL query limitations that are not trapped at compile time, along with (where possible) workarounds for the limitations?</p> <p>The list we have so far is:</p> <ul> <li>Calling methods such as <code>.Date</code> on <code>DateTime</code> <ul> <li>no workaround found</li> </ul></li> <li><code>string.IsNullOrEmpty</code> <ul> <li>simple, just use <code>== ""</code> instead</li> </ul></li> <li><code>.Last()</code> <ul> <li>we used <code>.OrderByDescending(x =&gt; x.WhateverProperty).First()</code></li> </ul></li> </ul>
[ { "answer_id": 482956, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "DateTime BOTTOM n TOP 1 OrderByDescending string.IsNullOrEmpty foo.Bar == null || foo.Bar == \"\" DateTime.Date DATEPART datetime datetime where ctx.Date(foo.SomeDate) == DateTime.Today\n System.Data.Linq.SqlClient.PostBindDotNetConverter+Visitor Translate... string" }, { "answer_id": 483261, "author": "Zhaph - Ben Duguid", "author_id": 33051, "author_profile": "https://Stackoverflow.com/users/33051", "pm_score": 0, "selected": false, "text": "BlogPosts post = (from blogs in blogPosts\n where blogs.PostPath == path \n select blogs)\n .ToList()\n .Where(blogs => blogs.Published.Date == publishedDate.Date)\n .SingleOrDefault();\n BlogPosts posts = from blogs in blogPosts\n where !blogs.IsDraft\n && blogs.Published.Year == year\n && blogs.Published.Month == month\n orderby blogs.Published descending\n select blogs\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39709/" ]
323,741
<p>I have an existing ASP.NET 2.0 website, stored in Team Foundation Server 2005. Some of the pages/controls are encoded as ANSI (according to Notepad++) and the Content-Type header is set to:</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/&gt; </code></pre> <p>I would like to change all pages to UTF-8, and therefore the Content-Type header to:</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; </code></pre> <p>Other than changing the meta element, I assume I also need to change the encoding of all the files. I can do this in Notepad++ though if anyone has any quicker methods, please mention them.</p> <p><strong>What sort of problems might I face when it comes to merging/comparing in TFS?</strong></p>
[ { "answer_id": 323760, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "for fn in os.listdir(srcdir):\n data = open(srcdir+\"\\\\\"+fn, \"rb\").read().decode(\"windows-1252\")\n data = data.replace(\"charset=windows-1252\", \"charset=utf-8\")\n open(srcdir+\"\\\\\"+fn, \"wb\").write(data.encode(\"utf-8\"))\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124/" ]
323,742
<p>Which one would you use to draw stuff on a winform? Format32bppRgb or Format24bppRgb or something else?</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx" rel="nofollow noreferrer">in any .net version</a></p> <pre><code>Format24bppRgb Specifies that the format is 24 bits per pixel; 8 bits each are used for the red, green, and blue components. Format32bppRgb Specifies that the format is 32 bits per pixel; 8 bits each are used for the red, green, and blue components. The remaining 8 bits are not used. </code></pre>
[ { "answer_id": 323760, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 2, "selected": false, "text": "for fn in os.listdir(srcdir):\n data = open(srcdir+\"\\\\\"+fn, \"rb\").read().decode(\"windows-1252\")\n data = data.replace(\"charset=windows-1252\", \"charset=utf-8\")\n open(srcdir+\"\\\\\"+fn, \"wb\").write(data.encode(\"utf-8\"))\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40868/" ]
323,750
<p>Is there a way to access a <code>list</code>'s (or <code>tuple</code>'s, or other iterable's) next or previous element while looping through it with a <code>for</code> loop?</p> <pre><code>l = [1, 2, 3] for item in l: if item == 2: get_previous(l, item) </code></pre>
[ { "answer_id": 323802, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": -1, "selected": false, "text": "def get_previous(l, item):\n idx = l.find(item)\n return None if idx == 0 else l[idx-1]\n for idx in range(len(l)):\n item = l[idx]\n if item == 2:\n l[idx-1]\n" }, { "answer_id": 323827, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 1, "selected": false, "text": "for index, item in enumerate(l):\n if index > 0:\n previous_item = l[index - 1]\n else:\n previous_item = None \n enumerate()" }, { "answer_id": 323910, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": false, "text": "def neighborhood(iterable):\n iterator = iter(iterable)\n prev_item = None\n current_item = next(iterator) # throws StopIteration if empty.\n for next_item in iterator:\n yield (prev_item, current_item, next_item)\n prev_item = current_item\n current_item = next_item\n yield (prev_item, current_item, None)\n for prev,item,next in neighborhood(l):\n print prev, item, next\n" }, { "answer_id": 323911, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "import collections, itertools\n\ndef window(it, winsize, step=1):\n \"\"\"Sliding window iterator.\"\"\"\n it=iter(it) # Ensure we have an iterator\n l=collections.deque(itertools.islice(it, winsize))\n while 1: # Continue till StopIteration gets raised.\n yield tuple(l)\n for i in range(step):\n l.append(it.next())\n l.popleft()\n >>> list(window([1,2,3,4,5],3))\n[(1, 2, 3), (2, 3, 4), (3, 4, 5)]\n l= range(10)\n# Print adjacent numbers\nfor cur, next in window(l + [None] ,2):\n if next is None: print \"%d is the last number.\" % cur\n else: print \"%d is followed by %d\" % (cur,next)\n" }, { "answer_id": 324069, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "previous = None\nfor item in someList:\n if item == target: break\n previous = item\n# previous is the item before the target\n queue = []\nfor item in someList:\n if item == target: break\n queue .append( item )\n if len(queue ) > n: queue .pop(0)\nif len(queue ) < n: previous = None\nprevious = previous[0]\n# previous is *n* before the target\n" }, { "answer_id": 324273, "author": "Rudiger Wolf", "author_id": 41431, "author_profile": "https://Stackoverflow.com/users/41431", "pm_score": 4, "selected": false, "text": "l = [1, 2, 3]\nfor i, item in enumerate(l):\n if item == 2:\n previous = l[i - 1]\n print(previous)\n 1\n if item == 1: 3" }, { "answer_id": 325864, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 3, "selected": false, "text": "> easy_install Tempita\n> python\n>>> from tempita import looper\n>>> for loop, i in looper([1, 2, 3]):\n... print loop.previous, loop.item, loop.index, loop.next, loop.first, loop.last, loop.length, loop.odd, loop.even\n... \nNone 1 0 2 True False 3 True 0\n1 2 1 3 False False 3 False 1\n2 3 2 None False True 3 True 0\n" }, { "answer_id": 4672737, "author": "Emilio M Bumachar", "author_id": 174365, "author_profile": "https://Stackoverflow.com/users/174365", "pm_score": -1, "selected": false, "text": "l=[1,2,3]\nfor index in range(len(l)):\n if l[index]==2:\n l[index-1]\n" }, { "answer_id": 22030004, "author": "RattleyCooper", "author_id": 2930045, "author_profile": "https://Stackoverflow.com/users/2930045", "pm_score": 3, "selected": false, "text": "enumerate l = ['adam', 'rick', 'morty', 'adam', 'billy', 'bob', 'wally', 'bob', 'jerry']\n\nfor i, item in enumerate(l):\n if i == 0:\n previous_item = None\n else:\n previous_item = l[i - 1]\n\n if i == len(l) - 1:\n next_item = None\n else:\n next_item = l[i + 1]\n\n print('Previous Item:', previous_item)\n print('Item:', item)\n print('Next Item:', next_item)\n print('')\n\n pass\n" }, { "answer_id": 23531068, "author": "Vicky Liau", "author_id": 1539385, "author_profile": "https://Stackoverflow.com/users/1539385", "pm_score": 5, "selected": false, "text": "l = [1, 2, 3]\n\nfor i, j in zip(l, l[1:]):\n print(i, j)\n" }, { "answer_id": 41047005, "author": "Francisco", "author_id": 1192111, "author_profile": "https://Stackoverflow.com/users/1192111", "pm_score": 2, "selected": false, "text": "itertools itertools.tee() import itertools\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n" }, { "answer_id": 60964286, "author": "deeenes", "author_id": 854988, "author_profile": "https://Stackoverflow.com/users/854988", "pm_score": 1, "selected": false, "text": "import itertools\n\niter0, iter1 = itertools.tee(iterable)\n\nfor item, next_item in itertools.zip_longest(\n iter0,\n itertools.islice(iter1, 1, None)\n):\n\n do_something(item, next_item)\n next import itertools\n\niter0, iter1 = itertools.tee(iterable)\n_ = next(iter1)\n\nfor item, next_item in itertools.zip_longest(iter0, iter1):\n\n do_something(item, next_item)\n" }, { "answer_id": 69584524, "author": "kosciej16", "author_id": 3361462, "author_profile": "https://Stackoverflow.com/users/3361462", "pm_score": 1, "selected": false, "text": "import itertools\n\nl = [1,2,3]\nfor x, y in itertools.pairwise(l):\n print(x, y)\n# 1 2\n# 2 3\n" }, { "answer_id": 69729660, "author": "InhirCode", "author_id": 17254775, "author_profile": "https://Stackoverflow.com/users/17254775", "pm_score": 2, "selected": false, "text": "def previous():\n class Plusprev():\n def __init__(pp, gen=None):\n pp.g = gen\n pp.nxt = ''\n pp.prev = 'start'\n\n def ppnext(pp):\n while pp.nxt != 'done':\n pp.nxt = next(pp.g,'done')\n yield pp.nxt\n pp.prev = pp.nxt\n\n sqgen = (n*n for n in range(13))\n ppcl = Plusprev(sqgen)\n nxtg = ppcl.ppnext()\n nxt = next(nxtg,'done')\n while nxt != 'done':\n print('\\nprevious ',ppcl.prev)\n print('current ',nxt)\n nxt = next(nxtg,'done')\n\nprevious()\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
323,763
<p>I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app?</p> <p>In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things):</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=255) </code></pre> <p>and in profiles/models.py I want to have:</p> <pre><code>class MovieProperty(models.Model): movie = models.ForeignKey(Movie) </code></pre> <p>But I can't get it to work. I've tried:</p> <pre><code> movie = models.ForeignKey(cf.Movie) </code></pre> <p>and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as:</p> <pre><code>NameError: name 'User' is not defined </code></pre> <p>Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?</p>
[ { "answer_id": 323900, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": 3, "selected": false, "text": "import from prototype.cf.models import Movie\n .models" }, { "answer_id": 323905, "author": "Michael Warkentin", "author_id": 422277, "author_profile": "https://Stackoverflow.com/users/422277", "pm_score": 8, "selected": true, "text": "class Car(models.Model):\n manufacturer = models.ForeignKey('production.Manufacturer')\n" }, { "answer_id": 32869639, "author": "andorov", "author_id": 1396904, "author_profile": "https://Stackoverflow.com/users/1396904", "pm_score": 5, "selected": false, "text": "from django.db import models\nfrom production import models as production_models\n\nclass Car(models.Model):\n manufacturer = models.ForeignKey(production_models.Manufacturer)\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11522/" ]
323,782
<p>It' possible to use Junitperf with junit4? I've a simplet Junit4 test class with several tests and I want to do a TimedTest on single test of that class. How can I do that?</p> <p>To be more clear my Junit4 class is something like:</p> <pre><code>public class TestCitta { @Test public void test1 {} @Test public void test2 {} } </code></pre> <p>with junit3 i shold write something like:</p> <pre><code>public class TestCittaPerformance { public static final long toleranceInMillis = 100; public static Test suite() { long maxElapsedTimeInMillis = 1000 + toleranceInMillis; Test testCase = new TestCitta("test2"); Test timedTest = new TimedTest(testCase, maxElapsedTimeInMillis); return timedTest; } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } </code></pre> <p>with Junit4?</p>
[ { "answer_id": 6095814, "author": "sandeep", "author_id": 765814, "author_profile": "https://Stackoverflow.com/users/765814", "pm_score": 1, "selected": false, "text": "@Test(timeout=1000)" }, { "answer_id": 8092158, "author": "davyjonestech", "author_id": 1041416, "author_profile": "https://Stackoverflow.com/users/1041416", "pm_score": 3, "selected": false, "text": " <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>4.10</version>\n <scope>test</scope>\n</dependency>\n<dependency>\n <groupId>org.databene</groupId>\n <artifactId>contiperf</artifactId>\n <version>2.0.0</version>\n <scope>test</scope>\n</dependency>\n public class PersonDAOTest {\n@Rule\npublic ContiPerfRule i = new ContiPerfRule();\n @Test\n@PerfTest(invocations = 1, threads = 1)\n@Required(max = 1200, average = 250)\npublic void test() {\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
323,790
<p>I have a project with several sources directories : </p> <pre><code>src/A /B /C </code></pre> <p>In each, the Makefile.am contains </p> <pre><code>AM_CXXFLAGS = -fPIC -Wall -Wextra </code></pre> <p>How can avoid repeating this in each source folder ? </p> <p>I tried to modifiy src/Makefile.am and the configure.in, but without success. I thought I could use AC_PROG_CXX to set the compilation flags globally but can't find much documentation on how to use those macro (do you have any pointer to such a documentation ?).</p> <p>Thanks in advance</p>
[ { "answer_id": 325436, "author": "adl", "author_id": 27835, "author_profile": "https://Stackoverflow.com/users/27835", "pm_score": 6, "selected": true, "text": "Makefile.am include $(top_srcdir)/common.mk\n...\nbin_PROGRAMS = foo\nfoo_SOURCES = ...\n AM_CXXFLAGS = -fpic -Wall -Wextra\n common.mk Makefile.am configure.ac configure.in ...\nAC_SUBST([AM_CXXFLAGS], [-fpic -Wall -Wextra])\n...\n Makefile.am common.mk Makefile.am configure.ac make make CXXFLAGS='-O0 -ggdb' \n CXXFLAGS AM_CXXFLAGS CXXFLAGS -fpic -Wall -Werror" }, { "answer_id": 36060425, "author": "Sergei Krivonos", "author_id": 525578, "author_profile": "https://Stackoverflow.com/users/525578", "pm_score": 0, "selected": false, "text": "EXTRA_CFLAGS=-fPIC -Wall -Wextra" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
323,816
<blockquote> <p>Write a class ListNode which has the following properties:</p> <ul> <li>int value;</li> <li>ListNode *next;</li> </ul> <p>Provide the following functions:</p> <ul> <li>ListNode(int v, ListNode *l)</li> <li>int getValue();</li> <li>ListNode* getNext();</li> <li>void insert(int i);</li> <li>bool listcontains(int j);</li> </ul> <p>Write a program which asks the user to enter some integers and stores them as ListNodes, and then asks for a number which it should seek in the list.</p> </blockquote> <p>Here is my code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class ListNode { private: struct Node { int value; Node *next; } *lnFirst; public: ListNode(); int Length(); void DisplayList(); void Insert( int num ); bool Contains( int num ); int GetValue( int num ); }; ListNode::ListNode() { lnFirst = NULL; } int ListNode::Length() { Node *lnTemp; int intCount = 0; for( lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp-&gt;next ) { intCount++; } return intCount; } void ListNode::DisplayList() { Node *lnTemp; for( lnTemp = lnFirst ; lnTemp != NULL ; lnTemp = lnTemp-&gt;next ) cout&lt;&lt;endl&lt;&lt;lnTemp-&gt;value; } void ListNode::Insert(int num) { Node *lnCurrent, *lnNew; if( lnFirst == NULL ) { lnFirst = new Node; lnFirst-&gt;value = num; lnFirst-&gt;next = NULL; } else { lnCurrent = lnFirst; while( lnCurrent-&gt;next != NULL ) lnCurrent = lnCurrent-&gt;next; lnNew = new Node; lnNew-&gt;value = num; lnNew-&gt;next = NULL; lnCurrent-&gt;next = lnNew; } } bool ListNode::Contains(int num) { bool boolDoesContain = false; Node *lnTemp,*lnCurrent; lnCurrent = lnFirst; lnTemp = lnCurrent; while( lnCurrent!=NULL ) { if( lnCurrent-&gt;value == num ) { boolDoesContain = true; return boolDoesContain; } lnTemp = lnCurrent; lnCurrent = lnCurrent-&gt;next; } return boolDoesContain; } int ListNode::GetValue(int num) { Node *lnTemp; int intCount = 1; for( lnTemp=lnFirst; lnTemp != NULL; lnTemp = lnTemp-&gt;next ) { if (intCount == num) { return lnTemp-&gt;value; } intCount++; } } int main() { cout &lt;&lt; &quot;Input integers below. Input the integer -1 to stop inputting.\n\n&quot;; ListNode lnList; int intNode = 1, intInput = 0; while (intInput != -1) { cout &lt;&lt; &quot;Please input integer number &quot; &lt;&lt; intNode &lt;&lt; &quot;: &quot;; cin &gt;&gt; intInput; intNode++; if (intInput != -1) { lnList.Insert(intInput); } } lnList.DisplayList(); cout &lt;&lt; &quot;\n\n&quot;; int intListLength = lnList.Length(); cout &lt;&lt; &quot;Which value do you wish to recall? (Between 1 and &quot; &lt;&lt; intListLength &lt;&lt; &quot;): &quot;; cin &gt;&gt; intNode; if ( intNode &gt;= 1 &amp;&amp; intNode &lt;= intListLength ) { cout &lt;&lt; &quot;Value at position &quot; &lt;&lt; intNode &lt;&lt; &quot; is &quot; &lt;&lt; lnList.GetValue(intNode) &lt;&lt; &quot;.&quot;; } else { cout &lt;&lt; &quot;No such position in the list. Positions run from 1 to &quot; &lt;&lt; intListLength &lt;&lt; &quot;. You asked for &quot; &lt;&lt; intNode &lt;&lt; &quot;.&quot;; } cout &lt;&lt; &quot;\n\nCheck if the following value is in the list: &quot;; cin &gt;&gt; intNode; bool IsThere = lnList.Contains(intNode); if (IsThere) { cout &lt;&lt; intNode &lt;&lt; &quot; is in the list.&quot;; } else { cout &lt;&lt; intNode &lt;&lt; &quot; is not in the list.&quot;; } cout &lt;&lt; &quot;\n\n&quot;; system(&quot;pause&quot;); return 0; } </code></pre> <p>Where can we improve this?</p>
[ { "answer_id": 323832, "author": "Cyrille Ka", "author_id": 39622, "author_profile": "https://Stackoverflow.com/users/39622", "pm_score": 2, "selected": false, "text": "cout << \"Please input integer number \" << intNode << \": \"; cin >> intInput;\n" }, { "answer_id": 323848, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "class ListNode {\nprivate:\n int value;\n ListNode * next;\n\npublic:\n bool listcontains(int v) { \n // does this node contain the value?\n if(value == v) return true; \n\n // was this the last node?\n if(next == 0) return false;\n\n // return whether nodes after us contain the value \n return next->listcontains(v);\n }\n};\n next == 0" }, { "answer_id": 323855, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 2, "selected": false, "text": "Node *lnTemp;\nint intCount = 0;\nfor( lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )\n{\n}\n int intCount = 0;\nfor(Node* lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next )\n{\n}\n Node *lnTemp,*lnCurrent;\nlnCurrent = lnFirst;\nlnTemp = lnCurrent;\n Node* lnCurrent = lnFirst;\nNode* lnTemp = lnCurrent;\n" }, { "answer_id": 324213, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 2, "selected": false, "text": "struct Node // Why doesn't this have a constructor initializing the members?\n{\n int value;\n Node *next;\n} *lnFirst; \n\n\nListNode::ListNode() : lnFirst(NULL) {} // Use initializer lists instead of initializing members in the ctor body. It's cleaner, more efficient and may avoid some nasty bugs (because otherwise the member gets default-initialized *first*, and then assigned to in the body)\n\nint ListNode::Length()\n{\n int intCount = 0;\n for( Node* lnTemp=lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next ) // Create the loop iteration variable lnTemp here, in the loop, not at the start of the function\n {\n intCount++;\n }\n return intCount;\n}\n\nvoid ListNode::DisplayList()\n{\n for(Node* lnTemp = lnFirst ; lnTemp != NULL ; lnTemp = lnTemp->next ) // And again, initialize the loop variable in the loop\n cout<<endl<<lnTemp->value; // Not a huge deal, but endl flushes the stream as well as inserting a newline. That can be needlessly slow. So you might want to just use \"\\n\" in cases where you don't need the flushing behavior.\n}\n\nvoid ListNode::Insert(int num)\n{\n// Node *lnCurrent, *lnNew; // Very subjective, but I prefer not declaring multiple variables on the same line, because the syntax if they're pointers can be surprising (You got it right, but a lot of people would write Node* lnCurrent, lnView, which would make lnView not a pointer. I find it clearer to just give ecah variable a separate line:\n if( lnFirst == NULL )\n {\n// lnFirst = new Node;\n// lnFirst->value = num;\n// lnFirst->next = NULL;\n lnFirst = new Node(num); // Make a constructor which initializes next to NULL, and sets value = num. Just like you would in other languages. ;)\n }\n else\n {\n Node* lnCurrent = lnFirst; // Don't declare variables until you need them. Both to improve readability, and because C++ distinguishes between initialization and assignment, so in some cases, default-initialization followed by assigment may not be the same as just initializing with the desired value.\n while( lnCurrent->next != NULL )\n lnCurrent = lnCurrent->next;\n\n Node* lnNew = new Node(num); // Again, let a constructor do the work.\n lnCurrent->next = lnNew;\n }\n}\n\nbool ListNode::Contains(int num)\n{\n bool boolDoesContain = false;\n// Node *lnTemp,*lnCurrent; // Again, don't initialize variables at the start of the function if they're not needed\n Node* lnCurrent = lnFirst;\n// lnTemp = lnCurrent;\n while( lnCurrent!=NULL )\n {\n if( lnCurrent->value == num )\n {\n// boolDoesContain = true;\n// return boolDoesContain;\n return true; // Just return directly, and remove the boolDoesContain variable. Alternatively, set boolDoesContain to true, and then break out of the loop without returning, so you have a single exit point from the function. Both approaches have their merits, but setting a variable you don't need, and then returning is silly. ;)\n }\n// Node* lnTemp = lnCurrent; // you don't actually use lnTemp for anything, it seems\n lnCurrent = lnCurrent->next;\n }\n// return boolDoesContain;\n return false; // just return false. If you get this far, it must be because you haven't found a match, so boolDoesContain can only be false anyway.\n}\n\nint ListNode::GetValue(int num)\n{\n// Node *lnTemp;\n int intCount = 1; // Wouldn't most people expect this indexing to be zero-based?\n for( Node* lnTemp=lnFirst; lnTemp != NULL; lnTemp = lnTemp->next )\n {\n if (intCount == num)\n {\n return lnTemp->value;\n }\n intCount++;\n } \n}\n int main(){\nListNode list;\nlist.Insert(1);\nlist.Insert(2);\nlist.Insert(3);\n}\nListNode list2 = list;\n ListNode(const ListNode& other);\nListNode& operator==(const ListNode& other);\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135/" ]
323,817
<p>I query all security groups in a specific domain using </p> <pre><code>PrincipalSearchResult&lt;Principal&gt; results = ps.FindAll(); </code></pre> <p>where ps is a PrincipalSearcher.</p> <p>I then need to iterate the result (casting it to a GroupPrincipal first ) and locate the ones that contains a specific string in the notes field.</p> <p>But the Notes field from AD is appearently not a public field in the GroupPrincipal class, doh. What am I doing wrong ?</p> <p>Update: I have given up on this one. It seems like there is no way to access that pesky Notes field.</p>
[ { "answer_id": 1983762, "author": "Brad", "author_id": 241316, "author_profile": "https://Stackoverflow.com/users/241316", "pm_score": 3, "selected": false, "text": "// Get the underlying directory entry from the principal\nSystem.DirectoryServices.DirectoryEntry UnderlyingDirectoryObject =\n PrincipalInstance.GetUnderlyingObject() as System.DirectoryServices.DirectoryEntry;\n\n// Read the content of the 'notes' property (It's actually called info in the AD schema)\nstring NotesPropertyContent = UnderlyingDirectoryObject.Properties[\"info\"].Value;\n\n// Set the content of the 'notes' field (It's actually called info in the AD schema)\nUnderlyingDirectoryObject.Properties[\"info\"].Value = \"Some Text\"\n\n// Commit changes to the directory entry\nUserDirectoryEntry.CommitChanges();\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23499/" ]
323,829
<p>This code</p> <pre><code>select.select([sys.stdin], [], [], 1.0) </code></pre> <p>does exactly what I want on Linux, but not in Windows.</p> <p>I've used <code>kbhit()</code> in <code>msvcrt</code> before to see if data is available on stdin for reading, but in this case it always returns <code>0</code>. Additionally <code>msvcrt.getch()</code> returns <code>'\xff'</code> whereas <code>sys.stdin.read(1)</code> returns <code>'\x01'</code>. It seems as if the msvcrt functions are not behaving properly.</p> <p>Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.</p>
[ { "answer_id": 323902, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "someprocess | python myprogram.py sys.stdin sys.stdin python myprogram.py <someFile sys.stdin python myprogram.py /dev/ttyxx sys.stdin sys.stdin stdin os.isatty( sys.stdin.fileno() ) sys.stdin sys.stdin Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nC:\\Documents and Settings\\slott>python\nPython 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> import sys\n>>> os.isatty( sys.stdin.fileno() )\nTrue\n>>>\n True sys.stdin kbhit False sys.stdin kbhit CON: sys.stdin" }, { "answer_id": 3541638, "author": "ideawu", "author_id": 427640, "author_profile": "https://Stackoverflow.com/users/427640", "pm_score": 1, "selected": false, "text": "q sys.stdin.read() # coding=UTF-8\n\"\"\" === Windows stdio ===\n@author ideawu@163.com\n@link http://www.ideawu.net/\nFile objects on Windows are not acceptable for select(),\nthis module creates two sockets: stdio.s_in and stdio.s_out,\nas pseudo stdin and stdout.\n\n@example\nfrom stdio import stdio\nstdio.write('hello world')\ndata = stdio.read()\nprint stdio.STDIN_FILENO\nprint stdio.STDOUT_FILENO\n\"\"\"\nimport thread\nimport sys, os\nimport socket\n\n# socket read/write in multiple threads may cause unexpected behaviors\n# so use two separated sockets for stdin and stdout\n\ndef __sock_stdio():\n def stdin_thread(sock, console):\n \"\"\" read data from stdin, and write the data to sock\n \"\"\"\n try:\n fd = sys.stdin.fileno()\n while True:\n # DO NOT use sys.stdin.read(), it is buffered\n data = os.read(fd, 1024)\n #print 'stdin read: ' + repr(data)\n if not data:\n break\n while True:\n nleft = len(data)\n nleft -= sock.send(data)\n if nleft == 0:\n break\n except:\n pass\n #print 'stdin_thread exit'\n sock.close()\n\n def stdout_thread(sock, console):\n \"\"\" read data from sock, and write to stdout\n \"\"\"\n try:\n fd = sys.stdout.fileno()\n while True:\n data = sock.recv(1024)\n #print 'stdio_sock recv: ' + repr(data)\n if not data:\n break\n while True:\n nleft = len(data)\n nleft -= os.write(fd, data)\n if nleft == 0:\n break\n except:\n pass\n #print 'stdin_thread exit'\n sock.close()\n\n\n class Console:\n def __init__(self):\n self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.serv.bind(('127.0.0.1', 0))\n self.serv.listen(5)\n port = self.serv.getsockname()[1]\n\n # data read from stdin will write to this socket\n self.stdin_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.stdin_sock.connect(('127.0.0.1', port))\n self.s_in, addr = self.serv.accept()\n self.STDIN_FILENO = self.s_in.fileno()\n thread.start_new_thread(stdin_thread, (self.stdin_sock, self))\n\n # data read from this socket will write to stdout\n #self.stdout_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #self.stdout_sock.connect(('127.0.0.1', port))\n #self.s_out, addr = self.serv.accept()\n #self.STDOUT_FILENO = self.s_out.fileno()\n #thread.start_new_thread(stdout_thread, (self.stdout_sock, self))\n\n self.read_str = '' # read buffer for readline\n\n def close(self):\n self.s_in.close()\n self.s_out.close()\n self.stdin_sock.close()\n self.stdout_sock.close()\n self.serv.close()\n\n def write(self, data):\n try:\n return self.s_out.send(data)\n except:\n return -1\n\n def read(self):\n try:\n data = self.s_in.recv(4096)\n except:\n return ''\n ret = self.read_str + data\n self.read_str = ''\n return ret\n\n def readline(self):\n while True:\n try:\n data = self.s_in.recv(4096)\n except:\n return ''\n if not data:\n return ''\n pos = data.find('\\n')\n if pos == -1:\n self.read_str += data\n else:\n left = data[0 : pos + 1]\n right = data[pos + 1 : ]\n ret = self.read_str + left\n self.read_str = right\n return ret\n\n stdio = Console()\n return stdio\n\ndef __os_stdio():\n class Console:\n def __init__(self):\n self.STDIN_FILENO = sys.stdin.fileno()\n self.STDOUT_FILENO = sys.stdout.fileno()\n\n def close(self):\n pass\n\n def write(self, data):\n try:\n return os.write(self.STDOUT_FILENO, data)\n except:\n return -1\n\n def read(self):\n try:\n return os.read(self.STDIN_FILENO, 4096)\n except:\n return ''\n\n def readline(self):\n try:\n return sys.stdin.readline()\n except:\n return ''\n\n stdio = Console()\n return stdio\n\nif os.name == 'posix':\n stdio = __os_stdio()\nelse:\n stdio = __sock_stdio()\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22847/" ]
323,834
<p>I am wondering how I should properly get rid of branches that no longer have any purpose. Right now even if i delete them and commit they are still listed as branches in the properties windows for a particular branching root (directory). If I select merge I don't get an option to merge to the deleted branch which obviously is as expected but therefore I am puzzled about the branch still showing up in the properties window.</p> <p>Any explanation on this behavior would be greatly appreciated.</p>
[ { "answer_id": 323962, "author": "Damien Ryan", "author_id": 12565, "author_profile": "https://Stackoverflow.com/users/12565", "pm_score": 4, "selected": false, "text": "tf destroy tf dir /deleted" }, { "answer_id": 10644444, "author": "Mike Q", "author_id": 1402135, "author_profile": "https://Stackoverflow.com/users/1402135", "pm_score": 4, "selected": false, "text": "tf tf tf dir $/MyPathTo/TheParent/Directory /deleted\n tf destroy $/MyPathTo/TheParent/Directory/TheDirectoryToGetRidOff;Ident\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32313/" ]
323,837
<p>I've been working a little with DevExpress CodeRush and Refactor! Pro this week, and I picked up a commentor plug-in that will automatically generate comments as you type code.</p> <p>I don't want to go into how good a job it does of picking out basic meaning (pretty good, actually) but it's default implementation does raise a question.</p> <p>By default, typing a } character to close a block will result in the plugin adding a comment like the following...</p> <pre><code>using(MyType myType = new MyType()) { myType.doWork(); } // using </code></pre> <p>(i.e. adding a comment to the closing brace labelling where it was opened.)</p> <p>While I can see that there are instances where this behaviour may be of great use, I feel that the resultant code looks very untidy with all the additional commenting.</p> <p>I was wondering what other people;'s take on this kind of comment was. Not just from an academic standpoint, but if I get a good number of negative comments about them I can decide whether to inflict them upon my co-workers or strip them out.</p>
[ { "answer_id": 323853, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<div id=\"content\">\n <div id=\"columns\">\n <div class=\"column\">\n\n <!-- .. snip a lot of lines .. -->\n\n </div> <!-- .column -->\n </div> <!-- #columns -->\n</div> <!-- #content -->\n" }, { "answer_id": 323856, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 2, "selected": false, "text": "}" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/377/" ]
323,842
<p>I am fairly new to MySQL and have a project in which I need to design a database that will store responses from an online questionnaire. Reports will need to be written from the data. Does anyone have any tips on what type of fields to use? The questions will either have a Yes No answer, a choice of 4 options from very satisfied to very dis-satisfied or multipul choice. It's mainly the choice questions that I'm unsure on, as I will need to be able to product a report to show the percentage of satisfied customers. I know it's probably really basic, but I don't want to get it wrong.</p>
[ { "answer_id": 323853, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<div id=\"content\">\n <div id=\"columns\">\n <div class=\"column\">\n\n <!-- .. snip a lot of lines .. -->\n\n </div> <!-- .column -->\n </div> <!-- #columns -->\n</div> <!-- #content -->\n" }, { "answer_id": 323856, "author": "Richard Ev", "author_id": 39709, "author_profile": "https://Stackoverflow.com/users/39709", "pm_score": 2, "selected": false, "text": "}" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41378/" ]
323,866
<p>I have a program that can have a lot of parameters (we have over +30 differents options).</p> <p>Example: <code>myProgram.exe -t alpha 1 -prod 1 2 -sleep 200</code></p> <p>This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection of String parameters for each command.</p> <p>For the moment, we use string comparison and we can get the whole thing works (instance the concrete command and return the ICommand interface). The problem is we require to do a lot of IF everytime to get the good command.</p> <p>Do you have some pattern that can be used to extract all parameters from an EXE without using a lot of IF?</p> <p>The code is in C# but I think the logic can be any other language too...</p>
[ { "answer_id": 323920, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 0, "selected": false, "text": "private void Main() \n{ \nstring c = \"-t alpha 1 -prod 1 2 -sleep 200\"; \n\nforeach (string incommand in Strings.Split(c, \"-\")) { \n HandleCommand(Strings.Split(incommand.Trim, \" \")); \n} \n} \n\n\npublic void HandleCommand(string[] c) \n{ \nswitch (c(0).ToLower) { \n case \"t\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n case \"prod\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n case \"sleep\": \n Interaction.MsgBox(\"Command:\" + c(0) + \" params: \" + c.Length - 1); \n break; \n} \n} \n" }, { "answer_id": 324013, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "public class Form1 \n{ \n\nprivate void main() \n{ \n MyCommandHandler CommandLineHandler = new MyCommandHandler(); \n CommandLineHandler.SetInput = \"-t alpha 1 -prod 1 2 -sleep 200\"; \n\n //now we can use strong name to work with the variables: \n //CommandLineHandler.prod.ProdID \n //CommandLineHandler.prod.ProdInstanceID \n //CommandLineHandler.Alpha.AlhaValue() \n //CommandLineHandler.Sleep.Miliseconds() \n if (CommandLineHandler.Alpha.AlhaValue > 255) { \n throw new Exception(\"Apha value out of bounds!\"); \n } \n\n} \n} \n\npublic class MyCommandHandler \n{ \nprivate string[] values; \npublic string SetInput { \n set { values = Strings.Split(value, \"-\"); } \n} \n\n//Handle Prod command \npublic struct prodstructure \n{ \n public string ProdID; \n public string ProdInstanceID; \n} \npublic prodstructure prod { \n get { \n prodstructure ret = new prodstructure(); \n ret.ProdID = GetArgsForCommand(\"prod\", 0); \n ret.ProdInstanceID = GetArgsForCommand(\"prod\", 1); \n return ret; \n } \n} \n\n//Handle Apha command \npublic struct Aphastructure \n{ \n public int AlhaValue; \n} \npublic Aphastructure Alpha { \n get { \n Aphastructure ret = new Aphastructure(); \n ret.AlhaValue = Convert.ToInt32(GetArgsForCommand(\"alpha\", 0)); \n return ret; \n } \n} \n\n\n//Handle Sleep command \npublic struct SleepStructure \n{ \n public int Miliseconds; \n} \npublic SleepStructure Sleep { \n get { \n SleepStructure ret = new SleepStructure(); \n ret.Miliseconds = Convert.ToInt32(GetArgsForCommand(\"sleep\", 0)); \n return ret; \n } \n} \n\n\nprivate string GetArgsForCommand(string key, int item) \n{ \n foreach (string c in values) { \n foreach (string cc in Strings.Split(c.Trim, \" \")) { \n if (cc.ToLower == key.ToLower) { \n try { \n return Strings.Split(c.Trim, \" \")(item + 1); \n } \n catch (Exception ex) { \n return \"\"; \n } \n } \n } \n } \n return \"\"; \n} \n} \n" }, { "answer_id": 325157, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 0, "selected": false, "text": "Dictionary<string, ICommand> Dictionary<string, Type> Activate.CreateInstance(/*dictionary-value*/) Dictionary<string, System.Linq.Expressions.Expression<T>>" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
323,874
<p>I have the following problem:</p> <p>I open the dialog, open the SIP keyboard to fill the form and then minimize the SIP. Then when I close the current dialog and return to the main dialog the SIP keyboard appears again. Does anyone know how could I show/hide SIP keyboard programatically or better what could be done to solve the described problem. Once the user minimizes the keyboard it should not appear on the screen on dialog switching.</p> <p>Thanks!</p>
[ { "answer_id": 437481, "author": "Malx", "author_id": 51086, "author_profile": "https://Stackoverflow.com/users/51086", "pm_score": 0, "selected": false, "text": "void CAaa::OnActivate( UINT nState, CWnd* pWndOther, BOOL bMinimized )\n{\nif(nState == WA_ACTIVE || nState == WA_CLICKACTIVE)\n{\n SHINITDLGINFO shidi;\n shidi.dwMask = SHIDIM_FLAGS;\n shidi.dwFlags = SHIDIF_FULLSCREENNOMENUBAR|SHIDIF_SIPDOWN | SHFS_HIDETASKBAR;\n shidi.hDlg = m_hWnd;\n SHInitDialog(&shidi);\n\n SHFullScreen(m_hWnd, SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON |SHFS_HIDESTARTICON);\n}\n}\n SHSipPreference(m_hWnd,SIP_UP); // SIP_DOWN\n HWND hwndCB = ::FindWindow(_T(\"SipWndClass\"),_T(\"\"));\n ::ShowWindow( hwndCB, SW_SHOW);\n hwndCB = ::FindWindow(_T(\"MS_SIPBUTTON\"),NULL);\n ::ShowWindow( hwndCB, SW_SHOW);\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
323,901
<p>I have recently converted 10 JavaScript files into one file, which I then run a JavaScript compiler on. I just had a bug where I had reused a function name.</p> <p>Is there a tool to check for duplicate rows/function names in the combined file?</p> <p>Or should I create a little program?</p>
[ { "answer_id": 324010, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "cat file.js | grep -o \"function\\([[:space:]]\\+[a-zA-Z0-9_]\\+\\)\\?[[:space:]]*(\" | sort | uniq -c | sort -n\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24459/" ]
323,907
<p>I have this code, which works fine, but I would like to be able to make it so when an image appears the text layer disapears, and there would be a link to bring the xt back and remove the image. How would I do this..., something to do with changing isibility and overlaying?</p> <pre><code>&lt;html&gt; &lt;script type="text/javascript"&gt; //&lt;!-- function sbox(boxName, xname) { theBox = document.getElementById(boxName); theBox.className = xname; } //--&gt; &lt;/script&gt; &lt;style&gt; #main { position: absolute; width: 800px; height: 600px; } .test1 { position: absolute; top: 20px; width: 80px; height: 80px; border-style: solid; border-color: green; } .test2 { position: absolute; top: 120px; width: 80px; height: 80px; border-style: solid; border-color: red; } .test3 { position: absolute; top: 220px; width: 80px; height: 80px; border-style: solid; border-color: blue; } .test4 { position: absolute; top: 320px; width: 80px; height: 80px; border-style: solid; border-color: black; } .test5 { position: absolute; top: 20px; width: 80px; height: 80px; border-style: solid; border-color: yellow; } #test6 { width: 80px; height: 80px; border-style: solid; border-color: green; } #test7 { width: 80px; height: 80px; border-style: solid; border-color: green; } &lt;/style&gt; &lt;div class="test1" id="test1"&gt; &lt;a href="#" onclick="sbox('test1', 'test5'); return false;"&gt;test1&lt;/a&gt; &lt;/div&gt; &lt;div class="test2" id="test2"&gt;test2&lt;/div&gt; &lt;div class="test3" id="test3"&gt;test3&lt;/div&gt; &lt;div class="test4" id="test4"&gt;test4&lt;/div&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 324010, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "cat file.js | grep -o \"function\\([[:space:]]\\+[a-zA-Z0-9_]\\+\\)\\?[[:space:]]*(\" | sort | uniq -c | sort -n\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1246613/" ]
323,922
<p>I want to create maintainable code, but this inheritance situation is causing me problems.</p> <p>The issue is with my 2nd database helper class named <b>InitUserExtension</b>.</p> <p>Since UserExtension inherits from User, I have to make sure that I <b>mirror</b> any changes in my InitUser helper to InitUserExtension.</p> <p>I really don't like this as <b>its prone to bugs, what's the solution?</b></p> <p>My class definitions:</p> <pre><code>public class User { public string Name {get; set; } public string Age { get; set; } } public class UserExtension : User { public string Lastname {get; set; } public string Password {get; set; } } </code></pre> <p>My database helpers:</p> <pre><code>public static SqlDataReader InitUser(SqlDataReader dr) { User user = new User(); user.Name = Convert.ToString(dr["name"]); user.Age ... } public static SqlDataReader InitUserExtension(SqlDataReader dr) { UserExtension user = new UserExtension(); // note: mirror attributes from User user.Name = Convert.ToString(dr["name"]); user.Age ... user.Lastname = Convert.ToString(dr["lastname"]); user.Password = ....; } </code></pre>
[ { "answer_id": 323947, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": false, "text": "InitUser InitUserExtension" }, { "answer_id": 323958, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "private static void InitUser(User user, SqlDataReader dr)\n{ // could also use an interface here, or generics with T : User\n user.Name = Convert.ToString(dr[\"name\"]);\n user.Age ...\n}\n\n\npublic static User InitUser(SqlDataReader dr)\n{\n User user = new User();\n InitUser(user, dr);\n return user;\n}\n\npublic static UserExtension InitUserExtension(SqlDataReader dr)\n{\n UserExtension user = new UserExtension();\n InitUser(user, dr);\n user.Lastname = Convert.ToString(dr[\"lastname\"]);\n user.Password = ....;\n return user;\n}\n private static T InitUserCore<T>(SqlDataReader dr) where T : User, new()\n{\n T user = new T();\n // ...\n return user;\n}\npublic static User InitUser(SqlDataReader dr)\n{\n return InitUserCore<User>(dr);\n}\npublic static UserExtension InitUserExtension(SqlDataReader dr)\n{\n UserExtension user = InitUserCore<UserExtension>(dr);\n // ...\n return user;\n}\n" }, { "answer_id": 323971, "author": "Wobin", "author_id": 15010, "author_profile": "https://Stackoverflow.com/users/15010", "pm_score": 0, "selected": false, "text": "public class User\n{\n public string Name {get; set; }\n public string Age { get; set; }\n\n public User(DataReader dr)\n {\n user.Name = Convert.ToString(dr[\"name\"]);\n user.Age ...\n }\n}\n\npublic class UserExtension : User\n{\n public string Lastname {get; set; }\n public string Password {get; set; }\n\n public UserExtension(DataReader dr):base(dr)\n {\n user.Lastname = Convert.ToString(dr[\"lastname\"]);\n user.Password = ....;\n\n }\n}\n var MyExtension = new UserExtension(dr); \n" }, { "answer_id": 323980, "author": "Din", "author_id": 41214, "author_profile": "https://Stackoverflow.com/users/41214", "pm_score": 1, "selected": false, "text": "public class InitUser\n{\n public InitUser(SqlDataReader dr, User u) { }\n}\n\npublic class InitUserExtension : InitUser\n{\n public InitUserExtension(SqlDataReader dr , UserExtension u) : base(dr, u) { }\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
323,928
<p>There are two pictureboxes with two different images.</p> <p>If I click on one picture box, the image in it should be cleared.</p> <p>To make the matters worse, both of the picture boxes have only one common event handler. How can I know which picturebox generated the event? I would appreciate source code in C++-CLI</p> <p>I need to know what to write inside the function:</p> <pre><code>private: System::Void sqaure_Click(System::Object^ sender, System::EventArgs^ e) { } </code></pre> <p>EDIT: The problem is that when I try to cast sender to picurebox, it gives an error saying that the types cannot be converted.</p>
[ { "answer_id": 325980, "author": "Toji", "author_id": 25968, "author_profile": "https://Stackoverflow.com/users/25968", "pm_score": 3, "selected": true, "text": "PictureBox ^pb = safe_cast<PictureBox^>(sender);\nif(pb != null) {\n // logic goes here\n}\n" }, { "answer_id": 326294, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 0, "selected": false, "text": "PictureBox ^pb = safe_cast<PictureBox^>(sender);\n PictureBox pb PictureBox *pb PictureBox ^pb" }, { "answer_id": 362012, "author": "shash", "author_id": 11684, "author_profile": "https://Stackoverflow.com/users/11684", "pm_score": 0, "selected": false, "text": "dynamic_cast safe_cast PictureBox ^ pb = dynamic_cast<PictureBox^>(sender);\nif (pb != nullptr)\n{\n...\n}\n try\n{\n PictureBox ^ pb = safe_cast<PictureBox^>(sender);\n ...\n}\ncatch(InvalidCastException ^ exp)\n{\n // Handle a cast that went awry\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
323,955
<p>How do you combine two jQuery search results? eg:</p> <pre><code>var $allFoos = $('.foo'), $allBars = $('.bar') $allFoosAndBars = $allFoos + $allBars; </code></pre> <p>Obviously, I just made up that last line, but I hope it makes it sorta clear what I mean. To be clear, the example is greatly simplified, and it could be any arbitrary sets i'm talking about, so <code>$('.foo, .bar')</code> is <em>not</em> what I'm after.</p>
[ { "answer_id": 323969, "author": "Simon", "author_id": 33036, "author_profile": "https://Stackoverflow.com/users/33036", "pm_score": 9, "selected": true, "text": "var $foos = $('.foo');\n\nvar $foosAndBars = $foos.add('.bar');\n var $allFoosAndBars = $allFoos.add($allBars);\n" }, { "answer_id": 64350309, "author": "Dylan KAS", "author_id": 11350193, "author_profile": "https://Stackoverflow.com/users/11350193", "pm_score": 3, "selected": false, "text": "var $allFoos = $('.foo');\nvar $allBars = $('.bar');\n\nvar $allFoosAndBars = $.merge($allFoos, $allBars);\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
323,957
<p>I need to edit <code>/etc/sudoers</code> from a script to add/remove stuff from white lists.</p> <p>Assuming I have a command that would work on a normal file, how could I apply it to <code>/etc/sudoers</code>?</p> <p>Can I copy and modify it, then have <code>visudo</code> replace the original with the modified copy? By providing my own script in <code>$EDITOR</code>?</p> <p>Or can I just use the same locks and <code>cp</code>?</p> <p>The question is more about potential issues than about just finding something that works.</p>
[ { "answer_id": 324009, "author": "Brian C. Lane", "author_id": 27461, "author_profile": "https://Stackoverflow.com/users/27461", "pm_score": 5, "selected": false, "text": "#!/bin/sh\nif [ -f \"/etc/sudoers.tmp\" ]; then\n exit 1\nfi\ntouch /etc/sudoers.tmp\nedit_sudoers /tmp/sudoers.new\nvisudo -c -f /tmp/sudoers.new\nif [ \"$?\" -eq \"0\" ]; then\n cp /tmp/sudoers.new /etc/sudoers\nfi\nrm /etc/sudoers.tmp\n" }, { "answer_id": 324012, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 4, "selected": false, "text": "/etc/sudoers r--r-----" }, { "answer_id": 324021, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 3, "selected": false, "text": "sudo EDITOR=/path/to/my_dummy_editor.sh visudo\n" }, { "answer_id": 3706774, "author": "sstendal", "author_id": 216911, "author_profile": "https://Stackoverflow.com/users/216911", "pm_score": 6, "selected": false, "text": "#!/bin/sh\nif [ -z \"$1\" ]; then\n echo \"Starting up visudo with this script as first parameter\"\n export EDITOR=$0 && sudo -E visudo\nelse\n echo \"Changing sudoers\"\n echo \"# Dummy change to sudoers\" >> $1\nfi\n if [ -z \"$1\" ]; then\n\n # When you run the script, you will run this block since $1 is empty.\n\n echo \"Starting up visudo with this script as first parameter\"\n\n # We first set this script as the EDITOR and then starts visudo.\n # Visudo will now start and use THIS SCRIPT as its editor\n export EDITOR=$0 && sudo -E visudo\nelse\n\n # When visudo starts this script, it will provide the name of the sudoers \n # file as the first parameter and $1 will be non-empty. Because of that, \n # visudo will run this block.\n\n echo \"Changing sudoers\"\n\n # We change the sudoers file and then exit \n echo \"# Dummy change to sudoers\" >> $1\nfi\n" }, { "answer_id": 15397032, "author": "Kamal", "author_id": 1902442, "author_profile": "https://Stackoverflow.com/users/1902442", "pm_score": -1, "selected": false, "text": "#!/usr/bin/env bash\nrm /etc/sudoers.new\ncp /etc/sudoers /etc/sudoers.new\necho \"%everyone ALL = NOPASSWD: /usr/sbin/installer -pkg /Volumes/Java 7 Update 17/Java 7 Update 17.pkg -target /\" >> /etc/sudoers.new\ncp /etc/sudoers.new /etc/sudoers\n sudo sh sudoersedit.sh\n" }, { "answer_id": 16820121, "author": "zelanix", "author_id": 2433501, "author_profile": "https://Stackoverflow.com/users/2433501", "pm_score": 2, "selected": false, "text": "/etc/sudoers sudo EDITOR=\"cp /tmp/sudoers.new\" visudo\n /tmp/sudoers.new visudo visudo -c -f /tmp/sudoers.new" }, { "answer_id": 17965815, "author": "pevik", "author_id": 1564946, "author_profile": "https://Stackoverflow.com/users/1564946", "pm_score": 5, "selected": false, "text": "/etc/sudoers.d/ 0440 man sudo" }, { "answer_id": 22239109, "author": "Albert Vonpupp", "author_id": 1332764, "author_profile": "https://Stackoverflow.com/users/1332764", "pm_score": 2, "selected": false, "text": "#!/bin/sh\n\nwhile [ -n \"$1\" ]; do\n echo \"$1 ALL=(ALL:ALL) ALL\" >> /etc/sudoers;\n shift # shift all parameters\ndone\n root prompt> ./addsudoers.sh user1 user2\n" }, { "answer_id": 24292024, "author": "Apollo", "author_id": 1151052, "author_profile": "https://Stackoverflow.com/users/1151052", "pm_score": 0, "selected": false, "text": "sudo sh -c \"echo \\\"group ALL=(user) NOPASSWD: ALL\\\" >> /etc/sudoers\"" }, { "answer_id": 28382838, "author": "beckerr", "author_id": 4540664, "author_profile": "https://Stackoverflow.com/users/4540664", "pm_score": 8, "selected": false, "text": "echo 'foobar ALL=(ALL:ALL) ALL' | sudo EDITOR='tee -a' visudo\n" }, { "answer_id": 36795583, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 3, "selected": false, "text": "sudo /etc/sudoers.d visudo /etc/sudoers.d sudo visudo -c -q -f filename\n if && /etc/sudoers.d" }, { "answer_id": 54309791, "author": "Im-Kirk-Dougla-Cus", "author_id": 6639527, "author_profile": "https://Stackoverflow.com/users/6639527", "pm_score": 3, "selected": false, "text": "sudo bash -c 'echo \"your_user ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/99_sudo_include_file'\n sudo visudo -cf /etc/sudoers.d/99_sudo_include_file\n" }, { "answer_id": 68000186, "author": "Adam Mazurkiewicz", "author_id": 8077668, "author_profile": "https://Stackoverflow.com/users/8077668", "pm_score": 2, "selected": false, "text": "echo \"username ALL=(ALL) NOPASSWD:ALL\" | sudo tee -a /etc/sudoers\n" }, { "answer_id": 73562228, "author": "DrInk", "author_id": 5485989, "author_profile": "https://Stackoverflow.com/users/5485989", "pm_score": 0, "selected": false, "text": "sed tee echo 's/^#\\s*\\(%wheel\\s*ALL=(ALL)\\s*ALL\\)/\\1/g' | EDITOR='sed -f- -i' visudo\n /etc/sudoers # %wheel ALL=(ALL) ALL\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23420/" ]
323,972
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>
[ { "answer_id": 325528, "author": "Philippe F", "author_id": 13618, "author_profile": "https://Stackoverflow.com/users/13618", "pm_score": 11, "selected": true, "text": "import threading\n\nclass StoppableThread(threading.Thread):\n \"\"\"Thread class with a stop() method. The thread itself has to check\n regularly for the stopped() condition.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(StoppableThread, self).__init__(*args, **kwargs)\n self._stop_event = threading.Event()\n\n def stop(self):\n self._stop_event.set()\n\n def stopped(self):\n return self._stop_event.is_set()\n stop() join() def _async_raise(tid, exctype):\n '''Raises an exception in the threads with id tid'''\n if not inspect.isclass(exctype):\n raise TypeError(\"Only types can be raised (not instances)\")\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),\n ctypes.py_object(exctype))\n if res == 0:\n raise ValueError(\"invalid thread id\")\n elif res != 1:\n # \"if it returns a number greater than one, you're in trouble,\n # and you should call it again with exc=NULL to revert the effect\"\n ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)\n raise SystemError(\"PyThreadState_SetAsyncExc failed\")\n\nclass ThreadWithExc(threading.Thread):\n '''A thread class that supports raising an exception in the thread from\n another thread.\n '''\n def _get_my_tid(self):\n \"\"\"determines this (self's) thread id\n\n CAREFUL: this function is executed in the context of the caller\n thread, to get the identity of the thread represented by this\n instance.\n \"\"\"\n if not self.isAlive():\n raise threading.ThreadError(\"the thread is not active\")\n\n # do we have it cached?\n if hasattr(self, \"_thread_id\"):\n return self._thread_id\n\n # no, look for it in the _active dict\n for tid, tobj in threading._active.items():\n if tobj is self:\n self._thread_id = tid\n return tid\n\n # TODO: in python 2.6, there's a simpler way to do: self.ident\n\n raise AssertionError(\"could not determine the thread's id\")\n\n def raiseExc(self, exctype):\n \"\"\"Raises the given exception type in the context of this thread.\n\n If the thread is busy in a system call (time.sleep(),\n socket.accept(), ...), the exception is simply ignored.\n\n If you are sure that your exception should terminate the thread,\n one way to ensure that it works is:\n\n t = ThreadWithExc( ... )\n ...\n t.raiseExc( SomeException )\n while t.isAlive():\n time.sleep( 0.1 )\n t.raiseExc( SomeException )\n\n If the exception is to be caught by the thread, you need a way to\n check that your thread has caught it.\n\n CAREFUL: this function is executed in the context of the\n caller thread, to raise an exception in the context of the\n thread represented by this instance.\n \"\"\"\n _async_raise( self._get_my_tid(), exctype )\n PyThreadState_SetAsyncExc" }, { "answer_id": 5817436, "author": "DoXiD", "author_id": 729137, "author_profile": "https://Stackoverflow.com/users/729137", "pm_score": -1, "selected": false, "text": "from threading import *\n\n...\n\nfor thread in enumerate():\n if thread.isAlive():\n try:\n thread._Thread__stop()\n except:\n print(str(thread.getName()) + ' could not be terminated'))\n thread._Thread__delete() thread.quit() quit() thread._Thread__stop() quit()" }, { "answer_id": 7752174, "author": "cfi", "author_id": 923794, "author_profile": "https://Stackoverflow.com/users/923794", "pm_score": 7, "selected": false, "text": "multiprocessing.Process p.terminate() threading.Thread multiprocessing.Process queue.Queue multiprocessing.Queue p.terminate() p multiprocessing import multiprocessing\nproc = multiprocessing.Process(target=your_proc_function, args=())\nproc.start()\n# Terminate the process\nproc.terminate() # sends a SIGTERM\n" }, { "answer_id": 15185771, "author": "Paolo Rovelli", "author_id": 2128591, "author_profile": "https://Stackoverflow.com/users/2128591", "pm_score": 6, "selected": false, "text": "yourProcess.terminate() # kill the process!\n TerminateProcess() multiprocessing.Event multiprocessing.Semaphore threading.Event threading.Semaphore yourThread.daemon = True # set the Thread as a \"daemon thread\"\n daemon start() daemon multiprocessing sys.exit() os.kill()" }, { "answer_id": 15274929, "author": "Johan Dahlin", "author_id": 14337, "author_profile": "https://Stackoverflow.com/users/14337", "pm_score": 5, "selected": false, "text": "PyThreadState_SetAsyncExc() ctypes PyThreadState_SetAsyncExc() import ctypes\n\ndef terminate_thread(thread):\n \"\"\"Terminates a python thread from another thread.\n\n :param thread: a threading.Thread instance\n \"\"\"\n if not thread.isAlive():\n return\n\n exc = ctypes.py_object(SystemExit)\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(\n ctypes.c_long(thread.ident), exc)\n if res == 0:\n raise ValueError(\"nonexistent thread id\")\n elif res > 1:\n # \"\"\"if it returns a number greater than one, you're in trouble,\n # and you should call it again with exc=NULL to revert the effect\"\"\"\n ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)\n raise SystemError(\"PyThreadState_SetAsyncExc failed\")\n" }, { "answer_id": 16146048, "author": "snyh", "author_id": 401883, "author_profile": "https://Stackoverflow.com/users/401883", "pm_score": 3, "selected": false, "text": "from ctypes import *\npthread = cdll.LoadLibrary(\"libpthread-2.15.so\")\npthread.pthread_cancel(c_ulong(t.ident))\n Thread Modules/threadmodule.c Python/thread_pthread.h Thread.ident pthread_t pthread libpthread" }, { "answer_id": 23920936, "author": "Chema", "author_id": 3521548, "author_profile": "https://Stackoverflow.com/users/3521548", "pm_score": 2, "selected": false, "text": "is_alive()" }, { "answer_id": 24353228, "author": "Matthias Urlichs", "author_id": 966179, "author_profile": "https://Stackoverflow.com/users/966179", "pm_score": -1, "selected": false, "text": "multiprocessing gevent" }, { "answer_id": 25670684, "author": "Noctis Skytower", "author_id": 216356, "author_profile": "https://Stackoverflow.com/users/216356", "pm_score": 4, "selected": false, "text": "Thread.stop import sys\nimport threading\nimport time\n\n\nclass StopThread(StopIteration):\n pass\n\nthreading.SystemExit = SystemExit, StopThread\n\n\nclass Thread2(threading.Thread):\n\n def stop(self):\n self.__stop = True\n\n def _bootstrap(self):\n if threading._trace_hook is not None:\n raise ValueError('Cannot run thread with tracing!')\n self.__stop = False\n sys.settrace(self.__trace)\n super()._bootstrap()\n\n def __trace(self, frame, event, arg):\n if self.__stop:\n raise StopThread()\n return self.__trace\n\n\nclass Thread3(threading.Thread):\n\n def _bootstrap(self, stop_thread=False):\n def stop():\n nonlocal stop_thread\n stop_thread = True\n self.stop = stop\n\n def tracer(*_):\n if stop_thread:\n raise StopThread()\n return tracer\n sys.settrace(tracer)\n super()._bootstrap()\n\n###############################################################################\n\n\ndef main():\n test1 = Thread2(target=printer)\n test1.start()\n time.sleep(1)\n test1.stop()\n test1.join()\n test2 = Thread2(target=speed_test)\n test2.start()\n time.sleep(1)\n test2.stop()\n test2.join()\n test3 = Thread3(target=speed_test)\n test3.start()\n time.sleep(1)\n test3.stop()\n test3.join()\n\n\ndef printer():\n while True:\n print(time.time() % 1)\n time.sleep(0.1)\n\n\ndef speed_test(count=0):\n try:\n while True:\n count += 1\n except StopThread:\n print('Count =', count)\n\nif __name__ == '__main__':\n main()\n Thread3 Thread2" }, { "answer_id": 27261365, "author": "Jon Coombs", "author_id": 1593924, "author_profile": "https://Stackoverflow.com/users/1593924", "pm_score": 6, "selected": false, "text": "if stop() import threading\nimport time\n\ndef do_work(id, stop):\n print(\"I am thread\", id)\n while True:\n print(\"I am thread {} doing something\".format(id))\n if stop():\n print(\" Exiting loop.\")\n break\n print(\"Thread {}, signing off\".format(id))\n\n\ndef main():\n stop_threads = False\n workers = []\n for id in range(0,3):\n tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads))\n workers.append(tmp)\n tmp.start()\n time.sleep(3)\n print('main: done sleeping; time to stop the threads.')\n stop_threads = True\n for worker in workers:\n worker.join()\n print('Finis.')\n\nif __name__ == '__main__':\n main()\n print() pr() sys.stdout.flush()" }, { "answer_id": 31698551, "author": "zzart", "author_id": 758202, "author_profile": "https://Stackoverflow.com/users/758202", "pm_score": 0, "selected": false, "text": "my_thread = threading.Thread()\nmy_thread.start()\nmy_thread._Thread__stop()\n" }, { "answer_id": 36631765, "author": "user1942887", "author_id": 1942887, "author_profile": "https://Stackoverflow.com/users/1942887", "pm_score": -1, "selected": false, "text": "processIds = []\n\ndef executeRecord(command):\n print(command)\n\n process = subprocess.Popen(command, stdout=subprocess.PIPE)\n processIds.append(process.pid)\n print(processIds[0])\n\n #Command that doesn't return by itself\n process.stdout.read().decode(\"utf-8\")\n return;\n\n\ndef recordThread(command, timeOut):\n\n thread = Thread(target=executeRecord, args=(command,))\n thread.start()\n thread.join(timeOut)\n\n os.kill(processIds.pop(), signal.SIGINT)\n\n return;\n" }, { "answer_id": 37285448, "author": "Sud", "author_id": 5899679, "author_profile": "https://Stackoverflow.com/users/5899679", "pm_score": -1, "selected": false, "text": "def bootstrap(_filename):\n mb = ModelBootstrap(filename=_filename) # Has many Daemon threads. All get stopped automatically when main thread is stopped.\n\nt = threading.Thread(target=bootstrap,args=('models.conf',))\nt.setDaemon(False)\n\nwhile True:\n t.start()\n time.sleep(10) # I am just allowing the sub-thread to run for 10 sec. You can listen on an event to stop execution.\n print('Thread stopped')\n break\n" }, { "answer_id": 47468102, "author": "wp78de", "author_id": 8291949, "author_profile": "https://Stackoverflow.com/users/8291949", "pm_score": 2, "selected": false, "text": "SystemExit import threading\nimport ctypes \n\ndef _async_raise(tid, excobj):\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))\n if res == 0:\n raise ValueError(\"nonexistent thread id\")\n elif res > 1:\n # \"\"\"if it returns a number greater than one, you're in trouble, \n # and you should call it again with exc=NULL to revert the effect\"\"\"\n ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)\n raise SystemError(\"PyThreadState_SetAsyncExc failed\")\n\nclass Thread(threading.Thread):\n def raise_exc(self, excobj):\n assert self.isAlive(), \"thread must be started\"\n for tid, tobj in threading._active.items():\n if tobj is self:\n _async_raise(tid, excobj)\n return\n\n # the thread was alive when we entered the loop, but was not found \n # in the dict, hence it must have been already terminated. should we raise\n # an exception here? silently ignore?\n\n def terminate(self):\n # must raise the SystemExit type, instead of a SystemExit() instance\n # due to a bug in PyThreadState_SetAsyncExc\n self.raise_exc(SystemExit)\n" }, { "answer_id": 49288286, "author": "Amit Chahar", "author_id": 4043524, "author_profile": "https://Stackoverflow.com/users/4043524", "pm_score": 3, "selected": false, "text": "kill_threads = False\n\ndef doSomething():\n global kill_threads\n while True:\n if kill_threads:\n thread.exit()\n ......\n ......\n\nthread.start_new_thread(doSomething, ())\n" }, { "answer_id": 49877671, "author": "SCB", "author_id": 1112586, "author_profile": "https://Stackoverflow.com/users/1112586", "pm_score": 5, "selected": false, "text": "time.sleep() event wait() sleep() import threading\n\nclass KillableThread(threading.Thread):\n def __init__(self, sleep_interval=1):\n super().__init__()\n self._kill = threading.Event()\n self._interval = sleep_interval\n\n def run(self):\n while True:\n print(\"Do Something\")\n\n # If no kill signal is set, sleep for the interval,\n # If kill signal comes in while sleeping, immediately\n # wake up and handle\n is_killed = self._kill.wait(self._interval)\n if is_killed:\n break\n\n print(\"Killing Thread\")\n\n def kill(self):\n self._kill.set()\n t = KillableThread(sleep_interval=5)\nt.start()\n# Every 5 seconds it prints:\n#: Do Something\nt.kill()\n#: Killing Thread\n wait() sleep() sleep()" }, { "answer_id": 50474315, "author": "slumtrimpet", "author_id": 2123176, "author_profile": "https://Stackoverflow.com/users/2123176", "pm_score": 3, "selected": false, "text": "import threading\nimport time\nimport atexit\n\ndef do_work():\n\n i = 0\n @atexit.register\n def goodbye():\n print (\"'CLEANLY' kill sub-thread with value: %s [THREAD: %s]\" %\n (i, threading.currentThread().ident))\n\n while True:\n print i\n i += 1\n time.sleep(1)\n\nt = threading.Thread(target=do_work)\nt.daemon = True\nt.start()\n\ndef after_timeout():\n print \"KILL MAIN THREAD: %s\" % threading.currentThread().ident\n raise SystemExit\n\nthreading.Timer(2, after_timeout).start()\n 0\n1\nKILL MAIN THREAD: 140013208254208\n'CLEANLY' kill sub-thread with value: 2 [THREAD: 140013674317568]\n" }, { "answer_id": 57791772, "author": "rundekugel", "author_id": 4130788, "author_profile": "https://Stackoverflow.com/users/4130788", "pm_score": 2, "selected": false, "text": "import time\nfrom threading import Thread\n\ndef doit(id=0):\n doit.stop=0\n print(\"start id:%d\"%id)\n while 1:\n time.sleep(1)\n print(\".\")\n if doit.stop==id:\n doit.stop=0\n break\n print(\"end thread %d\"%id)\n\nt5=Thread(target=doit, args=(5,))\nt6=Thread(target=doit, args=(6,))\n\nt5.start() ; t6.start()\ntime.sleep(2)\ndoit.stop =5 #kill t5\ntime.sleep(2)\ndoit.stop =6 #kill t6\n functionname.stop doit.stop" }, { "answer_id": 60856787, "author": "Tim Meehan", "author_id": 10744405, "author_profile": "https://Stackoverflow.com/users/10744405", "pm_score": 2, "selected": false, "text": "from threading import Thread, Event\n\nclass KillableThread(Thread):\n def __init__(self, sleep_interval=1, target=None, name=None, args=(), kwargs={}):\n super().__init__(None, target, name, args, kwargs)\n self._kill = Event()\n self._interval = sleep_interval\n print(self._target)\n\n def run(self):\n while True:\n # Call custom function with arguments\n self._target(*self._args)\n\n # If no kill signal is set, sleep for the interval,\n # If kill signal comes in while sleeping, immediately\n # wake up and handle\n is_killed = self._kill.wait(self._interval)\n if is_killed:\n break\n\n print(\"Killing Thread\")\n\n def kill(self):\n self._kill.set()\n\nif __name__ == '__main__':\n\n def print_msg(msg):\n print(msg)\n\n t = KillableThread(10, print_msg, args=(\"hello world\"))\n t.start()\n time.sleep(6)\n print(\"About to kill thread\")\n t.kill()\n" }, { "answer_id": 62132057, "author": "Basj", "author_id": 1422096, "author_profile": "https://Stackoverflow.com/users/1422096", "pm_score": 1, "selected": false, "text": "import sys, threading, time \n\nclass TraceThread(threading.Thread): \n def __init__(self, *args, **keywords): \n threading.Thread.__init__(self, *args, **keywords) \n self.killed = False\n def start(self): \n self._run = self.run \n self.run = self.settrace_and_run\n threading.Thread.start(self) \n def settrace_and_run(self): \n sys.settrace(self.globaltrace) \n self._run()\n def globaltrace(self, frame, event, arg): \n return self.localtrace if event == 'call' else None\n def localtrace(self, frame, event, arg): \n if self.killed and event == 'line': \n raise SystemExit() \n return self.localtrace \n\ndef f(): \n while True: \n print('1') \n time.sleep(2)\n print('2') \n time.sleep(2)\n print('3') \n time.sleep(2)\n\nt = TraceThread(target=f) \nt.start() \ntime.sleep(2.5) \nt.killed = True\n 1 2 3" }, { "answer_id": 65534218, "author": "serg06", "author_id": 5090928, "author_profile": "https://Stackoverflow.com/users/5090928", "pm_score": 3, "selected": false, "text": "import ctypes \n\ndef kill_thread(thread):\n \"\"\"\n thread: a threading.Thread object\n \"\"\"\n thread_id = thread.ident\n res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))\n if res > 1:\n ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)\n print('Exception raise failure')\n" }, { "answer_id": 66904089, "author": "林奕忠", "author_id": 1584100, "author_profile": "https://Stackoverflow.com/users/1584100", "pm_score": 2, "selected": false, "text": "def main():\n start_time = time.perf_counter()\n t1 = ExitThread(time.sleep, (10,), debug=False)\n t1.start()\n time.sleep(0.5)\n t1.exit()\n try:\n print(t1.result_future.result())\n except concurrent.futures.CancelledError:\n pass\n end_time = time.perf_counter()\n print(f\"time cost {end_time - start_time:0.2f}\")\n import concurrent.futures\nimport threading\nimport typing\nimport asyncio\n\n\nclass _WorkItem(object):\n \"\"\" concurrent\\futures\\thread.py\n\n \"\"\"\n\n def __init__(self, future, fn, args, kwargs, *, debug=None):\n self._debug = debug\n self.future = future\n self.fn = fn\n self.args = args\n self.kwargs = kwargs\n\n def run(self):\n if self._debug:\n print(\"ExitThread._WorkItem run\")\n if not self.future.set_running_or_notify_cancel():\n return\n\n try:\n coroutine = None\n if asyncio.iscoroutinefunction(self.fn):\n coroutine = self.fn(*self.args, **self.kwargs)\n elif asyncio.iscoroutine(self.fn):\n coroutine = self.fn\n if coroutine is None:\n result = self.fn(*self.args, **self.kwargs)\n else:\n result = asyncio.run(coroutine)\n if self._debug:\n print(\"_WorkItem done\")\n except BaseException as exc:\n self.future.set_exception(exc)\n # Break a reference cycle with the exception 'exc'\n self = None\n else:\n self.future.set_result(result)\n\n\nclass ExitThread:\n \"\"\" Like a stoppable thread\n\n Using coroutine for target then exit before running may cause RuntimeWarning.\n\n \"\"\"\n\n def __init__(self, target: typing.Union[typing.Coroutine, typing.Callable] = None\n , args=(), kwargs={}, *, daemon=None, debug=None):\n #\n self._debug = debug\n self._parent_thread = threading.Thread(target=self._parent_thread_run, name=\"ExitThread_parent_thread\"\n , daemon=daemon)\n self._child_daemon_thread = None\n self.result_future = concurrent.futures.Future()\n self._workItem = _WorkItem(self.result_future, target, args, kwargs, debug=debug)\n self._parent_thread_exit_lock = threading.Lock()\n self._parent_thread_exit_lock.acquire()\n self._parent_thread_exit_lock_released = False # When done it will be True\n self._started = False\n self._exited = False\n self.result_future.add_done_callback(self._release_parent_thread_exit_lock)\n\n def _parent_thread_run(self):\n self._child_daemon_thread = threading.Thread(target=self._child_daemon_thread_run\n , name=\"ExitThread_child_daemon_thread\"\n , daemon=True)\n self._child_daemon_thread.start()\n # Block manager thread\n self._parent_thread_exit_lock.acquire()\n self._parent_thread_exit_lock.release()\n if self._debug:\n print(\"ExitThread._parent_thread_run exit\")\n\n def _release_parent_thread_exit_lock(self, _future):\n if self._debug:\n print(f\"ExitThread._release_parent_thread_exit_lock {self._parent_thread_exit_lock_released} {_future}\")\n if not self._parent_thread_exit_lock_released:\n self._parent_thread_exit_lock_released = True\n self._parent_thread_exit_lock.release()\n\n def _child_daemon_thread_run(self):\n self._workItem.run()\n\n def start(self):\n if self._debug:\n print(f\"ExitThread.start {self._started}\")\n if not self._started:\n self._started = True\n self._parent_thread.start()\n\n def exit(self):\n if self._debug:\n print(f\"ExitThread.exit exited: {self._exited} lock_released: {self._parent_thread_exit_lock_released}\")\n if self._parent_thread_exit_lock_released:\n return\n if not self._exited:\n self._exited = True\n if not self.result_future.cancel():\n if self.result_future.running():\n self.result_future.set_exception(concurrent.futures.CancelledError())\n" }, { "answer_id": 72226463, "author": "David Lador", "author_id": 17701030, "author_profile": "https://Stackoverflow.com/users/17701030", "pm_score": -1, "selected": false, "text": "from threading import Thread\nfrom time import sleep\n\ndef do_something():\n global thread_work\n while thread_work:\n print('doing something')\n sleep(5)\n print('Thread stopped')\n\nthread_work = True\nThread(target=do_something).start()\nsleep(5)\nthread_work = False\n" }, { "answer_id": 72625368, "author": "reubano", "author_id": 408556, "author_profile": "https://Stackoverflow.com/users/408556", "pm_score": 1, "selected": false, "text": "signal.pthread_kill from signal import pthread_kill, SIGTSTP\nfrom threading import Thread\nfrom itertools import count\nfrom time import sleep\n\ndef target():\n for num in count():\n print(num)\n sleep(1)\n\nthread = Thread(target=target)\nthread.start()\nsleep(5)\npthread_kill(thread.ident, SIGTSTP)\n 0\n1\n2\n3\n4\n\n[14]+ Stopped\n" }, { "answer_id": 73731044, "author": "Noob Master", "author_id": 13767437, "author_profile": "https://Stackoverflow.com/users/13767437", "pm_score": -1, "selected": false, "text": "if thread.is_alive():\n print(\"thread alive\")\nelse:\n print(\"thread is killed\")\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28121/" ]
323,977
<p>i'm trying to use the GeoKit plugin to calculate the distance between 2 points. So the idea is, i do a search for an article, and the results i want to order by distance. So i have a form where I enter the article (that im looking for) and my address. Then rails must find all articles that match with my query and order by address.</p> <p>So now, i have two models: Article and User. Articles belongs_to User and User has_many Articles. At the User model i have the info related with my latitude and longitude.</p> <p>So my Article object has three fields:</p> <ul> <li>id</li> <li>name</li> <li>user_id (FK to User model)</li> </ul> <p>And my user model has four fields</p> <ul> <li>id</li> <li>name</li> <li>lat (latitude)</li> <li>lng (longitude)</li> </ul> <p>OK, to have access to the user info thru articles i do the query:</p> <pre><code>@articles = Article.find(:all,:conditions=&gt;"vectors @@ to_tsquery('büch')",:joins=&gt;" INNER JOIN users ON users.id = articles.user_id",:include=&gt;:user,:origin=&gt;"Augustusplatz,8,leipzig,germany") </code></pre> <p>it works. But when i wanna add an :order=>'distance ASC' it fails because the order by query is using a Article.lat, and Article.lng fields to calculate the distance, but these fields lat and lng, are User object's members and not Article member.</p> <p>BTW if I get the query generated by rails and i change the order by clause where uses articles.lat/lng to users.lat/lng it works.</p>
[ { "answer_id": 324067, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 3, "selected": true, "text": "if(!(foo != !bar & (!baz))) :joins :include @articles = Article.find(:all,\n :conditions=>\"vectors @@ to_tsquery('büch')\",\n :joins=>\" INNER JOIN users ON users.id = articles.user_id\",\n :include=>:user,\n :origin=>\"Augustusplatz,8,leipzig,germany\")\n SELECT (some_heavy_calculation(user.lat, user.long)) AS distance, ... ;\n" }, { "answer_id": 324088, "author": "VP.", "author_id": 18642, "author_profile": "https://Stackoverflow.com/users/18642", "pm_score": 1, "selected": false, "text": "SELECT \"articles\".\"id\" AS t0_r0, \"articles\".\"name\" AS t0_r1, \"articles\".\"price\" AS t0_r2, \"articles\".\"user_id\" AS t0_r3, \"articles\".\"created_at\" AS t0_r4, \"articles\".\"updated_at\" AS t0_r5, \"articles\".\"vectors\" AS t0_r6, \"users_articles\".\"id\" AS t1_r0, \"users_articles\".\"name\" AS t1_r1, \"users_articles\".\"address\" AS t1_r2, \"users_articles\".\"created_at\" AS t1_r3, \"users_articles\".\"updated_at\" AS t1_r4, \"users_articles\".\"lat\" AS t1_r5, \"users_articles\".\"lng\" AS t1_r6, \"users_articles\".\"zipcode\" AS t1_r7 FROM \"articles\" LEFT OUTER JOIN \"users\" users_articles ON \"users_articles\".id = \"articles\".user_id INNER JOIN users ON users.id = articles.user_id WHERE (vectors @@ to_tsquery('büch')) ORDER BY (ACOS(least(1,COS(0.896021391737553)*COS(0.216084610510851)*COS(RADIANS(articles.lat))*COS(RADIANS(articles.lng))+\n COS(0.896021391737553)*SIN(0.216084610510851)*COS(RADIANS(articles.lat))*SIN(RADIANS(articles.lng))+\n SIN(0.896021391737553)*SIN(RADIANS(articles.lat))))*3963.19)\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642/" ]
323,982
<p>I want to parse this XML Document <a href="http://www.google.de/ig/api?weather=Braunschweig,%20Deutschland" rel="nofollow noreferrer">http://www.google.de/ig/api?weather=Braunschweig,%20Deutschland</a> I want to be able to read out condition, temp_c and humidity. All this I want to do inside of JavaScript without using any server sided scripts such as PHP and I want it to work on modern browsers as well as IE7 and if without many problems IE6 EDIT: A solution without a framework would be ideal</p>
[ { "answer_id": 324016, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "var xmlDoc = this.req.responseXML.documentElement;\nvar tStatus = xmlDoc.getElementsByTagName(\"status\")[0].firstChild.data;\nvar tOtherURL = xmlDoc.getElementsByTagName(\"otherurl\")[0].firstChild.data;\nvar tRows = xmlDoc.getElementsByTagName(\"rows\")[0].firstChild.data;\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19929/" ]
323,987
<p>Quick question: Would it be a good or a bad idea to implement my domain-driven design style repositories as singletons? Why?</p> <p>Or should I maybe use a dependency injector container to manage my repositories and decide if they are singletons or not?</p> <p>I'm still reading <em>DDD Quickly</em>, and would like to see some good repository examples.</p>
[ { "answer_id": 323990, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "UserRepository.Instance.Find(userId);\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/323987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22621/" ]
324,014
<p>I've written an image processing script in php which is run as a cron scheduled task (in OSX). To avoid overloading the system, the script checks the system load (using 'uptime') and only runs when load is below a predefined threshold.</p> <p>I've now ported this over to Windows (2003 Server) and am looking for a similar command line function to report system load as an integer or float.</p>
[ { "answer_id": 324114, "author": "ringmaster", "author_id": 40413, "author_profile": "https://Stackoverflow.com/users/40413", "pm_score": 0, "selected": false, "text": "pve.exe -o\"%n\\t%c\"\n -?" }, { "answer_id": 368299, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "nice(1)" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12280/" ]
324,032
<p>After creating a translucent window (<a href="http://stormsilver.net/itunescheck/browser/tags/0.91/TransparentWindow.m?rev=25" rel="noreferrer">based on example code by Matt Gemmell</a>) I want to get keyboard events in this window. It seems that there are only keyboard events when my application is the active application while I want keyboard events even when my application isn't active but the window is visible.</p> <p>Basically I want behavior like that provided by the Quicksilver application (by blacktree).</p> <p>Does anybody have any hints on how to do this?</p>
[ { "answer_id": 324162, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "GetEventMonitorTarget() CGEventTapCreate" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15745/" ]
324,041
<p>I have a folder with these files:</p> <pre><code>alongfilename1.txt &lt;--- created first alongfilename3.txt &lt;--- created second </code></pre> <p>When I run <strong>DIR /x</strong> in command prompt, I see these short names assigned:</p> <pre><code>ALONGF~1.TXT alongfilename1.txt ALONGF~2.TXT alongfilename3.txt </code></pre> <p>Now, if I add another file:</p> <pre><code>alongfilename1.txt alongfilename2.txt &lt;--- created third alongfilename3.txt </code></pre> <p>I see this:</p> <pre><code>ALONGF~1.TXT alongfilename1.txt ALONGF~3.TXT alongfilename2.txt ALONGF~2.TXT alongfilename3.txt </code></pre> <p>Fine. It seems to be assigning the "~#" according to the date/time that I created the file. Is this correct?</p> <p>Now, if I delete "alongfilename1.txt", the other two files <strong>keep their short names</strong>.</p> <pre><code>ALONGF~3.TXT alongfilename2.txt ALONGF~2.TXT alongfilename3.txt </code></pre> <p>When will that ID (in this case, ~1) be released for use in another shortname. Will it ever? </p> <p>Also, is it possible that a file on my machine has a short name of X, whereas the same file has a short name of Y on another machine? I'm particularly concerned for installations whose custom actions utilize DOS short names.</p> <p>Thanks, guys.</p>
[ { "answer_id": 324064, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 4, "selected": true, "text": "counter = 1\nstripped_filename = strip_dots(strip_non_ascii_characters(filename))\nshortfn = first_6_characters(stripped_filename)\nwhile (file_exists(shortfn + \"~\" + counter + \".\" + extension)) {\n increment counter by 1\n if more digits are added to counter, shorten shortfn by 1 \n /* e.g. if counter comes to 9 and shortf~9.txt is taken. try short~10.txt next */\n}\n" }, { "answer_id": 324074, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "ALONGF~1.TXT alongfilename1.txt\nALONGF~2.TXT alongfilename2.txt\nALONGF~3.TXT alongfilename3.txt\n" }, { "answer_id": 6471531, "author": "Kevin Panko", "author_id": 125389, "author_profile": "https://Stackoverflow.com/users/125389", "pm_score": 0, "selected": false, "text": " G:\\>dir /x *.txt\n\n Directory of G:\\\n\n08/25/2009 12:34 PM 1,848 S2XYYV~1.TXT strace_output.txt\n03/01/2010 05:32 PM 325,428 TEY7IH~O.TXT tomcat-dump-march-1.txt\n03/11/2010 12:01 AM 5,811 DI356A~S.TXT ddmget-output.txt\n01/23/2009 01:03 PM 313,880 DLA94Q~K.TXT ddm-log-fn.txt\n04/20/2010 07:42 PM 7,491 A50QZP~A.TXT april-20-2010.txt\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21263/" ]
324,043
<p>Assuming a largish template library with around 100 files containing around 100 templates with overall more than 200,000 lines of code. Some of the templates use multiple inheritance to make the usage of the library itself rather simple (i.e. inherit from some base templates and only having to implement certain business rules).</p> <p>All that exists (grown over several years), "works" and is used for projects.</p> <p>However, compilation of projects using that library consumes a growing amount of time and it takes quite some time to locate the source for certain bugs. Fixing often causes unexpected side effects or is quite difficult, because some interdependent templates need changing. Testing is nearly impossible due to the sheer amount of functions.</p> <p>Now, I would really like to simplify the architecture to use less templates and more specialized smaller classes.</p> <p>Is there any proven way to go about that task? What would be a good place to start?</p>
[ { "answer_id": 324119, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "list<1, 3, 3, 1, 3> std::vector void run(); operator()" }, { "answer_id": 324606, "author": "Michel", "author_id": 31122, "author_profile": "https://Stackoverflow.com/users/31122", "pm_score": 0, "selected": false, "text": "boost::enable_shared_from_this" }, { "answer_id": 324819, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 1, "selected": false, "text": "<iosfwd> // .h\ntemplate <typename FLOAT> // float or double only\nFLOAT CalcIt(int len, FLOAT * values) { ... }\n // .h\nfloat CalcIt(int len, float * values);\ndouble CalcIt(int len, double * values);\n\n// .cpp\ntemplate <typename FLOAT> // float or double only\nFLOAT CalcItT(int len, FLOAT * values) { ... }\n\nfloat CalcIt(int len, float * values) { return CalcItT(len, values); }\ndouble CalcIt(int len, double * values) { return CalcItT(len, values); }\n detail .impl.h" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1398/" ]
324,045
<p>Using the .net framework you have the option to create temporary files with</p> <pre><code>Path.GetTempFileName(); </code></pre> <p>The MSDN doesn't tell us what happens to temporary files. I remember reading somewhere that they are deleted by the OS when it gets a restart. Is this true?</p> <p>If the files aren't deleted by the OS, why are they called temporary? They are normal files in a normal directory. </p>
[ { "answer_id": 324051, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "sealed class TempFile : IDisposable { // formatted for space\n string path;\n public string Path {\n get {\n if(path==null) throw new ObjectDisposedException(GetType().Name);\n return path;\n }\n }\n public TempFile() : this(System.IO.Path.GetTempFileName()) { }\n\n public TempFile(string path) {\n if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(\"path\");\n this.path = path;\n }\n\n private void Dispose(bool disposing) {\n if (path != null) {\n try {\n File.Delete(path);\n } catch { } // best endeavours...\n path = null;\n }\n }\n public void Dispose() {\n GC.SuppressFinalize(this);\n Dispose(true);\n }\n ~TempFile() {\n Dispose(false);\n }\n}\n" }, { "answer_id": 324345, "author": "Cristian Diaconescu", "author_id": 11545, "author_profile": "https://Stackoverflow.com/users/11545", "pm_score": 7, "selected": true, "text": "Path.GetTempFileName() GetTempFileName() //actual .NET 2.0 decompiled code \n// .NET Reflector rocks for looking at plumbing\npublic static string GetTempFileName()\n{\n string tempPath = GetTempPath();\n new FileIOPermission(FileIOPermissionAccess.Write, tempPath).Demand();\n StringBuilder tmpFileName = new StringBuilder(260);\n if (Win32Native.GetTempFileName(tempPath, \"tmp\", 0, tmpFileName) == 0)\n {\n __Error.WinIOError();\n }\n return tmpFileName.ToString();\n}\n FileOption.DeleteOnClose FileAttributes.Temporary using System;\nusing System.IO;\nusing System.Security.Permissions;\nusing System.Security.Principal;\nusing System.Security.AccessControl;\n\npublic static class PathUtility\n{\n private const int defaultBufferSize = 0x1000; // 4KB\n\n#region GetSecureDeleteOnCloseTempFileStream\n\n /// <summary>\n /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream.\n /// </summary>\n /// <remarks>\n /// <para>The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.</para>\n /// <para>The <see cref=\"GetSecureDeleteOnCloseTempFileStream\"/> method will raise an <see cref=\"IOException\"/> if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.</para>\n /// <para>The file is created as a zero-byte file in the system's temporary folder.</para>\n /// <para>The file owner is set to the current user. The file security permissions grant full control to the current user only.</para>\n /// <para>The file sharing is set to none.</para>\n /// <para>The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.</para>\n /// <para>The system deletes the file immediately after it is closed or the <see cref=\"FileStream\"/> is finalized.</para>\n /// </remarks>\n /// <returns>The opened <see cref=\"FileStream\"/> object.</returns>\n public static FileStream GetSecureDeleteOnCloseTempFileStream()\n { \n return GetSecureDeleteOnCloseTempFileStream(defaultBufferSize, FileOptions.DeleteOnClose); \n }\n\n /// <summary>\n /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream with the specified buffer size.\n /// </summary>\n /// <remarks>\n /// <para>The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.</para>\n /// <para>The <see cref=\"GetSecureDeleteOnCloseTempFileStream\"/> method will raise an <see cref=\"IOException\"/> if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.</para>\n /// <para>The file is created as a zero-byte file in the system's temporary folder.</para>\n /// <para>The file owner is set to the current user. The file security permissions grant full control to the current user only.</para>\n /// <para>The file sharing is set to none.</para>\n /// <para>The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.</para>\n /// <para>The system deletes the file immediately after it is closed or the <see cref=\"FileStream\"/> is finalized.</para>\n /// </remarks>\n /// <param name=\"bufferSize\">A positive <see cref=\"Int32\"/> value greater than 0 indicating the buffer size.</param>\n /// <returns>The opened <see cref=\"FileStream\"/> object.</returns>\n public static FileStream GetSecureDeleteOnCloseTempFileStream(int bufferSize)\n {\n return GetSecureDeleteOnCloseTempFileStream(bufferSize, FileOptions.DeleteOnClose);\n }\n\n /// <summary>\n /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream with the specified buffer size and file options.\n /// </summary> \n /// <remarks>\n /// <para>The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.</para>\n /// <para>The <see cref=\"GetSecureDeleteOnCloseTempFileStream\"/> method will raise an <see cref=\"IOException\"/> if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.</para>\n /// <para>The file is created as a zero-byte file in the system's temporary folder.</para>\n /// <para>The file owner is set to the current user. The file security permissions grant full control to the current user only.</para>\n /// <para>The file sharing is set to none.</para>\n /// <para>The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.</para>\n /// <para>The system deletes the file immediately after it is closed or the <see cref=\"FileStream\"/> is finalized.</para>\n /// <para>Use the <paramref name=\"options\"/> parameter to specify additional file options. You can specify <see cref=\"FileOptions.Encrypted\"/> to encrypt the file contents using the current user account. Specify <see cref=\"FileOptions.Asynchronous\"/> to enable overlapped I/O when using asynchronous reads and writes.</para>\n /// </remarks>\n /// <param name=\"bufferSize\">A positive <see cref=\"Int32\"/> value greater than 0 indicating the buffer size.</param>\n /// <param name=\"options\">A <see cref=\"FileOptions\"/> value that specifies additional file options.</param>\n /// <returns>The opened <see cref=\"FileStream\"/> object.</returns>\n public static FileStream GetSecureDeleteOnCloseTempFileStream(int bufferSize, FileOptions options)\n { \n FileStream fs = GetSecureFileStream(Path.GetTempPath(), bufferSize, options | FileOptions.DeleteOnClose);\n\n File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.Temporary);\n\n return fs; \n }\n\n#endregion\n\n#region GetSecureTempFileStream\n\n public static FileStream GetSecureTempFileStream()\n { \n return GetSecureTempFileStream(defaultBufferSize, FileOptions.None); \n }\n\n public static FileStream GetSecureTempFileStream(int bufferSize)\n {\n return GetSecureTempFileStream(bufferSize, FileOptions.None);\n }\n\n public static FileStream GetSecureTempFileStream(int bufferSize, FileOptions options)\n {\n FileStream fs = GetSecureFileStream(Path.GetTempPath(), bufferSize, options);\n\n File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.NotContentIndexed | FileAttributes.Temporary);\n\n return fs;\n }\n\n #endregion\n\n#region GetSecureTempFileName\n\n public static string GetSecureTempFileName()\n { \n return GetSecureTempFileName(false); \n }\n\n public static string GetSecureTempFileName(bool encrypted)\n { \n using (FileStream fs = GetSecureFileStream(Path.GetTempPath(), defaultBufferSize, encrypted ? FileOptions.Encrypted : FileOptions.None))\n { \n File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.NotContentIndexed | FileAttributes.Temporary);\n\n return fs.Name; \n }\n\n }\n\n#endregion\n\n#region GetSecureFileName\n\n public static string GetSecureFileName(string path)\n { \n return GetSecureFileName(path, false); \n }\n\n public static string GetSecureFileName(string path, bool encrypted)\n { \n using (FileStream fs = GetSecureFileStream(path, defaultBufferSize, encrypted ? FileOptions.Encrypted : FileOptions.None))\n { \n return fs.Name; \n } \n }\n\n#endregion\n\n#region GetSecureFileStream\n\n public static FileStream GetSecureFileStream(string path)\n { \n return GetSecureFileStream(path, defaultBufferSize, FileOptions.None); \n }\n\n public static FileStream GetSecureFileStream(string path, int bufferSize)\n {\n return GetSecureFileStream(path, bufferSize, FileOptions.None);\n }\n\n public static FileStream GetSecureFileStream(string path, int bufferSize, FileOptions options)\n { \n if (path == null)\n throw new ArgumentNullException(\"path\");\n\n if (bufferSize <= 0)\n throw new ArgumentOutOfRangeException(\"bufferSize\");\n\n if ((options & ~(FileOptions.Asynchronous | FileOptions.DeleteOnClose | FileOptions.Encrypted | FileOptions.RandomAccess | FileOptions.SequentialScan | FileOptions.WriteThrough)) != FileOptions.None)\n throw new ArgumentOutOfRangeException(\"options\");\n\n new FileIOPermission(FileIOPermissionAccess.Write, path).Demand();\n\n SecurityIdentifier user = WindowsIdentity.GetCurrent().User;\n\n FileSecurity fileSecurity = new FileSecurity();\n\n fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow));\n\n fileSecurity.SetAccessRuleProtection(true, false);\n\n fileSecurity.SetOwner(user);\n\n // Attempt to create a unique file three times before giving up.\n // It is highly improbable that there will ever be a name clash,\n // therefore we do not check to see if the file first exists.\n\n for (int attempt = 0; attempt < 3; attempt++)\n { \n try\n { \n return new FileStream(Path.Combine(path, Path.GetRandomFileName()),\n FileMode.CreateNew, FileSystemRights.FullControl,\n FileShare.None, bufferSize, options, fileSecurity);\n }\n\n catch (IOException)\n {\n if (attempt == 2)\n throw;\n }\n\n }\n\n // This code can never be reached.\n // The compiler thinks otherwise.\n throw new IOException();\n\n }\n\n#endregion\n\n}\n" }, { "answer_id": 1793676, "author": "Jonh Clark", "author_id": 212320, "author_profile": "https://Stackoverflow.com/users/212320", "pm_score": -1, "selected": false, "text": "Path.GetTempFileName Public Shared Function GetTempFileName(ByVal extensionWithDot As String) As String\n Dim tempFileName As String\n Do\n tempFileName = System.IO.Path.GetTempFileName\n If extensionWithDot IsNot Nothing Then\n tempFileName = tempFileName.Replace(System.IO.Path.GetExtension(tempFileName), extensionWithDot)\n End If\n Loop While System.IO.File.Exists(tempFileName)\n Return tempFileName\nEnd Function\n public static string GetTempFileName(string extensionWithDot)\n{\n string tempFileName = null;\n do {\n tempFileName = System.IO.Path.GetTempFileName;\n if (extensionWithDot != null) {\n tempFileName = tempFileName.Replace(System.IO.Path.GetExtension(tempFileName), extensionWithDot);\n }\n } while (System.IO.File.Exists(tempFileName));\n return tempFileName;\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21634/" ]
324,047
<p>In an ASP.NET 3.5 site we have a relatively standard payment checkout progess that contains a number of pages that need to be visited in sequence (shopping basket, payment details etc)</p> <p>Each page has a "Continue" button that redirects to the next page in the sequence.</p> <p>I would like a way of managing the page sequence so that:</p> <ol> <li>I can have a Master page that defines the "Continue" button and its code-behind OnClick event handler</li> <li>If the user attempts to visit a page out of sequence (by typing the URL directly into their browser, for example) they get redirected to the correct page</li> <li>This page sequence is nicely defined in one place in my code (in an enum for example)</li> </ol>
[ { "answer_id": 329970, "author": "IrishChieftain", "author_id": 31444, "author_profile": "https://Stackoverflow.com/users/31444", "pm_score": 1, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n Session[\"PreviousPage\"] = Request.UrlReferrer.ToString();\n ...\n }\n else\n {\n ...\n }\n} \n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39709/" ]
324,053
<p>I'm trying to find out how much memory my objects take to see how many of them are ending up on the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap" rel="nofollow noreferrer">Large Object Heap</a> (which is anything over 85,000 bytes).</p> <p>Is it as simple as adding 4 for an int, 8 for a long, 4 (or 8 if you're on 64 bit) for any reference types etc for each object, or are there overheads for methods, properties, etc.?</p>
[ { "answer_id": 324100, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 2, "selected": false, "text": "Single, Int32, UInt32 - 4\nIntPtr, UIntPtr, pointers, references - 4 on 32-bit, 8 on 64-bit\nDouble, Int64, UInt64 - 8\nChar, Int16, UInt16 - 2\nByte, SByte - 1\n" }, { "answer_id": 6580602, "author": "serhio", "author_id": 185593, "author_profile": "https://Stackoverflow.com/users/185593", "pm_score": 4, "selected": false, "text": "Dim myObjectSize As Long\n\nDim ms As New IO.MemoryStream\nDim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\nbf.Serialize(ms, myObject)\nmyObjectSize = ms.Position\n" }, { "answer_id": 7122653, "author": "Gomes", "author_id": 902539, "author_profile": "https://Stackoverflow.com/users/902539", "pm_score": 5, "selected": false, "text": ".load sos.dll !DumpHeap -type MyClass !ObjSize 00a8197c" }, { "answer_id": 9870537, "author": "IvanH", "author_id": 669527, "author_profile": "https://Stackoverflow.com/users/669527", "pm_score": 3, "selected": false, "text": ".load sos !ObjSize tbl .load sos\nextension C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\sos.dll loaded\n? string.Format(\"{0:x}\",Integer.Parse(System.Runtime.InteropServices.GCHandle.InternalAddrOfPinnedObject(System.Runtime.InteropServices.GCHandle.Alloc(tbl).GetHandleValue()).ToString())-4)\n\"27ccb18\"\n!ObjSize 27ccb18\nPDB symbol for clr.dll not loaded\nsizeof(027ccb18) = 154504 ( 0x25b88) bytes (System.Data.DataTable)\n" }, { "answer_id": 70094366, "author": "KUTlime", "author_id": 4553982, "author_profile": "https://Stackoverflow.com/users/4553982", "pm_score": 0, "selected": false, "text": "Dictionary<TKey, TValue> var dictionary = new DictionaryGenerator().GetSomeLargeDictionary();\nvar memoryStream = new System.IO.MemoryStream();\nvar binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\nbinaryFormatter.Serialize(memoryStream, dictionary);\nConsole.WriteLine($\"Size of dictionary: {memoryStream.Position} byte(s)\");\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6713/" ]
324,062
<p>I'm looking for a syntax highlighter cum code formatter for my blog on BlogSpot. I've tried several today, but the all want to include <code>&lt;style&gt;</code> tags, or reference a stylesheet. I'm looking for one that is ideal for segments of code, and includes styling inline. Any suggestions?</p>
[ { "answer_id": 324075, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 0, "selected": false, "text": "pygmentize -f png -o mysource.png mysource.cs \n" }, { "answer_id": 324190, "author": "Paul Fisher", "author_id": 39808, "author_profile": "https://Stackoverflow.com/users/39808", "pm_score": 3, "selected": true, "text": "<head>" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
324,066
<p>I have a BasePage class which all other pages derive from:</p> <pre><code>public class BasePage </code></pre> <p>This BasePage has a constructor which contains code which must always run:</p> <pre><code>public BasePage() { // Important code here } </code></pre> <p>I want to force derived classes to call the base constructor, like so:</p> <pre><code>public MyPage : base() { // Page specific code here } </code></pre> <p><strong>How can I enforce this (preferably at compile time)?</strong></p>
[ { "answer_id": 324078, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "this(...) base(...) base(...)" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124/" ]
324,080
<p>I'm extending the functionality of a class with a subclass, and I'm doing some dirty stuff that make superclass methods dangerous (app will hang in a loop) in the context of the subclass. I know it's not a genius idea, but I'm going for the low-hanging fruit, right now it's gonna save me some time. Oh it's a dirty job, but someone's gotta do it. </p> <p>Bottom line, I need to either block that method from outside, or throw an exception when it's called directly to the superclass. (But I still use it from the subclass, except with care).</p> <p>What would be the best way to do this?</p> <p>UPDATE ---</p> <p>So this is what I went for. I'm not self-answering, as Boaz' answer mentions multiple valid ways to do this, this is just the way that suited me. In the subclass, I overrode the method like this:</p> <pre><code>- (int)dangerousMethod { [NSException raise:@"Danger!" format:@"Do not call send this method directly to this subclass"]; return nil; } </code></pre> <p>I'm marking this as answered, but evidently that doesn't mean it's closed, further suggestions are welcome.</p>
[ { "answer_id": 324201, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "@implementation MyClass\n-(void)myMethod:(NSString *)txt{\n if([self class] != [MyClass class]) return;\n NSLog(@\"Hello\");\n}\n@end\n" }, { "answer_id": 16878136, "author": "Jeff Wolski", "author_id": 731773, "author_profile": "https://Stackoverflow.com/users/731773", "pm_score": 3, "selected": false, "text": ".h dangerousMethod .h - (int)dangerousMethod __attribute__((unavailable(\"message\")));\n dangerousMethod .m - (int)dangerousMethod \n{\n return nil; \n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36182/" ]
324,085
<p>I want to know how to set a Publishing page content through the code (MOSS 2007).<br> This is how I've created the page:</p> <pre><code>PublishingPage page = publishingWeb.GetPublishingPages().Add("MyPage.aspx", pageLayout); SPFile pageFile = page.ListItem.File; page.Title = "My Page"; page.Update(); </code></pre> <p>But my attempts of setting it's content didn't work.</p>
[ { "answer_id": 324313, "author": "Pedrin", "author_id": 36183, "author_profile": "https://Stackoverflow.com/users/36183", "pm_score": 3, "selected": false, "text": "string content = \"Welcome to <strong>My Page</strong>\";\npage.ListItem[FieldId.PublishingPageContent] = content;\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36183/" ]
324,091
<p>I saw something about needing to have the assembly available for the type of the first argument passed to the function. I think it is, I can't figure out what am I missing.</p> <p>This code is in a service. I was running the service under the 'NETWORK SERVICES' user account, when I changed the account to that of the session I was logged on with it worked ok. But, what's the difference, and how can I get it to work for the NETWORK SERVICES user.</p>
[ { "answer_id": 12169675, "author": "Haukman", "author_id": 793493, "author_profile": "https://Stackoverflow.com/users/793493", "pm_score": 0, "selected": false, "text": "<configuration>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <probing privatePath=\"bin\"/>\n </assemblyBinding>\n </runtime>\n</configuration>\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ]
324,099
<p>I know each iPhone has a electronic identifier other than the phone # or ESN - how do I call it and what does it return?</p>
[ { "answer_id": 324121, "author": "Rob Drimmie", "author_id": 24213, "author_profile": "https://Stackoverflow.com/users/24213", "pm_score": 3, "selected": false, "text": "[[UIDevice currentDevice] uniqueIdentifier]" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38953/" ]
324,102
<p>I'm building a full-screen demo where I need to simulate a YouTube video. I dragged a video that plays an external .flv file.</p> <p>It works fine if the stage isn't set to full-screen. But I need to set the stage to full-screen like this:</p> <pre><code>stage.displayState = StageDisplayState.FULL_SCREEN; stage.scaleMode = StageScaleMode.NO_SCALE; </code></pre> <p>The problem is that when the animation reaches the video the screen goes black and the video doesn't play. I already setting an instance name and tried putting the following code on the frame's actions:</p> <pre><code>video.fullScreenTakeOver = false; </code></pre> <p>But it doesn't affect the issue.</p> <p>Is there anyway to have the stage in full-screen mode and play the video at it's normal size?</p> <p>Thaks</p> <p>I'm using Flash CS3 Pro and generating a .exe.</p>
[ { "answer_id": 4167405, "author": "geepers", "author_id": 506066, "author_profile": "https://Stackoverflow.com/users/506066", "pm_score": 1, "selected": false, "text": "flvPlayback flvPlayback video.fullScreenTakeOver = false;" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
324,105
<p>Can anyone point me out, how can I parse/evaluate HQL and get map where key is table alias and value - full qualified class name.</p> <p>E.g. for HQL</p> <blockquote> <p>SELECT a.id from Foo a INNER JOIN a.test b</p> </blockquote> <p>I wish to have pairs:</p> <p>a, package1.Foo</p> <p>b. package2.TestClassName</p> <p>It's relatively easy to do for result set</p> <blockquote> <pre><code>HQLQueryPlan hqlPlan = ((SessionFactoryImpl)sf).getQueryPlanCache().getHQLQueryPlan( getQueryString(), false, ((SessionImpl)session).getEnabledFilters() ); String[] aliases = hqlPlan.getReturnMetadata().getReturnAliases(); Type[] types = hqlPlan.getReturnMetadata().getReturnTypes(); </code></pre> </blockquote> <p>See <a href="http://www.hibernate.org/389.html" rel="nofollow noreferrer">details here</a>.</p>
[ { "answer_id": 381210, "author": "Rolf Rander", "author_id": 47402, "author_profile": "https://Stackoverflow.com/users/47402", "pm_score": 3, "selected": true, "text": "QueryTranslator[] translators = hqlPlan.getTranslators();\nAST ast = (AST)((QueryTranslatorImpl)translators[0]).getSqlAST();\n new NodeTraverser(new NodeTraverser.VisitationStrategy() {\n public void visit(AST node) {\n if(node.getType() == SqlTokenTypes.FROM_FRAGMENT || node.getType() == SqlTokenTypes.JOIN_FRAGMENT) {\n FromElement id = (FromElement)node;\n System.out.println(node+\": \"+id.getClassAlias()+\" - \"+id.getClassName());\n }\n }\n}).traverseDepthFirst(ast);\n" }, { "answer_id": 383114, "author": "FoxyBOA", "author_id": 19347, "author_profile": "https://Stackoverflow.com/users/19347", "pm_score": 0, "selected": false, "text": "if(node.getType() == SqlTokenTypes.FROM_FRAGMENT || node.getType() == SqlTokenTypes.JOIN_FRAGMENT) {\n FromElement id = (FromElement)node;\n System.out.println(node+\": \"+id.getClassAlias()+\" - \"+id.getClassName());\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19347/" ]
324,132
<p>Imagine I have the following:</p> <pre><code>inFile = "/adda/adas/sdas/hello.txt" # that instruction give me hello.txt Name = inFile.name.split("/") [-1] # that one give me the name I want - just hello Name1 = Name.split(".") [0] </code></pre> <p>Is there any chance to simplify that doing the same job in just one expression?</p>
[ { "answer_id": 324139, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": ">>> inFile = \"/adda/adas/sdas/hello.txt\"\n>>> inFile.split('/')[-1]\n'hello.txt'\n>>> inFile.split('/')[-1].split('.')[0]\n'hello'\n" }, { "answer_id": 324141, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 5, "selected": true, "text": "from os.path import basename, splitext\n\npathname = \"/adda/adas/sdas/hello.txt\"\nname, extension = splitext(basename(pathname))\nprint name # --> \"hello\"\n" }, { "answer_id": 324175, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 1, "selected": false, "text": "from os.path import split, splitext\npath = \"/adda/adas/sdas/hello.txt\"\nprint splitext(split(path)[1])[0]\n" }, { "answer_id": 324684, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 2, "selected": false, "text": "import re\ninFile = \"/adda/adas/sdas/hello.txt\"\nprint re.split('\\.|/', inFile)[-2]\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
324,134
<p>I have a plugin project I've been developing for a few years where the plugin works with numerous combinations of [primary application version, 3rd party library version, 32-bit vs. 64-bit]. Is there a (clean) way to use autotools to create a single makefile that builds all versions of the plugin. </p> <p>As far as I can tell from skimming through the autotools documentation, the closest approximation to what I'd like is to have N independent copies of the project, each with its own makefile. This seems a little suboptimal for testing and development as (a) I'd need to continually propagate code changes across all the different copies and (b) there is a lot of wasted space in duplicating the project so many times. Is there a better way?</p> <p><strong>EDIT:</strong> </p> <p>I've been rolling my own solution for a while where I have a fancy makefile and some perl scripts to hunt down various 3rd party library versions, etc. As such, I'm open to other non-autotools solutions. For other build tools, I'd want them to be very easy for end users to install. The tools also need to be smart enough to hunt down various 3rd party libraries and headers without a huge amount of trouble. I'm mostly looking for a linux solution, but one that also works for Windows and/or the Mac would be a bonus. </p>
[ { "answer_id": 324156, "author": "Gregor", "author_id": 26153, "author_profile": "https://Stackoverflow.com/users/26153", "pm_score": 1, "selected": false, "text": "env.ParseConfig('pkg-config --cflags --libs glib-2.0')\n make" }, { "answer_id": 324372, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "./configure\n ./configure --use-tppkg=/opt/tp/pkg32-1.0.3\n ./configure --help Configure ./configure --use-tppkg=/opt/tp/pkg32-1.0.3 --use-tppkg=/opt/tp/pkg64-1.1.2\n ./configure --use-tppkg32=/opt/tp/pkg32-1.0.3 --use-tppkg64=/opt/tp/pkg64-1.1.2\n obj-32 obj-64 FLAGS_32 = ...32-bit compiler options...\nFLAGS_64 = ...64-bit compiler options...\n\nTPPKG32DIR = @TPPKG32DIR@\nTPPKG64DIR = @TPPKG64DIR@\n\nOBJ32DIR = obj-32\nOBJ64DIR = obj-64\n\nBUILD_32 = @BUILD_32@\nBUILD_64 = @BUILD_64@\n\nTPPKGDIR =\nOBJDIR =\nFLAGS =\n\nall: ${BUILD_32} ${BUILD_64}\n\nbuild_32:\n ${MAKE} TPPKGDIR=${TPPKG32DIR} OBJDIR=${OBJ32DIR} FLAGS=${FLAGS_32} build\n\nbuild_64:\n ${MAKE} TPPKGDIR=${TPPKG64DIR} OBJDIR=${OBJ64DIR} FLAGS=${FLAGS_64} build\n\nbuild: ${OBJDIR}/plugin.so\n make all make make make .c.o ${CC} ${CFLAGS} -o ${OBJDIR}/$*.o -c $*.c\n FLAGS_32 = -m32 , and so when building the 32-bit version, would be included in the" }, { "answer_id": 3016928, "author": "Alex", "author_id": 363762, "author_profile": "https://Stackoverflow.com/users/363762", "pm_score": 0, "selected": false, "text": "mkdir build1 build2 build3\ncd build1\n../configure $(YOUR_OPTIONS)\ncd build2\n../configure $(YOUR_OPTIONS2)\n[...]\n make -C build1 -C build2 -C build3\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25050/" ]
324,163
<p>We are deciding the naming convention for tables, columns, procedures, etc. at our development team at work. The singular-plural table naming <em>has already been decided</em>, we are using singular. We are discussing whether to use a prefix for each table name or not. I would like to read suggestions about using a prefix or not, and why.</p> <p>Does it provide any security at all (at least one more obstacle for a possible intruder)? I think it's generally more comfortable to name them with a prefix, in case we are using a table's name in the code, so to not confuse them with variables, attributes, etc. But I would like to read opinions from more experienced developers.</p>
[ { "answer_id": 324197, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": " stnUsers = 'users';\n stnPosts = 'posts';\n strtblUsers, strtblnmeUsers, thisisthenameofatableyouguysUsers..." }, { "answer_id": 953088, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 2, "selected": false, "text": "[ActiveRecord]\npublic class Person\n{\n [PrimaryKey]\n public Int32 Id { get; set; }\n\n [Property]\n public String Name { get; set; }\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1492/" ]
324,167
<p>Assuming a variable contains spaces, newlines, and tabs followed by some text, why does this:</p> <pre><code>${var#"${var%%[![:space:]]*}"} # strip var of everything # but whitespace # then remove what's left # (i.e. the whitespace) from var </code></pre> <p>remove the white space and leave the text, but this:</p> <pre><code>${var##[:space:]*} # strip all whitespace from var </code></pre> <p>does not?</p>
[ { "answer_id": 324221, "author": "flolo", "author_id": 36472, "author_profile": "https://Stackoverflow.com/users/36472", "pm_score": 6, "selected": true, "text": "var=\" This is a test \" ${var//[[:space:]]}\n" }, { "answer_id": 14726232, "author": "Bryant Hansen", "author_id": 2046366, "author_profile": "https://Stackoverflow.com/users/2046366", "pm_score": 0, "selected": false, "text": "> a=\" 123 456 \" ; a2=\"$(echo $a)\" ; echo \"a=\\\"${a}\\\" a2=\\\"${a2}\\\"\"\na=\" 123 456 \" a2=\"123 456\"\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1094969/" ]
324,168
<p>All,</p> <p>this is my code</p> <pre><code>//declare string pointer BSTR markup; //initialize markup to some well formed XML &lt;- //declare and initialize XML Document MSXML2::IXMLDOMDocument2Ptr pXMLDoc; HRESULT hr; hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40)); pXMLDoc-&gt;async = VARIANT_FALSE; pXMLDoc-&gt;validateOnParse = VARIANT_TRUE; pXMLDoc-&gt;preserveWhiteSpace = VARIANT_TRUE; //load markup into XML document vtBoolResult = pXMLDoc-&gt;loadXML(markup); //do some changes to the XML file&lt;- //get back string from XML doc markup = pXMLDoc-&gt;Getxml(); //&lt;-- this retrieves RUBBISH </code></pre> <p>At this point my string is mangled (just a few chinese characters at the start then rubbish) . Looks like an encoding issue.</p> <p>I also tried the following:</p> <pre><code>_bstr_t superMarkup = _bstr_t(markup); //did my stuff superMarkup = pXMLDoc-&gt;Getxml(); markup = superMarkup; </code></pre> <p>but still I am getting the same result.</p> <p>Even if I call GetXML() without changing anything in the xml document I still get rubbish.</p> <p>At this point if I try to assign the mangled pointer to another pointer it will trow an error:</p> <blockquote> <p>Attempted to restore write protected memory. this is often an indication that other memory is corrupted. </p> </blockquote> <p>Any suggestion?</p> <p>EDIT1:</p> <p><strong>I found out this is happening in relation to the size of the XML string. If it happens on a given XML string and I reduce the size (keeping the same schema) it will work fine. Looks like MSXML2::DOMDocument40 has a limitation on size? In detail it happens if I have more than 16407 characters. I have one more GetXML will retrieve RUBBISH - if it's &lt;= 16407 everything works fine.</strong></p> <p>EDIT2:</p> <p><strong>Roddy was right - I was missing that <code>_bstr_t</code> is a class ...</strong></p> <p>Rings any bell?</p> <p>Cheers</p>
[ { "answer_id": 324343, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 3, "selected": true, "text": " BSTR Markup;\n bstr_t Markup;\n" }, { "answer_id": 324475, "author": "Eugenio Miró", "author_id": 41236, "author_profile": "https://Stackoverflow.com/users/41236", "pm_score": 1, "selected": false, "text": "#import \"MSXML3.DLL\"\n extern \"C\" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, \n LPTSTR /*lpCmdLine*/, int nShowCmd)\n{\n CoInitialize(NULL);\n {\n //declare string pointer\n _bstr_t markup;\n //initialize markup to some well formed XML <-\n //declare and initialize XML Document\n MSXML2::IXMLDOMDocument2Ptr pXMLDoc;\n HRESULT hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument));\n\n pXMLDoc->async = VARIANT_FALSE;\n pXMLDoc->validateOnParse = VARIANT_TRUE;\n pXMLDoc->preserveWhiteSpace = VARIANT_TRUE; \n\n //load markup into XML document\n VARIANT_BOOL vtBoolResult = pXMLDoc->loadXML(L\"<XML></XML>\");\n\n //do some changes to the XML file<-\n //get back string from XML doc\n markup = pXMLDoc->Getxml(); //<-- this retrieves RUBBISH (not anymore...)\n ATLTRACE(\"%S\", (BSTR)markup.GetBSTR());\n }\n CoUninitialize();\n return _AtlModule.WinMain(nShowCmd);\n}\n 'getxmltest.exe': Loaded 'C:\\Windows\\winsxs\\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.6001.18000_none_5cdbaa5a083979cc\\comctl32.dll'\n<XML></XML>\n'getxmltest.exe': Unloaded 'C:\\Windows\\SysWOW64\\msxml3.dll'\nThe program '[6040] getxmltest.exe: Native' has exited with code 0 (0x0).\n" }, { "answer_id": 324593, "author": "Tom Leys", "author_id": 11440, "author_profile": "https://Stackoverflow.com/users/11440", "pm_score": 1, "selected": false, "text": "//get back string from XML doc\nmarkup = pXMLDoc->Getxml(); //<-- this retrieves RUBBISH\n //get back string from XML doc\nBSTR output = pXMLDoc->Getxml(); //<-- perhaps this doesn't\n" }, { "answer_id": 343895, "author": "Eugenio Miró", "author_id": 41236, "author_profile": "https://Stackoverflow.com/users/41236", "pm_score": 1, "selected": false, "text": "extern \"C\" int WINAPI _tWinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, \n LPTSTR /*lpCmdLine*/, int nShowCmd)\n{\n CoInitialize(NULL);\n {\n //declare string pointer\n _bstr_t markup;\n //initialize markup to some well formed XML <-\n //declare and initialize XML Document\n try {\n MSXML2::IXMLDOMDocument2Ptr pXMLDoc;\n HRESULT hr = pXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument)); \n pXMLDoc->async = VARIANT_FALSE;\n pXMLDoc->validateOnParse = VARIANT_TRUE;\n pXMLDoc->preserveWhiteSpace = VARIANT_TRUE; \n\n //load markup into XML document\n VARIANT_BOOL vtBoolResult = pXMLDoc->loadXML(L\"<XML></XML>\");\n\n for (int i = 0; i < 20000; i++) {\n MSXML2::IXMLDOMNodePtr node = pXMLDoc->createNode(_variant_t(\"element\"), _bstr_t(\"child\"), _bstr_t(\"\"));\n\n if (node)\n pXMLDoc->documentElement->appendChild(node);\n }\n\n //do some changes to the XML file<-\n //get back string from XML doc\n markup = pXMLDoc->Getxml(); //<-- th\n ATLTRACE(\"XML lenght = %d, xml=%S\\n\", markup.length(), (BSTR)markup.GetBSTR());\n } catch(_com_error e) {\n ATLTRACE(\"error = %S\\n\", (BSTR)e.ErrorMessage());\n }\n }\n CoUninitialize();\n return _AtlModule.WinMain(nShowCmd);\n}\n 'getxmltest.exe': Loaded 'C:\\Windows\\winsxs\\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.6001.18000_none_5cdbaa5a083979cc\\comctl32.dll'\nXML lenght = 160013, xml=<XML><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><child/><'getxmltest.exe': Unloaded 'C:\\Windows\\SysWOW64\\msxml3.dll'\nThe program '[4884] getxmltest.exe: Native' has exited with code 0 (0x0).\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
324,171
<p>trying to mount an smb share on OS X so that the 'www' user can read files from there.</p> <p>the SMB share is accessible via an Active Directory account. I can mount the share through the Finder (cmd-k ...)</p> <p>my basic approach is</p> <pre><code># 1) create mountpoint sudo mkdir /Volumes/www_mdisk # 2) permissions for mountpoint sudo chown www:www /Volumes/www_mdisk; sudo chmod 777 /Volumes/www_mdisk # 3) make a link from apache docroot to mountpoint (http.conf FollowSymlinks is on) cd /Library/WebServer/Documents; ln -s /Volumes/www_mdisk mdisk # 4) mount the SMB share using the Active Directory user 'ad_user' sudo mount_smbfs -O www/www '//DOMAIN;ad_user@smbshare_host/sharepath' </code></pre> <p>step 4 fails though. I have read the manpages, tried many different combinations (with or without -O switch), but can't get it to work</p> <p>can you help me get it right? thanks!</p>
[ { "answer_id": 325413, "author": "captnswing", "author_id": 41404, "author_profile": "https://Stackoverflow.com/users/41404", "pm_score": 2, "selected": false, "text": "# 4) mount the SMB share using the Active Directory user 'ad_user'\nsudo mount_smbfs -O www/www -u 70 -g 70 '//DOMAIN;ad_user@smbshare_host/sharepath' www_mdisk\n\n# 5) make sure http.conf has 'Options Indexes' enabled for Docroot\nduh.\n" }, { "answer_id": 3852209, "author": "Mitch Lindgren", "author_id": 108340, "author_profile": "https://Stackoverflow.com/users/108340", "pm_score": 3, "selected": true, "text": "sudo -u _www mount_smbfs //User:Password@Host/Share /mount/point\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41404/" ]
324,178
<p>We are looking at various options in porting our persistence layer from Oracle to another database and one that we are looking at is MS SQL. However we use Oracle sequences throughout the code and because of this it seems moving will be a headache. I understand about @identity but that would be a massive overhaul of the persistence code. </p> <p>Is it possible in SQL Server to create a function which could handle a sequence? </p>
[ { "answer_id": 324202, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": true, "text": "INSERT INTO SequenceTable (dummy) VALUES ('X');\nSELECT @ID = SCOPE_IDENTITY();\nINSERT INTO RealTable (ID, datacolumns) VALUES (@ID, @data1, @data2, ...)\n" }, { "answer_id": 327278, "author": "John MacIntyre", "author_id": 29043, "author_profile": "https://Stackoverflow.com/users/29043", "pm_score": 1, "selected": false, "text": "insert into mytable(id, ....) values( GetNextSequence('MySequence'), ....);\n declare @newID int;\nexec @newID = GetNextSequence 'MySequence';\ninsert into mytable(id, ....) values(@newID, ....);\n MySequence.Current\n MySequence.Next\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
324,200
<p>I have developed a framework that is used by several teams in our organisation. Those "modules", developed on top of this framework, can behave quite differently but they are all pretty resources consuming even though some are more than others. They all receive data in input, analyse and/or transform it, and send it further. </p> <p>We planned to buy new hardware and my boss asked me to define and implement a benchmark based on the modules in order to compare the different offers we have got. </p> <p>My idea is to simply start sequentially each module with a well chosen bunch of data as input. </p> <p>Do you have any advice? Any remarks on this simple procedure? </p>
[ { "answer_id": 32678022, "author": "user7610", "author_id": 1047788, "author_profile": "https://Stackoverflow.com/users/1047788", "pm_score": 0, "selected": false, "text": "time" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20986/" ]
324,214
<p>I am currently running the following code based on Chapter 12.5 of the Python Cookbook:</p> <pre><code>from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root </code></pre> <p>I am working with XML documents of about 1 GB in size. Does anyone know a faster way to parse these?</p>
[ { "answer_id": 324483, "author": "bhadra", "author_id": 30289, "author_profile": "https://Stackoverflow.com/users/30289", "pm_score": 4, "selected": false, "text": "cElementTree cElementTree cElementTree" }, { "answer_id": 326541, "author": "Steen", "author_id": 1448983, "author_profile": "https://Stackoverflow.com/users/1448983", "pm_score": 7, "selected": true, "text": "for event, elem in iterparse(source):\n if elem.tag == \"record\":\n ... process record elements ...\n elem.clear()\n # get an iterable\ncontext = iterparse(source, events=(\"start\", \"end\"))\n\n# turn it into an iterator\ncontext = iter(context)\n\n# get the root element\nevent, root = context.next()\n\nfor event, elem in context:\n if event == \"end\" and elem.tag == \"record\":\n ... process record elements ...\n root.clear()\n import xml.etree.ElementTree as ET\n\n# Get an iterable.\ncontext = ET.iterparse(source, events=(\"start\", \"end\"))\n \nfor index, (event, elem) in enumerate(context):\n # Get the root element.\n if index == 0:\n root = elem\n if event == \"end\" and elem.tag == \"record\":\n # ... process record elements ...\n root.clear()\n" }, { "answer_id": 33815832, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "import xml.parsers.expat\nparser = xml.parsers.expat.ParserCreate()\nparser.ParseFile(open('path.xml', 'r'))\n" }, { "answer_id": 56068500, "author": "Mitar", "author_id": 252025, "author_profile": "https://Stackoverflow.com/users/252025", "pm_score": 1, "selected": false, "text": "from lxml import etree\n\ncontext = etree.iterparse('path/to/file', events=('end',), tag='Record')\n\nfor event, element in context:\n record_id = element.findtext('.//{http://arxiv.org/OAI/arXiv/}id')\n created = element.findtext('.//{http://arxiv.org/OAI/arXiv/}created')\n\n print(record_id, created)\n\n # Free memory.\n element.clear()\n while element.getprevious() is not None:\n del element.getparent()[0]\n element.clear" }, { "answer_id": 70663249, "author": "Evgenia Kotova", "author_id": 2186684, "author_profile": "https://Stackoverflow.com/users/2186684", "pm_score": 0, "selected": false, "text": "# get the root element\nevent, root = context.next()\n # get the root element\nevent, root = next(context)\n # turn it into an iterator\ncontext = iter(context)\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7743/" ]
324,220
<p>I am looking for an inverse version of "RunOnceEx".</p> <p>RunOnceEx does run some program, before the user's shell(desktop&amp;taskbar) start. The login progress will not continue before the runonceex complete.</p> <p>I want to do exact the same but on user logout. When she/he logout, all running program shutdown, leaving shell(desktop&amp;taskbar), then ""I wish my program will be execute this moment"", finally logout.</p> <p>I think it is possible because the "mobsync.exe" is doing that. But I cannot find where and how to do it.</p>
[ { "answer_id": 324238, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "gpedit.msc HKCU HKLM" }, { "answer_id": 1908497, "author": "Pratap .R", "author_id": 231511, "author_profile": "https://Stackoverflow.com/users/231511", "pm_score": 1, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\@GinaDLL" }, { "answer_id": 1914661, "author": "Oliver", "author_id": 1838048, "author_profile": "https://Stackoverflow.com/users/1838048", "pm_score": 1, "selected": false, "text": "[HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Windows\\System\\Scripts] C:\\WINDOWS\\System32\\GroupPolicy" }, { "answer_id": 1921845, "author": "Wernight", "author_id": 167897, "author_profile": "https://Stackoverflow.com/users/167897", "pm_score": 0, "selected": false, "text": " private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n {\n if (e.CloseReason != CloseReason.UserClosing)\n {\n // It's not the user closing the application,\n // Let's do whatever you want here, for example starting a process\n Process notePad = new Process();\n\n notePad.StartInfo.FileName = \"notepad.exe\";\n notePad.StartInfo.Arguments = \"ProcessStart.cs\";\n\n notePad.Start();\n }\n }\n" }, { "answer_id": 1922235, "author": "Aaronaught", "author_id": 38360, "author_profile": "https://Stackoverflow.com/users/38360", "pm_score": 2, "selected": false, "text": "WM_QUERYENDSESSION lParam ENDSESSION_LOGOFF lParam WM_QUERYENDSESSION Microsoft.Win32.SystemEvents.SessionEnding" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40214/" ]
324,222
<p>I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.</p> <p>I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method). </p> <pre><code> protected void gridViewDelete(object sender, GridViewDeleteEventArgs e) { bool bDelete = false; bool bCheck = false; if (hfControl.Value != "1") { // check relationship bCheck = validation_method(.......); if (bCheck) { bDelete = true; } } else { hfControl.Value = ""; bDelete = true; } if (bDelete) { //process delete } else { string script = string.Empty; script += " var x; "; script += " x = confirm('are u sure?'); "; script += " if (x){ " ; script += " document.getElementById('hfControl').value = '1'; "; script += " setTimeOut(__doPostBack('gridView','Delete$" + e.RowIndex + "'),0);"; script += " } "; ScriptManager.RegisterClientScriptBlock(this, Page.GetType() , "confirm" , script ,true); } } </code></pre>
[ { "answer_id": 324238, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "gpedit.msc HKCU HKLM" }, { "answer_id": 1908497, "author": "Pratap .R", "author_id": 231511, "author_profile": "https://Stackoverflow.com/users/231511", "pm_score": 1, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\@GinaDLL" }, { "answer_id": 1914661, "author": "Oliver", "author_id": 1838048, "author_profile": "https://Stackoverflow.com/users/1838048", "pm_score": 1, "selected": false, "text": "[HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Windows\\System\\Scripts] C:\\WINDOWS\\System32\\GroupPolicy" }, { "answer_id": 1921845, "author": "Wernight", "author_id": 167897, "author_profile": "https://Stackoverflow.com/users/167897", "pm_score": 0, "selected": false, "text": " private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n {\n if (e.CloseReason != CloseReason.UserClosing)\n {\n // It's not the user closing the application,\n // Let's do whatever you want here, for example starting a process\n Process notePad = new Process();\n\n notePad.StartInfo.FileName = \"notepad.exe\";\n notePad.StartInfo.Arguments = \"ProcessStart.cs\";\n\n notePad.Start();\n }\n }\n" }, { "answer_id": 1922235, "author": "Aaronaught", "author_id": 38360, "author_profile": "https://Stackoverflow.com/users/38360", "pm_score": 2, "selected": false, "text": "WM_QUERYENDSESSION lParam ENDSESSION_LOGOFF lParam WM_QUERYENDSESSION Microsoft.Win32.SystemEvents.SessionEnding" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
324,231
<p>Here's the issue:</p> <p>I have a hook in IE that reacts on <code>WebBrowser.OnNavigateComplete2</code> event to parse the content of the document for some precise info.</p> <p>That document contains frames, so I look into the <code>HTMLDocument.frames</code>. For each one, I look into the document.body.outerHTML property to check for the content. </p> <p>Problem is, the string I'm looking for never shows there, whereas it is displayed in the finale page. So, am I looking in the wrong place? If it is displayed when the page is fully loaded, then it's downloaded at some point, right? But in which object should I look ?</p> <p>BTW, I Don't know if that is of any importance, but the page I'm searching into comes from a ASP.NET application.</p> <pre><code>public void OnNavigateComplete2(object pDisp, ref object url) { document = (HTMLDocument)webBrowser.Document; mshtml.FramesCollection frames = document.frames; for (int i = 0; i &lt; frames.length; i++) { object refIdx = i; IHTMLWindow2 frame = (IHTMLWindow2)frames.item(ref refIdx); string frameContent = frame.document.body.outerHTML; } } </code></pre> <p>Thank your for your help.</p> <hr> <p>@rams This event is launched many times for each page, so I figured it was each time a framed is loaded, even if i don't get to catch the one I'm looking for. If not, what would be the event to catch the frames content?</p> <p>What I want to do is detect some precise info on a precise frame, then save it. later, a web page is loaded triggered by some user action, where I need the info I got from parsing the frame.</p>
[ { "answer_id": 341537, "author": "rams", "author_id": 3635, "author_profile": "https://Stackoverflow.com/users/3635", "pm_score": 3, "selected": true, "text": "iFrame frm = document.frames(<your frame id>);\n\nint readyState=0;\n\nwhile(frm.readystate !=4){\n// do nothing. be careful to not create an endless loop\n}\n\nif(frm.readyState==4){\n // get your content now\n}\n" } ]
2008/11/27
[ "https://Stackoverflow.com/questions/324231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29568/" ]