qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
[ { "answer_id": 299278, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 2, "selected": false, "text": "from lxml import etree\n\ntry:\n parser = etree.XMLParser(dtd_validation=True)\n domTree = etree.parse(myXMLFileName, parser=parser)\nexcept etree.XMLSyntaxError, e:\n return e.args[0]\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
298,786
<p>I have a header </p> <pre><code>&lt;h1&gt;My Header&lt;/h1&gt; </code></pre> <p>It has a height of <code>150px</code> and a <code>font-size</code> of say <code>1.3em;</code> How can I make the header text vertically centered with CSS. I would rather not wrap it in a container DIV (wrapping divs really defeat the whole CSS idea).</p>
[ { "answer_id": 299278, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 2, "selected": false, "text": "from lxml import etree\n\ntry:\n parser = etree.XMLParser(dtd_validation=True)\n domTree = etree.parse(myXMLFileName, parser=parser)\nexcept etree.XMLSyntaxError, e:\n return e.args[0]\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
298,788
<p>Since Terminal appeared I've saved as ~/mySrvr.term a modified stock .term file which opens to execute an ssh to a remote server and to modify the appearance. I have NOT been able to save "use option key as meta" for emacs-ery; there's no slot for it in the term file and I'm reluctant to wrestle with a keyboard dictionary file. Am I missing something simple? How do I get option-as-meta to stick between sessions?</p> <p>Thanks</p>
[ { "answer_id": 298891, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "<key>useOptionAsMetaKey</key>\n<true/>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
298,791
<p>I have an IIS located on serverA</p> <p>I have userA at locationA who has opened a content management system site, hosted on serverA.</p> <p>One of the features of the system is that it allows the user to move a file to LocationB, all within the same network. Now when this move occurs and due to bandwidth restrictions, would this file move from LocationA to serverA to LocationB or is there a way for me to move the file from LocationA to LocationB without going through serverA, i.e using local memory on serverA</p> <p>I am not using BITS at the moment.</p>
[ { "answer_id": 298822, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "scp" }, { "answer_id": 299297, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 0, "selected": false, "text": "<form method=\"post\" action=\"http://serverB/locationB\" enctype=\"multipart/form-data\">\n ...\n <input type=\"file\" ... />\n ...\n</form>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38230/" ]
298,799
<p>Somebody <strong>please</strong> tell me it is possible to recover Visual Studio source after VS crashes!</p> <p>I have just spent 5 hours writing a new utility app, and running it with the "Save before Build" option turned on, as well as AutoRecover every 5-mins. But after VS crashed I am unabled to find anything other than an empty project folder!!! I can't believe that files are only "saved" to memory?!? That can't be right! That 5 hours of work has to be <strong>somewhere</strong> on the disk?</p> <p>I attempted to reproduce the scenario by creating a Junk project, running it, and then killing VS using Task Manager. It wasn't quite the same situation as a dialog box actually popped up asking to save the project. I ignored this and continued the kill. I was then able to find the Junk source in C:\Users{Username}\AppData\Local\Temporary Projects as advised - but not my earlier project.</p> <p>I think it's gone.</p>
[ { "answer_id": 298817, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 2, "selected": false, "text": "C:\\Users\\{Username}\\AppData\\Local\\Temporary Projects\n" }, { "answer_id": 677265, "author": "Klas Mellbourn", "author_id": 46194, "author_profile": "https://Stackoverflow.com/users/46194", "pm_score": 3, "selected": false, "text": "C:\\Users\\<username>\\Documents\\Visual Studio 2008\\Backup Files\\<ProjectName>\\\n C:\\Users{Username}\\AppData\\Local\n" }, { "answer_id": 3024960, "author": "SAinCA", "author_id": 364795, "author_profile": "https://Stackoverflow.com/users/364795", "pm_score": 0, "selected": false, "text": "C:\\Users\\<<User>>Documents\\SQL Server Management Studio\\Backup Files\\Solution1\\ ~AutoRecover%" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1885/" ]
298,812
<p>I have two Tables.</p> <p>Order - With Columns OrderID, OrderStatusID<br /> OrderStatus - With Columns OrderStatusID, Description</p> <p>I have an Order Object which calls to the database and fills its properties for use in my code. Right now I have access to Order.OrderStatusID, but in my application I really need access to the "Description" field.</p> <p>How do you handle this elegantly with good OO design?</p>
[ { "answer_id": 298845, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "Select O.OrderId, O.OrderStatusId, S.Descriptiuon\nFrom Order O\n Join OrderStatus S \n On S.OrderStatusId = O.OrderStatusId\nWhere OrderId = 23 -- or whatever\n" }, { "answer_id": 298877, "author": "dragonjujo", "author_id": 37344, "author_profile": "https://Stackoverflow.com/users/37344", "pm_score": 1, "selected": false, "text": "int OrderId = 5\nint OrderStatusId = 3\nOrderStatus OrderStatus_ref\n{\nget\n{\n if OrderStatus_ref == null\n OrderStatus_ref = new OrderStatus(OrderStatusId)\n return OrderStatus_ref\n}\n}\n" }, { "answer_id": 298912, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": true, "text": "public class Order {\n private int statusID;\n\n public OrderStatus Status {\n get {\n return OrderStatus.Resolve(statusID);\n }\n set {\n statusID = value != null ? value.ID : null;\n }\n }\n}\n\npublic class OrderStatus {\n public static OrderStatus Resolve(int statusID)\n {\n OrderStatus status = null;\n // read from cache or DB\n ...\n // if not found return Null object\n if (status == null)\n status = new OrderStatus(null, string.Empty);\n return status;\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37347/" ]
298,830
<p>I have a single string that contains the command-line parameters to be passed to another executable and I need to extract the string[] containing the individual parameters in the same way that C# would if the commands had been specified on the command-line. The string[] will be used when executing another assemblies entry-point via reflection.</p> <p>Is there a standard function for this? Or is there a preferred method (regex?) for splitting the parameters correctly? It must handle '"' delimited strings that may contain spaces correctly, so I can't just split on ' '.</p> <p>Example string:</p> <pre><code>string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam foo"; </code></pre> <p>Example result:</p> <pre><code>string[] parameterArray = new string[] { @"/src:C:\tmp\Some Folder\Sub Folder", @"/users:abcdefg@hijkl.com", @"tasks:SomeTask,Some Other Task", @"-someParam", @"foo" }; </code></pre> <p>I do not need a command-line parsing library, just a way to get the String[] that should be generated.</p> <p><strong>Update</strong>: I had to change the expected result to match what is actually generated by C# (removed the extra "'s in the split strings)</p>
[ { "answer_id": 298838, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "Split()" }, { "answer_id": 298852, "author": "Israr Khan", "author_id": 37280, "author_profile": "https://Stackoverflow.com/users/37280", "pm_score": -1, "selected": false, "text": "for" }, { "answer_id": 298968, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 5, "selected": false, "text": " static string[] ParseArguments(string commandLine)\n {\n char[] parmChars = commandLine.ToCharArray();\n bool inQuote = false;\n for (int index = 0; index < parmChars.Length; index++)\n {\n if (parmChars[index] == '\"')\n inQuote = !inQuote;\n if (!inQuote && parmChars[index] == ' ')\n parmChars[index] = '\\n';\n }\n return (new string(parmChars)).Split('\\n');\n }\n" }, { "answer_id": 298990, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 7, "selected": false, "text": " public static IEnumerable<string> SplitCommandLine(string commandLine)\n {\n bool inQuotes = false;\n\n return commandLine.Split(c =>\n {\n if (c == '\\\"')\n inQuotes = !inQuotes;\n\n return !inQuotes && c == ' ';\n })\n .Select(arg => arg.Trim().TrimMatchingQuotes('\\\"'))\n .Where(arg => !string.IsNullOrEmpty(arg));\n }\n public static IEnumerable<string> Split(this string str, \n Func<char, bool> controller)\n {\n int nextPiece = 0;\n\n for (int c = 0; c < str.Length; c++)\n {\n if (controller(str[c]))\n {\n yield return str.Substring(nextPiece, c - nextPiece);\n nextPiece = c + 1;\n }\n }\n\n yield return str.Substring(nextPiece);\n }\n public static string TrimMatchingQuotes(this string input, char quote)\n {\n if ((input.Length >= 2) && \n (input[0] == quote) && (input[input.Length - 1] == quote))\n return input.Substring(1, input.Length - 2);\n\n return input;\n }\n public static void Test(string cmdLine, params string[] args)\n {\n string[] split = SplitCommandLine(cmdLine).ToArray();\n\n Debug.Assert(split.Length == args.Length);\n\n for (int n = 0; n < split.Length; n++)\n Debug.Assert(split[n] == args[n]);\n }\n Test(\"\");\n Test(\"a\", \"a\");\n Test(\" abc \", \"abc\");\n Test(\"a b \", \"a\", \"b\");\n Test(\"a b \\\"c d\\\"\", \"a\", \"b\", \"c d\");\n Test(@\"/src:\"\"C:\\tmp\\Some Folder\\Sub Folder\"\" /users:\"\"abcdefg@hijkl.com\"\" tasks:\"\"SomeTask,Some Other Task\"\" -someParam\",\n @\"/src:\"\"C:\\tmp\\Some Folder\\Sub Folder\"\"\", @\"/users:\"\"abcdefg@hijkl.com\"\"\", @\"tasks:\"\"SomeTask,Some Other Task\"\"\", @\"-someParam\");\n" }, { "answer_id": 299795, "author": "Anton", "author_id": 341413, "author_profile": "https://Stackoverflow.com/users/341413", "pm_score": 0, "selected": false, "text": " private String[] SplitCommandLineArgument(String argumentString)\n {\n StringBuilder translatedArguments = new StringBuilder(argumentString);\n bool escaped = false;\n for (int i = 0; i < translatedArguments.Length; i++)\n {\n if (translatedArguments[i] == '\"')\n {\n escaped = !escaped;\n }\n if (translatedArguments[i] == ' ' && !escaped)\n {\n translatedArguments[i] = '\\n';\n }\n }\n\n string[] toReturn = translatedArguments.ToString().Split(new char[] { '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n for(int i = 0; i < toReturn.Length; i++)\n {\n toReturn[i] = RemoveMatchingQuotes(toReturn[i]);\n }\n return toReturn;\n }\n\n public static string RemoveMatchingQuotes(string stringToTrim)\n {\n int firstQuoteIndex = stringToTrim.IndexOf('\"');\n int lastQuoteIndex = stringToTrim.LastIndexOf('\"');\n while (firstQuoteIndex != lastQuoteIndex)\n {\n stringToTrim = stringToTrim.Remove(firstQuoteIndex, 1);\n stringToTrim = stringToTrim.Remove(lastQuoteIndex - 1, 1); //-1 because we've shifted the indicies left by one\n firstQuoteIndex = stringToTrim.IndexOf('\"');\n lastQuoteIndex = stringToTrim.LastIndexOf('\"');\n }\n return stringToTrim;\n }\n" }, { "answer_id": 467313, "author": "CS.", "author_id": 57085, "author_profile": "https://Stackoverflow.com/users/57085", "pm_score": 0, "selected": false, "text": "public static string[] SplitCommandLineArgument( String argumentString )\n{\n StringBuilder translatedArguments = new StringBuilder( argumentString ).Replace( \"\\\\\\\"\", \"\\r\" );\n bool InsideQuote = false;\n for ( int i = 0; i < translatedArguments.Length; i++ )\n {\n if ( translatedArguments[i] == '\"' )\n {\n InsideQuote = !InsideQuote;\n }\n if ( translatedArguments[i] == ' ' && !InsideQuote )\n {\n translatedArguments[i] = '\\n';\n }\n }\n\n string[] toReturn = translatedArguments.ToString().Split( new char[] { '\\n' }, StringSplitOptions.RemoveEmptyEntries );\n for ( int i = 0; i < toReturn.Length; i++ )\n {\n toReturn[i] = RemoveMatchingQuotes( toReturn[i] );\n toReturn[i] = toReturn[i].Replace( \"\\r\", \"\\\"\" );\n }\n return toReturn;\n}\n\npublic static string RemoveMatchingQuotes( string stringToTrim )\n{\n int firstQuoteIndex = stringToTrim.IndexOf( '\"' );\n int lastQuoteIndex = stringToTrim.LastIndexOf( '\"' );\n while ( firstQuoteIndex != lastQuoteIndex )\n {\n stringToTrim = stringToTrim.Remove( firstQuoteIndex, 1 );\n stringToTrim = stringToTrim.Remove( lastQuoteIndex - 1, 1 ); //-1 because we've shifted the indicies left by one\n firstQuoteIndex = stringToTrim.IndexOf( '\"' );\n lastQuoteIndex = stringToTrim.LastIndexOf( '\"' );\n }\n return stringToTrim;\n}\n" }, { "answer_id": 749653, "author": "Atif Aziz", "author_id": 6682, "author_profile": "https://Stackoverflow.com/users/6682", "pm_score": 7, "selected": true, "text": "CommandLineToArgvW LPWSTR *CommandLineToArgvW(\n LPCWSTR lpCmdLine, int *pNumArgs);\n [DllImport(\"shell32.dll\", SetLastError = true)]\nstatic extern IntPtr CommandLineToArgvW(\n [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);\n\npublic static string[] CommandLineToArgs(string commandLine)\n{\n int argc;\n var argv = CommandLineToArgvW(commandLine, out argc); \n if (argv == IntPtr.Zero)\n throw new System.ComponentModel.Win32Exception();\n try\n {\n var args = new string[argc];\n for (var i = 0; i < args.Length; i++)\n {\n var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);\n args[i] = Marshal.PtrToStringUni(p);\n }\n\n return args;\n }\n finally\n {\n Marshal.FreeHGlobal(argv);\n }\n}\n" }, { "answer_id": 2132004, "author": "Vapour in the Alley", "author_id": 158821, "author_profile": "https://Stackoverflow.com/users/158821", "pm_score": 4, "selected": false, "text": " public static string[] SplitArguments(string commandLine)\n {\n var parmChars = commandLine.ToCharArray();\n var inSingleQuote = false;\n var inDoubleQuote = false;\n for (var index = 0; index < parmChars.Length; index++)\n {\n if (parmChars[index] == '\"' && !inSingleQuote)\n {\n inDoubleQuote = !inDoubleQuote;\n parmChars[index] = '\\n';\n }\n if (parmChars[index] == '\\'' && !inDoubleQuote)\n {\n inSingleQuote = !inSingleQuote;\n parmChars[index] = '\\n';\n }\n if (!inSingleQuote && !inDoubleQuote && parmChars[index] == ' ')\n parmChars[index] = '\\n';\n }\n return (new string(parmChars)).Split(new[] { '\\n' }, StringSplitOptions.RemoveEmptyEntries);\n }\n" }, { "answer_id": 7774211, "author": "Monoman", "author_id": 231350, "author_profile": "https://Stackoverflow.com/users/231350", "pm_score": 3, "selected": false, "text": "IEnumerable<String> string public static IEnumerable<string> ParseArguments(this string commandLine)\n{\n if (string.IsNullOrWhiteSpace(commandLine))\n yield break;\n\n var sb = new StringBuilder();\n bool inQuote = false;\n foreach (char c in commandLine) {\n if (c == '\"' && !inQuote) {\n inQuote = true;\n continue;\n }\n\n if (c != '\"' && !(char.IsWhiteSpace(c) && !inQuote)) {\n sb.Append(c);\n continue;\n }\n\n if (sb.Length > 0) {\n var result = sb.ToString();\n sb.Clear();\n inQuote = false;\n yield return result;\n }\n }\n\n if (sb.Length > 0)\n yield return sb.ToString();\n}\n" }, { "answer_id": 19091999, "author": "Thomas Petersson", "author_id": 2830857, "author_profile": "https://Stackoverflow.com/users/2830857", "pm_score": 2, "selected": false, "text": " var re = @\"\\G(\"\"((\"\"\"\"|[^\"\"])+)\"\"|(\\S+)) *\";\n var ms = Regex.Matches(CmdLine, re);\n var list = ms.Cast<Match>()\n .Select(m => Regex.Replace(\n m.Groups[2].Success\n ? m.Groups[2].Value\n : m.Groups[4].Value, @\"\"\"\"\"\", @\"\"\"\")).ToArray();\n" }, { "answer_id": 19725880, "author": "Fabio Iotti", "author_id": 1135019, "author_profile": "https://Stackoverflow.com/users/1135019", "pm_score": 1, "selected": false, "text": "public static string[] SplitArguments(string args) {\n char[] parmChars = args.ToCharArray();\n bool inSingleQuote = false;\n bool inDoubleQuote = false;\n bool escaped = false;\n bool lastSplitted = false;\n bool justSplitted = false;\n bool lastQuoted = false;\n bool justQuoted = false;\n\n int i, j;\n\n for(i=0, j=0; i<parmChars.Length; i++, j++) {\n parmChars[j] = parmChars[i];\n\n if(!escaped) {\n if(parmChars[i] == '^') {\n escaped = true;\n j--;\n } else if(parmChars[i] == '\"' && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n parmChars[j] = '\\n';\n justSplitted = true;\n justQuoted = true;\n } else if(parmChars[i] == '\\'' && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n parmChars[j] = '\\n';\n justSplitted = true;\n justQuoted = true;\n } else if(!inSingleQuote && !inDoubleQuote && parmChars[i] == ' ') {\n parmChars[j] = '\\n';\n justSplitted = true;\n }\n\n if(justSplitted && lastSplitted && (!lastQuoted || !justQuoted))\n j--;\n\n lastSplitted = justSplitted;\n justSplitted = false;\n\n lastQuoted = justQuoted;\n justQuoted = false;\n } else {\n escaped = false;\n }\n }\n\n if(lastQuoted)\n j--;\n\n return (new string(parmChars, 0, j)).Split(new[] { '\\n' });\n}\n" }, { "answer_id": 23961658, "author": "ygoe", "author_id": 143684, "author_profile": "https://Stackoverflow.com/users/143684", "pm_score": 1, "selected": false, "text": "string[] args escape inQuote hadQuote prevCh currentArg args \\\\ \\ \\\" \" \"\" \" ^ cmd /c \"argdump.exe \"a b c\"\"\n cmd Regex StringBuilder /// <summary>\n/// Reads command line arguments from a single string.\n/// </summary>\n/// <param name=\"argsString\">The string that contains the entire command line.</param>\n/// <returns>An array of the parsed arguments.</returns>\npublic string[] ReadArgs(string argsString)\n{\n // Collects the split argument strings\n List<string> args = new List<string>();\n // Builds the current argument\n var currentArg = new StringBuilder();\n // Indicates whether the last character was a backslash escape character\n bool escape = false;\n // Indicates whether we're in a quoted range\n bool inQuote = false;\n // Indicates whether there were quotes in the current arguments\n bool hadQuote = false;\n // Remembers the previous character\n char prevCh = '\\0';\n // Iterate all characters from the input string\n for (int i = 0; i < argsString.Length; i++)\n {\n char ch = argsString[i];\n if (ch == '\\\\' && !escape)\n {\n // Beginning of a backslash-escape sequence\n escape = true;\n }\n else if (ch == '\\\\' && escape)\n {\n // Double backslash, keep one\n currentArg.Append(ch);\n escape = false;\n }\n else if (ch == '\"' && !escape)\n {\n // Toggle quoted range\n inQuote = !inQuote;\n hadQuote = true;\n if (inQuote && prevCh == '\"')\n {\n // Doubled quote within a quoted range is like escaping\n currentArg.Append(ch);\n }\n }\n else if (ch == '\"' && escape)\n {\n // Backslash-escaped quote, keep it\n currentArg.Append(ch);\n escape = false;\n }\n else if (char.IsWhiteSpace(ch) && !inQuote)\n {\n if (escape)\n {\n // Add pending escape char\n currentArg.Append('\\\\');\n escape = false;\n }\n // Accept empty arguments only if they are quoted\n if (currentArg.Length > 0 || hadQuote)\n {\n args.Add(currentArg.ToString());\n }\n // Reset for next argument\n currentArg.Clear();\n hadQuote = false;\n }\n else\n {\n if (escape)\n {\n // Add pending escape char\n currentArg.Append('\\\\');\n escape = false;\n }\n // Copy character from input, no special meaning\n currentArg.Append(ch);\n }\n prevCh = ch;\n }\n // Save last argument\n if (currentArg.Length > 0 || hadQuote)\n {\n args.Add(currentArg.ToString());\n }\n return args.ToArray();\n}\n" }, { "answer_id": 24829691, "author": "Kevin Thach", "author_id": 1348175, "author_profile": "https://Stackoverflow.com/users/1348175", "pm_score": 3, "selected": false, "text": "Test(\"\\\"He whispered to her \\\\\\\"I love you\\\\\\\".\\\"\", \"He whispered to her \\\"I love you\\\".\");\n \"He whispered to her \\\"I\nlove\nyou\\\".\"\n public static IEnumerable<string> SplitCommandLine(string commandLine)\n{\n bool inQuotes = false;\n bool isEscaping = false;\n\n return commandLine.Split(c => {\n if (c == '\\\\' && !isEscaping) { isEscaping = true; return false; }\n\n if (c == '\\\"' && !isEscaping)\n inQuotes = !inQuotes;\n\n isEscaping = false;\n\n return !inQuotes && Char.IsWhiteSpace(c)/*c == ' '*/;\n })\n .Select(arg => arg.Trim().TrimMatchingQuotes('\\\"').Replace(\"\\\\\\\"\", \"\\\"\"))\n .Where(arg => !string.IsNullOrEmpty(arg));\n}\n Test(\"\\\"C:\\\\Program Files\\\"\", \"C:\\\\Program Files\");\nTest(\"\\\"He whispered to her \\\\\\\"I love you\\\\\\\".\\\"\", \"He whispered to her \\\"I love you\\\".\");\n He whispered to her \\ \nI \nlove \nyou\". \n" }, { "answer_id": 31621370, "author": "Lucas De Jesus", "author_id": 4242029, "author_profile": "https://Stackoverflow.com/users/4242029", "pm_score": 0, "selected": false, "text": " string[] str_para_linha_comando(string str, out int argumentos)\n {\n string[] linhaComando = new string[32];\n bool entre_aspas = false;\n int posicao_ponteiro = 0;\n int argc = 0;\n int inicio = 0;\n int fim = 0;\n string sub;\n\n for(int i = 0; i < str.Length;)\n {\n if (entre_aspas)\n {\n // Está entre aspas\n sub = str.Substring(inicio+1, fim - (inicio+1));\n linhaComando[argc - 1] = sub;\n\n posicao_ponteiro += ((fim - posicao_ponteiro)+1);\n entre_aspas = false;\n i = posicao_ponteiro;\n }\n else\n {\n tratar_aspas:\n if (str.ElementAt(i) == '\\\"')\n {\n inicio = i;\n fim = str.IndexOf('\\\"', inicio + 1);\n entre_aspas = true;\n argc++;\n }\n else\n {\n // Se não for aspas, então ler até achar o primeiro espaço em branco\n if (str.ElementAt(i) == ' ')\n {\n if (str.ElementAt(i + 1) == '\\\"')\n {\n i++;\n goto tratar_aspas;\n }\n\n // Pular os espaços em branco adiconais\n while(str.ElementAt(i) == ' ') i++;\n\n argc++;\n inicio = i;\n fim = str.IndexOf(' ', inicio);\n if (fim == -1) fim = str.Length;\n sub = str.Substring(inicio, fim - inicio);\n linhaComando[argc - 1] = sub;\n posicao_ponteiro += (fim - posicao_ponteiro);\n\n i = posicao_ponteiro;\n if (posicao_ponteiro == str.Length) break;\n }\n else\n {\n argc++;\n inicio = i;\n fim = str.IndexOf(' ', inicio);\n if (fim == -1) fim = str.Length;\n\n sub = str.Substring(inicio, fim - inicio);\n linhaComando[argc - 1] = sub;\n posicao_ponteiro += fim - posicao_ponteiro;\n i = posicao_ponteiro;\n if (posicao_ponteiro == str.Length) break;\n }\n }\n }\n }\n\n argumentos = argc;\n\n return linhaComando;\n }\n" }, { "answer_id": 43288365, "author": "Vance McCorkle", "author_id": 4875891, "author_profile": "https://Stackoverflow.com/users/4875891", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace CmdArgProcessor\n{\n class Program\n {\n static void Main(string[] args)\n {\n // test switches and switches with values\n // -test1 1 -test2 2 -test3 -test4 -test5 5\n\n string dummyString = string.Empty;\n\n var argDict = BurstCmdLineArgs(args);\n\n Console.WriteLine(\"Value for switch = -test1: {0}\", argDict[\"test1\"]);\n Console.WriteLine(\"Value for switch = -test2: {0}\", argDict[\"test2\"]);\n Console.WriteLine(\"Switch -test3 is present? {0}\", argDict.TryGetValue(\"test3\", out dummyString));\n Console.WriteLine(\"Switch -test4 is present? {0}\", argDict.TryGetValue(\"test4\", out dummyString));\n Console.WriteLine(\"Value for switch = -test5: {0}\", argDict[\"test5\"]);\n\n // Console output:\n //\n // Value for switch = -test1: 1\n // Value for switch = -test2: 2\n // Switch -test3 is present? True\n // Switch -test4 is present? True\n // Value for switch = -test5: 5\n }\n\n public static Dictionary<string, string> BurstCmdLineArgs(string[] args)\n {\n var argDict = new Dictionary<string, string>();\n\n // Flatten the args in to a single string separated by a space.\n // Then split the args on the dash delimiter of a cmd line \"switch\".\n // E.g. -mySwitch myValue\n // or -JustMySwitch (no value)\n // where: all values must follow a switch.\n // Then loop through each string returned by the split operation.\n // If the string can be split again by a space character,\n // then the second string is a value to be paired with a switch,\n // otherwise, only the switch is added as a key with an empty string as the value.\n // Use dictionary indexer to retrieve values for cmd line switches.\n // Use Dictionary::ContainsKey(...) where only a switch is recorded as the key.\n string.Join(\" \", args).Split('-').ToList().ForEach(s => argDict.Add(s.Split()[0], (s.Split().Count() > 1 ? s.Split()[1] : \"\")));\n\n return argDict;\n }\n }\n}\n" }, { "answer_id": 48008872, "author": "HarryP", "author_id": 9149464, "author_profile": "https://Stackoverflow.com/users/9149464", "pm_score": 0, "selected": false, "text": "public static IEnumerable<String> SplitArguments(string commandLine)\n{\n Char quoteChar = '\"';\n Char escapeChar = '\\\\';\n Boolean insideQuote = false;\n Boolean insideEscape = false;\n\n StringBuilder currentArg = new StringBuilder();\n\n // needed to keep \"\" as argument but drop whitespaces between arguments\n Int32 currentArgCharCount = 0; \n\n for (Int32 i = 0; i < commandLine.Length; i++)\n {\n Char c = commandLine[i];\n if (c == quoteChar)\n {\n currentArgCharCount++;\n\n if (insideEscape)\n {\n currentArg.Append(c); // found \\\" -> add \" to arg\n insideEscape = false;\n }\n else if (insideQuote)\n {\n insideQuote = false; // quote ended\n }\n else\n {\n insideQuote = true; // quote started\n }\n }\n else if (c == escapeChar)\n {\n currentArgCharCount++;\n\n if (insideEscape) // found \\\\ -> add \\\\ (only \\\" will be \")\n currentArg.Append(escapeChar + escapeChar); \n\n insideEscape = !insideEscape;\n }\n else if (Char.IsWhiteSpace(c))\n {\n if (insideQuote)\n {\n currentArgCharCount++;\n currentArg.Append(c); // append whitespace inside quote\n }\n else\n {\n if (currentArgCharCount > 0)\n yield return currentArg.ToString();\n\n currentArgCharCount = 0;\n currentArg.Clear();\n }\n }\n else\n {\n currentArgCharCount++;\n if (insideEscape)\n {\n // found non-escaping backslash -> add \\ (only \\\" will be \")\n currentArg.Append(escapeChar); \n currentArgCharCount = 0;\n insideEscape = false;\n }\n currentArg.Append(c);\n }\n }\n\n if (currentArgCharCount > 0)\n yield return currentArg.ToString();\n}\n" }, { "answer_id": 53290784, "author": "TylerY86", "author_id": 2879498, "author_profile": "https://Stackoverflow.com/users/2879498", "pm_score": 2, "selected": false, "text": "internal static unsafe string[] InternalCreateCommandLine(bool includeArg0)\nprivate static unsafe int SegmentCommandLine(char * pCmdLine, string[] argArray, bool includeArg0)\nprivate static unsafe int ScanArgument0(ref char* psrc, char[] arg)\nprivate static unsafe int ScanArgument(ref char* psrc, ref bool inquote, char[] arg)\n // First, parse the program name (argv[0]). Argv[0] is parsed under special rules. Anything up to \n// the first whitespace outside a quoted subtring is accepted. Backslashes are treated as normal \n// characters.\n // Rules: 2N backslashes + \" ==> N backslashes and begin/end quote\n// 2N+1 backslashes + \" ==> N backslashes + literal \"\n// N backslashes ==> N backslashes\n CommandLineToArgvW private static readonly Regex RxWinArgs\n = new Regex(\"([^\\\\s\\\"]+\\\"|((?<=\\\\s|^)(?!\\\"\\\"(?!\\\"))\\\")+)(\\\"\\\"|.*?)*\\\"[^\\\\s\\\"]*|[^\\\\s]+\",\n RegexOptions.Compiled\n | RegexOptions.Singleline\n | RegexOptions.ExplicitCapture\n | RegexOptions.CultureInvariant);\n\ninternal static IEnumerable<string> ParseArgumentsWindows(string args) {\n var match = RxWinArgs.Match(args);\n\n while (match.Success) {\n yield return match.Value;\n match = match.NextMatch();\n }\n}\n CommandLineToArgvW" }, { "answer_id": 55903304, "author": "Louis Somers", "author_id": 659778, "author_profile": "https://Stackoverflow.com/users/659778", "pm_score": 0, "selected": false, "text": "public static string[] SplitArguments(string commandLine)\n{\n List<string> args = new List<string>();\n List<char> currentArg = new List<char>();\n char? quoteSection = null; // Keeps track of a quoted section (and the type of quote that was used to open it)\n char[] quoteChars = new[] {'\\'', '\\\"'};\n char previous = ' '; // Used for escaping double quotes\n\n for (var index = 0; index < commandLine.Length; index++)\n {\n char c = commandLine[index];\n if (quoteChars.Contains(c))\n {\n if (previous == c) // Escape sequence detected\n {\n previous = ' '; // Prevent re-escaping\n if (!quoteSection.HasValue)\n {\n quoteSection = c; // oops, we ended the quoted section prematurely\n continue; // don't add the 2nd quote (un-escape)\n }\n\n if (quoteSection.Value == c)\n quoteSection = null; // appears to be an empty string (not an escape sequence)\n }\n else if (quoteSection.HasValue)\n {\n if (quoteSection == c)\n quoteSection = null; // End quoted section\n }\n else\n quoteSection = c; // Start quoted section\n }\n else if (char.IsWhiteSpace(c))\n {\n if (!quoteSection.HasValue)\n {\n args.Add(new string(currentArg.ToArray()));\n currentArg.Clear();\n previous = c;\n continue;\n }\n }\n\n currentArg.Add(c);\n previous = c;\n }\n\n if (currentArg.Count > 0)\n args.Add(new string(currentArg.ToArray()));\n\n return args.ToArray();\n}\n" }, { "answer_id": 58233585, "author": "user2126375", "author_id": 2126375, "author_profile": "https://Stackoverflow.com/users/2126375", "pm_score": 0, "selected": false, "text": "static void Main(string[] args) public static IList<string> ParseCommandLineArgsString(string commandLineArgsString)\n {\n List<string> args = new List<string>();\n\n commandLineArgsString = commandLineArgsString.Trim();\n if (commandLineArgsString.Length == 0)\n return args;\n\n int index = 0;\n while (index != commandLineArgsString.Length)\n {\n args.Add(ReadOneArgFromCommandLineArgsString(commandLineArgsString, ref index));\n }\n\n return args;\n }\n\n private static string ReadOneArgFromCommandLineArgsString(string line, ref int index)\n {\n if (index >= line.Length)\n return string.Empty;\n\n var sb = new StringBuilder(512);\n int state = 0;\n while (true)\n {\n char c = line[index];\n index++;\n switch (state)\n {\n case 0: //string outside quotation marks\n if (c == '\\\\') //possible escaping character for quotation mark otherwise normal character\n {\n state = 1;\n }\n else if (c == '\"') //opening quotation mark for string between quotation marks\n {\n state = 2;\n }\n else if (c == ' ') //closing arg\n {\n return sb.ToString();\n }\n else\n {\n sb.Append(c);\n }\n\n break;\n case 1: //possible escaping \\ for quotation mark or normal character\n if (c == '\"') //If escaping quotation mark only quotation mark is added into result\n {\n state = 0;\n sb.Append(c);\n }\n else // \\ works as not-special character\n {\n state = 0;\n sb.Append('\\\\');\n index--;\n }\n\n break;\n case 2: //string between quotation marks\n if (c == '\"') //quotation mark in string between quotation marks can be escape mark for following quotation mark or can be ending quotation mark for string between quotation marks\n {\n state = 3;\n }\n else if (c == '\\\\') //escaping \\ for possible following quotation mark otherwise normal character\n {\n state = 4;\n }\n else //text in quotation marks\n {\n sb.Append(c);\n }\n\n break;\n case 3: //quotation mark in string between quotation marks\n if (c == '\"') //Quotation mark after quotation mark - that means that this one is escaped and can added into result and we will stay in string between quotation marks state\n {\n state = 2;\n sb.Append(c);\n }\n else //we had two consecutive quotation marks - this means empty string but the following chars (until space) will be part of same arg result as well\n {\n state = 0;\n index--;\n }\n\n break;\n case 4: //possible escaping \\ for quotation mark or normal character in string between quotation marks\n if (c == '\"') //If escaping quotation mark only quotation mark added into result\n {\n state = 2;\n sb.Append(c);\n }\n else\n {\n state = 2;\n sb.Append('\\\\');\n index--;\n }\n\n break;\n }\n\n if (index == line.Length)\n return sb.ToString();\n }\n }\n" }, { "answer_id": 59131568, "author": "Dilip Nannaware", "author_id": 3926504, "author_profile": "https://Stackoverflow.com/users/3926504", "pm_score": 0, "selected": false, "text": "static string[] ParseMultiSpacedArguments(string commandLine)\n{\n var isLastCharSpace = false;\n char[] parmChars = commandLine.ToCharArray();\n bool inQuote = false;\n for (int index = 0; index < parmChars.Length; index++)\n {\n if (parmChars[index] == '\"')\n inQuote = !inQuote;\n if (!inQuote && parmChars[index] == ' ' && !isLastCharSpace)\n parmChars[index] = '\\n';\n\n isLastCharSpace = parmChars[index] == '\\n' || parmChars[index] == ' ';\n }\n\n return (new string(parmChars)).Split('\\n');\n}\n" }, { "answer_id": 64236441, "author": "Mikescher", "author_id": 1761622, "author_profile": "https://Stackoverflow.com/users/1761622", "pm_score": 4, "selected": false, "text": " Test( 0, m, \"One\", new[] { \"One\" });\n Test( 1, m, \"One \", new[] { \"One\" });\n Test( 2, m, \" One\", new[] { \"One\" });\n Test( 3, m, \" One \", new[] { \"One\" });\n Test( 4, m, \"One Two\", new[] { \"One\", \"Two\" });\n Test( 5, m, \"One Two\", new[] { \"One\", \"Two\" });\n Test( 6, m, \"One Two\", new[] { \"One\", \"Two\" });\n Test( 7, m, \"\\\"One Two\\\"\", new[] { \"One Two\" });\n Test( 8, m, \"One \\\"Two Three\\\"\", new[] { \"One\", \"Two Three\" });\n Test( 9, m, \"One \\\"Two Three\\\" Four\", new[] { \"One\", \"Two Three\", \"Four\" });\n Test(10, m, \"One=\\\"Two Three\\\" Four\", new[] { \"One=Two Three\", \"Four\" });\n Test(11, m, \"One\\\"Two Three\\\" Four\", new[] { \"OneTwo Three\", \"Four\" });\n Test(12, m, \"One\\\"Two Three Four\", new[] { \"OneTwo Three Four\" });\n Test(13, m, \"\\\"One Two\\\"\", new[] { \"One Two\" });\n Test(14, m, \"One\\\" \\\"Two\", new[] { \"One Two\" });\n Test(15, m, \"\\\"One\\\" \\\"Two\\\"\", new[] { \"One\", \"Two\" });\n Test(16, m, \"One\\\\\\\" Two\", new[] { \"One\\\"\", \"Two\" });\n Test(17, m, \"\\\\\\\"One\\\\\\\" Two\", new[] { \"\\\"One\\\"\", \"Two\" });\n Test(18, m, \"One\\\"\", new[] { \"One\" });\n Test(19, m, \"\\\"One\", new[] { \"One\" });\n Test(20, m, \"One \\\"\\\"\", new[] { \"One\", \"\" });\n Test(21, m, \"One \\\"\", new[] { \"One\", \"\" });\n Test(22, m, \"1 A=\\\"B C\\\"=D 2\", new[] { \"1\", \"A=B C=D\", \"2\" });\n Test(23, m, \"1 A=\\\"B \\\\\\\" C\\\"=D 2\", new[] { \"1\", \"A=B \\\" C=D\", \"2\" });\n Test(24, m, \"1 \\\\A 2\", new[] { \"1\", \"\\\\A\", \"2\" });\n Test(25, m, \"1 \\\\\\\" 2\", new[] { \"1\", \"\\\"\", \"2\" });\n Test(26, m, \"1 \\\\\\\\\\\" 2\", new[] { \"1\", \"\\\\\\\"\", \"2\" });\n Test(27, m, \"\\\"\", new[] { \"\" });\n Test(28, m, \"\\\\\\\"\", new[] { \"\\\"\" });\n Test(29, m, \"'A B'\", new[] { \"'A\", \"B'\" });\n Test(30, m, \"^\", new[] { \"^\" });\n Test(31, m, \"^A\", new[] { \"A\" });\n Test(32, m, \"^^\", new[] { \"^\" });\n Test(33, m, \"\\\\^^\", new[] { \"\\\\^\" });\n Test(34, m, \"^\\\\\\\\\", new[] { \"\\\\\\\\\" });\n Test(35, m, \"^\\\"A B\\\"\", new[] { \"A B\" });\n\n // Test cases Anton\n\n Test(36, m, @\"/src:\"\"C:\\tmp\\Some Folder\\Sub Folder\"\" /users:\"\"abcdefg@hijkl.com\"\" tasks:\"\"SomeTask,Some Other Task\"\" -someParam foo\", new[] { @\"/src:C:\\tmp\\Some Folder\\Sub Folder\", @\"/users:abcdefg@hijkl.com\", @\"tasks:SomeTask,Some Other Task\", @\"-someParam\", @\"foo\" });\n\n // Test cases Daniel Earwicker \n\n Test(37, m, \"\", new string[] { });\n Test(38, m, \"a\", new[] { \"a\" });\n Test(39, m, \" abc \", new[] { \"abc\" });\n Test(40, m, \"a b \", new[] { \"a\", \"b\" });\n Test(41, m, \"a b \\\"c d\\\"\", new[] { \"a\", \"b\", \"c d\" });\n\n // Test cases Fabio Iotti \n\n Test(42, m, \"this is a test \", new[] { \"this\", \"is\", \"a\", \"test\" });\n Test(43, m, \"this \\\"is a\\\" test\", new[] { \"this\", \"is a\", \"test\" });\n\n // Test cases Kevin Thach\n\n Test(44, m, \"\\\"C:\\\\Program Files\\\"\", new[] { \"C:\\\\Program Files\" });\n Test(45, m, \"\\\"He whispered to her \\\\\\\"I love you\\\\\\\".\\\"\", new[] { \"He whispered to her \\\"I love you\\\".\" });\n static void Main(string[] args) => Console.Out.WriteLine($\"Count := {args.Length}\\n{string.Join(\"\\n\", args.Select((v,i) => $\"[{i}] => '{v}'\"))}\");\n \nSolution | Failed Tests\n------------------------------|------------------------------------- \nAtif Aziz (749653) | 2, 3, 10, 11, 12, 14, 16, 17, 18, 26, 28, 31, 32, 33, 34, 35, 36, 37, 39, 45\nJeffrey L Whitledge (298968) | 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45\nDaniel Earwicker (298990) | 10, 11, 12, 14, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 45\nAnton (299795) | 12, 16, 17, 18, 19, 21, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 45\nCS. (467313) | 12, 18, 19, 21, 27, 31, 32, 33, 34, 35\nVapour in the Alley (2132004) | 10, 11, 12, 14, 16, 17, 20, 21, 22, 23, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 45\nMonoman (7774211) | 14, 16, 17, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 45\nThomas Petersson (19091999) | 2, 3, 10, 11, 12, 14, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 39, 45\nFabio Iotti (19725880) | 1, 2, 3, 7, 10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 22, 23, 25, 26, 28, 29, 30, 35, 36, 37, 39, 40, 42, 44, 45\nygoe (23961658) | 26, 31, 32, 33, 34, 35\nKevin Thach (24829691) | 10, 11, 12, 14, 18, 19, 20, 21, 22, 23, 26, 27, 31, 32, 33, 34, 35, 36\nLucas De Jesus (31621370) | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45\nHarryP (48008872) | 24, 26, 31, 32, 33, 34, 35\nTylerY86 (53290784) | 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 41, 43, 44, 45\nLouis Somers (55903304) | 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 39, 41, 43, 44, 45\nuser2126375 (58233585) | 5, 6, 15, 16, 17, 31, 32, 33, 34, 35\nDilipNannaware (59131568) | 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45\nMikescher (this) | -\n public static IEnumerable<string> SplitArgs(string commandLine)\n{\n var result = new StringBuilder();\n\n var quoted = false;\n var escaped = false;\n var started = false;\n var allowcaret = false;\n for (int i = 0; i < commandLine.Length; i++)\n {\n var chr = commandLine[i];\n\n if (chr == '^' && !quoted)\n {\n if (allowcaret)\n {\n result.Append(chr);\n started = true;\n escaped = false;\n allowcaret = false;\n }\n else if (i + 1 < commandLine.Length && commandLine[i + 1] == '^')\n {\n allowcaret = true;\n }\n else if (i + 1 == commandLine.Length)\n {\n result.Append(chr);\n started = true;\n escaped = false;\n }\n }\n else if (escaped)\n {\n result.Append(chr);\n started = true;\n escaped = false;\n }\n else if (chr == '\"')\n {\n quoted = !quoted;\n started = true;\n }\n else if (chr == '\\\\' && i + 1 < commandLine.Length && commandLine[i + 1] == '\"')\n {\n escaped = true;\n }\n else if (chr == ' ' && !quoted)\n {\n if (started) yield return result.ToString();\n result.Clear();\n started = false;\n }\n else\n {\n result.Append(chr);\n started = true;\n }\n }\n\n if (started) yield return result.ToString();\n}\n" }, { "answer_id": 64545161, "author": "Robin Hartmann", "author_id": 3859863, "author_profile": "https://Stackoverflow.com/users/3859863", "pm_score": 2, "selected": false, "text": "using Microsoft.CodeAnalysis;\n// [...]\nvar cli = @\"/src:\"\"C:\\tmp\\Some Folder\\Sub Folder\"\" /users:\"\"abcdefg@hijkl.com\"\" tasks:\"\"SomeTask,Some Other Task\"\" -someParam foo\";\nvar cliArgs = CommandLineParser.SplitCommandLineIntoArguments(cli, true);\n\nConsole.WriteLine(string.Join('\\n', cliArgs));\n// prints out:\n// /src:\"C:\\tmp\\Some Folder\\Sub Folder\"\n// /users:\"abcdefg@hijkl.com\"\n// tasks:\"SomeTask,Some Other Task\"\n// -someParam\n// foo\n" }, { "answer_id": 66512779, "author": "Brunni", "author_id": 2415316, "author_profile": "https://Stackoverflow.com/users/2415316", "pm_score": 0, "selected": false, "text": "ProcessStartInfo \"C:\\Users\\Me\\Something.exe\" -a { \"C:\\Users\\Me\\Something.exe\", \"-a\" } public static string[] SplitCommandFromArgs(string commandLine)\n {\n commandLine = commandLine.Trim();\n if (commandLine[0] == '\"')\n {\n bool isEscaped = false;\n for (int c = 1; c < commandLine.Length; c++)\n {\n if (commandLine[c] == '\"' && !isEscaped)\n {\n return new string[] { commandLine.Substring(1, c - 1), commandLine.Substring(c + 1).Trim() };\n }\n isEscaped = commandLine[c] == '\\\\';\n }\n }\n else\n {\n for (int c = 1; c < commandLine.Length; c++) {\n if (commandLine[c] == ' ')\n {\n return new string[] { commandLine.Substring(0, c), commandLine.Substring(c).Trim() };\n }\n }\n }\n return new string[] { commandLine, \"\" };\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341413/" ]
298,840
<p>I have a .NET Web app which consumes a Java-based Web service. One of the objects, named Optional, contains search criteria fields. The schema is the following:</p> <pre><code>&lt;xsd:complexType name="Optional"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="FromAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="ToAmount" nillable="true" type="xsd:float" minOccurs="0" /&gt; &lt;xsd:element name="FromDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="ToDate" nillable="true" type="xsd:dateTime" minOccurs="0" /&gt; &lt;xsd:element name="FromCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;xsd:element name="ToCheckNumber" nillable="true" type="xsd:long" minOccurs="0" /&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; </code></pre> <p>The problem that I am running into is that the child elements will not serialize even when a value is assigned to them in the Web app. If I remove the minOccurs attribute, then all is well.</p> <p>How do I get these elements to be optional, but to serialize when a value is assigned to them?</p> <p>Thanks in advance for your help.</p>
[ { "answer_id": 300992, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 0, "selected": false, "text": "<Optional/>" }, { "answer_id": 324517, "author": "superfell", "author_id": 41455, "author_profile": "https://Stackoverflow.com/users/41455", "pm_score": 3, "selected": true, "text": "x.ToAmmount = 24.0f;\nx.ToAmmountSpecified = true;\n// etc for the rest of the poperties\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15883/" ]
298,841
<p>Is there a way to read the properties inside an <a href="https://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow noreferrer">MSI</a> file?</p> <p>For example, given a MSI file named <em>Testpackage.msi</em>, I need to find</p> <pre><code>productName PackageCode version </code></pre> <p>This I am going to use it with WMI uninstall</p> <pre><code>string objPath = string.Format(&quot;Win32_Product.IdentifyingNumber='{0}', Name='{1}', Version='{2}'&quot;, &quot;{AC9C1263-2BA8-4863-BE18-01232375CE42}&quot;, &quot;testproduct&quot;, &quot;10.0.0.0&quot;); </code></pre> <p>Using <a href="http://msdn.microsoft.com/en-us/library/aa370557(v=vs.85).aspx" rel="nofollow noreferrer">Orca</a> is a great option, if this can be achieved programmatically. Then I can use this to generate automatic release notes. And in un-installing program too.</p>
[ { "answer_id": 328710, "author": "Arnout", "author_id": 3496, "author_profile": "https://Stackoverflow.com/users/3496", "pm_score": 4, "selected": true, "text": "Function GetVersion(ByVal msiName)\n\n Const msiOpenDatabaseModeReadOnly = 0\n Dim msi, db, view\n\n Set msi = CreateObject(\"WindowsInstaller.Installer\")\n Set db = msi.OpenDataBase(msiName, msiOpenDatabaseModeReadOnly)\n Set view = db.OpenView(\"SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'\")\n Call view.Execute()\n\n GetVersion = view.Fetch().StringData(1)\n\nEnd Function\n" }, { "answer_id": 1061606, "author": "Stein Åsmul", "author_id": 129130, "author_profile": "https://Stackoverflow.com/users/129130", "pm_score": 3, "selected": false, "text": "Microsoft.Deployment.WindowsInstaller.dll WixInstallPath\\SDK using (var db = new Database(FullPath, DatabaseOpenMode.ReadOnly))\n{ \n PackageCode = db.SummaryInfo.RevisionNumber;\n AppVendor = db.SummaryInfo.Author;\n AppName = db.SummaryInfo.Title;\n ProductName = db.SummaryInfo.Subject;\n ProductCode = (string)db.ExecuteScalar(\"SELECT `Value` FROM \"+\n \"`Property` WHERE `Property` = 'ProductCode'\");\n AppVersion = (string)db.ExecuteScalar(\"SELECT `Value` FROM \"+\n \"`Property` WHERE `Property` = 'ProductVersion'\");\n UpgradeCode = (string)db.ExecuteScalar(\"SELECT `Value` FROM \"+\n \" `Property` WHERE `Property` = 'UpgradeCode'\");\n}\n" }, { "answer_id": 1063548, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 2, "selected": false, "text": "Option Explicit\nConst MY_MSI = \"product.msi\"\n\nDim installer, database, view, result, sumInfo, sPackageCode\n\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nSet database = installer.OpenDatabase (MY_MSI, 0)\n\nSet sumInfo = installer.SummaryInformation(MY_MSI, 0)\nsPackageCode = sumInfo.Property(9) ' PID_REVNUMBER = 9, contains the package code.\n\nWScript.Echo \"ProductVersion=\" & getproperty(\"ProductVersion\")\nWScript.Echo \"ProductCode=\" & getproperty(\"ProductCode\") \nWScript.Echo \"PackageCode=\" & sPackageCode \nWScript.Echo \"ProductName=\" & getproperty(\"ProductName\") \n\nFunction getproperty(property)\n\n Set view = database.OpenView (\"SELECT Value FROM Property WHERE Property='\" & property & \"'\")\n view.Execute\n Set result = view.Fetch\n getproperty = result.StringData(1)\n\nEnd Function \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32670/" ]
298,850
<p>I have a 5 ASPX page <code>wizard</code>. Each one contains a <code>SaveAndExit</code> button that executes a C# function on a common static class. After saving, the C# code redirects to another page.</p> <p>Is there a way for running <code>javascript: alert('Data Saved');</code> after the saving, and before new page is Loaded.</p>
[ { "answer_id": 299456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "if exist" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
298,867
<p>How do I export all of the names and email addresses from a distribution list in Outlook using code? I have access to an Outlook 2000 or Outlook 2007 client. Ideally I would like the code to be in C#.</p>
[ { "answer_id": 299034, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "Const olFolderContacts = 10\n\nSet objOutlook = CreateObject(\"Outlook.Application\")\nSet objNamespace = objOutlook.GetNamespace(\"MAPI\")\n\nSet colContacts = objNamespace.GetDefaultFolder(olFolderContacts).Items\nintCount = colContacts.Count\n\nFor i = 1 To intCount\n If TypeName(colContacts.Item(i)) = \"DistListItem\" Then\n Set objDistList = colContacts.Item(i)\n Wscript.Echo objDistList.DLName\n For j = 1 To objDistList.MemberCount\n Wscript.Echo objDistList.GetMember(j).Name & \" -- \" & _\n objDistList.GetMember(j).Address\n Next \n Wscript.Echo\n End If\nNext\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
298,873
<p>I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing).</p> <p>That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have some assertion that would inform me (log or something) if some method(s) of it was called from multiple threads.</p> <p>I'm longing for something similar that could be made for AWT dispatch thread with the following:</p> <pre><code>public static void checkDispatchThread() { if(!SwingUtilities.isEventDispatchThread()) { throw new RuntimeException("GUI change made outside AWT dispatch thread"); } } </code></pre> <p>I'd only want something more general. The problem description isn't so clear but I hope somebody has some good approaches =)</p>
[ { "answer_id": 299197, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "class Foo {\n\n private final Thread owner = Thread.currentThread();\n\n void x() {\n assert Thread.currentThread() == owner;\n /* Implement method. */\n }\n\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28482/" ]
298,886
<p>Does .NET have a way to pull email from a POP3 server out of the box or you have to code/buy a 3rd party component?</p>
[ { "answer_id": 669697, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 2, "selected": false, "text": "using(Pop3 pop3 = new Pop3())\n{\n pop3.Connect(\"mail.host.com\"); // Connect to server\n pop3.Login(\"user\", \"password\");\n\n foreach(string uid in pop3.GetAll())\n {\n IMail email = new MailBuilder()\n .CreateFromEml(pop3.GetMessageByUID(uid));\n Console.WriteLine( email.Subject );\n }\n pop3.Close(false); \n}\n" }, { "answer_id": 1827068, "author": "Martin Vobr", "author_id": 16132, "author_profile": "https://Stackoverflow.com/users/16132", "pm_score": 0, "selected": false, "text": "// create client, connect and log in \nPop3 client = new Pop3();\nclient.Connect(\"pop3.example.org\");\nclient.Login(\"username\", \"password\");\n\n// get message list - full headers \nPop3MessageCollection messages = client.GetMessageList(Pop3ListFields.FullHeaders);\n\n// display info about each message \nConsole.WriteLine(\"UID | From | To | Subject\");\nforeach (Pop3MessageInfo message in messages)\n{\n Console.WriteLine\n (\n \"{0} | {1} | {2} | {3}\",\n message.UniqueId,\n message.From,\n message.To,\n message.Subject\n );\n}\n\nclient.Disconnect();\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
298,897
<p>I've been putting together a small web form for our technicians to use from their phones out in the field. However I'm having a lot of trouble getting things working using ASP.NET Mobile, and there seems to be few resources out there to help learn this stuff. I'm also having trouble <a href="https://stackoverflow.com/questions/291638/how-do-you-get-the-value-of-a-bound-mobilelistitem" title="Getting Help">getting help</a>. </p> <p>So the thing is, do I really need to use the mobile controls? The phones will all have web browsers, so I'm thinking if I'm careful with the interface I can get as good or better results than using the mobile controls. </p> <p>The only thing I would like from the mobile controls is the PhoneCall control... so the follow up question would be: Can I get the functionality of the PhoneCall control without using it?</p>
[ { "answer_id": 299244, "author": "fravelgue", "author_id": 22055, "author_profile": "https://Stackoverflow.com/users/22055", "pm_score": 0, "selected": false, "text": "<a ref=\"wtai://wp/mc;34123456789\">Call</a>" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
298,909
<p>I'm wondering why the <code>assert</code> keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of:</p> <pre><code>assert param != null : "Param cannot be null"; </code></pre> <p>to the verbosity of:</p> <pre><code>if (param == null) { throw new IllegalArgumentException("Param cannot be null"); } </code></pre> <p>My suspicion is that they're underused because</p> <ul> <li>They arrived relatively late (Java 1.4), by which time many people had already established their Java programming style/habit</li> <li>They are turned off at runtime by default</li> </ul>
[ { "answer_id": 298929, "author": "Denis R.", "author_id": 32015, "author_profile": "https://Stackoverflow.com/users/32015", "pm_score": 0, "selected": false, "text": "if" }, { "answer_id": 298973, "author": "Adam Jaskiewicz", "author_id": 35322, "author_profile": "https://Stackoverflow.com/users/35322", "pm_score": 6, "selected": false, "text": "IllegalArgumentException assert assert" }, { "answer_id": 666082, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 3, "selected": false, "text": "if (!expr) throw Ex Note: %n assertions inlined.\n" }, { "answer_id": 43262017, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 0, "selected": false, "text": "requireThat(\"name\", value).isNotNull();\n assertThat(\"name\", value).isNotNull();\n java.lang.NullPointerException: name may not be null\n" }, { "answer_id": 54778330, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": "assert BigDecimal assert org.junit.jupiter.api.Assertions package work.basil.example;\n\npublic class Assertions {\n static public void assertTrue ( Boolean booleanExpression , CharSequence message ) throws java.lang.AssertionError {\n if ( booleanExpression ) {\n // No code needed here.\n } else { // If booleanExpression is false rather than expected true, throw assertion error.\n // FIXME: Add logging.\n throw new java.lang.AssertionError( message.toString() );\n }\n }\n\n}\n Assertions.assertTrue( \n localTime.isBefore( LocalTime.NOON ) , \n \"The time-of-day is too late, after noon: \" + localTime + \". Message # 816a2a26-2b95-45fa-9b0a-5d10884d819d.\" \n) ;\n assert assert" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
298,926
<p>In vb.net / winforms, how can a hashtable be bound to a drop down list or any other datasource-driven control?</p>
[ { "answer_id": 298935, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": " DropDownList dd = new DropDownList();\n Hashtable mycountries = New Hashtable();\n mycountries.Add(\"N\",\"Norway\");\n mycountries.Add(\"S\",\"Sweden\");\n mycountries.Add(\"F\",\"France\");\n mycountries.Add(\"I\",\"Italy\");\n dd.DataSource=mycountries;\n dd.DataValueField=\"Key\";\n dd.DataTextField=\"Value\";\n dd.DataBind();\n" }, { "answer_id": 298943, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 0, "selected": false, "text": "myCtrl.DataSource = myHashtable\nmyCtrl.DataBind()\n <itemtemplate>\n <%# DataBinder.Eval(Container.DataItem, \"Key\", \"<td>{0}</td>\") %>\n <%# DataBinder.Eval(Container.DataItem, \"Value\", \"<td>${0:f2}</td>\") %>\n</itemtemplate>\n" }, { "answer_id": 298998, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "IList IListSource IList List<T> BindingList<T> T HashTable Dictionary<,> ArrayList class MyData\n{\n public int Key { get; set; }\n public string Text { get; set; }\n}\n[STAThread]\nstatic void Main()\n{\n var data = new List<MyData>\n {\n new MyData { Key = 1, Text = \"abc\"},\n new MyData { Key = 2, Text = \"def\"},\n new MyData { Key = 3, Text = \"ghi\"},\n };\n ComboBox cbo = new ComboBox\n {\n DataSource = data,\n DisplayMember = \"Text\",\n ValueMember = \"Key\"\n };\n cbo.SelectedValueChanged += delegate {\n Debug.WriteLine(cbo.SelectedValue);\n };\n Application.Run(new Form {Controls = {cbo}});\n}\n" }, { "answer_id": 2119550, "author": "Aaron Barker", "author_id": 181935, "author_profile": "https://Stackoverflow.com/users/181935", "pm_score": 1, "selected": false, "text": "List<Order> list = new List<Order>{};\n\nforeach (Order o in OOS.AppVars.FinalizedOrders.Values)\n{\n list.Add(o);\n}\n\nthis.comboBox_Orders.DataSource = list;\nthis.comboBox_Orders.DisplayMember = \"Description\";\n Order order = (Order)this.comboBox_Orders.SelectedValue;\n" }, { "answer_id": 2828258, "author": "Brady Moritz", "author_id": 177242, "author_profile": "https://Stackoverflow.com/users/177242", "pm_score": 0, "selected": false, "text": "MyDDL.Datasouce = myDict.ToList();\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259/" ]
298,962
<p>Clearly separation of concerns is a desirable trait in our code and the first obvious step most people take is to separate data access from presentation. In my situation, LINQ To SQL is being used within data access objects for the data access.</p> <p>My question is, where should the use of the entity object stop? To clarify, I could pass the entity objects up to the domain layer but I feel as though an entity object is more than just a data object - it's like passing a bit of the DAL up to the next layer too.</p> <p>Let's say I have a UserDAL class, should it expose an entity User object to the domain when a method GetByID() is called, or should it spit out a plain data object purely for storing the data and nothing more? (seems like wasteful duplication in this case)</p> <p>What have you guys done in this same situation? Is there an alternative method to this?</p> <p>Hope that wasn't too vague.</p> <p>Thanks a lot,</p> <p>Martin.</p>
[ { "answer_id": 299008, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 3, "selected": false, "text": " IQueryable<MyObjects.Product> products = from p in linqDataContext.Products \n select new MyObjects.Product //POCO\n {\n ProductID = p.ProductID\n };\n return products;\n" }, { "answer_id": 321911, "author": "Rafael Romão", "author_id": 39281, "author_profile": "https://Stackoverflow.com/users/39281", "pm_score": 0, "selected": false, "text": "\npublic interface IConcept {\n long Code { get; set; }\n string Name { get; set; }\n bool IsDefault { get; set; }\n}\n \npublic partial class Concept : IConcept { }\n \n[Table(Name=\"dbo.Concepts\")]\npublic partial class Concept\n{\n private long _Code;\n private string _Name;\n private bool _IsDefault;\n partial void OnCreated();\n public Concept() { OnCreated(); }\n [Column(Storage=\"_Code\", DbType=\"BigInt NOT NULL IDENTITY\", IsPrimaryKey=true)]\n public long Code\n {\n //***\n }\n [Column(Storage=\"_Name\", DbType=\"VarChar(50) NOT NULL\")]\n public string Name\n {\n //***\n }\n [Column(Storage=\"_IsDefault\", DbType=\"Bit NOT NULL\")]\n public bool IsDefault\n {\n //***\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
298,972
<p>I am using a query like this on my postgres database:</p> <pre><code>SELECT TableA.id FROM TableA , TableB WHERE TableA.id = 100; </code></pre> <p>Each TableA.id is unique (it's an autoincrement), I am getting more than 1 result. Am I missing something in here?</p>
[ { "answer_id": 298983, "author": "Ben McEvoy", "author_id": 15234, "author_profile": "https://Stackoverflow.com/users/15234", "pm_score": 3, "selected": false, "text": "SELECT TableA.ID from TableA\nINNER JOIN TableB \nON TableB.TableAID = TableA.ID \nWHERE TableA.ID = 100\n" }, { "answer_id": 298985, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "TableA TableB SELECT TableA.id FROM TableA, TableB WHERE TableA.id=TableB.id AND TableA.id = 100\n" }, { "answer_id": 299286, "author": "Chris Parkinson", "author_id": 17530, "author_profile": "https://Stackoverflow.com/users/17530", "pm_score": 0, "selected": false, "text": "INNER JOIN TableB ON TableA.Id = TableB.Id\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
298,976
<p>Seeing as C# can't <code>switch</code> on a Type (which I gather wasn't added as a special case because <code>is</code> relationships mean that more than one distinct <code>case</code> might apply), is there a better way to simulate switching on type other than this?</p> <pre><code>void Foo(object o) { if (o is A) { ((A)o).Hop(); } else if (o is B) { ((B)o).Skip(); } else { throw new ArgumentException("Unexpected type: " + o.GetType()); } } </code></pre>
[ { "answer_id": 298994, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "Type Action" }, { "answer_id": 299001, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 9, "selected": false, "text": "case switch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"<unknown shape>\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n switch(o.GetType().Name) {\n case nameof(AType):\n break;\n case nameof(BType):\n break;\n}\n switch(o.GetType().Name) {\n case \"AType\":\n break;\n}\n" }, { "answer_id": 299015, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "class Mine {\n static List<Func<object, bool>> predicates;\n static List<Action<object>> actions;\n\n static Mine() {\n AddAction<A>(o => o.Hop());\n AddAction<B>(o => o.Skip());\n }\n\n static void AddAction<T>(Action<T> action) {\n predicates.Add(o => o is T);\n actions.Add(o => action((T)o);\n }\n\n static void RunAction(object o) {\n for (int i=0; o < predicates.Count; i++) {\n if (predicates[i](o)) {\n actions[i](o);\n break;\n }\n }\n }\n\n void Foo(object o) {\n RunAction(o);\n }\n}\n" }, { "answer_id": 299043, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 0, "selected": false, "text": "A a = o as A;\nif (a != null) {\n a.Hop();\n return;\n}\nB b = o as B;\nif (b != null) {\n b.Skip();\n return;\n}\nthrow new ArgumentException(\"...\");\n" }, { "answer_id": 299052, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": false, "text": "IFooable A B interface IFooable\n{\n public void Foo();\n}\n\nclass A : IFooable\n{\n //other methods ...\n\n public void Foo()\n {\n this.Hop();\n }\n}\n\nclass B : IFooable\n{\n //other methods ...\n\n public void Foo()\n {\n this.Skip();\n }\n}\n\nclass ProcessingClass\n{\n public void Foo(object o)\n {\n if (o == null)\n throw new NullRefferenceException(\"Null reference\", \"o\");\n\n IFooable f = o as IFooable;\n if (f != null)\n {\n f.Foo();\n }\n else\n {\n throw new ArgumentException(\"Unexpected type: \" + o.GetType());\n }\n }\n}\n as is" }, { "answer_id": 299120, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 9, "selected": true, "text": "TypeSwitch.Do(\n sender,\n TypeSwitch.Case<Button>(() => textBox1.Text = \"Hit a Button\"),\n TypeSwitch.Case<CheckBox>(x => textBox1.Text = \"Checkbox is \" + x.Checked),\n TypeSwitch.Default(() => textBox1.Text = \"Not sure what is hovered over\"));\n static class TypeSwitch {\n public class CaseInfo {\n public bool IsDefault { get; set; }\n public Type Target { get; set; }\n public Action<object> Action { get; set; }\n }\n\n public static void Do(object source, params CaseInfo[] cases) {\n var type = source.GetType();\n foreach (var entry in cases) {\n if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) {\n entry.Action(source);\n break;\n }\n }\n }\n\n public static CaseInfo Case<T>(Action action) {\n return new CaseInfo() {\n Action = x => action(),\n Target = typeof(T)\n };\n }\n\n public static CaseInfo Case<T>(Action<T> action) {\n return new CaseInfo() {\n Action = (x) => action((T)x),\n Target = typeof(T)\n };\n }\n\n public static CaseInfo Default(Action action) {\n return new CaseInfo() {\n Action = x => action(),\n IsDefault = true\n };\n }\n}\n" }, { "answer_id": 299182, "author": "jgarcia", "author_id": 32633, "author_profile": "https://Stackoverflow.com/users/32633", "pm_score": 2, "selected": false, "text": "public interface IThing\n{\n void Move();\n}\n\npublic class ThingA : IThing\n{\n public void Move()\n {\n Hop();\n }\n\n public void Hop(){ \n //Implementation of Hop \n }\n\n}\n\npublic class ThingA : IThing\n{\n public void Move()\n {\n Skip();\n }\n\n public void Skip(){ \n //Implementation of Skip \n }\n\n}\n\npublic class Foo\n{\n static void Main(String[] args)\n {\n\n }\n\n private void Foo(IThing a)\n {\n a.Move();\n }\n}\n" }, { "answer_id": 302228, "author": "Paul Batum", "author_id": 48281, "author_profile": "https://Stackoverflow.com/users/48281", "pm_score": 3, "selected": false, "text": "class Thing\n{\n\n void Foo(A a)\n {\n a.Hop();\n }\n\n void Foo(B b)\n {\n b.Skip();\n }\n\n}\n object aOrB = Get_AOrB();\nThing t = GetThing();\n((dynamic)t).Foo(aorB);\n" }, { "answer_id": 5911051, "author": "Evren Kuzucuoglu", "author_id": 486172, "author_profile": "https://Stackoverflow.com/users/486172", "pm_score": 3, "selected": false, "text": "{\n string s = \"a\";\n if (s is string) Print(\"Foo\");\n else if (s is object) Print(\"Bar\");\n}\n {\n string s = \"a\";\n if (s is object) Print(\"Foo\");\n else if (s is string) Print(\"Bar\");\n}\n switch(foo) case foo is T foo.GetType() == typeof(T)" }, { "answer_id": 10025398, "author": "Daniel A.A. Pelsmaeker", "author_id": 146622, "author_profile": "https://Stackoverflow.com/users/146622", "pm_score": 6, "selected": false, "text": "TypeSwitch class A { string Name { get; } }\nclass B : A { string LongName { get; } }\nclass C : A { string FullName { get; } }\nclass X { public string ToString(IFormatProvider provider); }\nclass Y { public string GetIdentifier(); }\n\npublic string GetName(object value)\n{\n string name = null;\n TypeSwitch.On(value)\n .Case((C x) => name = x.FullName)\n .Case((B x) => name = x.LongName)\n .Case((A x) => name = x.Name)\n .Case((X x) => name = x.ToString(CultureInfo.CurrentCulture))\n .Case((Y x) => name = x.GetIdentifier())\n .Default((x) => name = x.ToString());\n return name;\n}\n Case() TypeSwitch public static class TypeSwitch\n{\n public static Switch<TSource> On<TSource>(TSource value)\n {\n return new Switch<TSource>(value);\n }\n\n public sealed class Switch<TSource>\n {\n private readonly TSource value;\n private bool handled = false;\n\n internal Switch(TSource value)\n {\n this.value = value;\n }\n\n public Switch<TSource> Case<TTarget>(Action<TTarget> action)\n where TTarget : TSource\n {\n if (!this.handled && this.value is TTarget)\n {\n action((TTarget) this.value);\n this.handled = true;\n }\n return this;\n }\n\n public void Default(Action<TSource> action)\n {\n if (!this.handled)\n action(this.value);\n }\n }\n}\n" }, { "answer_id": 14132744, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 0, "selected": false, "text": "enum ObjectType { A, B, Default }\n\ninterface IIdentifiable\n{\n ObjectType Type { get; };\n}\nclass A : IIdentifiable\n{\n public ObjectType Type { get { return ObjectType.A; } }\n}\n\nclass B : IIdentifiable\n{\n public ObjectType Type { get { return ObjectType.B; } }\n}\n\nvoid Foo(IIdentifiable o)\n{\n switch (o.Type)\n {\n case ObjectType.A:\n case ObjectType.B:\n //......\n }\n}\n GetTypeCode void Foo(object o)\n{\n switch (Type.GetTypeCode(o.GetType())) // for IConvertible, just o.GetTypeCode()\n {\n case TypeCode.Int16:\n case TypeCode.Int32:\n //etc ......\n }\n}\n" }, { "answer_id": 14157259, "author": "Sergey Berezovskiy", "author_id": 470005, "author_profile": "https://Stackoverflow.com/users/470005", "pm_score": 2, "selected": false, "text": "void Foo(A a) \n{ \n a.Hop(); \n}\n\nvoid Foo(B b) \n{ \n b.Skip(); \n}\n\nvoid Foo(object o) \n{ \n throw new ArgumentException(\"Unexpected type: \" + o.GetType()); \n}\n dynamic Foo((dynamic)something);\n" }, { "answer_id": 17173625, "author": "scobi", "author_id": 14582, "author_profile": "https://Stackoverflow.com/users/14582", "pm_score": 3, "selected": false, "text": "public static class TypeSwitch\n{\n public static void On<TV, T1>(TV value, Action<T1> action1)\n where T1 : TV\n {\n if (value is T1) action1((T1)value);\n }\n\n public static void On<TV, T1, T2>(TV value, Action<T1> action1, Action<T2> action2)\n where T1 : TV where T2 : TV\n {\n if (value is T1) action1((T1)value);\n else if (value is T2) action2((T2)value);\n }\n\n public static void On<TV, T1, T2, T3>(TV value, Action<T1> action1, Action<T2> action2, Action<T3> action3)\n where T1 : TV where T2 : TV where T3 : TV\n {\n if (value is T1) action1((T1)value);\n else if (value is T2) action2((T2)value);\n else if (value is T3) action3((T3)value);\n }\n\n // ... etc.\n}\n <#@ template debug=\"false\" hostSpecific=\"true\" language=\"C#\" #>\n<#@ output extension=\".cs\" #>\n<#@ Assembly Name=\"System.Core.dll\" #>\n<#@ import namespace=\"System.Linq\" #> \n<#@ import namespace=\"System.IO\" #> \n<#\n string GenWarning = \"// THIS FILE IS GENERATED FROM \" + Path.GetFileName(Host.TemplateFile) + \" - ANY HAND EDITS WILL BE LOST!\";\n const int MaxCases = 15;\n#>\n<#=GenWarning#>\n\nusing System;\n\npublic static class TypeSwitch\n{\n<# for(int icase = 1; icase <= MaxCases; ++icase) {\n var types = string.Join(\", \", Enumerable.Range(1, icase).Select(i => \"T\" + i));\n var actions = string.Join(\", \", Enumerable.Range(1, icase).Select(i => string.Format(\"Action<T{0}> action{0}\", i)));\n var wheres = string.Join(\" \", Enumerable.Range(1, icase).Select(i => string.Format(\"where T{0} : TV\", i)));\n#>\n <#=GenWarning#>\n\n public static void On<TV, <#=types#>>(TV value, <#=actions#>)\n <#=wheres#>\n {\n if (value is T1) action1((T1)value);\n<# for(int i = 2; i <= icase; ++i) { #>\n else if (value is T<#=i#>) action<#=i#>((T<#=i#>)value);\n<#}#>\n }\n\n<#}#>\n <#=GenWarning#>\n}\n TypeSwitch.On(operand,\n (C x) => name = x.FullName,\n (B x) => name = x.LongName,\n (A x) => name = x.Name,\n (X x) => name = x.ToString(CultureInfo.CurrentCulture),\n (Y x) => name = x.GetIdentifier(),\n (object x) => name = x.ToString());\n" }, { "answer_id": 20009354, "author": "Edward Ned Harvey", "author_id": 1726692, "author_profile": "https://Stackoverflow.com/users/1726692", "pm_score": 3, "selected": false, "text": "switch (Type.GetTypeCode(someObject.GetType()))\n{\n case TypeCode.Boolean:\n break;\n case TypeCode.Byte:\n break;\n case TypeCode.Char:\n break;\n}\n public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };\npublic abstract class Foo\n{\n public abstract FooTypes FooType { get; }\n}\npublic class FooFighter : Foo\n{\n public override FooTypes FooType { get { return FooTypes.FooFighter; } }\n}\n public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };\npublic abstract class Foo\n{\n public abstract FooTypes GetFooType();\n}\npublic class FooFighter : Foo\n{\n public override FooTypes GetFooType() { return FooTypes.FooFighter; }\n}\n public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };\npublic interface IFooType\n{\n FooTypes FooType { get; }\n}\npublic class FooFighter : IFooType\n{\n public FooTypes FooType { get { return FooTypes.FooFighter; } }\n}\n public enum FooTypes { FooFighter, AbbreviatedFool, Fubar, Fugu };\npublic interface IFooType\n{\n FooTypes GetFooType();\n}\npublic class FooFighter : IFooType\n{\n public FooTypes GetFooType() { return FooTypes.FooFighter; }\n}\n public static class TypeEnumerator\n{\n public class TypeEnumeratorException : Exception\n {\n public Type unknownType { get; private set; }\n public TypeEnumeratorException(Type unknownType) : base()\n {\n this.unknownType = unknownType;\n }\n }\n public enum TypeEnumeratorTypes { _int, _string, _Foo, _TcpClient, };\n private static Dictionary<Type, TypeEnumeratorTypes> typeDict;\n static TypeEnumerator()\n {\n typeDict = new Dictionary<Type, TypeEnumeratorTypes>();\n typeDict[typeof(int)] = TypeEnumeratorTypes._int;\n typeDict[typeof(string)] = TypeEnumeratorTypes._string;\n typeDict[typeof(Foo)] = TypeEnumeratorTypes._Foo;\n typeDict[typeof(System.Net.Sockets.TcpClient)] = TypeEnumeratorTypes._TcpClient;\n }\n /// <summary>\n /// Throws NullReferenceException and TypeEnumeratorException</summary>\n /// <exception cref=\"System.NullReferenceException\">NullReferenceException</exception>\n /// <exception cref=\"MyProject.TypeEnumerator.TypeEnumeratorException\">TypeEnumeratorException</exception>\n public static TypeEnumeratorTypes EnumerateType(object theObject)\n {\n try\n {\n return typeDict[theObject.GetType()];\n }\n catch (KeyNotFoundException)\n {\n throw new TypeEnumeratorException(theObject.GetType());\n }\n }\n}\n switch (TypeEnumerator.EnumerateType(someObject))\n{\n case TypeEnumerator.TypeEnumeratorTypes._int:\n break;\n case TypeEnumerator.TypeEnumeratorTypes._string:\n break;\n}\n" }, { "answer_id": 39099323, "author": "jruizaranguren", "author_id": 2660176, "author_profile": "https://Stackoverflow.com/users/2660176", "pm_score": 0, "selected": false, "text": " var result = \n TSwitch<string>\n .On(val)\n .Case((string x) => \"is a string\")\n .Case((long x) => \"is a long\")\n .Default(_ => \"what is it?\");\n public class TSwitch<TResult>\n{\n class CaseInfo<T>\n {\n public Type Target { get; set; }\n public Func<object, T> Func { get; set; }\n }\n\n private object _source;\n private List<CaseInfo<TResult>> _cases;\n\n public static TSwitch<TResult> On(object source)\n {\n return new TSwitch<TResult> { \n _source = source,\n _cases = new List<CaseInfo<TResult>>()\n };\n }\n\n public TResult Default(Func<object, TResult> defaultFunc)\n {\n var srcType = _source.GetType();\n foreach (var entry in _cases)\n if (entry.Target.IsAssignableFrom(srcType))\n return entry.Func(_source);\n\n return defaultFunc(_source);\n }\n\n public TSwitch<TResult> Case<TSource>(Func<TSource, TResult> func)\n {\n _cases.Add(new CaseInfo<TResult>\n {\n Func = x => func((TSource)x),\n Target = typeof(TSource)\n });\n return this;\n }\n}\n" }, { "answer_id": 43233256, "author": "Serge Intern", "author_id": 5996289, "author_profile": "https://Stackoverflow.com/users/5996289", "pm_score": 3, "selected": false, "text": "switch (o)\n{\n case A a:\n a.Hop();\n break;\n case B b:\n b.Skip();\n break;\n case C _: \n return new ArgumentException(\"Type C will be supported in the next version\");\n default:\n return new ArgumentException(\"Unexpected type: \" + o.GetType());\n}\n" }, { "answer_id": 45455991, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 2, "selected": false, "text": "Discriminated Unions switch if exceptions as control flow void Foo(OneOf<A, B> o)\n{\n o.Switch(\n a => a.Hop(),\n b => b.Skip()\n );\n}\n .Match double Area(OneOf<Square, Circle> o)\n{\n return o.Match(\n square => square.Length * square.Length,\n circle => Math.PI * circle.Radius * circle.Radius\n );\n}\n" }, { "answer_id": 52298059, "author": "Davide Cannizzo", "author_id": 8154765, "author_profile": "https://Stackoverflow.com/users/8154765", "pm_score": 2, "selected": false, "text": "case switch object a = \"Hello world\";\nswitch (a)\n{\n case string myString:\n // The variable 'a' is a string!\n break;\n case int myInt:\n // The variable 'a' is an int!\n break;\n case Foo myFoo:\n // The variable 'a' is of type Foo!\n break;\n}\n boolean Dictionary<K, V> if object a = \"Hello world\";\nif (a is string)\n{\n // The variable 'a' is a string!\n} else if (a is int)\n{\n // The variable 'a' is an int!\n} // etc.\n" }, { "answer_id": 53045145, "author": "James Harcourt", "author_id": 1461680, "author_profile": "https://Stackoverflow.com/users/1461680", "pm_score": 0, "selected": false, "text": "IObject concrete1 = new ObjectImplementation1();\nIObject concrete2 = new ObjectImplementation2();\n\nswitch (concrete1)\n{\n case ObjectImplementation1 c1: return \"type 1\"; \n case ObjectImplementation2 c2: return \"type 2\"; \n}\n" }, { "answer_id": 53213010, "author": "Natalie Perret", "author_id": 4636721, "author_profile": "https://Stackoverflow.com/users/4636721", "pm_score": 2, "selected": false, "text": "IDoable void Do() public interface IDoable\n{\n void Do();\n}\n\npublic class A : IDoable\n{\n public void Hop() \n {\n // ...\n }\n\n public void Do()\n {\n Hop();\n }\n}\n\npublic class B : IDoable\n{\n public void Skip() \n {\n // ...\n }\n\n public void Do()\n {\n Skip();\n }\n}\n void Foo<T>(T obj)\n where T : IDoable\n{\n // ...\n obj.Do();\n // ...\n}\n" }, { "answer_id": 53529442, "author": "mdimai666", "author_id": 6723966, "author_profile": "https://Stackoverflow.com/users/6723966", "pm_score": 0, "selected": false, "text": " public T Store<T>()\n {\n Type t = typeof(T);\n\n if (t == typeof(CategoryDataStore))\n return (T)DependencyService.Get<IDataStore<ItemCategory>>();\n else\n return default(T);\n }\n" }, { "answer_id": 54373142, "author": "alhpe", "author_id": 2998185, "author_profile": "https://Stackoverflow.com/users/2998185", "pm_score": 4, "selected": false, "text": "switch (foo.GetType())\n{\n case var type when type == typeof(Player):\n break;\n case var type when type == typeof(Address):\n break;\n case var type when type == typeof(Department):\n break;\n case var type when type == typeof(ContactType):\n break;\n default:\n break;\n}\n" }, { "answer_id": 55516576, "author": "jean-maurice Destraz", "author_id": 9720519, "author_profile": "https://Stackoverflow.com/users/9720519", "pm_score": 3, "selected": false, "text": "case type _:\n int i = 1;\nbool b = true;\ndouble d = 1.1;\nobject o = i; // whatever you want\n\nswitch (o)\n{\n case int _:\n Answer.Content = \"You got the int\";\n break;\n case double _:\n Answer.Content = \"You got the double\";\n break;\n case bool _:\n Answer.Content = \"You got the bool\";\n break;\n}\n" }, { "answer_id": 55573781, "author": "Chan", "author_id": 11329086, "author_profile": "https://Stackoverflow.com/users/11329086", "pm_score": 2, "selected": false, "text": "private string GetAcceptButtonText<T>() where T : BaseClass, new()\n{\n switch (new T())\n {\n case BaseClassReview _: return \"Review\";\n case BaseClassValidate _: return \"Validate\";\n case BaseClassAcknowledge _: return \"Acknowledge\";\n default: return \"Accept\";\n }\n}\n" }, { "answer_id": 59730274, "author": "PilgrimViis", "author_id": 2075057, "author_profile": "https://Stackoverflow.com/users/2075057", "pm_score": 4, "selected": false, "text": " public Animal Animal { get; set; }\n ...\n var animalName = Animal switch\n {\n Cat cat => \"Tom\",\n Mouse mouse => \"Jerry\",\n _ => \"unknown\"\n };\n" }, { "answer_id": 60386560, "author": "Desmond", "author_id": 8330412, "author_profile": "https://Stackoverflow.com/users/8330412", "pm_score": 2, "selected": false, "text": " return document switch {\n Invoice _ => \"Is Invoice\",\n ShippingList _ => \"Is Shipping List\",\n _ => \"Unknown\"\n };\n" }, { "answer_id": 62894085, "author": "pablocom", "author_id": 9461439, "author_profile": "https://Stackoverflow.com/users/9461439", "pm_score": 1, "selected": false, "text": "public void Test(BaseType @base)\n{\n switch (@base)\n {\n case ConcreteType concrete:\n DoSomething(concrete);\n break;\n\n case AnotherConcrete concrete:\n DoSomething(concrete);\n break;\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
298,981
<p>I'm trying to have an XSLT that copies most of the tags but removes empty "<code>&lt;b/&gt;</code>" tags. That is, it should copy as-is "<code>&lt;b&gt; &lt;/b&gt;</code>" or "<code>&lt;b&gt;toto&lt;/b&gt;</code>" but completely remove "<code>&lt;b/&gt;</code>".</p> <p>I think the template would look like :</p> <pre><code>&lt;xsl:template match="b"&gt; &lt;xsl:if test=".hasChildren()"&gt; &lt;xsl:element name="b"&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:element&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; </code></pre> <p>But of course, the "<code>hasChildren()</code>" part doesn't exist ... Any idea ?</p>
[ { "answer_id": 298997, "author": "Darren Steinweg", "author_id": 418, "author_profile": "https://Stackoverflow.com/users/418", "pm_score": 3, "selected": true, "text": "<xsl:template match=\"b\">\n <xsl:if test=\"b/text()\">\n ...\n" }, { "answer_id": 299031, "author": "Guillaume", "author_id": 23704, "author_profile": "https://Stackoverflow.com/users/23704", "pm_score": 2, "selected": false, "text": "<xsl:template match=\"b\">\n <xsl:if test=\"./* or ./text()\">\n <xsl:element name=\"b\">\n <xsl:apply-templates/>\n </xsl:element>\n </xsl:if>\n</xsl:template>\n" }, { "answer_id": 299040, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<xsl:template match=\"b\">\n <xsl:if test=\".!=''\">\n <xsl:element name=\"b\">\n <xsl:apply-templates/>\n </xsl:element>\n </xsl:if>\n</xsl:template>\n" }, { "answer_id": 299066, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 0, "selected": false, "text": "<html xml:space=\"preserve\">\n...\n</html>\n <xsl:template match=\"b\">\n <xsl:if test=\"text() != ''\">\n ....\n </xsl:if>\n</xsl:template>\n" }, { "answer_id": 299279, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 1, "selected": false, "text": "<xsl:template match=\"b[not(text())]\" />\n\n<xsl:template match=\"b\">\n <b>\n <xsl:apply-templates/>\n </b>\n</xsl:template>\n" }, { "answer_id": 299459, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 1, "selected": false, "text": "<xsl:template match=\"b[not(node())] />\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/298981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23704/" ]
299,002
<p>Is there anybody who has successfully accessed a Web service from an Oracle stored procedure? If so, was it a Java stored procedure? A PL/SQL stored procedure?</p> <p>Is there any reason why I should not be trying to access a WS from a stored proc?</p> <p>Here are a couple refs that I found so far</p> <ul> <li><a href="http://download.oracle.com/docs/cd/B19306_01/java.102/b14187/chtwelve.htm#CBBEFCHI" rel="noreferrer">Database Web Services</a></li> <li><a href="http://www.oracle.com/technology/sample_code/tech/java/jsp/samples/wsclient/Readme.html" rel="noreferrer">Calling external Web Service from a Java Stored Procedure</a></li> </ul> <p><em>..Just to clarify, this is for SOAP calls</em></p>
[ { "answer_id": 430042, "author": "kurosch", "author_id": 30153, "author_profile": "https://Stackoverflow.com/users/30153", "pm_score": 3, "selected": false, "text": "FUNCTION post\n(\n p_url IN VARCHAR2,\n p_data IN CLOB,\n p_timeout IN BINARY_INTEGER DEFAULT 60\n) \n RETURN CLOB\nIS\n --\n v_request utl_http.req;\n v_response utl_http.resp;\n v_buffer CLOB;\n v_chunk VARCHAR2(4000);\n v_length NUMBER;\n v_index NUMBER;\nBEGIN\n\n v_index := 1;\n v_length := nvl(length(p_data), 0);\n\n -- configure HTTP\n utl_http.set_response_error_check(enable => FALSE);\n utl_http.set_detailed_excp_support(enable => FALSE);\n utl_http.set_transfer_timeout(p_timeout);\n\n -- send request\n v_request := utl_http.begin_request(p_url, 'POST','HTTP/1.0');\n utl_http.set_header(v_request, 'Content-Type', 'text/xml');\n utl_http.set_header(v_request, 'Content-Length', v_length);\n WHILE v_index <= v_length LOOP\n utl_http.write_text(v_request, substr(p_data, v_index, 4000));\n v_index := v_index + 4000;\n END LOOP;\n\n -- check HTTP status code for error\n IF v_response.status_code <> utl_http.http_ok THEN \n raise_application_error(\n cn_http_error,\n v_response.status_code || ' - ' || v_response.reason_phrase\n );\n END IF;\n\n -- get response\n dbms_lob.createtemporary(v_buffer, FALSE);\n v_response := utl_http.get_response(v_request);\n BEGIN\n LOOP\n utl_http.read_text(v_response, v_chunk, 4000);\n dbms_lob.writeappend(v_buffer, length(v_chunk), v_chunk);\n END LOOP;\n EXCEPTION\n WHEN utl_http.end_of_body THEN NULL;\n END;\n utl_http.end_response(v_response);\n\n RETURN v_buffer;\n\nEND;\n FUNCTION invoke\n(\n p_url IN VARCHAR2,\n p_method IN XMLTYPE,\n p_timeout IN NUMBER := 60\n)\n RETURN XMLTYPE\nIS\n -- calls the given SOAP service\n cn_procedure_name CONSTANT VARCHAR2(30) := 'invoke';\n --\n v_envelope XMLTYPE;\n v_response CLOB;\n v_fault XMLTYPE;\n v_sqlerrm VARCHAR2(2000);\nBEGIN\n\n -- wrap method in SOAP envelope\n SELECT\n XMLElement(\n \"soap:Envelope\",\n XMLAttributes(\n 'http://schemas.xmlsoap.org/soap/envelope/' AS \"xmlns:soap\"\n ),\n XMLElement(\n \"soap:Body\",\n p_method\n )\n )\n INTO\n v_envelope\n FROM\n dual;\n\n -- POST request\n v_response := post(\n p_url,\n '<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>' || chr(10) || v_envelope.getClobVal(),\n p_timeout\n );\n IF v_response IS NULL THEN\n RAISE null_response;\n END IF;\n\n -- parse response\n BEGIN\n v_envelope := XMLType(v_response);\n EXCEPTION\n WHEN OTHERS THEN\n v_sqlerrm := SQLERRM;\n RAISE xml_parse_error;\n END;\n\n -- check for a fault\n v_fault := v_envelope.extract( \n '/soap:Envelope/soap:Body/soap:Fault', \n 'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"'\n );\n IF v_fault IS NOT NULL THEN\n v_sqlerrm := v_fault.extract('.//faultstring/text()').getStringVal();\n RAISE soap_fault;\n END IF;\n\n -- the actual response is the child of the <soap:Body /> element\n RETURN v_envelope.extract(\n '/soap:Envelope/soap:Body/*[position() = 1]', \n 'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"'\n );\n\nEND;\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25502/" ]
299,011
<p>I am getting a lot of errors when starting RAD7. The server doesn't respond to class changes. Sometimes the server won't start. Sometimes RAD will not acknowledge modules that I added to the server. It is kind of buggy.</p> <p>I know there is metadata in the workspace, are there safe ways to clean the metadata or RAD in general?</p> <p>Where RAD = Rational Application Developer</p>
[ { "answer_id": 324672, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": ".metadata" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
299,027
<p>I'm not sure what this practice is actually called, so perhaps someone can edit the title to more accurately reflect my question.</p> <p>Let's say we have a site that stores objects of different types. Each type of object has its own database (a database of books and assorted information with its tables, a database of CDs and information with its tables, and so on). However, all of the objects have keywords and the keywords should be uniform across all objects, regardless of type. A new database with a few tables is made to store keywords, however each object database is responsible for mapping the object ID to a keyword.</p> <p>Is that a good practice?</p>
[ { "answer_id": 299069, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 4, "selected": true, "text": "GENERIC_OBJECT BOOK_OBJECT BOOK_OBJECT.ID = GENERIC_OBJECT.ID CD_OBJECT CD_OBJECT.ID = GENERIC_OBJECT.ID GENERIC_OBJECT" }, { "answer_id": 299085, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM books b\nINNER JOIN KeywordDB.dbo.Keywords k\nON b.keywordID = k.keywordID\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
299,068
<p>Question: Is exception handling in Java actually slow?</p> <p>Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn't be used for normal program flow in Java. Two reasons are usually given,</p> <ol> <li>it is really slow - even an order of magnitude slower than regular code (the reasons given vary), </li> </ol> <p>and </p> <ol start="2"> <li>it is messy because people expect only errors to be handled in exceptional code. </li> </ol> <p>This question is about #1.</p> <p>As an example, <a href="http://leepoint.net/notes-java/flow/exceptions/03exceptions.html" rel="noreferrer">this page</a> describes Java exception handling as "very slow" and relates the slowness to the creation of the exception message string - "this string is then used in creating the exception object that is thrown. This is not fast." The article <a href="http://adtmag.com/articles/2000/08/22/effective-exception-handling-in-java.aspx" rel="noreferrer">Effective Exception Handling in Java</a> says that "the reason for this is due to the object creation aspect of exception handling, which thereby makes throwing exceptions inherently slow". Another reason out there is that the stack trace generation is what slows it down.</p> <p>My testing (using Java 1.6.0_07, Java HotSpot 10.0, on 32 bit Linux), indicates that exception handling is no slower than regular code. I tried running a method in a loop that executes some code. At the end of the method, I use a boolean to indicate whether to <em>return</em> or <em>throw</em>. This way the actual processing is the same. I tried running the methods in different orders and averaging my test times, thinking it may have been the JVM warming up. In all my tests, the throw was at least as fast as the return, if not faster (up to 3.1% faster). I am completely open to the possibility that my tests were wrong, but I haven't seen anything out there in the way of the code sample, test comparisons, or results in the last year or two that show exception handling in Java to actually be slow.</p> <p>What leads me down this path was an API I needed to use that threw exceptions as part of normal control logic. I wanted to correct them in their usage, but now I may not be able to. Will I instead have to praise them on their forward thinking?</p> <p>In the paper <a href="http://portal.acm.org/citation.cfm?id=337453" rel="noreferrer">Efficient Java exception handling in just-in-time compilation</a>, the authors suggest that the presence of exception handlers alone, even if no exceptions are thrown, is enough to prevent the JIT compiler from optimizing the code properly, thus slowing it down. I haven't tested this theory yet.</p>
[ { "answer_id": 299214, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "fillInStackTrace" }, { "answer_id": 299315, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 10, "selected": true, "text": "public class Test {\n int value;\n\n\n public int getValue() {\n return value;\n }\n\n public void reset() {\n value = 0;\n }\n\n // Calculates without exception\n public void method1(int i) {\n value = ((value + i) / i) << 1;\n // Will never be true\n if ((i & 0xFFFFFFF) == 1000000000) {\n System.out.println(\"You'll never see this!\");\n }\n }\n\n // Could in theory throw one, but never will\n public void method2(int i) throws Exception {\n value = ((value + i) / i) << 1;\n // Will never be true\n if ((i & 0xFFFFFFF) == 1000000000) {\n throw new Exception();\n }\n }\n\n // This one will regularly throw one\n public void method3(int i) throws Exception {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw new Exception();\n }\n }\n\n public static void main(String[] args) {\n int i;\n long l;\n Test t = new Test();\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < 100000000; i++) {\n t.method1(i);\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method1 took \" + l + \" ms, result was \" + t.getValue()\n );\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < 100000000; i++) {\n try {\n t.method2(i);\n } catch (Exception e) {\n System.out.println(\"You'll never see this!\");\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method2 took \" + l + \" ms, result was \" + t.getValue()\n );\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < 100000000; i++) {\n try {\n t.method3(i);\n } catch (Exception e) {\n // Do nothing here, as we will get here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method3 took \" + l + \" ms, result was \" + t.getValue()\n );\n }\n}\n method1 took 972 ms, result was 2\nmethod2 took 1003 ms, result was 2\nmethod3 took 66716 ms, result was 2\n" }, { "answer_id": 3980148, "author": "BorisOkunskiy", "author_id": 240049, "author_profile": "https://Stackoverflow.com/users/240049", "pm_score": 3, "selected": false, "text": "Thread.currentThread().getStackTrace() dumpThreads Throwable fillInStackTrace catch ControlThrowable Throwable fillInStackTrace override def fillInStackTrace(): Throwable = this\n class ControlException extends ControlThrowable\n\nclass T {\n var value = 0\n\n def reset = {\n value = 0\n }\n\n def method1(i: Int) = {\n value = ((value + i) / i) << 1\n if ((i & 0xfffffff) == 1000000000) {\n println(\"You'll never see this!\")\n }\n }\n\n def method2(i: Int) = {\n value = ((value + i) / i) << 1\n if ((i & 0xfffffff) == 1000000000) {\n throw new Exception()\n }\n }\n\n def method3(i: Int) = {\n value = ((value + i) / i) << 1\n if ((i & 0x1) == 1) {\n throw new Exception()\n }\n }\n\n def method4(i: Int) = {\n value = ((value + i) / i) << 1\n if ((i & 0x1) == 1) {\n throw new ControlException()\n }\n }\n}\n\nclass Main {\n var l = System.currentTimeMillis\n val t = new T\n for (i <- 1 to 10000000)\n t.method1(i)\n l = System.currentTimeMillis - l\n println(\"method1 took \" + l + \" ms, result was \" + t.value)\n\n t.reset\n l = System.currentTimeMillis\n for (i <- 1 to 10000000) try {\n t.method2(i)\n } catch {\n case _ => println(\"You'll never see this\")\n }\n l = System.currentTimeMillis - l\n println(\"method2 took \" + l + \" ms, result was \" + t.value)\n\n t.reset\n l = System.currentTimeMillis\n for (i <- 1 to 10000000) try {\n t.method4(i)\n } catch {\n case _ => // do nothing\n }\n l = System.currentTimeMillis - l\n println(\"method4 took \" + l + \" ms, result was \" + t.value)\n\n t.reset\n l = System.currentTimeMillis\n for (i <- 1 to 10000000) try {\n t.method3(i)\n } catch {\n case _ => // do nothing\n }\n l = System.currentTimeMillis - l\n println(\"method3 took \" + l + \" ms, result was \" + t.value)\n\n}\n method1 took 146 ms, result was 2\nmethod2 took 159 ms, result was 2\nmethod4 took 1551 ms, result was 2\nmethod3 took 42492 ms, result was 2\n method3 method4 method4 method1 method2" }, { "answer_id": 4596399, "author": "inflamer", "author_id": 562888, "author_profile": "https://Stackoverflow.com/users/562888", "pm_score": 2, "selected": false, "text": " public static int parseUnsignedInt(String s, int defaultValue) {\n final int strLength = s.length();\n if (strLength == 0)\n return defaultValue;\n int value = 0;\n for (int i=strLength-1; i>=0; i--) {\n int c = s.charAt(i);\n if (c > 47 && c < 58) {\n c -= 48;\n for (int j=strLength-i; j!=1; j--)\n c *= 10;\n value += c;\n } else {\n return defaultValue;\n }\n }\n return value < 0 ? /* übergebener wert > Integer.MAX_VALUE? */ defaultValue : value;\n }\n" }, { "answer_id": 8024032, "author": "Hot Licks", "author_id": 581994, "author_profile": "https://Stackoverflow.com/users/581994", "pm_score": 8, "selected": false, "text": "method1 took 1733 ms, result was 2\nmethod2 took 1248 ms, result was 2\nmethod3 took 83997 ms, result was 2\nmethod4 took 1692 ms, result was 2\nmethod5 took 60946 ms, result was 2\nmethod6 took 25746 ms, result was 2\n new Integer(1) throw new Exception() new Exception()" }, { "answer_id": 8054932, "author": "inder", "author_id": 1031635, "author_profile": "https://Stackoverflow.com/users/1031635", "pm_score": 0, "selected": false, "text": "// Calculates without exception\npublic boolean method1(int i) {\n value = ((value + i) / i) << 1;\n // Will never be true\n return ((i & 0xFFFFFFF) == 1000000000);\n\n}\n....\n for (i = 1; i < 100000000; i++) {\n if (t.method1(i)) {\n System.out.println(\"Will never be true!\");\n }\n }\n method1 took 841 ms, result was 2\nmethod2 took 841 ms, result was 2\nmethod3 took 85058 ms, result was 2\n method1 took 821 ms, result was 2\nmethod2 took 838 ms, result was 2\nmethod3 took 85929 ms, result was 2\n" }, { "answer_id": 9754873, "author": "David Jeske", "author_id": 519568, "author_profile": "https://Stackoverflow.com/users/519568", "pm_score": 2, "selected": false, "text": "int value;\n\n\npublic int getValue() {\n return value;\n}\n\npublic void reset() {\n value = 0;\n}\n\npublic boolean baseline_null(boolean shouldfail, int recurse_depth) {\n if (recurse_depth <= 0) {\n return shouldfail;\n } else {\n return baseline_null(shouldfail,recurse_depth-1);\n }\n}\n\npublic boolean retval_error(boolean shouldfail, int recurse_depth) {\n if (recurse_depth <= 0) {\n if (shouldfail) {\n return false;\n } else {\n return true;\n }\n } else {\n boolean nested_error = retval_error(shouldfail,recurse_depth-1);\n if (nested_error) {\n return true;\n } else {\n return false;\n }\n }\n}\n\npublic void exception_error(boolean shouldfail, int recurse_depth) throws Exception {\n if (recurse_depth <= 0) {\n if (shouldfail) {\n throw new Exception();\n }\n } else {\n exception_error(shouldfail,recurse_depth-1);\n }\n\n}\n\npublic static void main(String[] args) {\n int i;\n long l;\n TestIt t = new TestIt();\n int failures;\n\n int ITERATION_COUNT = 100000000;\n\n\n // (0) baseline null workload\n for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {\n for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) { \n int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq); \n\n failures = 0;\n long start_time = System.currentTimeMillis();\n t.reset(); \n for (i = 1; i < ITERATION_COUNT; i++) {\n boolean shoulderror = (i % EXCEPTION_MOD) == 0;\n t.baseline_null(shoulderror,recurse_depth);\n }\n long elapsed_time = System.currentTimeMillis() - start_time;\n System.out.format(\"baseline: recurse_depth %s, exception_freqeuncy %s (%s), time elapsed %s ms\\n\",\n recurse_depth, exception_freq, failures,elapsed_time);\n }\n }\n\n\n // (1) retval_error\n for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {\n for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) { \n int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq); \n\n failures = 0;\n long start_time = System.currentTimeMillis();\n t.reset(); \n for (i = 1; i < ITERATION_COUNT; i++) {\n boolean shoulderror = (i % EXCEPTION_MOD) == 0;\n if (!t.retval_error(shoulderror,recurse_depth)) {\n failures++;\n }\n }\n long elapsed_time = System.currentTimeMillis() - start_time;\n System.out.format(\"retval_error: recurse_depth %s, exception_freqeuncy %s (%s), time elapsed %s ms\\n\",\n recurse_depth, exception_freq, failures,elapsed_time);\n }\n }\n\n // (2) exception_error\n for (int recurse_depth = 2; recurse_depth <= 10; recurse_depth+=3) {\n for (float exception_freq = 0.0f; exception_freq <= 1.0f; exception_freq += 0.25f) { \n int EXCEPTION_MOD = (exception_freq == 0.0f) ? ITERATION_COUNT+1 : (int)(1.0f / exception_freq); \n\n failures = 0;\n long start_time = System.currentTimeMillis();\n t.reset(); \n for (i = 1; i < ITERATION_COUNT; i++) {\n boolean shoulderror = (i % EXCEPTION_MOD) == 0;\n try {\n t.exception_error(shoulderror,recurse_depth);\n } catch (Exception e) {\n failures++;\n }\n }\n long elapsed_time = System.currentTimeMillis() - start_time;\n System.out.format(\"exception_error: recurse_depth %s, exception_freqeuncy %s (%s), time elapsed %s ms\\n\",\n recurse_depth, exception_freq, failures,elapsed_time); \n }\n }\n}\n baseline: recurse_depth 2, exception_freqeuncy 0.0 (0), time elapsed 683 ms\nbaseline: recurse_depth 2, exception_freqeuncy 0.25 (0), time elapsed 790 ms\nbaseline: recurse_depth 2, exception_freqeuncy 0.5 (0), time elapsed 768 ms\nbaseline: recurse_depth 2, exception_freqeuncy 0.75 (0), time elapsed 749 ms\nbaseline: recurse_depth 2, exception_freqeuncy 1.0 (0), time elapsed 731 ms\nbaseline: recurse_depth 5, exception_freqeuncy 0.0 (0), time elapsed 923 ms\nbaseline: recurse_depth 5, exception_freqeuncy 0.25 (0), time elapsed 971 ms\nbaseline: recurse_depth 5, exception_freqeuncy 0.5 (0), time elapsed 982 ms\nbaseline: recurse_depth 5, exception_freqeuncy 0.75 (0), time elapsed 947 ms\nbaseline: recurse_depth 5, exception_freqeuncy 1.0 (0), time elapsed 937 ms\nbaseline: recurse_depth 8, exception_freqeuncy 0.0 (0), time elapsed 1154 ms\nbaseline: recurse_depth 8, exception_freqeuncy 0.25 (0), time elapsed 1149 ms\nbaseline: recurse_depth 8, exception_freqeuncy 0.5 (0), time elapsed 1133 ms\nbaseline: recurse_depth 8, exception_freqeuncy 0.75 (0), time elapsed 1117 ms\nbaseline: recurse_depth 8, exception_freqeuncy 1.0 (0), time elapsed 1116 ms\nretval_error: recurse_depth 2, exception_freqeuncy 0.0 (0), time elapsed 742 ms\nretval_error: recurse_depth 2, exception_freqeuncy 0.25 (24999999), time elapsed 743 ms\nretval_error: recurse_depth 2, exception_freqeuncy 0.5 (49999999), time elapsed 734 ms\nretval_error: recurse_depth 2, exception_freqeuncy 0.75 (99999999), time elapsed 723 ms\nretval_error: recurse_depth 2, exception_freqeuncy 1.0 (99999999), time elapsed 728 ms\nretval_error: recurse_depth 5, exception_freqeuncy 0.0 (0), time elapsed 920 ms\nretval_error: recurse_depth 5, exception_freqeuncy 0.25 (24999999), time elapsed 1121 ms\nretval_error: recurse_depth 5, exception_freqeuncy 0.5 (49999999), time elapsed 1037 ms\nretval_error: recurse_depth 5, exception_freqeuncy 0.75 (99999999), time elapsed 1141 ms\nretval_error: recurse_depth 5, exception_freqeuncy 1.0 (99999999), time elapsed 1130 ms\nretval_error: recurse_depth 8, exception_freqeuncy 0.0 (0), time elapsed 1218 ms\nretval_error: recurse_depth 8, exception_freqeuncy 0.25 (24999999), time elapsed 1334 ms\nretval_error: recurse_depth 8, exception_freqeuncy 0.5 (49999999), time elapsed 1478 ms\nretval_error: recurse_depth 8, exception_freqeuncy 0.75 (99999999), time elapsed 1637 ms\nretval_error: recurse_depth 8, exception_freqeuncy 1.0 (99999999), time elapsed 1655 ms\nexception_error: recurse_depth 2, exception_freqeuncy 0.0 (0), time elapsed 726 ms\nexception_error: recurse_depth 2, exception_freqeuncy 0.25 (24999999), time elapsed 17487 ms\nexception_error: recurse_depth 2, exception_freqeuncy 0.5 (49999999), time elapsed 33763 ms\nexception_error: recurse_depth 2, exception_freqeuncy 0.75 (99999999), time elapsed 67367 ms\nexception_error: recurse_depth 2, exception_freqeuncy 1.0 (99999999), time elapsed 66990 ms\nexception_error: recurse_depth 5, exception_freqeuncy 0.0 (0), time elapsed 924 ms\nexception_error: recurse_depth 5, exception_freqeuncy 0.25 (24999999), time elapsed 23775 ms\nexception_error: recurse_depth 5, exception_freqeuncy 0.5 (49999999), time elapsed 46326 ms\nexception_error: recurse_depth 5, exception_freqeuncy 0.75 (99999999), time elapsed 91707 ms\nexception_error: recurse_depth 5, exception_freqeuncy 1.0 (99999999), time elapsed 91580 ms\nexception_error: recurse_depth 8, exception_freqeuncy 0.0 (0), time elapsed 1144 ms\nexception_error: recurse_depth 8, exception_freqeuncy 0.25 (24999999), time elapsed 30440 ms\nexception_error: recurse_depth 8, exception_freqeuncy 0.5 (49999999), time elapsed 59116 ms\nexception_error: recurse_depth 8, exception_freqeuncy 0.75 (99999999), time elapsed 116678 ms\nexception_error: recurse_depth 8, exception_freqeuncy 1.0 (99999999), time elapsed 116477 ms\n" }, { "answer_id": 25324557, "author": "manikanta", "author_id": 340290, "author_profile": "https://Stackoverflow.com/users/340290", "pm_score": 5, "selected": false, "text": "Throwable(String message, Throwable cause, boolean enableSuppression,boolean writableStackTrace) // This one will regularly throw one\npublic void method4(int i) throws NoStackTraceThrowable {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw new NoStackTraceThrowable();\n }\n}\n\n// This one will regularly throw one\npublic void method5(int i) throws NoStackTraceRuntimeException {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw new NoStackTraceRuntimeException();\n }\n}\n\npublic static void main(String[] args) {\n int i;\n long l;\n Test t = new Test();\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < 100000000; i++) {\n try {\n t.method4(i);\n } catch (NoStackTraceThrowable e) {\n // Do nothing here, as we will get here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println( \"method4 took \" + l + \" ms, result was \" + t.getValue() );\n\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < 100000000; i++) {\n try {\n t.method5(i);\n } catch (RuntimeException e) {\n // Do nothing here, as we will get here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println( \"method5 took \" + l + \" ms, result was \" + t.getValue() );\n}\n method1 took 883 ms, result was 2\nmethod2 took 882 ms, result was 2\nmethod3 took 32270 ms, result was 2 // throws Exception\nmethod4 took 8114 ms, result was 2 // throws NoStackTraceThrowable\nmethod5 took 8086 ms, result was 2 // throws NoStackTraceRuntimeException\n public class NoStackTraceThrowable extends Throwable { \n public NoStackTraceThrowable() { \n super(\"my special throwable\", null, false, false);\n }\n}\n" }, { "answer_id": 28075127, "author": "Doval", "author_id": 1272233, "author_profile": "https://Stackoverflow.com/users/1272233", "pm_score": 6, "selected": false, "text": "if" }, { "answer_id": 32542012, "author": "Jacek Cz", "author_id": 794606, "author_profile": "https://Stackoverflow.com/users/794606", "pm_score": -1, "selected": false, "text": "class Example {\npublic static Example Parse(String input) throws AnyRuntimeParsigException\n...\n}\n public static Example Parse(String input, Example defaultValue)\n Xxxxx.regex(\".....pattern\", src);\nif(ImTotallySure)\n{\n Example v = Example.Parse(src);\n}\n try { parse } catch(ParsingException ) // concrete exception from javadoc\n{\n}\n" }, { "answer_id": 49415201, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 2, "selected": false, "text": "Benchmark Mode Samples Mean Mean error Units\n\ndynamicException avgt 25 1901.196 14.572 ns/op\ndynamicException_NoStack avgt 25 67.029 0.212 ns/op\ndynamicException_NoStack_UsedData avgt 25 68.952 0.441 ns/op\ndynamicException_NoStack_UsedStack avgt 25 137.329 1.039 ns/op\ndynamicException_UsedData avgt 25 1900.770 9.359 ns/op\ndynamicException_UsedStack avgt 25 20033.658 118.600 ns/op\n\nplain avgt 25 1.259 0.002 ns/op\nstaticException avgt 25 1.510 0.001 ns/op\nstaticException_NoStack avgt 25 1.514 0.003 ns/op\nstaticException_NoStack_UsedData avgt 25 4.185 0.015 ns/op\nstaticException_NoStack_UsedStack avgt 25 19.110 0.051 ns/op\nstaticException_UsedData avgt 25 4.159 0.007 ns/op\nstaticException_UsedStack avgt 25 25.144 0.186 ns/op\n Benchmark Mode Samples Mean Mean error Units\n\nexception_0000 avgt 25 1959.068 30.783 ns/op\nexception_0001 avgt 25 1945.958 12.104 ns/op\nexception_0002 avgt 25 2063.575 47.708 ns/op\nexception_0004 avgt 25 2211.882 29.417 ns/op\nexception_0008 avgt 25 2472.729 57.336 ns/op\nexception_0016 avgt 25 2950.847 29.863 ns/op\nexception_0032 avgt 25 4416.548 50.340 ns/op\nexception_0064 avgt 25 6845.140 40.114 ns/op\nexception_0128 avgt 25 11774.758 54.299 ns/op\nexception_0256 avgt 25 21617.526 101.379 ns/op\nexception_0512 avgt 25 42780.434 144.594 ns/op\nexception_1024 avgt 25 82839.358 291.434 ns/op\n return" }, { "answer_id": 66320622, "author": "john16384", "author_id": 1262865, "author_profile": "https://Stackoverflow.com/users/1262865", "pm_score": 1, "selected": false, "text": "Loop 1 10000 cycles\nmethod1 took 1 ms, result was 2\nmethod2 took 0 ms, result was 2\nmethod3 took 22 ms, result was 2\nmethod4 took 22 ms, result was 2\nmethod5 took 24 ms, result was 2\nLoop 2 10000000 cycles\nmethod1 took 39 ms, result was 2\nmethod2 took 39 ms, result was 2\nmethod3 took 1558 ms, result was 2\nmethod4 took 1640 ms, result was 2\nmethod5 took 1717 ms, result was 2\nLoop 3 10000000 cycles\nmethod1 took 49 ms, result was 2\nmethod2 took 48 ms, result was 2\nmethod3 took 126 ms, result was 2\nmethod4 took 88 ms, result was 2\nmethod5 took 87 ms, result was 2\nLoop 4 10000000 cycles\nmethod1 took 34 ms, result was 2\nmethod2 took 34 ms, result was 2\nmethod3 took 33 ms, result was 2\nmethod4 took 98 ms, result was 2\nmethod5 took 58 ms, result was 2\nLoop 5 10000000 cycles\nmethod1 took 34 ms, result was 2\nmethod2 took 33 ms, result was 2\nmethod3 took 33 ms, result was 2\nmethod4 took 48 ms, result was 2\nmethod5 took 49 ms, result was 2\n package hs.jfx.eventstream.api;\n\npublic class Snippet {\n int value;\n\n\n public int getValue() {\n return value;\n }\n\n public void reset() {\n value = 0;\n }\n\n // Calculates without exception\n public void method1(int i) {\n value = ((value + i) / i) << 1;\n // Will never be true\n if ((i & 0xFFFFFFF) == 1000000000) {\n System.out.println(\"You'll never see this!\");\n }\n }\n\n // Could in theory throw one, but never will\n public void method2(int i) throws Exception {\n value = ((value + i) / i) << 1;\n // Will never be true\n if ((i & 0xFFFFFFF) == 1000000000) {\n throw new Exception();\n }\n }\n\n private static final NoStackTraceRuntimeException E = new NoStackTraceRuntimeException();\n\n // This one will regularly throw one\n public void method3(int i) throws NoStackTraceRuntimeException {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw E;\n }\n }\n\n // This one will regularly throw one\n public void method4(int i) throws NoStackTraceThrowable {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw new NoStackTraceThrowable();\n }\n }\n\n // This one will regularly throw one\n public void method5(int i) throws NoStackTraceRuntimeException {\n value = ((value + i) / i) << 1;\n // i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both\n // an AND operation between two integers. The size of the number plays\n // no role. AND on 32 BIT always ANDs all 32 bits\n if ((i & 0x1) == 1) {\n throw new NoStackTraceRuntimeException();\n }\n }\n\n public static void main(String[] args) {\n for(int k = 0; k < 5; k++) {\n int cycles = 10000000;\n if(k == 0) {\n cycles = 10000;\n try {\n Thread.sleep(500);\n }\n catch(InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(\"Loop \" + (k + 1) + \" \" + cycles + \" cycles\");\n int i;\n long l;\n Snippet t = new Snippet();\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < cycles; i++) {\n t.method1(i);\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method1 took \" + l + \" ms, result was \" + t.getValue()\n );\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < cycles; i++) {\n try {\n t.method2(i);\n } catch (Exception e) {\n System.out.println(\"You'll never see this!\");\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method2 took \" + l + \" ms, result was \" + t.getValue()\n );\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < cycles; i++) {\n try {\n t.method3(i);\n } catch (NoStackTraceRuntimeException e) {\n // always comes here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println(\n \"method3 took \" + l + \" ms, result was \" + t.getValue()\n );\n\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < cycles; i++) {\n try {\n t.method4(i);\n } catch (NoStackTraceThrowable e) {\n // always comes here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println( \"method4 took \" + l + \" ms, result was \" + t.getValue() );\n\n\n l = System.currentTimeMillis();\n t.reset();\n for (i = 1; i < cycles; i++) {\n try {\n t.method5(i);\n } catch (RuntimeException e) {\n // always comes here\n }\n }\n l = System.currentTimeMillis() - l;\n System.out.println( \"method5 took \" + l + \" ms, result was \" + t.getValue() );\n }\n }\n\n public static class NoStackTraceRuntimeException extends RuntimeException {\n public NoStackTraceRuntimeException() {\n super(\"my special throwable\", null, false, false);\n }\n }\n\n public static class NoStackTraceThrowable extends Throwable {\n public NoStackTraceThrowable() {\n super(\"my special throwable\", null, false, false);\n }\n }\n}\n\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69572/" ]
299,080
<p>I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp_trace_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!</p>
[ { "answer_id": 13794798, "author": "brian beuning", "author_id": 1862101, "author_profile": "https://Stackoverflow.com/users/1862101", "pm_score": 2, "selected": false, "text": "public void FileToTable()\n{\n TraceServer reader = new TraceServer();\n\n ConnectionInfoBase ci = new SqlConnectionInfo(\"localhost\");\n ((SqlConnectionInfo)ci).UseIntegratedSecurity = true;\n\n reader.InitializeAsReader(ci, @\"Standard.tdf\");\n\n int eventNumber = 0;\n\n while (reader.Read())\n {\n Console.Write( \"{0}\\n\", reader.GetValue(0).ToString() );\n }\n reader.Close(); \n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36243/" ]
299,086
<p>I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?</p>
[ { "answer_id": 299093, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": false, "text": " TextBox tb = new TextBox();\n Button btn = new Button { Dock = DockStyle.Bottom };\n btn.Click += delegate { Debug.WriteLine(\"Submit: \" + tb.Text); };\n Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });\n TextBox tb = new TextBox();\n Button btn = new Button { Dock = DockStyle.Bottom };\n btn.Click += delegate { Debug.WriteLine(\"Submit: \" + tb.Text); };\n tb.KeyDown += (sender,args) => {\n if (args.KeyCode == Keys.Return)\n {\n btn.PerformClick();\n }\n };\n Application.Run(new Form { Controls = { tb, btn } });\n" }, { "answer_id": 299194, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": 5, "selected": false, "text": "Form AcceptButton AcceptButton GotFocus TextBox void TextBox1_GotFocus(object sender, EventArgs e)\n{\n this.AcceptButton = ProcessTextBox1;\n}\n\nvoid TextBox2_GotFocus(object sender, EventArgs e)\n{\n this.AcceptButton = ProcessTextBox2;\n}\n AcceptButton ProcessTextBox1 TextBox3 LostFocus TextBox AcceptButton GotFocus AcceptButton" }, { "answer_id": 10890151, "author": "RJ Lohan", "author_id": 897994, "author_profile": "https://Stackoverflow.com/users/897994", "pm_score": 4, "selected": false, "text": "private void textBox_KeyPress(object sender, KeyPressEventArgs e)\n{\n if (e.KeyChar == 13)\n {\n if (!textBox.AcceptsReturn)\n {\n button1.PerformClick();\n }\n }\n}\n" }, { "answer_id": 17852867, "author": "ruvi", "author_id": 2118614, "author_profile": "https://Stackoverflow.com/users/2118614", "pm_score": 5, "selected": false, "text": "private void textBox_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.KeyCode == Keys.Enter)\n {\n button.PerformClick();\n // these last two lines will stop the beep sound\n e.SuppressKeyPress = true;\n e.Handled = true;\n }\n}\n" }, { "answer_id": 21751474, "author": "philx_x", "author_id": 3301188, "author_profile": "https://Stackoverflow.com/users/3301188", "pm_score": 3, "selected": false, "text": "keyDown private void yourNameOfTextbox_KeyDown(object sender, KeyEventArgs e)\n{\n\n}\n if (e.KeyCode == Keys.Enter)\n{\n yourNameOfButton.PerformClick();\n}\n" }, { "answer_id": 35012192, "author": "user5841303", "author_id": 5841303, "author_profile": "https://Stackoverflow.com/users/5841303", "pm_score": 3, "selected": false, "text": "this.acceptbutton = btnName;" }, { "answer_id": 35640152, "author": "Michael", "author_id": 5983246, "author_profile": "https://Stackoverflow.com/users/5983246", "pm_score": 1, "selected": false, "text": "this.textboxName.KeyDown += (sender, args) => {\n if (args.KeyCode == Keys.Return)\n {\n buttonName.PerformClick();\n }\n};\n" }, { "answer_id": 35659372, "author": "jake mariano", "author_id": 5143462, "author_profile": "https://Stackoverflow.com/users/5143462", "pm_score": 2, "selected": false, "text": "if (e.KeyCode == Keys.Enter)\n button1.PerformClick();\n" }, { "answer_id": 49277945, "author": "zdarova", "author_id": 7642202, "author_profile": "https://Stackoverflow.com/users/7642202", "pm_score": 2, "selected": false, "text": "this.btnLogIn = new System.Windows.Forms.Button();\n//....other settings\nthis.AcceptButton = this.btnLogIn;\n" }, { "answer_id": 52649157, "author": "Matt Gregory", "author_id": 10577, "author_profile": "https://Stackoverflow.com/users/10577", "pm_score": 1, "selected": false, "text": "public class EnterTextBox : TextBox\n{\n [Browsable(true), EditorBrowsable]\n public event EventHandler EnterKeyPressed;\n\n protected override bool ProcessDialogKey(Keys keyData)\n {\n if (keyData == Keys.Enter)\n {\n EnterKeyPressed?.Invoke(this, EventArgs.Empty);\n return true;\n }\n return base.ProcessDialogKey(keyData);\n }\n}\n" }, { "answer_id": 73772711, "author": "Александр Смирнов", "author_id": 14287586, "author_profile": "https://Stackoverflow.com/users/14287586", "pm_score": -1, "selected": false, "text": "private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if (e.KeyChar == '\\r')\n {\n button1_Click(textBox1.Focus(),e);\n } \n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,094
<p>i want the result of an equation rounded to the nearest integer. e.g. </p> <pre><code>137 * (3/4) = 103 </code></pre> <p>Consider the following incorrect code. </p> <pre><code>int width1 = 4; int height1 = 3; int width2 = 137; int height2 = width2 * (height1 / width1); </code></pre> <p>What is the proper way to perform "integer" math in C#?</p> <p>Do i really have to do:</p> <pre><code>int height2 = (int)Math.Round( (float)width2 * ((float)height1 / (float)width1) ); </code></pre>
[ { "answer_id": 299102, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "int height2 = (width2 * height1) / width1;\n" }, { "answer_id": 299143, "author": "Aaron", "author_id": 30763, "author_profile": "https://Stackoverflow.com/users/30763", "pm_score": 5, "selected": true, "text": "int height2 = (int)Math.Round(width2 * (height1 / (float)width1));\n" }, { "answer_id": 300813, "author": "dongilmore", "author_id": 31962, "author_profile": "https://Stackoverflow.com/users/31962", "pm_score": 0, "selected": false, "text": "int height2 = ((width2 * height1 * 10) + 5) / (width1 * 10);\n" }, { "answer_id": 300834, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 1, "selected": false, "text": "float width1 = 4;\nfloat height1 = 3;\n\nfloat width2 = 137;\nfloat height2 = width2 * (height1 / width1);\n" }, { "answer_id": 5318543, "author": "Ruben", "author_id": 661459, "author_profile": "https://Stackoverflow.com/users/661459", "pm_score": 2, "selected": false, "text": "Math.round(myinteger * 0.75);\n" }, { "answer_id": 7154448, "author": "Tod", "author_id": 633267, "author_profile": "https://Stackoverflow.com/users/633267", "pm_score": 0, "selected": false, "text": "int height2 = Convert.ToInt32(width2 * height1 / (double)width1);\n" }, { "answer_id": 18659853, "author": "Pianoman", "author_id": 2618261, "author_profile": "https://Stackoverflow.com/users/2618261", "pm_score": 1, "selected": false, "text": "int height2 = (int)Math.Round(width2 * (height1 / (float)width1),MidpointRounding.AwayFromZero);\n Console.WriteLine((int)Math.Round(0.5));\n Console.WriteLine((int)Math.Round(1.5));\n Console.WriteLine((int)Math.Round(2.5));\n Console.WriteLine((int)Math.Round(3.5));\n Console.WriteLine((int)Math.Round(0.5, MidpointRounding.AwayFromZero));\n Console.WriteLine((int)Math.Round(1.5, MidpointRounding.AwayFromZero));\n Console.WriteLine((int)Math.Round(2.5, MidpointRounding.AwayFromZero));\n Console.WriteLine((int)Math.Round(3.5, MidpointRounding.AwayFromZero));\n Console.ReadLine();\n" }, { "answer_id": 19739460, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "(a*10+1)>>1" }, { "answer_id": 24592301, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": 1, "selected": false, "text": " int height2 = (width2 * height1 + width1 / 2) / width1;\n int height2 = width2 * height1 / 4; // No rounding\n int height2 = (width2 * height1 + 2) / 4;\n private static Size ResizeWithPercentage(Size oldSize, int resizePercentage)\n {\n return new Size((oldSize.Width * resizePercentage + 50) / 100, \n (oldSize.Height * resizePercentage + 50) / 100);\n }\n int height2 = (width2 * height1 * 2 + width1) / (width1 * 2);\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
299,095
<p>Is there a way to turn off the automatic selection of the first row in the built-in DataGrid in Silverlight?</p> <p>We build a lot of functionality based off the user selecting a row in a data grid. The automatic firing of SelectionChanged when databinding or sorting is really causing us issues. We have tried to put some guards around the selection, but can't seem get all problems covered.</p> <p>For example, if you have DataGrid in a tab of a TabControl that is not shown when loading the screen and the DataGrid has a binding to a property of the DataContext that is a list of objects. The grid is not databound until the tab is shown. Is there an event telling us that the grid is databinding? Shouldn't the default behavior of databinding be not to select a row?</p> <p>Thanks Mike</p>
[ { "answer_id": 413410, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " int LastSelectedIndex = -1;\n bool JustRefreshed = false;\n\n private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)\n {\n if (JustRefreshed)\n {\n JustRefreshed = false;\n dataGrid.SelectedIndex = LastSelectedIndex;\n return;\n }\n if (e.AddedItems.Count > 0)\n {\n LastSelectedIndex = dataGrid.SelectedIndex;\n } \n //Your logic comes here...\n }\n }\n" }, { "answer_id": 546602, "author": "AlignedDev", "author_id": 54288, "author_profile": "https://Stackoverflow.com/users/54288", "pm_score": 1, "selected": false, "text": "private bool IsFirstLoad { get; set; }\nprivate bool IsFirstLoadDetails { get; set; }\npublic BookDisplay()\n{\n //code here\n this.IsFirstLoad = true;\n this.IsFirstLoadDetails = true;\n BindBooks(); //define this function (not in this snippet for the sake of brevity)\n}\nprivate void GridBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n if (this.IsFirstLoad)\n {\n GridBooks.SelectedItem = -1;\n this.IsFirstLoad = false;\n }\n else\n {\n //do your stuff\n }\n}\nprivate void GridBooksWithDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n if (this.IsFirstLoadDetails)\n {\n GridBooksWithDetails.SelectedItem = -1;\n this.IsFirstLoadDetails = false;\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4231/" ]
299,097
<p>I'm currently monitoring a large network with Hobbit and have been tasked with lowering the amount of false (or at least irrelevant) alarms. At the top of my list are the tests "http" and "conn", initiated by bbtest-net. This command checks ping, ssh, etc, and if for instance a ping times out, it immediately sets the status to red. One minute later, the bbretest command kicks in, checks all the newly reddened hosts, and finds it to be green again. This happens <strong>all the time</strong>, and it clutters up my log. </p> <p>Is there any way for me to make Hobbit report a red status AFTER bbretest has been run the first time? </p>
[ { "answer_id": 438436, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<ip> <hostname> # noconn \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18673/" ]
299,106
<p>I have a following xslt code :</p> <pre><code>&lt;xsl:template match="table_terms_and_abbr"&gt; &lt;informaltable frame='none' colsep='none' rowsep='none'&gt; &lt;tgroup cols='2' align='left'&gt; &lt;colspec colnum="1" colwidth='1*'/&gt; &lt;colspec colnum="2" colwidth='1*'/&gt; &lt;xsl:apply-templates/&gt; &lt;/tgroup&gt; &lt;/informaltable&gt; &lt;/xsl:template&gt; </code></pre> <p>and the following xml that it's processing : </p> <pre><code>&lt;table_terms_and_abbr&gt; &lt;tblrow_hdr&gt;Name ,, Description&lt;/tblrow_hdr&gt; &lt;tbody&gt; &lt;tblrow_bold_first&gt; BOT ,, &amp;j_bot;&lt;/tblrow_bold_first&gt; ... &lt;/tbody&gt; &lt;/table_terms_and_abbr&gt; </code></pre> <p>Now i want to improve the xslt by moving following lines inside the <code>table_terms_and_abbr</code>:</p> <pre><code>&lt;tblrow_hdr&gt;Name ,, Description&lt;/tblrow_hdr&gt; &lt;tbody&gt; &lt;/tbody&gt; </code></pre> <p>So i will have something like : </p> <pre><code>&lt;xsl:template match="table_terms_and_abbr"&gt; &lt;informaltable frame='none' colsep='none' rowsep='none'&gt; &lt;tgroup cols='2' align='left'&gt; &lt;colspec colnum="1" colwidth='1*'/&gt; &lt;colspec colnum="2" colwidth='1*'/&gt; &lt;xsl:call-template name="tblrow_hdr"&gt; BOT ,, &amp;j_bot; * ???? * &lt;/xsl:call-template&gt; &lt;tbody&gt; &lt;xsl:apply-templates/&gt; &lt;/tbody&gt; &lt;/tgroup&gt; &lt;/informaltable&gt; &lt;/xsl:template&gt; </code></pre> <p>The line marked with * ???? * does not work. I using saxon9 (xslt 2.0 stylesheet) on linux platform and got this error: </p> <p><em>XTSE0010: No character data is allowed within xsl:call-template</em></p> <p>I know how to pass the attributes to the template i.e: </p> <pre><code>&lt;xsl:with-param name="is_make_first_bold" select = "1" as="xs:integer"/&gt; </code></pre> <p>but how to pass free text ? </p> <p>The idea is move to the template all static data and in xml only use variable data i.e </p> <pre><code>&lt;table_terms_and_abbr&gt; &lt;tblrow_bold_first&gt; BOT ,, &amp;j_bot;&lt;/tblrow_bold_first&gt; ... &lt;/table_terms_and_abbr&gt; </code></pre> <p><strong>More Info</strong><br> My requirement was to create a simplified syntax for defining repeatable tables for our DocBook documentation. For that i created a general named template <code>tblrow</code> that will split the line delimited by ",," to separate entities and will create a list of entries in the table row.<br> Each entry can be a simple string, an ENTITY or another template. Since the parameter numbers are undefined (the tables can have different number of cells) i can't use a standard parameters for the templates and used delimited string. If i want to have one of the table entries to contain a link to some place in the document i can't use the parameters again since i can't pass xref template as a parameter.<br> The main reason not to change the <code>tblrow</code> template is that it's working :) and it's kind of complex. It's took me ages to achieve this and I'm not completely understand how it's working :). </p> <p>Now on top of this i have a few variables that can control the displayed output like <code>tblrow_hdr</code> that will underline and bold the text in each entry. Since <code>tblrow_hdr</code> is common for all <code>table_terms_and_abbr</code> tables it just sounds logical to me not having this in xml rather put the call to the <code>tblrow_hdr</code> inside the <code>table_terms_and_abbr</code> template and here i stuck. </p>
[ { "answer_id": 299145, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 2, "selected": false, "text": "<xsl:with-param name=\"is_make_first_bold\" select = \"1\" as=\"xs:integer\"/>\n xsl:with-param <xsl:with-param\n name = qname\n select = expression>\n <!-- Content: template -->\n</xsl:with-param>\n xsl:with-param name xsl:call-template xsl:apply-templates xsl:variable xsl:param xsl:with-param xsl:apply-templates xsl:call-template xsl:param <xsl:template name=\"numbered-block\">\n <xsl:param name=\"format\">1. </xsl:param>\n <fo:block>\n <xsl:number format=\"{$format}\"/>\n <xsl:apply-templates/>\n </fo:block>\n <xsl:template match=\"ol//ol/li\">\n <xsl:call-template name=\"numbered-block\">\n <xsl:with-param name=\"format\">a. </xsl:with-param>\n </xsl:call-template>\n</xsl:template>\n" }, { "answer_id": 300698, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 1, "selected": false, "text": "<xsl:variable/> <xsl:param/>" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6807/" ]
299,117
<p>Everything I can find in linq for aggregation has a "group by" clause. How would I write this query in LINQ? I have a list of date-value pairs, and I want to take the average of the values:</p> <pre><code>SELECT AVG(MySuff.Value) AS AvgValue FROM MyStuff </code></pre>
[ { "answer_id": 299123, "author": "Alan", "author_id": 37843, "author_profile": "https://Stackoverflow.com/users/37843", "pm_score": 2, "selected": false, "text": "int count = (from a in myContext.MyStuff\n select a).Count();\n var allResults = from a in myContext.MyStuff\n select a;\n\n//sometime later when needed\nint count = allResults.Count(); // executes the SQL query now!\n" }, { "answer_id": 299139, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "var q = from a in MyStuff select a;\nint count = q.count();\nforeach(MyStuff m in q) {...}\n" }, { "answer_id": 299141, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "Count" }, { "answer_id": 299159, "author": "Alan", "author_id": 37843, "author_profile": "https://Stackoverflow.com/users/37843", "pm_score": 2, "selected": true, "text": "var average = (from a in MyStuff\n select a.Value).Average();\n" }, { "answer_id": 299178, "author": "AlanR", "author_id": 7311, "author_profile": "https://Stackoverflow.com/users/7311", "pm_score": 0, "selected": false, "text": "(from s in series select s).Average( a => a.Value )\n" }, { "answer_id": 305516, "author": "Olmo", "author_id": 38670, "author_profile": "https://Stackoverflow.com/users/38670", "pm_score": 1, "selected": false, "text": "pairs.Average(a=>a.Value) \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7311/" ]
299,128
<p>Is there an easy way to chase down table/stored procedure/function dependencies in SQL Server 2005+? I've inherited a giant application with lots of tables and even more stored procedures and functions that are long and interlinked. </p> <p>At the end of the day is there a way to build a dependency tree? Ideally what I'm looking for goes in both directions:</p> <p><strong>For a table/procedure - what depends ON it?</strong>: Show me all the stored procedures that eventually reference it (ideally in a tree view such that sub procedures nest out to the bigger procedures that call them)</p> <p><strong>For a procedure - what does IT depend on?</strong>: Show me all the procedures and tables that a given procedure will (or could) touch when running.</p> <p>It seems this tool shouldn't be that hard to make and would be incredibly useful for DB maintenance generally. Is anyone aware of such a thing? If this doesn't exist, why the heck not?</p> <p>The built-in functionality in Management Studio is nice but the information does not appear to be complete at all.</p>
[ { "answer_id": 299137, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "View Dependencies" }, { "answer_id": 538287, "author": "Jeremy S", "author_id": 65228, "author_profile": "https://Stackoverflow.com/users/65228", "pm_score": 5, "selected": false, "text": "SELECT o.name, o.type_desc, p.name, p.type_desc\nFROM sys.sql_dependencies d\nINNER JOIN sys.objects o\n ON d.object_id = o.object_id\nINNER JOIN sys.objects p\n ON d.referenced_major_id = p.object_id\n" }, { "answer_id": 32858945, "author": "DareDevil", "author_id": 1147352, "author_profile": "https://Stackoverflow.com/users/1147352", "pm_score": 2, "selected": false, "text": "SELECT referencing_schema_name, referencing_entity_name,\nreferencing_id, referencing_class_desc, is_caller_dependent\nFROM sys.dm_sql_referencing_entities ('dbo.udf_func', 'OBJECT');\n" }, { "answer_id": 33936046, "author": "Endy Tjahjono", "author_id": 196451, "author_profile": "https://Stackoverflow.com/users/196451", "pm_score": 0, "selected": false, "text": "SELECT * FROM sys.sql_expression_dependencies\nWHERE referenced_id = OBJECT_ID(N'Production.Product');\n select\nI.name depending, I.xtype dependingtype,\nE.name depended, E.xtype dependedtype\nfrom sys.sql_expression_dependencies D\nleft outer join sysobjects I on D.referencing_id = I.id\nleft outer join sysobjects E on D.referenced_id = E.id\nwhere 1 = 1\nand ( E.name = 'mytable' or I.name = 'mytable' ) -- customize this any way you want\norder by dependedtype, depended, dependingtype, depending\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8207/" ]
299,129
<p>im trying to kick off a Runnable classes run method however i keep getting a NullPointerException, Im using WebSpheres commonj.workmanager to get an instance of executorService.this is the code im using.</p> <pre><code>executorService.execute(new Runnable() { public void run() { System.out.println("Inside run ()method.."); } }); ANY IDEAS? </code></pre>
[ { "answer_id": 299177, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "executorService execute()" }, { "answer_id": 299218, "author": "cdugga", "author_id": 24481, "author_profile": "https://Stackoverflow.com/users/24481", "pm_score": 1, "selected": false, "text": "executorService null" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
299,135
<p>Let's say I have <strong>a <code>List</code> object</strong> and <strong>an iterator</strong> for that list.</p> <p>Now I sort the list with <code>java.util.Collections.sort()</code></p> <ul> <li>What happens to the iterator? </li> <li>Is its behavior still defined and can it still be used? </li> <li>If not, can I prevent destroying the iterators for the list?</li> </ul> <p>I know, this problem could be circumvented by changing the program design, cloning the list for example, but I specificly want to know the "official" behavior of Java.</p>
[ { "answer_id": 299151, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "ListIterator" }, { "answer_id": 299169, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "CopyOnWriteArrayList" }, { "answer_id": 299171, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "java.util ConcurrentModificationException AbstractList CopyOnWriteArrayList" }, { "answer_id": 299224, "author": "MaitreKaio", "author_id": 38619, "author_profile": "https://Stackoverflow.com/users/38619", "pm_score": 2, "selected": false, "text": "public static void main(String[] args) {\n List<String> list = new ArrayList<String>();\n list.add(\"D\");\n list.add(\"B\");\n list.add(\"A\");\n list.add(\"C\");\n list.add(\"E\");\n\n Iterator<String> it = list.iterator();\n String s = it.next();\n System.out.println(s);\n s = it.next();\n System.out.println(s);\n\n Collections.sort(list);\n Iterator<String> it2 = list.iterator();\n\n s = it.next();\n System.out.println(s);\n s = it.next();\n System.out.println(s);\n s = it.next();\n System.out.println(s);\n\n while (it2.hasNext()) {\n System.out.println(it2.next());\n }\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23368/" ]
299,142
<p>I've been reading up on branching/merging with Subversion 1.5 using the excellent and free <a href="http://svnbook.red-bean.com/" rel="noreferrer">Version Control with Subversion</a> book. I think that I understand how to use the Subversion command line client to perform the actions that I need most often, which are:</p> <p><strong>Update Branch with Changes from Trunk</strong></p> <p>From the branch's working directory run: </p> <blockquote> <p>svn merge <a href="http://svn.myurl.com/proj/trunk" rel="noreferrer">http://svn.myurl.com/proj/trunk</a></p> </blockquote> <p><strong>Merge Branch into Trunk</strong></p> <p>From the trunk's working directory run:</p> <blockquote> <p>svn merge --reintegrate <a href="http://svn.myurl.com/proj/branches/mybranch" rel="noreferrer">http://svn.myurl.com/proj/branches/mybranch</a></p> </blockquote> <p>However, we are using TortoiseSVN 1.5 as our interface to Subversion. I would like to know how best to perform these operations with TortoiseSVN. The new dialog provides three different options on the main menu. </p> <ol> <li>Merge a range of revisions</li> <li>Reintegrate a branch</li> <li>Merge two different trees</li> </ol> <p>From what I can gather, TortoiseSVN always executes svn with the following syntax.</p> <blockquote> <p>svn merge [--dry-run] --force From_URL@revN To_URL@revM PATH</p> </blockquote> <p>Additionally, reintegrate a branch often fails with a message stating that some targets have not been merged and so it cannot continue, and so I had to use option #3.</p> <p>My questions are:</p> <ol> <li>How do I use TortoiseSVN 1.5 to merge changes from the trunk to a branch?</li> <li>How do I use TortoiseSVN 1.5 to merge the branch to the trunk, with and without the reintegrate method?</li> <li>Which of the above options should I use for each, and why?</li> </ol> <hr> <p><strong>EDIT</strong></p> <p>Through "dry run" testing I have found that the command line Subversion operation</p> <blockquote> <p>svn merge <a href="http://svn.myurl.com/proj/trunk" rel="noreferrer">http://svn.myurl.com/proj/trunk</a></p> </blockquote> <p>is analogous to option #1 (Merge a Range of Revisions) in TortoiseSVN, as long as I leave the revision range blank.</p>
[ { "answer_id": 15658849, "author": "icc97", "author_id": 327074, "author_profile": "https://Stackoverflow.com/users/327074", "pm_score": 8, "selected": false, "text": "trunk -> branch branch -> trunk trunk -> branch branch -> trunk" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19977/" ]
299,148
<p>I'm playing with <a href="http://www.dncompute.com/blog/2007/03/19/seed-based-pseudorandom-number-generator-in-actionscript.html" rel="nofollow noreferrer">this ActionScript</a> which generates a random 'squiggle'.</p> <p>Each time a 'squiggle' is placed, it appears within a sprite with a white background.</p> <p>If I change the background colour of the flash file to pink for example, it would still show up as white.</p> <p>Does anybody know how I might make the sprite background transparent? Thanks.</p>
[ { "answer_id": 299544, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "bitmapData.draw(paintSurface);\n sprite.attachBitmap(bitmapData, 3);\n" }, { "answer_id": 299552, "author": "Iain", "author_id": 11911, "author_profile": "https://Stackoverflow.com/users/11911", "pm_score": 3, "selected": true, "text": "bitmapData = new BitmapData(width,height,false,0xfafafa);\n bitmapData = new BitmapData(width,height,true,0x000000);\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25773/" ]
299,158
<p>What does the SQL Action keyword do? Can I use this keyword in a trigger and determine if the trigger was called by an Insert, Delete or Update?</p>
[ { "answer_id": 299187, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 1, "selected": false, "text": "If exists (select * from inserted) and exists (select * from deleted)\n --Update happened\nIf exists (select * from inserted)\n --Insert happened\nIf exists (select * from deleted)\n --Delete happened\nElse\n --Nothing happened\n" }, { "answer_id": 299289, "author": "GluedHands", "author_id": 37726, "author_profile": "https://Stackoverflow.com/users/37726", "pm_score": 3, "selected": true, "text": "CREATE TRIGGER TriggerName\nON TableName\n [FOR|AFTER|INSTEAD OF]\n AFTER,UPDATE,DELETE\nAS\n ...\n IF EXISTS (SELECT TOP 1 * FROM Inserted) AND NOT EXISTS (SELECT TOP 1 * FROM Deleted) --INSERT\n ...\n\nIF EXISTS (SELECT TOP 1 * FROM Inserted) AND EXISTS (SELECT TOP 1 * FROM Deleted) --UPDATE\n ...\n\nIF NOT EXISTS (SELECT TOP 1 * FROM Inserted) AND EXISTS (SELECT TOP 1 * FROM Deleted) --DELETE\n ...\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38613/" ]
299,160
<p>Just started getting into jQuery and have an issue with a jQuery Post call working perfectly on my local dev box (VS 2008 built-in web server), but failing when I deploy to a windows 2003 server (IIS 6) box.</p> <p>The post works and the page being posted to process things correctly, but a response is never received by the calling Post function. The submitting page just reloads with no changes.</p> <p>Here is my Post function (it is enclosed in the <code>$(document).ready(function() {...</code></p> <p>The alert in the response function never fires:</p> <pre><code> $('.nextButton').click(function() { var idString = ''; $("div.dropZone &gt; div").each(function(n) { idString += this.id + '|'; }); $.post('CustomPostHandler.aspx?step=criteria', { selected: idString }, function(data) { alert(data); }); }); </code></pre> <p>The post handler page does receive the idString variable fine, after some processing it attempts to write back a response:</p> <pre><code> // Return dummy response to caller Response.Clear(); Response.ContentType = "text/plain"; Response.Write("success"); Response.End(); </code></pre> <p>I've checked the deployment server environment and don't see anything missing (this is running against the 3.5 SP1 framework). Anyone have any ideas or am I missing something?</p>
[ { "answer_id": 299204, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 1, "selected": false, "text": "$.post('CustomPostHandler.aspx?step=criteria&random=' + Math.random().toString(), { \n selected: idString\n },\n" }, { "answer_id": 299820, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 0, "selected": false, "text": "$.ajax" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38615/" ]
299,168
<p>I need to style links for a Blackberry browser that has disabled CSS.</p> <p>The following is what I try to achieve: </p> <pre><code>&lt;style type="text/css"&gt; a.hover { border:0; } a { text-decoration: none; } &lt;/style&gt; </code></pre> <p>Is it even possible, just using html?</p>
[ { "answer_id": 299202, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 4, "selected": true, "text": "<body link=\"XXX\" alink=\"YYY\" vlink=\"ZZZ\"> \n #AABBCC\n" }, { "answer_id": 838807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "tex-decoration:bilnk" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532/" ]
299,176
<p>I've been running into some problems duplicating some old ASP files into some newer .NET 2.0 code. One of the tasks is to merge the 4-5 SQL statements into one. While I have done this and had some success in performance boosts, Oracle is a new bag for me. This problem however surpasses my own SQL skills as I haven't done this before.</p> <p>Basically, I have a QUANTITY in one table from a bunch of Sales. Each sale has an integer value. Each sale also has an ITEM attached to it. Each ITEM has a CONVERSION factor as in if I sell 1 bag of something = 10 bundles of something. So, when I run a report and want to find out the end value, I need to take each sale and its quantity and multiple it by its conversion factor. Most are simple 1 to 1, so it's basically doing 25 * 1, 30 * 1 etc.</p> <p>My problem is that there are past sales in my records in which the ITEM has been removed from our system, therefore the CONVERSION factor does not exist. Those records get dropped from my query because the FACTOR is gone.</p> <pre><code>SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code FROM salesdetails rth, salesheader rsh WHERE rsh.number = rth.number(+) AND rsh.customer_code = '05' AND rsh.r_code = '01' AND rsh.location_code = '12' AND rth.sale_code IN('ITEM07') AND rth.c_code = 'WLMT' AND rsh.year = '2008' </code></pre> <p>This is my first QUERY. If I add the conversion in:</p> <pre><code>SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code, rth.quantity * cf.conversion FROM salesdetails rth, salesheader rsh, conversionfactor cf WHERE rsh.number = rth.number(+) AND rsh.customer_code = '05' AND rsh.r_code = '01' AND rsh.location_code = '12' AND rth.sale_code IN('ITEM07') AND rth.c_code = 'WLMT' AND rsh.year = '2008' AND cf.item_code = rth.item_code and cf.code = '01' and cf.loc_code = '00001' </code></pre> <p>This works to an extent. It lists all the same records, but it is missing any records in which the CONVERSION factor did not exist. Is there anyway I can still include those records where the FACTOR didn't exist in the second query, short from going line by line and doing the conversion that way.</p>
[ { "answer_id": 299220, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 0, "selected": false, "text": "SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code, rth.quantity * cf.conversion\nFROM salesdetails rth, salesheader rsh, conversionfactor cf\nWHERE rsh.number = rth.number(+)\nAND rsh.customer_code = '05'\nAND rsh.r_code = '01'\nAND rsh.location_code = '12'\nAND rth.sale_code IN('ITEM07')\nAND rth.c_code = 'WLMT'\nAND rsh.year = '2008'\nAND rth.item_code = cf.item_code (+)\nand cf.code = '01'\nand cf.loc_code = '00001'\n" }, { "answer_id": 299237, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 0, "selected": false, "text": "select \n rth.code, rth.number, rth.quantity, rth.sale_code, rth.quantity * coalesce(cf.conversion,1)\nfrom \n salesdetails rth\n inner join salesheader rsh on rsh.number = rth.number\n left join conversionfactor cf on cf.item_code = rth.item_code\nwhere \nrsh.customer_code = '05'\nand rsh.r_code = '01'\nand rsh.location_code = '12'\nand rth.sale_code in('item07')\nand rth.c_code = 'wlmt'\nand rsh.year = '2008'\nand cf.code = '01'\nand cf.loc_code = '00001'\n" }, { "answer_id": 299268, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 1, "selected": false, "text": "SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code,\n rth.quantity * cf.conversion\nFROM salesdetails rth, salesheader rsh, conversionfactor cf\nWHERE rsh.number = rth.number(+)\nAND rsh.customer_code = '05'\nAND rsh.r_code = '01'\nAND rsh.location_code = '12'\nAND rth.sale_code (+) IN('ITEM07')\nAND rth.c_code (+) = 'WLMT'\nAND rsh.year = '2008'\nAND cf.item_code (+) = rth.item_code\nand cf.code (+) = '01'\nand cf.loc_code (+) = '00001'\n SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code,\n rth.quantity * cf.conversion\nFROM salesheader rsh\nLEFT OUTER JOIN salesdetails rth\n ON rsh.number = rth.number\n AND rth.sale_code IN ('ITEM07')\n AND rth.c_code = 'WLMT'\nLEFT OUTER JOIN conversionfactor cf\n ON cf.item_code = rth.item_code\n AND cf.code = '01'\n AND cf.loc_code = '00001'\nWHERE rsh.customer_code = '05'\nAND rsh.r_code = '01'\nAND rsh.location_code = '12'\nAND rsh.year = '2008'\n" }, { "answer_id": 299282, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 2, "selected": false, "text": "Select D.CODE, D.NUMBER, D.QUANTITY, D.sale_code, \n D.quantity * Coalesce((Select conversion \n From conversionfactor\n Where item_code = H.item_code\n And code = '01'\n And loc_code = '00001'), 1.0)\nFrom salesheader H\n Left Join salesdetails D\n On D.Number = H.Number\nWhere H.customer_code = '05'\n And H.r_code = '01'\n And H.location_code = '12'\n And H.year = '2008'\n And D.sale_code In ('ITEM07')\n And D.c_code = 'WLMT'\n" }, { "answer_id": 304343, "author": "Bert", "author_id": 38065, "author_profile": "https://Stackoverflow.com/users/38065", "pm_score": 0, "selected": false, "text": "SELECT rth.CODE, rth.NUMBER, rth.QUANTITY, rth.sale_code, rth.quantity * NVL(cf.conversion,1)\nFROM salesdetails rth, salesheader rsh, conversionfactor cf\nWHERE rsh.number = rth.number(+)\nAND rsh.customer_code = '05'\nAND rsh.r_code = '01'\nAND rsh.location_code = '12'\nAND rth.sale_code IN('ITEM07')\nAND rth.c_code = 'WLMT'\nAND rsh.year = '2008'\nAND cf.item_code = rth.item_code\nand cf.code = '01'\nand cf.loc_code = '00001'\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,198
<p>I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.</p> <pre><code>TemperamentalClass tc = new TemperamentalClass(); tc.DoSomething(); // normally runs in 30 sec. Want to error at 1 min </code></pre> <p>I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).</p> <p>In addition, I would like to have the offending "timed out" code stopped from executing further if possible.</p>
[ { "answer_id": 299212, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": " static void Main()\n {\n DoWork(OK, 5000);\n DoWork(Nasty, 5000);\n }\n static void OK()\n {\n Thread.Sleep(1000);\n }\n static void Nasty()\n {\n Thread.Sleep(10000);\n }\n static void DoWork(Action action, int timeout)\n {\n ManualResetEvent evt = new ManualResetEvent(false);\n AsyncCallback cb = delegate {evt.Set();};\n IAsyncResult result = action.BeginInvoke(cb, null);\n if (evt.WaitOne(timeout))\n {\n action.EndInvoke(result);\n }\n else\n {\n throw new TimeoutException();\n }\n }\n static T DoWork<T>(Func<T> func, int timeout)\n {\n ManualResetEvent evt = new ManualResetEvent(false);\n AsyncCallback cb = delegate { evt.Set(); };\n IAsyncResult result = func.BeginInvoke(cb, null);\n if (evt.WaitOne(timeout))\n {\n return func.EndInvoke(result);\n }\n else\n {\n throw new TimeoutException();\n }\n }\n" }, { "answer_id": 299226, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\n\n\nnamespace TemporalThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n Action action = () => Thread.Sleep(10000);\n DoSomething(action, 5000);\n Console.ReadKey();\n }\n\n static void DoSomething(Action action, int timeout)\n {\n EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);\n AsyncCallback callback = ar => waitHandle.Set();\n action.BeginInvoke(callback, null);\n\n if (!waitHandle.WaitOne(timeout))\n throw new Exception(\"Failed to complete in the timeout specified.\");\n }\n }\n\n}\n" }, { "answer_id": 299273, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 8, "selected": true, "text": "class Program\n{\n\n static void Main(string[] args)\n {\n //try the five second method with a 6 second timeout\n CallWithTimeout(FiveSecondMethod, 6000);\n\n //try the five second method with a 4 second timeout\n //this will throw a timeout exception\n CallWithTimeout(FiveSecondMethod, 4000);\n }\n\n static void FiveSecondMethod()\n {\n Thread.Sleep(5000);\n }\n static void CallWithTimeout(Action action, int timeoutMilliseconds)\n {\n Thread threadToKill = null;\n Action wrappedAction = () =>\n {\n threadToKill = Thread.CurrentThread;\n try\n {\n action();\n }\n catch(ThreadAbortException ex){\n Thread.ResetAbort();// cancel hard aborting, lets to finish it nicely.\n }\n };\n\n IAsyncResult result = wrappedAction.BeginInvoke(null, null);\n if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))\n {\n wrappedAction.EndInvoke(result);\n }\n else\n {\n threadToKill.Abort();\n throw new TimeoutException();\n }\n }\n\n}\n" }, { "answer_id": 299395, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 3, "selected": false, "text": "public static class Runner\n{\n public static void Run(Action action, TimeSpan timeout)\n {\n IAsyncResult ar = action.BeginInvoke(null, null);\n if (ar.AsyncWaitHandle.WaitOne(timeout))\n action.EndInvoke(ar); // This is necesary so that any exceptions thrown by action delegate is rethrown on completion\n else\n throw new TimeoutException(\"Action failed to complete using the given timeout!\");\n }\n}\n" }, { "answer_id": 869257, "author": "George Tsiokos", "author_id": 5869, "author_profile": "https://Stackoverflow.com/users/5869", "pm_score": 4, "selected": false, "text": "public static T Invoke<T> (Func<CancelEventArgs, T> function, TimeSpan timeout) {\n if (timeout.TotalMilliseconds <= 0)\n throw new ArgumentOutOfRangeException (\"timeout\");\n\n CancelEventArgs args = new CancelEventArgs (false);\n IAsyncResult functionResult = function.BeginInvoke (args, null, null);\n WaitHandle waitHandle = functionResult.AsyncWaitHandle;\n if (!waitHandle.WaitOne (timeout)) {\n args.Cancel = true; // flag to worker that it should cancel!\n /* •————————————————————————————————————————————————————————————————————————•\n | IMPORTANT: Always call EndInvoke to complete your asynchronous call. |\n | http://msdn.microsoft.com/en-us/library/2e08f6yc(VS.80).aspx |\n | (even though we arn't interested in the result) |\n •————————————————————————————————————————————————————————————————————————• */\n ThreadPool.UnsafeRegisterWaitForSingleObject (waitHandle,\n (state, timedOut) => function.EndInvoke (functionResult),\n null, -1, true);\n throw new TimeoutException ();\n }\n else\n return function.EndInvoke (functionResult);\n}\n\npublic static T Invoke<T> (Func<T> function, TimeSpan timeout) {\n return Invoke (args => function (), timeout); // ignore CancelEventArgs\n}\n\npublic static void Invoke (Action<CancelEventArgs> action, TimeSpan timeout) {\n Invoke<int> (args => { // pass a function that returns 0 & ignore result\n action (args);\n return 0;\n }, timeout);\n}\n\npublic static void TryInvoke (Action action, TimeSpan timeout) {\n Invoke (args => action (), timeout); // ignore CancelEventArgs\n}\n" }, { "answer_id": 990566, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 6, "selected": false, "text": "var result = WaitFor<Result>.Run(1.Minutes(), () => service.GetSomeFragileResult());\n /// <summary>\n/// Helper class for invoking tasks with timeout. Overhead is 0,005 ms.\n/// </summary>\n/// <typeparam name=\"TResult\">The type of the result.</typeparam>\n[Immutable]\npublic sealed class WaitFor<TResult>\n{\n readonly TimeSpan _timeout;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"WaitFor{T}\"/> class, \n /// using the specified timeout for all operations.\n /// </summary>\n /// <param name=\"timeout\">The timeout.</param>\n public WaitFor(TimeSpan timeout)\n {\n _timeout = timeout;\n }\n\n /// <summary>\n /// Executes the spcified function within the current thread, aborting it\n /// if it does not complete within the specified timeout interval. \n /// </summary>\n /// <param name=\"function\">The function.</param>\n /// <returns>result of the function</returns>\n /// <remarks>\n /// The performance trick is that we do not interrupt the current\n /// running thread. Instead, we just create a watcher that will sleep\n /// until the originating thread terminates or until the timeout is\n /// elapsed.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\">if function is null</exception>\n /// <exception cref=\"TimeoutException\">if the function does not finish in time </exception>\n public TResult Run(Func<TResult> function)\n {\n if (function == null) throw new ArgumentNullException(\"function\");\n\n var sync = new object();\n var isCompleted = false;\n\n WaitCallback watcher = obj =>\n {\n var watchedThread = obj as Thread;\n\n lock (sync)\n {\n if (!isCompleted)\n {\n Monitor.Wait(sync, _timeout);\n }\n }\n // CAUTION: the call to Abort() can be blocking in rare situations\n // http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx\n // Hence, it should not be called with the 'lock' as it could deadlock\n // with the 'finally' block below.\n\n if (!isCompleted)\n {\n watchedThread.Abort();\n }\n };\n\n try\n {\n ThreadPool.QueueUserWorkItem(watcher, Thread.CurrentThread);\n return function();\n }\n catch (ThreadAbortException)\n {\n // This is our own exception.\n Thread.ResetAbort();\n\n throw new TimeoutException(string.Format(\"The operation has timed out after {0}.\", _timeout));\n }\n finally\n {\n lock (sync)\n {\n isCompleted = true;\n Monitor.Pulse(sync);\n }\n }\n }\n\n /// <summary>\n /// Executes the spcified function within the current thread, aborting it\n /// if it does not complete within the specified timeout interval.\n /// </summary>\n /// <param name=\"timeout\">The timeout.</param>\n /// <param name=\"function\">The function.</param>\n /// <returns>result of the function</returns>\n /// <remarks>\n /// The performance trick is that we do not interrupt the current\n /// running thread. Instead, we just create a watcher that will sleep\n /// until the originating thread terminates or until the timeout is\n /// elapsed.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\">if function is null</exception>\n /// <exception cref=\"TimeoutException\">if the function does not finish in time </exception>\n public static TResult Run(TimeSpan timeout, Func<TResult> function)\n {\n return new WaitFor<TResult>(timeout).Run(function);\n }\n}\n static void Main(string[] args) {\n\n // Use a sb instead of Console.WriteLine() that is modifying how synchronous object are working\n var sb = new StringBuilder();\n\n for (var j = 1; j < 10; j++) // do the experiment 10 times to have chances to see the ThreadAbortException\n for (var ii = 8; ii < 15; ii++) {\n int i = ii;\n try {\n\n Debug.WriteLine(i);\n try {\n WaitFor<int>.Run(TimeSpan.FromMilliseconds(10), () => {\n Thread.Sleep(i);\n sb.Append(\"Processed \" + i + \"\\r\\n\");\n return i;\n });\n }\n catch (TimeoutException) {\n sb.Append(\"Time out for \" + i + \"\\r\\n\");\n }\n\n Thread.Sleep(10); // Here to wait until we get the abort procedure\n }\n catch (ThreadAbortException) {\n Thread.ResetAbort();\n sb.Append(\" *** ThreadAbortException on \" + i + \" *** \\r\\n\");\n }\n }\n\n Console.WriteLine(sb.ToString());\n }\n }\n WaitFor<int>.Run()" }, { "answer_id": 1268391, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static void CallWithTimeout(Action act, int millisecondsTimeout)\n{\n var thread = new Thread(new ThreadStart(act));\n thread.Start();\n if (!thread.Join(millisecondsTimeout))\n throw new Exception(\"Timed out\");\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28736/" ]
299,200
<p>Topic: Programmatically manipulate web browser in OS X 10.4.x+ Tiger/Leopard. Subjects: Webkit, Safari, Firefox, APIs, Applescript, Automator, Javascript, Ruby, Ruby on Rails, OS X, Tiger Goal: Collect/Read/Extract URLs from Safari into text (Ruby on Rails code) file. Note: A solution that uses FF would be very appreciated, too. I use Safari (v. 3.x, OS X 10.4.x) more and much prefer a solution that works in Safari.</p> <p>At times, I use the web browser to find/display multiple site pages that I 1) want to visit again later and 2) the URLs of which I want to group together in a text file for a) future reference and/or b) programmatically manipulate.</p> <p>For example: In today's NYT I find seven NYT articles I want to post to my del.icio.us acct. and share via email in their "printer friendly" format long after they are headlined in that day's online edition. I open each one in a browser window's tap, then Presto! their URLs automagically are wooshed into a file where a (custom) Ruby on Rails app sends the print versions' URLs to email addresses and my Del.icio.us acct.</p> <p>I figure there's a way to do the URL extracting step from the OS using Applescript or Automator. I figure there MAY be a way to do it with Javascript.</p> <p>My Question: How to read the web browser's tabs' location field and collate these strings into a text file (either within my OS or over the wire to a web app.)?</p> <p>Much appreciated.</p>
[ { "answer_id": 1369382, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "function getGetDocData(){\nvar wm = Components.classes[\"@mozilla.org/appshell/window-mediator;1\"]\n .getService(Components.interfaces.nsIWindowMediator);\nvar mainWindow = wm.getMostRecentWindow(\"navigator:browser\");\nvar tab = mainWindow.getBrowser().selectedTab;\ntitleDG = tab.label;\nfor(var i = 0; i < window.opener.length; i++){\n var doc = window.opener[i].document;\n if(doc.title == tab.label){\n hrefToDG = doc.location.href;\n }\n}\n" }, { "answer_id": 6836406, "author": "fireshadow52", "author_id": 544963, "author_profile": "https://Stackoverflow.com/users/544963", "pm_score": 0, "selected": false, "text": "property these_URLs : {}\nset the text item delimeters of AppleScript to \"\"\n----------------------------------------------------------------------------------\n--Initialize the program\nset the action to the button returned of (display dialog \"Create or view a list of favorites...\" buttons{\"Cancel\",\"View\",\"Create\"} default button 3)\nif the action is \"Create\" then\n create_text_file()\nelse\n open_favorites()\nend if\n\n---------------------------------SUBROUTINES--------------------------------------\n\non create_text_file()\n --get the URL of every tab of every window\n tell application \"Safari\"\n set theWindows to (get every document) as list\n repeat with i from 1 to the count of theWindows\n set this_Window to item i of theWindows\n set theTabs to (get every tab of this_Window) as list\n repeat with x from 1 to the count of theTabs\n set this_Tab to item x of theTabs\n set this_URL to (the URL of this_tab) as string\n set the end of these_URLs to this_URL\n end repeat\n end repeat\n end tell\n\n --put the URLs into a text document\n set newFile to (choose file name with prompt \"Choose a name and location for the new file:\" default location (path to desktop folder))\n try\n open for access newFile with write permission\n set the text item delimiters of AppleScript to return\n set the_URLs to these_URLs as string\n write the_URLS to file newFile\n close access newFile\n on error\n try\n close access newFile\n end try\n end try\n set the text item delimiters of AppleScript to \"\"\nend create_text_file()\n\non open_favorites()\n --Verify whether you have saved any favorites with this script\n if these_URLs is {} then display dialog \"You have not added any favorites with this script.\" with icon note buttons{\"Cancel\"}\n --there are favorites so open all the URLs you stored in the text file\n repeat with i from 1 to the count of these_URLs\n set this_URL to item i of these_URLs\n tell application \"Safari\" to make new tab at the end of tabs of document 1 with properties {URL:this_URL}\n end repeat\nend open_favorites\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23306/" ]
299,209
<p>i'm a long-time newbie to c#, and this question may be too obvious, so please forgive if i'm "doing it wrong."</p> <p>Using Visual Studio 2005 Pro, C#, SQL Server 2000 EE SP3.</p> <p>I have a stored proc that takes one input param and returns several output params pertaining to that input. I am also calling it successfully, and String.Format-ing the outputs into a RichTextBox. I'd like to call this proc periodically and each time stick the output params into a DataGridView row, so the results accumulate over time.</p> <ul> <li>What's the simplest/most elegant way to do get those parameters into the DataGridView? I'd prefer code instead of some GUI builder solution.</li> <li>Am i overlooking some better approach, such as a more appropriate control?</li> </ul> <p>Thanks!</p>
[ { "answer_id": 299228, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": true, "text": "//set up the datatable\nDataTable dt = new DataTable(\"parms\");\ndt.Columns.Add(\"ParmName\",typeof(string));\ndt.Columns.Add(\"ParmValue\",typeof(string));\n//bind to a gui object\nmyDataGridView.DataSource = dt;\n\n//do this after each sproc call\nforeach (SqlParameter parm in cmd.Parameters)\n{\n if (parm.Direction == ParameterDirection.Output)\n {\n //do something with parm.Value\n dt.Rows.Add(new object [] { parm.ParameterName, \n Convert.ToString(parm.Value) } );\n }\n}\n" }, { "answer_id": 299364, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 0, "selected": false, "text": "dgvOutput.Columns.Add(\"@col1\", \"Val 1\");\ndgvOutput.Columns.Add(\"@col2\", \"Val 2\");\ndgvOutput.Columns.Add(\"@col3\", \"Val 3\");\n dgvOutput.Rows.Add(new object[]{\n Convert.ToString(cmd.Parameters[\"@col1\"].Value),\n Convert.ToString(cmd.Parameters[\"@col2\"].Value),\n Convert.ToString(cmd.Parameters[\"@col3\"].Value)\n});\ndgvOutput.AutoResizeColumns();\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4126/" ]
299,217
<p>I am trying to monitor my outlook inbox so whenever new emails come in with attachments I save the attachment to some other location. Can anyone help me out?</p>
[ { "answer_id": 299234, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "using Outlook;\n\n Outlook.Application oOutlook;\n Outlook.NameSpace oNs;\n Outlook.MAPIFolder oFldr;\n long iAttachCnt;\n\n try\n {\n oOutlook = new Outlook.Application();\n oNs = oOutlook.GetNamespace(”MAPI”);\n\n //getting mail folder from inbox\n oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);\n Response.Write(”Total Mail(s) in Inbox :” + oFldr.Items.Count + “<br>”);\n Response.Write(”Total Unread items = ” + oFldr.UnReadItemCount);\n foreach (Outlook.MailItem oMessage in oFldr.Items)\n {\n StringBuilder str = new StringBuilder();\n str.Append(”<table style=’border:1px solid gray;font-family:Arial;font-size:x-small;width:80%;’ align=’center’><tr><td style=’width:20%;’><b>Sender :</b></td><td>”);\n str.Append(oMessage.SenderEmailAddress.ToString() + “</td></tr>”);\n //basic info about message\n str.Append(”<tr><td><b>Date :</b></td><td>” + oMessage.SentOn.ToShortDateString() + “</td></tr>”);\n if (oMessage.Subject != null)\n {\n str.Append(”<tr><td><b>Subject :</b></td><td>” + oMessage.Subject.ToString() + “</td></tr>”);\n }\n //reference and save all attachments\n\n iAttachCnt = oMessage.Attachments.Count;\n if (iAttachCnt > 0)\n {\n for (int i = 1; i <= iAttachCnt; i++)\n {\n str.Append(”<tr><td><b>Attachment(” + i.ToString() + “) :</b></td><td>” + oMessage.Attachments[i].FileName + “</td></tr>”);\n }\n }\n str.Append(”</table><br>”);\n Response.Write(str.ToString());\n\n }\n\n }\n catch (System.Exception ex)\n {\n Response.Write(”Execption generated:” + ex.Message);\n }\n finally\n {\n GC.Collect();\n oFldr = null;\n oNs = null;\n oOutlook = null;\n\n }\n" }, { "answer_id": 299309, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 0, "selected": false, "text": " private RDOSession _MailSession = new RDOSession();\n private RDOFolder _IncommingInbox;\n private RDOFolder _ArchiveFolder;\n private string _SaveAttachmentPath;\n\n public MailBox(string Logon_Profile, string IncommingMailPath, \n string ArchiveMailPath, string SaveAttPath)\n {\n _MailSession.Logon(Logon_Profile, null, null, true, null, null);\n _IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath);\n _ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath);\n _SaveAttachmentPath = SaveAttPath;\n }\npublic void ProcessMail()\n {\n\n foreach (RDOMail msg in _IncommingInbox.Items)\n {\n foreach (RDOAttachment attachment in msg.Attachments)\n {\n attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName);\n }\n }\n if (msg.Body != null)\n {\n ProcessBody(msg.Body);\n }\n\n }\n\n }\n MailBox pwaMail = new MailBox(\"Self Email User\", @\"\\\\Mailbox - Someone\\Inbox\",\n @\"\\\\EMail - Incomming\\Backup\", @\"\\\\SomePath\");\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,249
<p>I am familiar with using the <em>os.system</em> to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: <code>c:\test&gt;java -jar run_this.jar required_parameter.ext</code> ? I'm a python newbie so details are greatly appreciated. Thanks in advance. </p>
[ { "answer_id": 299377, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": true, "text": "import os\n\nif __name__ == \"__main__\":\n startingDir = os.getcwd() # save our current directory\n testDir = \"\\\\test\" # note that \\ is windows specific, and we have to escape it\n os.chdir(testDir) # change to our test directory\n os.system(\"java -jar run_this.jar required_paramter.ext\")\n os.chdir(startingDir) # change back to where we started\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
299,251
<p>I am attempting to write a component in C# to be consumed by classic ASP that allows me to access the indexer of the component (aka default property).</p> <p>For example:<br> C# component:</p> <pre><code>public class MyCollection { public string this[string key] { get { /* return the value associated with key */ } } public void Add(string key, string value) { /* add a new element */ } } </code></pre> <p>ASP consumer:</p> <pre><code>Dim collection Set collection = Server.CreateObject("MyCollection ") Call collection.Add("key", "value") Response.Write(collection("key")) ' should print "value" </code></pre> <p>Is there an attribute I need to set, do I need to implement an interface or do I need to do something else? Or this not possible via COM Interop?</p> <p>The purpose is that I am attempting to create test doubles for some of the built-in ASP objects such as Request, which make use of collections using these default properties (such as <code>Request.QueryString("key")</code>). Alternative suggestions are welcome.</p> <p>Update: I asked a follow-up question: <a href="https://stackoverflow.com/questions/317759/why-is-the-indexer-on-my-net-component-not-always-accessible-from-vbscript">Why is the indexer on my .NET component not always accessible from VBScript?</a></p>
[ { "answer_id": 301260, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "[DispId(0)]\npublic string Item(string key) {\n return this[key];\n}\n" }, { "answer_id": 311946, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "Item public class MyCollection {\n private NameValueCollection _collection;\n\n [DispId(0)]\n public string this[string name] {\n get { return _collection[name]; }\n set { _collection[name] = value; }\n }\n}\n Dim collection\nSet collection = Server.CreateObject(\"MyCollection\")\ncollection(\"key\") = \"value\"\nResponse.Write(collection(\"key\")) ' should print \"value\"\n this[string name] this[int index]" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14934/" ]
299,254
<p>In essence I'd like to store some rows in a temporary variable for the life of a procedure in MySQL.</p> <p>My procedure will grab a column of foreign keys at the beginning of the procedure. Once I'm done working with them I want to update the table to indicate that they have been processed. There may be inserts into this table while my procedure is working on it's set of data so I don't want to erroneously mark these new rows as processed. I also do not want to lock this table and hold up the thread that is making the inserts. </p> <p>Is a temporary table the best solution?</p>
[ { "answer_id": 301260, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "[DispId(0)]\npublic string Item(string key) {\n return this[key];\n}\n" }, { "answer_id": 311946, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "Item public class MyCollection {\n private NameValueCollection _collection;\n\n [DispId(0)]\n public string this[string name] {\n get { return _collection[name]; }\n set { _collection[name] = value; }\n }\n}\n Dim collection\nSet collection = Server.CreateObject(\"MyCollection\")\ncollection(\"key\") = \"value\"\nResponse.Write(collection(\"key\")) ' should print \"value\"\n this[string name] this[int index]" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21906/" ]
299,255
<p>I'm starting to try and test my Doctrine objects with PHPUnit, and would like to reload the DB from my model objects afresh each time.</p> <p>My first attempt looks something like this:</p> <pre><code>class Tests_User extends PHPUnit_Framework_TestCase { public function setUp() { Doctrine_Manager::connection('mysql://user:pass@localhost/testdb'); Doctrine::createDatabases(); Doctrine::createTablesFromModels('../../application/models'); } public function testSavingWorks() { $user = new User(); $user-&gt;save(); } public function testSavingWorksAgain() { $user = new User(); $user-&gt;save(); } public function tearDown() { Doctrine::dropDatabases(); } } </code></pre> <p>The problem is that when setUp() is called again for the second test, createTablesFromModels() fails, so I get an error because none of the tables are present.</p> <p>I'd really appreciate an example of how someone else has reinitialised a Doctrine connection for PHPUnit or other unit testing purposes.</p>
[ { "answer_id": 301260, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "[DispId(0)]\npublic string Item(string key) {\n return this[key];\n}\n" }, { "answer_id": 311946, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 0, "selected": false, "text": "Item public class MyCollection {\n private NameValueCollection _collection;\n\n [DispId(0)]\n public string this[string name] {\n get { return _collection[name]; }\n set { _collection[name] = value; }\n }\n}\n Dim collection\nSet collection = Server.CreateObject(\"MyCollection\")\ncollection(\"key\") = \"value\"\nResponse.Write(collection(\"key\")) ' should print \"value\"\n this[string name] this[int index]" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34024/" ]
299,267
<p>What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I should get a new image of size 0.68*1024 x 0.68*2048. some pixels will be collapsed onto each other. And, if I scale by a factor of say 3.15, I would get a larger image with pixels being duplicated. So, what's the best way to accomplish this?</p> <p>Next, I would like to be able to rotate an image by an arbitrary angle, in the range of 0 to 360 degrees (0 - 2Pi). Cropping of the image after rotating isn't an issue. What would be the best way to do this?</p>
[ { "answer_id": 299305, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": false, "text": "dest[dx,dy] = src[dx*src_width/dest_width,dy*src_height/dest_height]\n sx,sy = M(dx,dy)\n" }, { "answer_id": 299383, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": false, "text": "x' = x * (width' / width)\ny' = y * (height' / height)\n x' = x * cos(a) + y * sin(a)\ny' = y * cos(a) - x * sin(a)\n" }, { "answer_id": 1228131, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "point scaling(point p,float sx,float sy) {\n point s;\n\n int c[1][3];\n int a[1][3]={p.x,p.y,1};\n int b[3][3]={sx,0,0,0,sy,0,0,0,1};\n\n multmat(a,b,c);\n\n s.x=c[0][0];\n s.y=c[0][1];\n\n return s;\n}\n" }, { "answer_id": 39226234, "author": "Meta", "author_id": 978551, "author_profile": "https://Stackoverflow.com/users/978551", "pm_score": 2, "selected": false, "text": "float scaleFactor = 0.68f;\ncv::Mat original = cv::imread(path);\ncv::Mat scaled;\ncv::resize(original, scaled, cv::Size(0, 0), scaleFactor, scaleFactor, cv::INTER_LANCZOS4);\ncv::imwrite(\"new_image.jpg\", scaled);\n /// Compute a rotation matrix with respect to the center of the image\nPoint center = Point(original.size().width / 2, original.size().height / 2);\ndouble angle = -50.0;\ndouble scale = 0.6;\n\n/// Get the rotation matrix with the specifications above\nMat rot_mat( 2, 3, CV_32FC1 );\nrot_mat = getRotationMatrix2D(center, angle, scale);\n\n/// Rotate the image\nMat rotated_image;\nwarpAffine(src, rotated_image, rot_mat, src.size());\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22371/" ]
299,272
<p>Assuming I have a tree structure</p> <pre><code>UL --LI ---INPUT (checkbox) </code></pre> <p>And I want to grab the checked inputs, I would select </p> <pre><code>$('ul li input:checked') </code></pre> <p>However, I want to select the checked inputs of a specific object $myUL that doesn't have an ID.</p> <pre><code>$myUL.children('li input:checked') </code></pre> <p>returns all li's since children filters immediate children - the checked filter has no impact. </p> <p>Is there another way around this? Another descendant filter?</p>
[ { "answer_id": 299302, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": true, "text": "$myUL.find('li>input:checked')" }, { "answer_id": 3108313, "author": "Thach Lockevn", "author_id": 161471, "author_profile": "https://Stackoverflow.com/users/161471", "pm_score": 0, "selected": false, "text": "$myUL.find('li>input:checked')" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37731/" ]
299,291
<p>Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together?</p> <p>E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB"</p> <p>I want to create a new field called "Fullname" which is </p> <pre><code>Forenames + " " + Surname </code></pre> <p>So i end up with "ID", "Forename", "Surname", "DOB", "Fullname".</p> <p>I know i can do this using Linq programmatically i.e.</p> <pre><code>var results = from p in db.People select new { ID = p.ID, Forename = p.Forename, Surname = p.Surname, DOB = p.DOB, Fullname = p.Forename+ " " + p.Surname }; </code></pre> <p>Then calling something like</p> <pre><code>var resultsAfterConcat = from q in results where q.Fullname.Contains(value) select q; </code></pre> <p>However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.</p>
[ { "answer_id": 301894, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 0, "selected": false, "text": "SELECT \n1 AS [C1], \n[Extent1].[PeopleID] AS [PeopleID], \n[Extent1].[Forenames] AS [Forenames], \n[Extent1].[Surname] AS [Surname]\nFROM [dbo].[People] AS [Extent1]\nWHERE (CHARINDEX(N'Dave', [Extent1].[Forenames] + N' ' + [Extent1].[Surname])) > 0\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30317/" ]
299,296
<p>Since yesterday, I am analyzing one of our project with <a href="http://www.ndepend.com/" rel="nofollow noreferrer">Ndepend</a> (free for most of its features) and more I am using it, and more I have doubt about the real value of this type of software (code-analysis software).</p> <p>Let me explain, The system build a report about the health of the system and class by Rank every metric. I thought it would be a good starting point to do modifications but most of the top result are here because they have over 100 lines inside the class (we have big headers and we do use VS comments styles) so it's not a big deal... than the number of Afferent Coupling level (CA) is always too high and this is almost very true for Interface that we used a lot... so at this moment I do not see something wrong but NDepend seem to do not like it (if you have suggestion to improve that tell me because I do not see the need for). It's the samething for the metric called "NOC" for Number of children that most of my Interface are too high...</p> <p>For the moment, the only very useful metric is the Cyclomatic Complexity...</p> <p><strong>My question is</strong> : Do you find is worth it to analyse code with Automatic Code Analyser like NDepend? If yes, how do you filter all information that I have mentionned that doesn't really show the real health of the system?</p>
[ { "answer_id": 301894, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 0, "selected": false, "text": "SELECT \n1 AS [C1], \n[Extent1].[PeopleID] AS [PeopleID], \n[Extent1].[Forenames] AS [Forenames], \n[Extent1].[Surname] AS [Surname]\nFROM [dbo].[People] AS [Extent1]\nWHERE (CHARINDEX(N'Dave', [Extent1].[Forenames] + N' ' + [Extent1].[Surname])) > 0\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
299,304
<p>Per the Java documentation, the <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#hashCode()" rel="noreferrer">hash code</a> for a <code>String</code> object is computed as:</p> <blockquote> <pre><code>s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] </code></pre> <p>using <code>int</code> arithmetic, where <code>s[i]</code> is the <i>i</i>th character of the string, <code>n</code> is the length of the string, and <code>^</code> indicates exponentiation.</p> </blockquote> <p>Why is 31 used as a multiplier?</p> <p>I understand that the multiplier should be a relatively large prime number. So why not 29, or 37, or even 97?</p>
[ { "answer_id": 299385, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "RSB r1, r0, r0, ASL #5 ; r1 := - r0 + (r0<<5)\n" }, { "answer_id": 299748, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 10, "selected": true, "text": "31 * i == (i << 5) - i" }, { "answer_id": 884257, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "n * 31 (n << 5) - n" }, { "answer_id": 6850231, "author": "hrr", "author_id": 680410, "author_profile": "https://Stackoverflow.com/users/680410", "pm_score": 5, "selected": false, "text": "y := x + 8 * x; z := x + 4 * y y := x + 8 * x; z := x + 8 * y" }, { "answer_id": 35304979, "author": "David Ongaro", "author_id": 2727750, "author_profile": "https://Stackoverflow.com/users/2727750", "pm_score": 5, "selected": false, "text": "P(31) P(31) P(33)" }, { "answer_id": 44508855, "author": "Flow", "author_id": 194894, "author_profile": "https://Stackoverflow.com/users/194894", "pm_score": 4, "selected": false, "text": "String.hashCode() Webster's Code Strings URLs\n --------- ------------ ----\nCurrent Java Fn. 1.2509 1.2738 13.2560\nP(37) [Java] 1.2508 1.2481 1.2454\nP(65599) [Aho et al] 1.2490 1.2510 1.2450\nP(31) [K+R] 1.2500 1.2488 1.2425\nP(33) [Torek] 1.2500 1.2500 1.2453\nVo's Fn 1.2487 1.2471 1.2462\nWAIS Fn 1.2497 1.2519 1.2452\nWeinberger's Fn(MatPak) 6.5169 7.2142 30.6864\nWeinberger's Fn(24) 1.3222 1.2791 1.9732\nWeinberger's Fn(28) 1.2530 1.2506 1.2439\n" }, { "answer_id": 54739533, "author": "James Grey", "author_id": 3728901, "author_profile": "https://Stackoverflow.com/users/3728901", "pm_score": 3, "selected": false, "text": "^" }, { "answer_id": 57100339, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 3, "selected": false, "text": "31 * i == (i << 5) - i\n" }, { "answer_id": 62545515, "author": "Altan", "author_id": 4415649, "author_profile": "https://Stackoverflow.com/users/4415649", "pm_score": 1, "selected": false, "text": "hash(x) % N p = 2^n - 1\n x * p = x * (2^n - 1) = x * 2^n - x = (x << n) - x\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318/" ]
299,326
<p>I'm looking for an implementation of the <a href="http://en.wikipedia.org/wiki/Logo_programming_language" rel="nofollow noreferrer">LOGO</a> programming language that supports 'dynaturtles' - animated turtles that can programmatically change shape, speed and direction as well as detect collisions with each other or other objects in the environment.</p> <p>Back in the mists of time when the earth was new and 8 bit micros ruled supreme, <a href="http://en.wikipedia.org/wiki/Atari_LOGO" rel="nofollow noreferrer">Atari LOGO</a> did this famously well. One could create all sorts of small games and simulated environments using this technique very easily as that implementation of the language had a very well thought out, elegant syntax.</p> <p>I know about LCSI's <a href="http://www.microworlds.com/" rel="nofollow noreferrer">Microworlds</a> but I'm looking for something I can use to get some friends and their kids involved in programming without breaking my budget.</p>
[ { "answer_id": 831097, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "PR test\n ;* ##### Startdatei ######\n SETZE \"sprung.x\" 0\n SETZE \"sprung.y\" 0\n flug\nENDE\n\nPR flug\n sprung\n tasten\n flug\nENDE\n\nPR sprung\n SETZE \"sprung.x\" :sprung.x + (SIN KURS)/2\n SETZE \"sprung.y\" :sprung.y + (COS KURS)/2\n AUFXY (XKO + :sprung.x) (YKO + :sprung.y)\nENDE\n\nPR tasten\n SETZE \"t\" TASTE\n WENN :t = \"d\" DANN LI 30\n WENN :t = \"e\" DANN DZ \"Abbruch!\" AUSSTIEG\n WENN :t = \"f\" DANN RE 30\n WENN :t = \"h\" DANN sprung\n tasten\nENDE\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32514/" ]
299,332
<p>I'm doing a basic homework assignment which looks like this:</p> <pre><code> While input &lt;&gt; -1 input = CDbl(InputBox("Enter numbers to add, enter -1 to stop")) values = values + input End While </code></pre> <p>It works fine until I press 'cancel' on the input box. Then the string input is "", and I get the following error:</p> <pre><code>System.InvalidCastException {"Conversion from string "" to type 'Double' is not valid."} </code></pre> <p>I think I understand the error, I'm trying to convert using CDbl a non-numeric value. My question is what would be a more proper way to write this code? Is it the code, or just a lack of error handling?</p>
[ { "answer_id": 299353, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 3, "selected": true, "text": "Dim value as Double = Nothing\nIf Double.TryParse(InputBox(\"Enter numbers...\"), value) Then\n values = values + value\nEnd If\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28658/" ]
299,342
<p>I have a web service which has a generic function that returns a dataset from results of stored procedures... Some of the stored procedures have optional parameters where the value can be null but not all the time.</p> <p>Anyhow I am trying to pass in a parameter which has a value of DBNull.Value</p> <p>and I get this <strong>There was an error generating the XML document.</strong> back from the web service when doing so</p> <p>If I leave this parameter out it works fine... but really would like to know why DBNull.Value causes this problem.</p>
[ { "answer_id": 7518178, "author": "markhazleton", "author_id": 479571, "author_profile": "https://Stackoverflow.com/users/479571", "pm_score": 0, "selected": false, "text": "Using dtResult as New DataTable \n Using cn as SqlConnection = New SqlConnection (\"ConnectionString\") \n Using sqlcmd as SqlCommand - New SqlCommand(\"StoredProceName\", cn) with {.CommandType=CommandType.StoredProcedure}\n\n Dim sp As SqlParameter\n sp = sqlcmd.Parameters.Add(\"@Count\", SqlDbType.Int)\n sp.value = CType(Nothing, SqlTypes.SqlInt32) \n\n Using myDR as SqlDataReader = sqlcmd.ExecuteReader\n dtResult.Load(myDR)\n end using \n return dtResult \n End Using ' For sqlcmd \n cn.Close() ' Close the connection \n end using ' For cn \nend using ' For dtResult\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
299,370
<p>I'm trying to use <code>SetWindowsHookEx</code> to set up a <code>WH_SHELL</code> hook to get notified of system-wide <code>HSHELL_WINDOWCREATED</code> and <code>HSHELL_WINDOWDESTROYED</code> events. I pass 0 for the final <code>dwThreadId</code> argument which, according to <a href="http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx" rel="noreferrer">the docs</a>, should "associate the hook procedure with all existing threads running in the same desktop as the calling thread". I also pass in the handle to my DLL (<code>HInstance</code> in Delphi) for the <code>hMod</code> parameter as did all the examples I looked at.</p> <p>Yet, I only ever get notified of windows created by my own app and - more often than not - my tests result in the desktop process going down in flames once I close down my app. Before you ask, I do call <code>UnhookWindowsHookEx</code>. I also always call <code>CallNextHookEx</code> from within my handler.</p> <p>I am running my test app from a limited user account but so far I haven't found any hints indicating that this would play a role... (though that actually surprises me)</p> <p>AFAICT, I did everything by the book (obviously I didn't but so far I fail to see where).</p> <p>I'm using Delphi (2007) but that shouldn't really matter I think.</p> <p><strong>EDIT:</strong> Maybe I should have mentioned this before: I did download and try a couple of examples (though there are unfortunately not that many available for Delphi - especially none for <code>WH_SHELL</code> or <code>WH_CBT</code>). While they do not crash the system like my test app does, they still do not capture events from other processes (even though I can verify with ProcessExplorer that they get loaded into them alright). So it seems there is either something wrong with my system configuration or the examples are wrong or it is simply not possible to capture events from other processes. Can anyone enlighten me?</p> <p><strong>EDIT2:</strong> OK, here's the source of my test project.</p> <p>The DLL containing the hook procedure:</p> <pre><code>library HookHelper; uses Windows; {$R *.res} type THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall; var WndHookCallback: THookCallback; Hook: HHook; function HookProc(ACode, AWParam, ALParam: Integer): Integer; stdcall; begin Result := CallNextHookEx(Hook, ACode, AWParam, ALParam); if ACode &lt; 0 then Exit; try if Assigned(WndHookCallback) // and (ACode in [HSHELL_WINDOWCREATED, HSHELL_WINDOWDESTROYED]) then and (ACode in [HCBT_CREATEWND, HCBT_DESTROYWND]) then WndHookCallback(ACode, AWParam, ALParam); except // plop! end; end; procedure InitHook(ACallback: THookCallback); register; begin // Hook := SetWindowsHookEx(WH_SHELL, @HookProc, HInstance, 0); Hook := SetWindowsHookEx(WH_CBT, @HookProc, HInstance, 0); if Hook = 0 then begin // ShowMessage(SysErrorMessage(GetLastError)); end else begin WndHookCallback := ACallback; end; end; procedure UninitHook; register; begin if Hook &lt;&gt; 0 then UnhookWindowsHookEx(Hook); WndHookCallback := nil; end; exports InitHook, UninitHook; begin end. </code></pre> <p>And the main form of the app using the hook:</p> <pre><code>unit MainFo; interface uses Windows, SysUtils, Forms, Dialogs, Classes, Controls, Buttons, StdCtrls; type THookTest_Fo = class(TForm) Hook_Btn: TSpeedButton; Output_Lbx: TListBox; Test_Btn: TButton; procedure Hook_BtnClick(Sender: TObject); procedure Test_BtnClick(Sender: TObject); public destructor Destroy; override; end; var HookTest_Fo: THookTest_Fo; implementation {$R *.dfm} type THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall; procedure InitHook(const ACallback: THookCallback); register; external 'HookHelper.dll'; procedure UninitHook; register; external 'HookHelper.dll'; procedure HookCallback(ACode, AWParam, ALParam: Integer); stdcall; begin if Assigned(HookTest_Fo) then case ACode of // HSHELL_WINDOWCREATED: HCBT_CREATEWND: HookTest_Fo.Output_Lbx.Items.Add('created handle #' + IntToStr(AWParam)); // HSHELL_WINDOWDESTROYED: HCBT_DESTROYWND: HookTest_Fo.Output_Lbx.Items.Add('destroyed handle #' + IntToStr(AWParam)); else HookTest_Fo.Output_Lbx.Items.Add(Format('code: %d, WParam: $%x, LParam: $%x', [ACode, AWParam, ALParam])); end; end; procedure THookTest_Fo.Test_BtnClick(Sender: TObject); begin ShowMessage('Boo!'); end; destructor THookTest_Fo.Destroy; begin UninitHook; // just to make sure inherited; end; procedure THookTest_Fo.Hook_BtnClick(Sender: TObject); begin if Hook_Btn.Down then InitHook(HookCallback) else UninitHook; end; end. </code></pre>
[ { "answer_id": 308328, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "procedure THooktest_FO.UnInitClick(Sender: TObject);\nbegin\n UninitHook;\nend;\n\nprocedure THooktest_FO.InitClick(Sender: TObject);\nbegin\n InitHook(HookCallback)\nend;\n created handle #1902442\ndestroyed handle #1902442\ncreated handle #1967978\ncreated handle #7276488\n destroyed handle #1967978\n" }, { "answer_id": 308811, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "function SetWindowsHookEx(idHook: Integer; lpfn: TFNHookProc; \n hmod: HInst; dwThreadId: DWORD): HHOOK;\n hand := GetModuleHandle('hookhelper.dll');\nHook := SetWindowsHookEx(WH_SHELL, @HookProc, hand, 0);\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9784/" ]
299,382
<p>I am looking for example code that provides a unit test to serialize and deserialize an object from a memory stream. I have found <a href="https://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializablable">examples using C# 2.0</a>, however my current project uses VB.NET 1.1 (don't ask me why...), so the solution can not use generics. I am also using the NUnit framework for the unit tests.</p> <p>Thanks!</p>
[ { "answer_id": 299470, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 1, "selected": false, "text": "[Test]\npublic void ClassIsXmlSerializable()\n{\n bool exceptionWasThrown = false;\n\n try\n {\n // .. serialize object\n }\n catch(XmlSerializationException ex)\n {\n exceptionWasThrown = true;\n }\n\n Asset.IsFalse(exceptionWasThrown, \"An XmlSerializationException was thrown. The type xx is not xml serializable!\");\n}\n" }, { "answer_id": 1064003, "author": "Technobabble", "author_id": 19063, "author_profile": "https://Stackoverflow.com/users/19063", "pm_score": 3, "selected": true, "text": "<Test()> _\nPublic Sub SerializationTest()\n Dim obj As New MySerializableObject()\n 'Perform additional construction as necessary\n\n Dim obj2 As MySerializableObject\n Dim formatter As New BinaryFormatter\n Dim memoryStream As New MemoryStream()\n\n 'Run through serialization process\n formatter.Serialize(memoryStream, obj)\n memoryStream.Seek(0, SeekOrigin.Begin)\n obj2 = DirectCast(formatter.Deserialize(memoryStream), MySerializableObject)\n\n 'Test for equality using Assert methods\n Assert.AreEqual(obj.Property1, obj.Property1)\n 'etc...\nEnd Sub\n" }, { "answer_id": 1723804, "author": "Patrik Hägne", "author_id": 46187, "author_profile": "https://Stackoverflow.com/users/46187", "pm_score": 2, "selected": false, "text": "Dim obj As New MySerializableObject()\nAssert.That(obj, Is.BinarySerializable)\n Dim obj As New MySerializableObject()\nAssert.That(obj, Is.XmlSerializable)\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19063/" ]
299,387
<p>I'm serializing class which contains DateTime property.</p> <pre><code>public DateTime? Delivered { get; set; } </code></pre> <p>After serializing Delivered node contains DateTime formatted like this:</p> <pre><code>2008-11-20T00:00:00 </code></pre> <p>How can I change this property to make it look like this:</p> <pre><code>2008-11-20 00:00:00 </code></pre> <p>Thanks in advance</p>
[ { "answer_id": 299508, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 5, "selected": true, "text": "//normal DateTime accessor\n[XmlIgnore]\npublic DateTime Delivered { get; set; }\n\n//special XmlSerialization accessor\n[XmlAttribute(\"DateTime\")]\npublic string XmlDateTime\n{\n get { return this.Delivered.ToString(\"o\"); }\n set { this.Delivered = new DateTime.Parse(value); }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23280/" ]
299,390
<p>Say I have the following Objective-C class:</p> <pre><code>@interface Foo { int someNumber; NSString *someString; } </code></pre> <p>and for reasons I won't get into here, I want to use KVC to update, in a generic fashion, the values for those variables:</p> <pre><code>[f setValue:object forKey:@"someNumber"]; or [f setValue:object forKey:@"someString"];` </code></pre> <p>If <code>object</code> is a string and I'm updating the <code>someNumber</code> variable, it seems that I need to know to use an NSNumberFormatter to get an NSNumber and then Cocoa automatically converts that to an int inside <code>setValue:forKey:</code>. </p> <p>Is there any way to avoid this custom code and have Cocoa infer the conversion to an int from a string, or do I need to catch this situation each time and handle it myself?</p>
[ { "answer_id": 299496, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 2, "selected": true, "text": "id object_getClassName" }, { "answer_id": 299533, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 2, "selected": false, "text": "object integerValue NSNumber NSString - (void)setValue:(id)object forKey:(NSString *)key\n{\n if ([key isEqual:@\"someNumber\"])\n {\n someNumber = [object integerValue];\n }\n //...\n} setValue:forKey: someNumber someString" }, { "answer_id": 299914, "author": "Alex", "author_id": 35999, "author_profile": "https://Stackoverflow.com/users/35999", "pm_score": 1, "selected": false, "text": "- (void)setSomeValue:(NSInteger)aValue\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967/" ]
299,392
<p>How do I create a batch file timer to execute / call another batch through out the day Maybe on given times to run but not to run on weekends ? Must run on system times can also be .cmd to run on xp server 2003 </p>
[ { "answer_id": 493156, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 2, "selected": false, "text": "@ECHO OFF\n\n:LOOP\nECHO Waiting for 1 minute...\n PING -n 60 127.0.0.1>nul\n IF %DATE:~0,3%==Mon CALL SomeOtherFile.cmd\n IF %DATE:~0,3%==Tue CALL SomeOtherFile.cmd\n IF %DATE:~0,3%==Wed CALL SomeOtherFile.cmd\n IF %DATE:~0,3%==Thu CALL WootSomeOtherFile.cmd\n IF %DATE:~0,3%==Fri CALL SomeOtherFile.cmd\n IF %DATE:~0,3%==Sat ECHO Saturday...nothing to do.\n IF %DATE:~0,3%==Sun ECHO Sunday...nothing to do.\nGOTO LOOP\n" }, { "answer_id": 4340058, "author": "daniel11", "author_id": 524670, "author_profile": "https://Stackoverflow.com/users/524670", "pm_score": 5, "selected": false, "text": "echo.\necho Waiting For One Hour... \nTIMEOUT /T 3600 /NOBREAK\necho.\necho (Put some Other Processes Here)\necho.\npause >nul\n Timeout /t 3600 /nobreak >nul\n" }, { "answer_id": 20304417, "author": "imthegman55", "author_id": 3052884, "author_profile": "https://Stackoverflow.com/users/3052884", "pm_score": 0, "selected": false, "text": "@echo off\n:loop\nset a=60\nset /a a-1\nif a GTR 1 (\necho %a% minutes remaining...\ntimeout /t 60 /nobreak >nul\ngoto a\n) else if a LSS 1 goto finished\n:finished\n::code\n::code\n::code\npause>nul\n" }, { "answer_id": 23171891, "author": "adwait", "author_id": 3551995, "author_profile": "https://Stackoverflow.com/users/3551995", "pm_score": 1, "selected": false, "text": "@echo off\n:Start\ntitle timer\ncolor EC\necho Type in an amount of time (Seconds)\nset /p time=\n\ncolor CE\n\n:loop\ncls\nping localhost -n 2 >nul\nset /a time=%time%-1\necho %time%\nif %time% EQU 0 goto Timesup\ngoto loop\n\n:Timesup\ntitle Time Is Up!\nping localhost -n 2 >nul\nping localhost -n 2 >nul\ncls\necho The Time is up!\npause\ncls\necho Thank you for using this software.\npause\ngoto Web\ngoto Exit\n\n:Web\nrem type ur command here\n\n:Exit\nExit\ngoto Exit\n" }, { "answer_id": 35083214, "author": "nocktok toker", "author_id": 5856797, "author_profile": "https://Stackoverflow.com/users/5856797", "pm_score": 1, "selected": false, "text": "@echo off\n:Start # seting a ponter\ntitle timer #name the cmd window to \"Timer\"\necho Type in an amount of time (Seconds) \nset /p A= #wating for input from user\nset B=1 \n\ncls \n:loop \nping localhost -n 2 >nul #pinging your self for 1 second\nset /A A=A-B #sets the value A - 1\necho %A% # printing A\nif %A% EQU 0 goto Timesup #if A = 0 go to ponter Timesup eles loop it\ngoto loop\n\n:Timesup #ponter Timesup\ncls #clear the screen\nMSG * /v \"time Is Up!\" #makes a pop up saying \"time Is Up!\"\ngoto Exit #go to exit\n\n:Exit \n" }, { "answer_id": 57452475, "author": "Patrick Warren", "author_id": 9655868, "author_profile": "https://Stackoverflow.com/users/9655868", "pm_score": 1, "selected": false, "text": "SET COUNTER=0\n:loop\nSET /a COUNTER=%COUNTER%+1\nXCOPY \"Server\\*\" \"c:\\minecraft\\backups\\server_backup_%COUNTER%\" /i /s\ntimeout /t 600 /nobreak >nul\ngoto loop\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,405
<p>I'm just learning Perl.</p> <p>When is it advisable to use OO Perl instead of non-OO Perl?</p> <p>My tendency would be to always prefer OO unless the project is just a code snippet of &lt; 10 lines.</p> <p>TIA</p>
[ { "answer_id": 300117, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 5, "selected": true, "text": "DB::check ISBN::check Shape::check" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16609/" ]
299,412
<p>I love <a href="https://en.wikipedia.org/wiki/WinSCP" rel="noreferrer">WinSCP</a> for Windows. What is the best equivalent software for Linux?</p> <p>I tried to use sshfs to mount the remote file system on my local machine, but it is not as user friendly as simply launching a GUI, plus it seems to require root access on the client machine, which is not very convenient.</p> <p>Of course command-line tools such as scp are possible, but I am looking for a simple GUI.</p>
[ { "answer_id": 299516, "author": "William Brendel", "author_id": 2405, "author_profile": "https://Stackoverflow.com/users/2405", "pm_score": 6, "selected": false, "text": "sudo apt-get install filezilla\n" }, { "answer_id": 14485912, "author": "Alois Mahdal", "author_id": 835945, "author_profile": "https://Stackoverflow.com/users/835945", "pm_score": 5, "selected": false, "text": "sftp://yourhost/ ssh scp ~/.ssh/config" }, { "answer_id": 23163453, "author": "NABA", "author_id": 3550403, "author_profile": "https://Stackoverflow.com/users/3550403", "pm_score": 5, "selected": false, "text": "sudo apt-get install wine wine WinSCP.exe" }, { "answer_id": 24357492, "author": "Ivaylo Toskov", "author_id": 2572994, "author_profile": "https://Stackoverflow.com/users/2572994", "pm_score": 6, "selected": false, "text": "sudo apt-get install filezilla\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38626/" ]
299,414
<p>I have several aspx pages that can be opened either normally (full screen in browser), or called from another page as a popup (I am using Greybox, fwiw)</p> <p>If the page is opened as a popup in Greybox, I would like to NOT display the master page content (which displays common top and left menus, etc).</p> <p>As far as I know, there is no way of knowing server side if the page is a popup, this must be detected in client side javascript (in the case of Greybox, by checking window.parent.parent), and therefore the master page content must be hidden via javascript as well.</p> <p>Any ideas on how to approach this?</p>
[ { "answer_id": 299601, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 4, "selected": true, "text": "protected override void OnPreInit(EventArgs e)\n{\n base.OnPreInit(e);\n\n if(Request[\"PopUp\"] == \"Y\")\n {\n MasterPageFile = \"~/MyPopUp.master\";\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
299,416
<p>I'm working with a existing database and trying to write a sql query to get out all the account information including permission levels. This is for a security audit. We want to dump all of this information out in a readible fashion to make it easy to compare. My problem is that there is a bridge/link table for the permissions so there are multiple records per user. I want to get back results with all the permission for one user on one line. Here is an example:</p> <pre><code>Table_User: UserId UserName 1 John 2 Joe 3 James Table_UserPermissions: UserId PermissionId Rights 1 10 1 1 11 2 1 12 3 2 11 2 2 12 3 3 10 2 </code></pre> <p>PermissionID links to a table with the name of the Permission and what it does. Right is like 1 = view, 2 = modify, and etc.</p> <p>What I get back from a basic query for User 1 is:</p> <pre><code>UserId UserName PermissionId Rights 1 John 10 1 1 John 11 2 1 John 12 3 </code></pre> <p>What I would like something like this:</p> <pre><code>UserId UserName Permission1 Rights1 Permission2 Right2 Permission3 Right3 1 John 10 1 11 2 12 3 </code></pre> <p>Ideally I would like this for all users. The closest thing I've found is the Pivot function in SQL Server 2005. <a href="https://web.archive.org/web/20191230182030/http://geekswithblogs.net:80/lorint/archive/2006/08/04/87166.aspx" rel="nofollow noreferrer">Link</a> The problem with this from what I can tell is that I need to name each column for each user and I'm not sure how to get the rights level. With real data I have about 130 users and 40 different permissions.</p> <p>Is there another way with just sql that I can do this?</p>
[ { "answer_id": 299505, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "select userid, username\n, max(case when permissionid=10 then rights end) as permission10_rights\n, max(case when permissionid=11 then rights end) as permission11_rights\n, max(case when permissionid=12 then rights end) as permission12_rights\nfrom userpermissions\ngroup by userid, username;\n" }, { "answer_id": 299560, "author": "James", "author_id": 16282, "author_profile": "https://Stackoverflow.com/users/16282", "pm_score": 1, "selected": false, "text": "SELECT Table_User.userID, userName, permissionid, rights\nFROM Table_User\n LEFT JOIN Table_UserPermissions ON Table_User.userID =Table_UserPermissions.userID\nORDER BY userName\n userID = recordset[0][0]\nuserName = recordset[0][1]\nfor row in recordset:\n if userID != row[0]:\n printUserPermissions(username, user_permissions)\n user_permissions = []\n username = row[1]\n userID = row[0]\n\n user_permissions.append((row[2], row[3]))\n\nprintUserPermissions(username, user_permissions)\n" }, { "answer_id": 300762, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 2, "selected": false, "text": "select UserId, UserName, \n group_concat(PermissionId) as PermIdList,\n group_concat(Rights SEPARATOR ',') as RightsList\nfrom Table_user join Table_UserPermissions on \n Table_User.UserId = Table_UserPermissions.UserId=\nGROUP BY Table_User.UserId\n UserId UserName PermIdList RightsList\n1 John 10,11,12 1,2,3\n" }, { "answer_id": 13992502, "author": "Taryn", "author_id": 426671, "author_profile": "https://Stackoverflow.com/users/426671", "pm_score": 0, "selected": false, "text": "UNPIVOT PIVOT CREATE TABLE Table_User\n ([UserId] int, [UserName] varchar(5))\n;\n\nINSERT INTO Table_User\n ([UserId], [UserName])\nVALUES\n (1, 'John'),\n (2, 'Joe'),\n (3, 'James')\n;\n\nCREATE TABLE Table_UserPermissions\n ([UserId] int, [PermissionId] int, [Rights] int)\n;\n\nINSERT INTO Table_UserPermissions\n ([UserId], [PermissionId], [Rights])\nVALUES\n (1, 10, 1),\n (1, 11, 2),\n (1, 12, 3),\n (2, 11, 2),\n (2, 12, 3),\n (3, 10, 2)\n;\n select *\nfrom\n(\n select userid,\n username,\n value,\n col + '_'+ cast(rn as varchar(10)) col\n from\n (\n select u.userid,\n u.username,\n p.permissionid,\n p.rights,\n row_number() over(partition by u.userid \n order by p.permissionid, p.rights) rn\n from table_user u\n left join Table_UserPermissions p\n on u.userid = p.userid\n ) src\n unpivot\n (\n value\n for col in (permissionid, rights)\n ) unpiv\n) src\npivot\n(\n max(value)\n for col in (permissionid_1, rights_1, \n permissionid_2, rights_2, \n permissionid_3, rights_3)\n) piv\norder by userid\n permissionid rights DECLARE \n @query AS NVARCHAR(MAX),\n @colsPivot as NVARCHAR(MAX)\n\nselect @colsPivot = STUFF((SELECT ',' \n + quotename(c.name +'_'+ cast(t.rn as varchar(10)))\n from\n (\n select row_number() over(partition by u.userid \n order by p.permissionid, p.rights) rn\n from table_user u\n left join Table_UserPermissions p\n on u.userid = p.userid\n ) t\n cross apply sys.columns as C\n where C.object_id = object_id('Table_UserPermissions') and\n C.name not in ('UserId')\n group by c.name, t.rn\n order by t.rn\n FOR XML PATH(''), TYPE\n ).value('.', 'NVARCHAR(MAX)') \n ,1,1,'')\n\n\nset @query \n = 'select *\n from\n (\n select userid,\n username,\n value,\n col + ''_''+ cast(rn as varchar(10)) col\n from\n (\n select u.userid,\n u.username,\n p.permissionid,\n p.rights,\n row_number() over(partition by u.userid \n order by p.permissionid, p.rights) rn\n from table_user u\n left join Table_UserPermissions p\n on u.userid = p.userid\n ) src\n unpivot\n (\n value\n for col in (permissionid, rights)\n ) unpiv\n ) x1\n pivot\n (\n max(value)\n for col in ('+ @colspivot +')\n ) p\n order by userid'\n\nexec(@query)\n | USERID | USERNAME | PERMISSIONID_1 | RIGHTS_1 | PERMISSIONID_2 | RIGHTS_2 | PERMISSIONID_3 | RIGHTS_3 |\n---------------------------------------------------------------------------------------------------------\n| 1 | John | 10 | 1 | 11 | 2 | 12 | 3 |\n| 2 | Joe | 11 | 2 | 12 | 3 | (null) | (null) |\n| 3 | James | 10 | 2 | (null) | (null) | (null) | (null) |\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8664/" ]
299,433
<p>Is there a way to programatically access the DragHandleTemplate of a ReorderList (ASP.NET AJAX Control Toolkit) ... Specifically during ItemDataBound for the ReorderList, in order to change its appearance at the per item level?</p>
[ { "answer_id": 502744, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 1, "selected": false, "text": "<DragHandleTemplate>\n <div class=\"dragHandle\">\n <asp:Label ID=\"lblDragHandle\" runat=\"server\" />\n </div>\n</DragHandleTemplate>\n protected void ReorderList1_ItemDataBound(object sender, AjaxControlToolkit.ReorderListItemEventArgs e)\n{\n Label lblDragHandle = (Label)FindControlRecursive(e.Item, \"lblDragHandle\");\n lblDragHandle.Text = e.Item.ItemIndex.ToString();\n}\n\nprivate Control FindControlRecursive(Control root, string id)\n{\n if (root.ID == id)\n {\n return root;\n }\n\n foreach (Control c in root.Controls)\n {\n Control t = FindControlRecursive(c, id);\n if (t != null)\n {\n return t;\n }\n }\n\n return null;\n}\n" }, { "answer_id": 5835396, "author": "NateMpls", "author_id": 367807, "author_profile": "https://Stackoverflow.com/users/367807", "pm_score": 1, "selected": false, "text": " private Control FindControlRecursive(Control root, string id)\n {\n return root.ID == id\n ? root\n : (root.Controls.Cast<Control>().Select(c => FindControlRecursive(c, id)))\n .FirstOrDefault(t => t != null);\n }\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36263/" ]
299,439
<p>I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal much.</p>
[ { "answer_id": 1277101, "author": "Alexey Romanov", "author_id": 9204, "author_profile": "https://Stackoverflow.com/users/9204", "pm_score": 5, "selected": true, "text": "public ICollection GetData(Nullable<int> id, string xml, ICollection col)\n{\n // Check all preconditions:\n id.Requires(\"id\")\n .IsNotNull() // throws ArgumentNullException on failure\n .IsInRange(1, 999) // ArgumentOutOfRangeException on failure\n .IsNotEqualTo(128); // throws ArgumentException on failure\n\n xml.Requires(\"xml\")\n .StartsWith(\"<data>\") // throws ArgumentException on failure\n .EndsWith(\"</data>\"); // throws ArgumentException on failure\n\n col.Requires(\"col\")\n .IsNotNull() // throws ArgumentNullException on failure\n .IsEmpty(); // throws ArgumentException on failure\n\n // Do some work\n\n // Example: Call a method that should not return null\n object result = BuildResults(xml, col);\n\n // Check all postconditions:\n result.Ensures(\"result\")\n .IsOfType(typeof(ICollection)); // throws PostconditionException on failure\n\n return (ICollection)result;\n}\n public static void Copy<T>(T[] dst, long dstOffset, T[] src, long srcOffset, long length)\n{\n Validate.Begin()\n .IsNotNull(dst, \"dst\")\n .IsNotNull(src, \"src\")\n .Check()\n .IsPositive(length)\n .IsIndexInRange(dst, dstOffset, \"dstOffset\")\n .IsIndexInRange(dst, dstOffset + length, \"dstOffset + length\")\n .IsIndexInRange(src, srcOffset, \"srcOffset\")\n .IsIndexInRange(src, srcOffset + length, \"srcOffset + length\")\n .Check();\n\n for (int di = dstOffset; di < dstOffset + length; ++di)\n dst[di] = src[di - dstOffset + srcOffset];\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656/" ]
299,441
<p>I have a simple class in my WCF service that doesn't seem to be showing up properly for the client that accesses my WCF.</p> <p>My class has 4 public properties that are of type string.</p> <p>I marked the class with [DataContract()] and each member with [DataMember].</p> <p>Why is my constructor not visible? Is there a special [attribute] for constructors?</p>
[ { "answer_id": 299455, "author": "Brian Genisio", "author_id": 36687, "author_profile": "https://Stackoverflow.com/users/36687", "pm_score": 3, "selected": false, "text": "public partial class SomeDataItem\n{\n public SomeDataItem(int a, int b)\n {\n A = a;\n B = b;\n }\n}\n" }, { "answer_id": 2201167, "author": "Lance Larsen - Microsoft MVP", "author_id": 88665, "author_profile": "https://Stackoverflow.com/users/88665", "pm_score": 3, "selected": false, "text": "[DataContract]\npublic class MyClassWithSpecialInitialization\n{\n List<string> myList;\n string str1;\n [DataMember]\n public string Str1\n {\n get { return str1; }\n set\n {\n this.myList.Add(value);\n str1 = value;\n }\n }\n string str2;\n [DataMember]\n public string Str2\n {\n get { return str2; }\n set\n {\n this.myList.Add(value);\n str2 = value;\n }\n }\n public MyClassWithSpecialInitialization()\n {\n this.myList = new List<string>();\n }\n [OnDeserializing]\n public void OnDeserializing(StreamingContext context)\n {\n Console.WriteLine(\"Before deserializing the fields\");\n this.myList = new List<string>();\n }\n [OnDeserialized]\n public void OnDeserialized(StreamingContext context)\n {\n Console.WriteLine(\"After deserializing the fields... myList should be populated with the values of str1 and str2\");\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
[ { "answer_id": 299462, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 6, "selected": true, "text": "os.chdir(owd)\n" }, { "answer_id": 300204, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 4, "selected": false, "text": "os.chdir(owd) try:finally with: return def run(): \n owd = os.getcwd()\n try:\n #first change dir to build_dir path\n os.chdir(testDir)\n #run jar from test directory\n os.system(cmd)\n finally:\n #change dir back to original working directory (owd)\n os.chdir(owd)\n" }, { "answer_id": 5963196, "author": "eagle3ye", "author_id": 748508, "author_profile": "https://Stackoverflow.com/users/748508", "pm_score": 2, "selected": false, "text": "import os\n\nos.getcwd()\n\nos.chdir('C:\\\\')\n" }, { "answer_id": 37996581, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 6, "selected": false, "text": "from contextlib import contextmanager\n\n@contextmanager\ndef cwd(path):\n oldpwd = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(oldpwd)\n os.chdir('/tmp') # for testing purposes, be in a known directory\nprint(f'before context manager: {os.getcwd()}')\nwith cwd('/'):\n # code inside this block, and only inside this block, is in the new directory\n print(f'inside context manager: {os.getcwd()}')\nprint(f'after context manager: {os.getcwd()}')\n before context manager: /tmp\ninside context manager: /\nafter context manager: /tmp\n cd - with cwd(testDir):\n os.system(cmd)\n subprocess.call() os.system() # note: better to modify this to not need shell=True if possible\nsubprocess.call(cmd, cwd=testDir, shell=True)\n subprocess.run call cwd" }, { "answer_id": 64608699, "author": "Nzbuu", "author_id": 21322, "author_profile": "https://Stackoverflow.com/users/21322", "pm_score": 2, "selected": false, "text": "subprocess run popen cwd def run(): \n #run jar from test directory\n subprocess.run(cmd, cwd=testDir)\n" }, { "answer_id": 73933834, "author": "Vladimir Vilimaitis", "author_id": 11010254, "author_profile": "https://Stackoverflow.com/users/11010254", "pm_score": 0, "selected": false, "text": "from collections.abc import Callable\nfrom functools import wraps\nfrom typing import ParamSpec, TypeVar\n\n\nT = TypeVar('T')\nP = ParamSpec('P')\n \n \ndef enter_subdir(subdir: str) -> Callable[[Callable[P, T]], Callable[P, T]]:\n \"\"\"During the execution of a function, temporarily enter a subdirectory.\"\"\"\n\n def decorator(function: Callable[P, T]) -> Callable[P, T]:\n @wraps(function)\n def wrapper(*args, **kwargs) -> T:\n os.makedirs(subdir, exist_ok=True)\n os.chdir(subdir)\n result = function(*args, **kwargs)\n os.chdir(\"..\")\n return result\n\n return wrapper\n\n return decorator\n" }, { "answer_id": 74535480, "author": "S.B", "author_id": 13944524, "author_profile": "https://Stackoverflow.com/users/13944524", "pm_score": 0, "selected": false, "text": "contextlib.chdir from contextlib import chdir\nfrom os import getcwd\n\nprint(f\"Before: {getcwd()}\")\nwith chdir(\"/\"):\n print(f\"inside: {getcwd()}\")\nprint(f\"after: {getcwd()}\")\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
299,490
<p>I need to query Active Directory for a list of users whose password is about to expire. The obvious (and easy) way to do this is with:</p> <pre><code>dsquery user -stalepwd n </code></pre> <p>The problem is that I need to add additional filters to only look for users who are in certain security groups. This is hard to do with the "dsquery user" syntax that has the built-in -stalepwd option, so I've been using the "dsquery * -filter" option which allows you to use LDAP query syntax. Unfortunately, while its relatively easy to do apply the other filters with an LDAP query, I'm having trouble filtering users who have a password age greater than n.</p> <p>Does anyone know the syntax (or if it is even possible) to filter for old passwords using the "dsquery * -filter" method instead of the "dsquery user -stalepwd" method.</p>
[ { "answer_id": 300169, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 2, "selected": false, "text": "&(objectCategory=user)(memberof=CN=User Group,OU=Test,DC=foo,dc=com)\n" }, { "answer_id": 300227, "author": "Alan", "author_id": 37843, "author_profile": "https://Stackoverflow.com/users/37843", "pm_score": 2, "selected": false, "text": "(&(objectClass=person)(objectClass=User)(pwdLastSet<=n))\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,495
<p>I have a <a href="http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JPanel.html" rel="noreferrer">JPanel</a> to which I'd like to add JPEG and PNG images that I generate on the fly.</p> <p>All the examples I've seen so far in the <a href="http://java.sun.com/docs/books/tutorial/uiswing/" rel="noreferrer">Swing Tutorials</a>, specially in the <a href="http://java.sun.com/docs/books/tutorial/uiswing/examples/components/" rel="noreferrer">Swing examples</a> use <code>ImageIcon</code>s.</p> <p>I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.</p> <ol> <li>Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?</li> <li>What's the <em>usual</em> way of doing it?</li> <li>How to add an image to a JPanel without using the ImageIcon class?</li> </ol> <p><strong>Edit</strong>: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...</p>
[ { "answer_id": 299545, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 3, "selected": false, "text": "protected void paintComponent(Graphics gc) {\n super.paintComponent(gc);\n\n Dimension cs=getSize(); // component size\n\n gc=gc.create();\n gc.clipRect(insets.left,insets.top,(cs.width-insets.left-insets.right),(cs.height-insets.top-insets.bottom));\n if(mmImage!=null) { gc.drawImage(mmImage,(((cs.width-mmSize.width)/2) +mmHrzShift),(((cs.height-mmSize.height)/2) +mmVrtShift),null); }\n if(tlImage!=null) { gc.drawImage(tlImage,(insets.left +tlHrzShift),(insets.top +tlVrtShift),null); }\n if(trImage!=null) { gc.drawImage(trImage,(cs.width-insets.right-trSize.width+trHrzShift),(insets.top +trVrtShift),null); }\n if(blImage!=null) { gc.drawImage(blImage,(insets.left +blHrzShift),(cs.height-insets.bottom-blSize.height+blVrtShift),null); }\n if(brImage!=null) { gc.drawImage(brImage,(cs.width-insets.right-brSize.width+brHrzShift),(cs.height-insets.bottom-brSize.height+brVrtShift),null); }\n }\n" }, { "answer_id": 299547, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": false, "text": "ImageIcon JPanel paintComponent" }, { "answer_id": 299555, "author": "Brendan Cashman", "author_id": 5814, "author_profile": "https://Stackoverflow.com/users/5814", "pm_score": 9, "selected": true, "text": "import java.awt.Graphics;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.imageio.ImageIO;\nimport javax.swing.JPanel;\n\npublic class ImagePanel extends JPanel{\n\n private BufferedImage image;\n\n public ImagePanel() {\n try { \n image = ImageIO.read(new File(\"image name and path\"));\n } catch (IOException ex) {\n // handle exception...\n }\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters \n }\n\n}\n" }, { "answer_id": 299643, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "JPanel JComponent ImageIcon MediaTracker ImageObserver" }, { "answer_id": 299669, "author": "Thomas Jones-Low", "author_id": 23030, "author_profile": "https://Stackoverflow.com/users/23030", "pm_score": 3, "selected": false, "text": "Class MapIcon implements Icon {...}\n Class MapIcon extends ImageIcon {...}\n Class MapLabel extends Scrollable, MouseMotionListener {...}\n MapIcon map = new MapIcon (); \nMapLabel mapLabel = new MapLabel (map);\nJScrollPane scrollPane = new JScrollPane();\n\nscrollPane.getViewport ().add (mapLabel);\n" }, { "answer_id": 2706730, "author": "Fred Haslam", "author_id": 194980, "author_profile": "https://Stackoverflow.com/users/194980", "pm_score": 9, "selected": false, "text": "BufferedImage myPicture = ImageIO.read(new File(\"path-to-file\"));\nJLabel picLabel = new JLabel(new ImageIcon(myPicture));\nadd(picLabel);\n" }, { "answer_id": 4537073, "author": "shawalli", "author_id": 439756, "author_profile": "https://Stackoverflow.com/users/439756", "pm_score": 5, "selected": false, "text": "BufferedImage wPic = ImageIO.read(this.getClass().getResource(\"snow.png\"));\nJLabel wIcon = new JLabel(new ImageIcon(wPic));\n" }, { "answer_id": 16379229, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "JLabel imgLabel = new JLabel(new ImageIcon(\"path_to_image.png\"));\n" }, { "answer_id": 32871981, "author": "Filipe Brito", "author_id": 4744263, "author_profile": "https://Stackoverflow.com/users/4744263", "pm_score": 3, "selected": false, "text": " JPanel jPanel = new JPanel(); \n jPanel.add(new JLabel(new ImageIcon(getClass().getClassLoader().getResource(\"resource/images/polygon.jpg\"))));\n" }, { "answer_id": 36685782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "JFrame snakeFrame = new JFrame();\nsnakeFrame.setBounds(100, 200, 800, 800);\nsnakeFrame.setVisible(true);\nsnakeFrame.add(new JLabel(new ImageIcon(\"Images/Snake.png\")));\nsnakeFrame.pack();\n" }, { "answer_id": 48943160, "author": "Muskovets", "author_id": 7013460, "author_profile": "https://Stackoverflow.com/users/7013460", "pm_score": 3, "selected": false, "text": "Component ImageIO File f = new File(\"hello.jpg\");\nJLabel imgLabel = new JLabel(new ImageIcon(file.getName()));\n" }, { "answer_id": 49204158, "author": "Gee Bee", "author_id": 5903395, "author_profile": "https://Stackoverflow.com/users/5903395", "pm_score": 2, "selected": false, "text": "@Override\nprotected void paintComponent(Graphics g) {\n super.paintComponent(g);\n g.drawImage(image, 0, 0, this); \n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15649/" ]
299,497
<p>I've created a windows form control which works successfully hosted in Internet Explorer. I'd like to give it an event and be able to respond to the event through javascript. I found a link that talks about it <a href="http://msdn.microsoft.com/en-ca/magazine/cc301932.aspx" rel="nofollow noreferrer">here</a>. It shows me how to create the interfaces but I'm not sure how to fire the event from my control? </p> <p>Here's my code snippetS:</p> <pre><code>//Control Code: public class CardReader : Panel,ICardReaderEvents, ICardReaderProperties { public void Error() { } public void Success() { } } //Interface for events [Guid("DD0C202B-12B4-4457-9FC6-05F88A6E8BC5")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface ICardReaderEvents { [DispId(0x60020000)] void Error(); [DispId(0x60020001)] void Success(); } //Interface for public properties/methods public interface ICardReaderProperties { ... } //JavaScript to handle events &lt;SCRIPT FOR="CardReader1" EVENT="Error"&gt; window.status = "Error..."; &lt;/SCRIPT&gt; &lt;SCRIPT FOR="CardReader1" EVENT="Success"&gt; window.alert("Success"); window.status = ""; &lt;/SCRIPT&gt; </code></pre>
[ { "answer_id": 299551, "author": "Brian Genisio", "author_id": 36687, "author_profile": "https://Stackoverflow.com/users/36687", "pm_score": 1, "selected": false, "text": "public event Error;\npublic event Success;\n\nprotected void OnError()\n{\n if(Error != null)\n Error();\n}\n\nprotected void OnSuccess()\n{\n if(Success != null)\n Success();\n}\n" }, { "answer_id": 299857, "author": "Brian Genisio", "author_id": 36687, "author_profile": "https://Stackoverflow.com/users/36687", "pm_score": 0, "selected": false, "text": "<object id=\"CR\" ...></object>\n\n<script type=\"text/javascript\">\n function CR::Error()\n {\n alert(\"Error!\");\n }\n\n function CR::Success()\n {\n alert(\"Success\");\n }\n</script>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
299,504
<p>I'm trying to use cygwin sqlplus to connect to a remote oracle installation located at myserver.mycompany.com port 1530. When I try</p> <pre><code>sqlplus username@myserver.mycompany.com:1530/orcl </code></pre> <p>I get the error:</p> <pre><code>ORA-12154: TNS:could not resolve the connect identifier specified </code></pre> <p>When I set <code>ORACLE_HOME</code> to /<code>cygdrive/c/oracle/product/10.2.0/client_1</code>, I get a different error:</p> <pre><code>Error 6 initializing SQL*Plus Message file sp1&lt;lang&gt;.msb not found SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory </code></pre> <p>I can telnet to the server's port 1530, and the SQL Developer installed locally is also able to connect to the database. What am I doing wrong?</p>
[ { "answer_id": 299709, "author": "MCS", "author_id": 1094969, "author_profile": "https://Stackoverflow.com/users/1094969", "pm_score": 0, "selected": false, "text": "ORACLE_HOME ORACLE_SID net_service_name" }, { "answer_id": 29122954, "author": "Sina", "author_id": 4685386, "author_profile": "https://Stackoverflow.com/users/4685386", "pm_score": 0, "selected": false, "text": "/cygdrive/d /cygdrive/c d:/ c:/ sqlplus /cygdrive/DriveLetter" }, { "answer_id": 36891705, "author": "Izzy", "author_id": 2533433, "author_profile": "https://Stackoverflow.com/users/2533433", "pm_score": 2, "selected": false, "text": "$ORACLE_SID $TNS_ADMIN $PATH /drives/c/… .bashrc export ORACLE_HOME=c:\\\\Oracle\\\\product\\\\12.1.0\\\\dbhome_1\nexport TNS_ADMIN=d:\\\\Oracle\\TNSAdmin\nexport PATH=$PATH:$(cygpath -u $ORACLE_HOME)/BIN\n tnsping sqlplus" }, { "answer_id": 38004225, "author": "user3073309", "author_id": 3073309, "author_profile": "https://Stackoverflow.com/users/3073309", "pm_score": 0, "selected": false, "text": "ORACLE_HOME PATH %ORACLE_HOME%\\bin sqlplus username/password@your_define_tnsname ORACLE PATH" }, { "answer_id": 71710057, "author": "Tamás Tapsonyi", "author_id": 18667715, "author_profile": "https://Stackoverflow.com/users/18667715", "pm_score": 0, "selected": false, "text": "export TNS_ADMIN=$(cygpath -m $TNS_ADMIN)\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1094969/" ]
299,512
<p>What steps do I take? Any gotchas to be aware of or tips to enhance the IDE experience that are specific to SQL Server when using Emacs?</p>
[ { "answer_id": 299816, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 6, "selected": true, "text": "M-x sql-ms RET\nM-x sql-mode \n select 'foo' as bar\n select 'foo' as bar\ngo\n bar \n ----- \n foo\n\n(1 row affected)\n C-c C-s go RET\n" }, { "answer_id": 6894794, "author": "fangzhzh", "author_id": 415673, "author_profile": "https://Stackoverflow.com/users/415673", "pm_score": 2, "selected": false, "text": "M-x toggle-truncate-lines\n select left(columnName, 25) from table\n" }, { "answer_id": 32300987, "author": "Pliny Suetonious", "author_id": 4147474, "author_profile": "https://Stackoverflow.com/users/4147474", "pm_score": 1, "selected": false, "text": "M-x sql-mysql (setq sql-mysql-program \"/usr/local/mysql/bin/mysql\")" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
299,515
<p>In C# is there a technique using reflection to determine if a method has been added to a class as an extension method?</p> <p>Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class?</p> <pre><code>public static class StringExtensions { public static string Reverse(this string value) { char[] cArray = value.ToCharArray(); Array.Reverse(cArray); return new string(cArray); } } </code></pre> <p>We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer. One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.</p>
[ { "answer_id": 299526, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "ExtensionAttribute ExtensionAttribute using System;\nusing System.Runtime.CompilerServices;\nusing System.Reflection;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic static class FirstExtensions\n{\n public static void Foo(this string x) {}\n public static void Bar(string x) {} // Not an ext. method\n public static void Baz(this int x) {} // Not on string\n}\n\npublic static class SecondExtensions\n{\n public static void Quux(this string x) {}\n}\n\npublic class Test\n{\n static void Main()\n {\n Assembly thisAssembly = typeof(Test).Assembly;\n foreach (MethodInfo method in GetExtensionMethods(thisAssembly,\n typeof(string)))\n {\n Console.WriteLine(method);\n }\n }\n\n static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly,\n Type extendedType)\n {\n var query = from type in assembly.GetTypes()\n where type.IsSealed && !type.IsGenericType && !type.IsNested\n from method in type.GetMethods(BindingFlags.Static\n | BindingFlags.Public | BindingFlags.NonPublic)\n where method.IsDefined(typeof(ExtensionAttribute), false)\n where method.GetParameters()[0].ParameterType == extendedType\n select method;\n return query;\n }\n}\n" }, { "answer_id": 299598, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "string rev = myStr.Reverse();\n string rev = StringExtensions.Reverse(myStr);\n" }, { "answer_id": 299777, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "CustomerExtension.Foo(myCustomer);\n" }, { "answer_id": 8016708, "author": "Drakarah", "author_id": 694640, "author_profile": "https://Stackoverflow.com/users/694640", "pm_score": 3, "selected": false, "text": "public static IEnumerable<KeyValuePair<Type, MethodInfo>> GetExtensionMethodsDefinedInType(this Type t)\n{\n if (!t.IsSealed || t.IsGenericType || t.IsNested)\n return Enumerable.Empty<KeyValuePair<Type, MethodInfo>>();\n\n var methods = t.GetMethods(BindingFlags.Public | BindingFlags.Static)\n .Where(m => m.IsDefined(typeof(ExtensionAttribute), false));\n\n List<KeyValuePair<Type, MethodInfo>> pairs = new List<KeyValuePair<Type, MethodInfo>>();\n foreach (var m in methods)\n {\n var parameters = m.GetParameters();\n if (parameters.Length > 0)\n {\n if (parameters[0].ParameterType.IsGenericParameter)\n {\n if (m.ContainsGenericParameters)\n {\n var genericParameters = m.GetGenericArguments();\n Type genericParam = genericParameters[parameters[0].ParameterType.GenericParameterPosition];\n foreach (var constraint in genericParam.GetGenericParameterConstraints())\n pairs.Add(new KeyValuePair<Type, MethodInfo>(parameters[0].ParameterType, m));\n }\n }\n else\n pairs.Add(new KeyValuePair<Type, MethodInfo>(parameters[0].ParameterType, m));\n }\n }\n\n return pairs;\n}\n public List<MethodInfo> GetExtensionMethodsOf(Type t)\n{\n List<MethodInfo> methods = new List<MethodInfo>();\n Type cur = t;\n while (cur != null)\n {\n\n TypeInfo tInfo;\n if (typeInfo.TryGetValue(cur.GUID, out tInfo))\n methods.AddRange(tInfo.ExtensionMethods);\n\n\n foreach (var iface in cur.GetInterfaces())\n {\n if (typeInfo.TryGetValue(iface.GUID, out tInfo))\n methods.AddRange(tInfo.ExtensionMethods);\n }\n\n cur = cur.BaseType;\n }\n return methods;\n}\n private Dictionary<Guid, TypeInfo> typeInfo = new Dictionary<Guid, TypeInfo>();\n TypeInfo public class TypeInfo\n{\n public TypeInfo()\n {\n ExtensionMethods = new List<MethodInfo>();\n }\n\n public List<ConstructorInfo> Constructors { get; set; }\n\n public List<FieldInfo> Fields { get; set; }\n public List<PropertyInfo> Properties { get; set; }\n public List<MethodInfo> Methods { get; set; }\n\n public List<MethodInfo> ExtensionMethods { get; set; }\n}\n" }, { "answer_id": 8793755, "author": "Stelzi79", "author_id": 965953, "author_profile": "https://Stackoverflow.com/users/965953", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\nnamespace System\n{\n public static class TypeExtension\n {\n /// <summary>\n /// This Methode extends the System.Type-type to get all extended methods. It searches hereby in all assemblies which are known by the current AppDomain.\n /// </summary>\n /// <remarks>\n /// Insired by Jon Skeet from his answer on http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify-extension-methods\n /// </remarks>\n /// <returns>returns MethodInfo[] with the extended Method</returns>\n\n public static MethodInfo[] GetExtensionMethods(this Type t)\n {\n List<Type> AssTypes = new List<Type>();\n\n foreach (Assembly item in AppDomain.CurrentDomain.GetAssemblies())\n {\n AssTypes.AddRange(item.GetTypes());\n }\n\n var query = from type in AssTypes\n where type.IsSealed && !type.IsGenericType && !type.IsNested\n from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)\n where method.IsDefined(typeof(ExtensionAttribute), false)\n where method.GetParameters()[0].ParameterType == t\n select method;\n return query.ToArray<MethodInfo>();\n }\n\n /// <summary>\n /// Extends the System.Type-type to search for a given extended MethodeName.\n /// </summary>\n /// <param name=\"MethodeName\">Name of the Methode</param>\n /// <returns>the found Methode or null</returns>\n public static MethodInfo GetExtensionMethod(this Type t, string MethodeName)\n {\n var mi = from methode in t.GetExtensionMethods()\n where methode.Name == MethodeName\n select methode;\n if (mi.Count<MethodInfo>() <= 0)\n return null;\n else\n return mi.First<MethodInfo>();\n }\n }\n}\n Type t = typeof(Type);\nMethodInfo[] extendedMethods = t.GetExtensionMethods();\nMethodInfo extendedMethodInfo = t.GetExtensionMethod(\"GetExtensionMethods\");\n" }, { "answer_id": 40163048, "author": "billy", "author_id": 384701, "author_profile": "https://Stackoverflow.com/users/384701", "pm_score": 0, "selected": false, "text": "void Main()\n{\n var test = new Test();\n var testWithMethod = new TestWithExtensionMethod();\n Tools.IsExtensionMethodCall(() => test.Method()).Dump();\n Tools.IsExtensionMethodCall(() => testWithMethod.Method()).Dump();\n}\n\npublic class Test \n{\n public void Method() { }\n}\n\npublic class TestWithExtensionMethod\n{\n}\n\npublic static class Extensions\n{\n public static void Method(this TestWithExtensionMethod test) { }\n}\n\npublic static class Tools\n{\n public static MethodInfo GetCalledMethodInfo(Expression<Action> expr)\n {\n var methodCall = expr.Body as MethodCallExpression;\n return methodCall.Method;\n }\n\n public static bool IsExtensionMethodCall(Expression<Action> expr)\n {\n var methodInfo = GetCalledMethodInfo(expr);\n return methodInfo.IsStatic;\n }\n}\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27887/" ]
299,529
<p>I'm using Apache JMeter 2.3, which now supports "attempt HTTPS spoofing" under the Proxy Server element. </p> <p>I've tried this on several different servers, and have had no success. Has anyone been able to successfully record from an HTTPS source with this setting?</p> <p>Or barring successfully recording, can anyone share a work-around? When available, I simply have HTTPS turned off at the server level, but this is not always feasible. Thoughts?</p>
[ { "answer_id": 49614949, "author": "UBIK LOAD PACK", "author_id": 460802, "author_profile": "https://Stackoverflow.com/users/460802", "pm_score": 3, "selected": false, "text": "8888 File -> Templates -> Recording -> Create\n Root CA Certificate" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
299,536
<p>Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column.</p> <p>The only way to add subItems to a ListViewItem I found are:</p> <pre><code>listviewitem.SubItems.Add("1"); </code></pre> <p>I would like to avoid parsing these strings to get the int representation for every sort!</p>
[ { "answer_id": 299572, "author": "Mariusz", "author_id": 13541, "author_profile": "https://Stackoverflow.com/users/13541", "pm_score": 1, "selected": false, "text": ".Text int a = 0;\nlistView1.Items.Add(a.ToString());\n int a = Convert.ToInt32(listView1.Items[0].SubItems[0].Text);\n DataTime String ListView" }, { "answer_id": 299968, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": true, "text": "private void setListItem(int row, int column, int value) {\n ListViewItem.ListViewSubItem item = listView1.Items[row].SubItems[column];\n item.Tag = value;\n item.Text = value.ToString();\n}\nprivate int getListItem(int row, int column) {\n return (int)listView1.Items[row].SubItems[column].Tag;\n}\n" }, { "answer_id": 40690060, "author": "Vipul Patel", "author_id": 7181343, "author_profile": "https://Stackoverflow.com/users/7181343", "pm_score": 0, "selected": false, "text": "Compare public int Compare(object x, object y)\n{\n //(...)\n switch (ColumnToSort)\n {\n case 2:\n compareResult = objectComparer.Compare(DateTime.Parse(listviewX.SubItems[ColumnToSort].Text), DateTime.Parse(listviewY.SubItems[ColumnToSort].Text));\n break;\n case 3:\n compareResult = objectComparer.Compare(float.Parse(listviewX.SubItems[ColumnToSort].Text.Replace(\"kb\", \"\").Replace(\"mb\", \"\")), float.Parse(listviewY.SubItems[ColumnToSort].Text.Replace(\"kb\", \"\").Replace(\"mb\", \"\")));\n break;\n\n default:\n compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);\n break;\n }\n //(...)\n} \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ]
299,546
<p>I can query the AD and find all the IIS sites and their virtual directories, now I need to be able to update those home directories and save the changes.</p> <p>After I fetch the directory entry I can display the site path using <code>$site.Path</code>, however setting it doesn't seem to have any effect. It never changes the actual stored path. </p> <p>I have tried <code>$site.Path = &lt;new path&gt;</code> and <code>$site.Put( "Path", &lt;new path&gt; )</code> but neither have these seem to be affecting the stored path.</p> <pre><code> $site = $iis.psbase.children | where {$_.keyType -eq "iiswebserver"} | where {$_.psbase.properties.servercomment -eq $siteConfig.name }; $s = [ADSI]($site.psbase.path + "/ROOT"); $s.Path # $s.Path = $siteConfig.path # $s.Put("Path", $siteConfig.path ) $s.psbase.CommitChanges() </code></pre>
[ { "answer_id": 299561, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 1, "selected": true, "text": " $s.psbase.properties.path[0] = $siteConfig.path\n $s.psbase.CommitChanges()\n" }, { "answer_id": 5463780, "author": "Glennular", "author_id": 14753, "author_profile": "https://Stackoverflow.com/users/14753", "pm_score": 4, "selected": false, "text": "Import-Module WebAdministration\nSet-ItemProperty 'IIS:\\Sites\\Default Web Site\\' -name physicalPath -value $siteConfig.path\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24279/" ]
299,548
<p>In the helpfile entry for TDBComboBox, it says that the text of the selected option becomes the new value for the field. Is there any similar control that goes by ItemIndex instead of text? (To represent an enumerated type, for example.)</p>
[ { "answer_id": 300011, "author": "vrad", "author_id": 12891, "author_profile": "https://Stackoverflow.com/users/12891", "pm_score": 2, "selected": false, "text": "procedure TForm1.DBComboBox1DrawItem(Control: TWinControl; Index: Integer;\n Rect: TRect; State: TOwnerDrawState);\nbegin\n with (Sender as TDBComboBox).Canvas do\n begin\n FillRect(Rect);\n TextRect(Rect, Rect.Left+1, Rect.Top+1, MyValueDescriptions[Index]);\n end;\nend;\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
299,553
<p>I'm using .NET 2.0, and a recent code change has invalidated my previous Assert.AreEqual call (which compared two strings of XML). Only one element of the XML is actually different in the new codebase, so my hope is that a comparison of all the other elements will give me the result I want. The comparison needs to be done programmatically, since it's part of a unit test.</p> <p>At first, I was considering using a couple instances of XmlDocument. But then I found this: <a href="http://drowningintechnicaldebt.com/blogs/scottroycraft/archive/2007/05/06/comparing-xml-files.aspx" rel="nofollow noreferrer">http://drowningintechnicaldebt.com/blogs/scottroycraft/archive/2007/05/06/comparing-xml-files.aspx</a></p> <p>It looks like it might work, but I was interested in Stack Overflow feedback in case there's a better way.</p> <p>I'd like to avoid adding another dependency for this if at all possible.</p> <h2>Similar questions</h2> <ul> <li><a href="https://stackoverflow.com/questions/3552648/is-there-an-xml-asserts-for-nunit">Is there an XML asserts for NUnit?</a></li> <li><a href="https://stackoverflow.com/questions/167946/how-would-you-compare-two-xml-documents">How would you compare two XML Documents?</a></li> </ul>
[ { "answer_id": 299607, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "xml <MyElement></MyElmennt> <MyElment/> xml xml .Net" }, { "answer_id": 299725, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 2, "selected": false, "text": " XmlDocument doc = new XmlDocument( \"Testdoc.xml\" );\n XPathNavigator nav = doc.CreateNavigator();\n AssertNodeValue( nav, \"/root/foo\", \"foo_val\" );\n AssertNodeCount( nav, \"/root/bar\", 6 )\n\n private static void AssertNodeValue(XPathNavigator nav,\n string xpath, string expected_val)\n {\n XPathNavigator node = nav.SelectSingleNode(xpath, nav);\n Assert.IsNotNull(node, \"Node '{0}' not found\", xpath);\n Assert.AreEqual( expected_val, node.Value );\n }\n\n private static void AssertNodeExists(XPathNavigator nav,\n string xpath)\n {\n XPathNavigator node = nav.SelectSingleNode(xpath, nav);\n Assert.IsNotNull(node, \"Node '{0}' not found\", xpath);\n }\n\n private static void AssertNodeDoesNotExist(XPathNavigator nav,\n string xpath)\n {\n XPathNavigator node = nav.SelectSingleNode(xpath, nav);\n Assert.IsNull(node, \"Node '{0}' found when it should not exist\", xpath);\n }\n\n private static void AssertNodeCount(XPathNavigator nav, string xpath, int count)\n {\n XPathNodeIterator nodes = nav.Select( xpath, nav );\n Assert.That( nodes.Count, Is.EqualTo( count ) );\n }\n" }, { "answer_id": 300243, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 0, "selected": false, "text": "IEqualityComparer and/or IEqualityComparer<T> IEnumerable<T>.Contains\nIEnumerable<T>.Equals\nThe constructior of a Dictionary etc etc\n" }, { "answer_id": 303746, "author": "Scott Lawrence", "author_id": 3475, "author_profile": "https://Stackoverflow.com/users/3475", "pm_score": 0, "selected": false, "text": "private static void ValidateResult(string validationXml, XPathNodeIterator iterator, params string[] excludedElements)\n {\n while (iterator.MoveNext())\n {\n if (!((IList<string>)excludedElements).Contains(iterator.Current.Name))\n {\n Assert.IsTrue(validationXml.Contains(iterator.Current.Value), \"{0} is not the right value for {1}.\", iterator.Current.Value, iterator.Current.Name);\n }\n }\n }\n XPathNavigator nav = xdoc.CreateNavigator();\n XPathExpression expression = XPathExpression.Compile(\"/blah/*\");\n XPathNodeIterator iterator = nav.Select(expression);\n" }, { "answer_id": 36931305, "author": "Johan Larsson", "author_id": 1069200, "author_profile": "https://Stackoverflow.com/users/1069200", "pm_score": 1, "selected": false, "text": "[Test]\npublic void Foo()\n{\n ...\n XmlAssert.Equal(expected, actual, XmlAssertOptions.IgnoreDeclaration | XmlAssertOptions.IgnoreNamespaces);\n}\n" }, { "answer_id": 58596292, "author": "DLeh", "author_id": 526704, "author_profile": "https://Stackoverflow.com/users/526704", "pm_score": 0, "selected": false, "text": "static XElement MakeFromXPath(string xpath)\n{\n XElement root = null;\n XElement parent = null;\n var splits = xpath.Split('/'); //split xpath into parts\n foreach (var split in splits)\n {\n var el = new XElement(split);\n if (parent != null)\n parent.Add(el);\n else\n root = el; //first element created, set as root\n parent = el;\n }\n return root;\n}\n var element = MakeFromXPath(\"My/Path/To/Element\")' element <My>\n <Path>\n <To>\n <Element></Element>\n </To>\n </Path>\n</My>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475/" ]
299,554
<p>I am using a JSP bean and when I do an assignment to a new object, it gets over-written on a submit to the previous object.</p> <pre><code>&lt;jsp:useBean id="base" class="com.example.StandardBase" scope="session" /&gt; ... //base object id = 396 base = new Base() //base object id = 1000 </code></pre> <p>and on a resubmit of the page I get</p> <pre><code>&lt;jsp:useBean id="base" class="com.example.StandardBase" scope="session" /&gt; //base object id = 396 </code></pre> <p>Is there a way to tell JSP to do a new assignment?</p>
[ { "answer_id": 299573, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "base = new Base() <jsp:useBean/> base = new Base() HttpSession.setAttribute() session.setAttribute(\"bean\", bean);\n session" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
299,563
<p>I don't understand why one method would work and the other would throw a NoMethodError if they come from the same lib file.</p> <pre><code># app/views/bunnies/show.html.erb &lt;% if logged_in? %&gt; &lt;%= current_user.login %&gt; | &lt;%= link_to 'Logout', logout_path %&gt; | &lt;% if authorized? %&gt; &lt;%= link_to 'Edit Details', edit_bunny_path(@broker) %&gt; | &lt;% end %&gt; &lt;%= link_to 'Back', bunnies_path %&gt; &lt;% end %&gt; </code></pre> <p>... throws a NoMethodError for <code>authorized?</code>. If I comment that if block out, the page works fine (with <code>logged<code>_</code>in?</code>).</p> <pre><code># lib/authenticated_system.rb def logged_in? !!current_user end def authorized? current_user.login == "admin" end # app/controllers/application.rb class ApplicationController &lt; ActionController::Base include AuthenticatedSystem end </code></pre> <p>What gives?</p>
[ { "answer_id": 299764, "author": "neezer", "author_id": 32154, "author_profile": "https://Stackoverflow.com/users/32154", "pm_score": 1, "selected": true, "text": "helper_method :is_admin?\ndef is_admin?\n if logged_in? && current_user.login == \"admin\"\n true\n else\n false\n end\nend\n authorized?" }, { "answer_id": 305421, "author": "Yardboy", "author_id": 9550, "author_profile": "https://Stackoverflow.com/users/9550", "pm_score": 2, "selected": false, "text": "def authorized?\n logged_in? and current_user.login == \"admin\"\nend\n # Inclusion hook to make #current_user and #logged_in?\n# available as ActionView helper methods.\ndef self.included(base)\n base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method\nend\n" }, { "answer_id": 569739, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "def is_admin?\n logged_in? && current_user.login == \"admin\"\nend\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
299,565
<p>I am compiling a legacy C code here and there is a lot of variables and struct members named "interface", but VC2008 express is complaining about these, do you know how to disable this?</p> <p>I already changed settings to compile the code only as a C code, but no effect on this.</p>
[ { "answer_id": 299593, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 3, "selected": true, "text": "#define interface QQInterface\n" }, { "answer_id": 5432241, "author": "Sebastian Brandt", "author_id": 676662, "author_profile": "https://Stackoverflow.com/users/676662", "pm_score": 3, "selected": false, "text": "interface Name {...}\n #define interface __STRUCT__ #undef interface" }, { "answer_id": 12564662, "author": "Shweta", "author_id": 1694333, "author_profile": "https://Stackoverflow.com/users/1694333", "pm_score": 0, "selected": false, "text": "error: expected ',' or '...' before 'struct' #ifdef interface \n#undef interface \n#endif \n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440867/" ]
299,574
<p>If I have the following setting in my app.config file. It is a setting I need to make sure my WCF client can negotiate the default proxy server.</p> <pre><code>&lt;system.net&gt; &lt;defaultProxy enabled="true" useDefaultCredentials="true"&gt;&lt;/defaultProxy&gt; &lt;/system.net&gt; </code></pre> <p>Unfortunately, I can't add to the app.config file in my environment. How do I ensure these settings by setting them at runtime?</p>
[ { "answer_id": 299632, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 1, "selected": true, "text": "System.Net.WebProxy System.Net.WebRequest.DefaultWebProxy System.Net.WebProxy proxy = new WebProxy();\nproxy.UseDefaultCredentials = true;\nWebRequest.DefaultWebProxy = proxy;\n" }, { "answer_id": 310966, "author": "Mitch Baker", "author_id": 37896, "author_profile": "https://Stackoverflow.com/users/37896", "pm_score": 0, "selected": false, "text": "myWSHttpBinding.UseDefaultWebProxy = True;\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36687/" ]
299,582
<p>I want to use JavaScript to control an embedded Windows Media Player, as well as access any properties that the player exposes. I've found a few hacky examples online, but nothing concrete. </p> <p>I really need access to play, pause, stop, seek, fullscreen, etc. I'd also like to have access to any events the player happens to broadcast. </p> <p>Help would be wonderful (I already have a Flash equiv, just so you know), thanks! </p>
[ { "answer_id": 728100, "author": "Mister Lucky", "author_id": 81589, "author_profile": "https://Stackoverflow.com/users/81589", "pm_score": 4, "selected": false, "text": "<html>\n<head>\n <title>so-wmp</title>\n <script>\n\n onload=function() {\n player = document.getElementById(\"wmp\");\n player.URL = \"test.mp3\";\n };\n\n function add(text) {\n document.body\n .appendChild(document.createElement(\"div\"))\n .appendChild(document.createTextNode(text));\n };\n\n function handler(type) {\n var a = arguments;\n add(type +\" = \"+ PlayStates[a[1]]);\n };\n\n // http://msdn.microsoft.com/en-us/library/bb249361(VS.85).aspx\n var PlayStates = {\n 0: \"Undefined\", // Windows Media Player is in an undefined state.\n 1: \"Stopped\", // Playback of the current media item is stopped.\n 2: \"Paused\", // Playback of the current media item is paused. When a media item is paused, resuming playback begins from the same location.\n 3: \"Playing\", // The current media item is playing.\n 4: \"ScanForward\", // The current media item is fast forwarding.\n 5: \"ScanReverse\", // The current media item is fast rewinding.\n 6: \"Buffering\", // The current media item is getting additional data from the server.\n 7: \"Waiting\", // Connection is established, but the server is not sending data. Waiting for session to begin.\n 8: \"MediaEnded\", // Media item has completed playback.\n 9: \"Transitioning\", // Preparing new media item.\n 10: \"Ready\", // Ready to begin playing.\n 11: \"Reconnecting\" // Reconnecting to stream.\n };\n\n </script>\n <script for=\"wmp\" event=\"PlayStateChange(newState)\">\n // http://msdn.microsoft.com/en-us/library/bb249362(VS.85).aspx\n handler.call(this, \"playstatechange\", newState);\n </script>\n</head>\n<body>\n <div id=\"page\">\n <object id=\"wmp\"\n classid=\"clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6\"\n type=\"application/x-oleobject\">\n </object>\n </div>\n</body>\n</html>\n" }, { "answer_id": 14372697, "author": "Konstantin Konopko", "author_id": 1621111, "author_profile": "https://Stackoverflow.com/users/1621111", "pm_score": 0, "selected": false, "text": " objPlayer = document.getElementById(\"wmp\"); \n objPlayer.controls.stop();\n objPlayer.URL = this.url;\n objPlayer.controls.play();\n\n<EMBED id=\"wmp\" TYPE=\"application/x-mplayer2\" name=\"MediaPlayer\" width=\"0\" height=\"0\" ShowControls=\"0\" ShowStatusBar=\"0\" ShowDisplay=\"0\" autostart=\"0\"></EMBED>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4106/" ]
299,585
<p>The net is overflowing with explanations of the <a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="nofollow noreferrer">"dreaded diamond problem"</a>. So is StackOverflow. I think I understand that bit, but I fail to translate that knowledge into comprehending something similar yet different.</p> <p>My question begins as a pure C++ question, but the answer might well branch over into MS-COM specifics. The general problem question goes:</p> <pre><code>class Base { /* pure virtual stuff */ }; class Der1 : Base /* Non-virtual! */ { /* pure virtual stuff */ }; class Der2 : Base /* Non-virtual! */ { /* pure virtual stuff */ }; class Join : virtual Der1, virtual Der2 { /* implementation stuff */ }; class Join2 : Join { /* more implementation stuff + overides */ }; </code></pre> <p>This is <em>not</em> the classic diamond solution. Exactly what does "virtual" do here?</p> <p>My real problem is trying to understand a <a href="http://www.codeproject.com/KB/COM/flashcontrol.aspx?fid=915540&amp;select=2784823&amp;tid=2774438" rel="nofollow noreferrer">discussion over at our friends' place at CodeProject.</a> It involves a custom class for creating a transparent container for the Flash player.</p> <p>I thought I would try this place for fun. It turns out that the following declaration crashes your app, with version 10 of the Flash player.</p> <pre><code>class FlashContainerWnd: virtual public IOleClientSite, virtual public IOleInPlaceSiteWindowless, virtual public IOleInPlaceFrame, virtual public IStorage </code></pre> <p>Debugging shows that when entering the function implementations (QueryInterface etc), from different callers, I get different "this"-pointer values for different calls. But <strong>removing "virtual" does the trick!</strong> No crashes, and same "this"-pointer.</p> <p>I would like to clearly understand exactly what is going on. Thanks a lot.</p> <p>Cheers Adam</p>
[ { "answer_id": 299961, "author": "deft_code", "author_id": 28817, "author_profile": "https://Stackoverflow.com/users/28817", "pm_score": 2, "selected": false, "text": "Der1 Der2 Base auto p = new Join2;\nstatic_cast<Base*>(static_cast<Der1*>(p)) !=\n static_cast<Base*>(static_cast<Der2*>(p))\n class A {};\nclass B : virtual public A {};\nclass C : virtual public A {};\nclass D : public A {};\nclass E : virtual public A, public B, public C, public D {};\nclass F : public A, public B, public C, public D {};\n\nF::A != F::B::A or F::C::A or F::D::A\nF::B::A == F::C::A\nF::D::A != F::B::A or F::C::A or F::A\n\nE::B::A == E::C::A == E::A\nE::D::A != E::B::A or E::C::A or E::D::A\n" }, { "answer_id": 1254243, "author": "Kees-Jan", "author_id": 114197, "author_profile": "https://Stackoverflow.com/users/114197", "pm_score": 0, "selected": false, "text": "#include \"stdafx.h\"\n#include <stdio.h>\n\nclass Base\n{\npublic:\n virtual void say_hi(const char* s)=0;\n};\n\nclass Der1 : public Base\n{\npublic:\n virtual void d1()=0;\n};\n\nclass Der2 : public Base\n{\npublic:\n virtual void d2()=0;\n};\n\nclass Join : virtual public Der1, virtual public Der2\n // class Join : public Der1, public Der2\n{\npublic:\n virtual void say_hi(const char* s);\n virtual void d1();\n virtual void d2();\n};\n\nclass Join2 : public Join\n{\n virtual void d1();\n};\n\nvoid Join::say_hi(const char* s)\n{\n printf(\"Hi %s (%p)\\n\", s, this);\n}\n\nvoid Join::d1()\n{}\n\nvoid Join::d2()\n{}\n\nvoid Join2::d1()\n{\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n Join2* j2 = new Join2();\n Join* j = dynamic_cast<Join*>(j2);\n Der1* d1 = dynamic_cast<Der1*>(j2);\n Der2* d2 = dynamic_cast<Der2*>(j2);\n Base* b1 = dynamic_cast<Base*>(d1);\n Base* b2 = dynamic_cast<Base*>(d2);\n\n printf(\"j2: %p\\n\", j2);\n printf(\"j: %p\\n\", j);\n printf(\"d1: %p\\n\", d1);\n printf(\"d2: %p\\n\", d2);\n printf(\"b1: %p\\n\", b1);\n printf(\"b2: %p\\n\", b2);\n\n j2->say_hi(\"j2\");\n j->say_hi(\" j\");\n d1->say_hi(\"d1\");\n d2->say_hi(\"d2\");\n b1->say_hi(\"b1\");\n b2->say_hi(\"b2\");\n\n return 0;\n}\n j2: 00376C10\nj: 00376C10\nd1: 00376C14\nd2: 00376C18\nb1: 00376C14\nb2: 00376C18\nHi j2 (00376C10)\nHi j (00376C10)\nHi d1 (00376C10)\nHi d2 (00376C10)\nHi b1 (00376C10)\nHi b2 (00376C10)\n" }, { "answer_id": 1284617, "author": "AI0867", "author_id": 145413, "author_profile": "https://Stackoverflow.com/users/145413", "pm_score": 0, "selected": false, "text": "a a a\n| | |\nb c d <-- b, c and d inherit a normally\n \\ | /\n e\n a\n / | \\\nb c d <-- b, c and d inherit a virtually\n \\ | /\n d\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38656/" ]
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
[ { "answer_id": 299611, "author": "altunyurt", "author_id": 37491, "author_profile": "https://Stackoverflow.com/users/37491", "pm_score": 3, "selected": false, "text": "...\nroot = etree.XML(_bytes(\"<b/>\")) \ndtd = etree.DTD(BytesIO(\"<!ELEMENT b EMPTY>\")) \nself.assert_(dtd.validate(root)) \n" }, { "answer_id": 32228567, "author": "Komu", "author_id": 2768067, "author_profile": "https://Stackoverflow.com/users/2768067", "pm_score": 4, "selected": false, "text": "pip install lxml from lxml import etree, objectify\nfrom lxml.etree import XMLSyntaxError\n\ndef xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'):\n try:\n schema = etree.XMLSchema(file=xsd_file)\n parser = objectify.makeparser(schema=schema)\n objectify.fromstring(some_xml_string, parser)\n print \"YEAH!, my xml file has validated\"\n except XMLSyntaxError:\n #handle exception here\n print \"Oh NO!, my xml file does not validate\"\n pass\n\nxml_file = open('my_xml_file.xml', 'r')\nxml_string = xml_file.read()\nxml_file.close()\n\nxml_validator(xml_string, '/path/to/my_schema_file.xsd')\n >> xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml" }, { "answer_id": 37972081, "author": "SergO", "author_id": 685410, "author_profile": "https://Stackoverflow.com/users/685410", "pm_score": 5, "selected": false, "text": "pip install lxml\n # Debian/Ubuntu\napt-get install python-dev python3-dev libxml2-dev libxslt-dev\n\n# Fedora 23+\ndnf install python-devel python3-devel libxml2-devel libxslt-devel\n from lxml import etree\n\ndef validate(xml_path: str, xsd_path: str) -> bool:\n\n xmlschema_doc = etree.parse(xsd_path)\n xmlschema = etree.XMLSchema(xmlschema_doc)\n\n xml_doc = etree.parse(xml_path)\n result = xmlschema.validate(xml_doc)\n\n return result\n from validator import validate\n\nif validate(\"path/to/file.xml\", \"path/to/scheme.xsd\"):\n print('Valid! :)')\nelse:\n print('Not valid! :(')\n from lxml import etree\n\nclass Validator:\n\n def __init__(self, xsd_path: str):\n xmlschema_doc = etree.parse(xsd_path)\n self.xmlschema = etree.XMLSchema(xmlschema_doc)\n\n def validate(self, xml_path: str) -> bool:\n xml_doc = etree.parse(xml_path)\n result = self.xmlschema.validate(xml_doc)\n\n return result\n import os\nfrom validator import Validator\n\nvalidator = Validator(\"path/to/scheme.xsd\")\n\n# The directory with XML files\nXML_DIR = \"path/to/directory\"\n\nfor file_name in os.listdir(XML_DIR):\n print('{}: '.format(file_name), end='')\n\n file_path = '{}/{}'.format(XML_DIR, file_name)\n\n if validator.validate(file_path):\n print('Valid! :)')\n else:\n print('Not valid! :(')\n" }, { "answer_id": 52310735, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 5, "selected": false, "text": "import xmlschema\nxmlschema.validate('doc.xml', 'some.xsd')\n xsd = xmlschema.XMLSchema('some.xsd')\nfor filename in filenames:\n xsd.validate(filename)\n if xsd.is_valid('doc.xml'):\n print('do something useful')\n import xml.etree.ElementTree as ET\nt = ET.parse('doc.xml')\nresult = xsd.is_valid(t)\nprint('Document is valid? {}'.format(result))\n" }, { "answer_id": 68095530, "author": "Vijay Anand Pandian", "author_id": 2868367, "author_profile": "https://Stackoverflow.com/users/2868367", "pm_score": 1, "selected": false, "text": "import xmlschema\n\n\ndef get_validation_errors(xml_file, xsd_file):\n schema = xmlschema.XMLSchema(xsd_file)\n validation_error_iterator = schema.iter_errors(xml_file)\n errors = list()\n for idx, validation_error in enumerate(validation_error_iterator, start=1):\n err = validation_error.__str__()\n errors.append(err)\n print(err)\n return errors\n\nerrors = get_validation_errors('sample3.xml', 'sample_schema.xsd')\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
299,597
<p>To implement data access code in our application we need some framework to wrap around jdbc (ORM is not our choice, because of scalability).</p> <p>The coolest framework I used to work with is <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jdbc.html" rel="noreferrer">Spring-Jdbc</a>. However, the policy of my company is to avoid external dependencies, especially spring, J2EE, etc. So we are thinking about writing own handy-made jdbc framework, with functionality similar Spring-jdbc: row mapping, error handling, supporting features of java5, but without transaction support.</p> <p>Does anyone have experience of writing such jdbc wrapper framework? If anyone has experience of using other jdbc wrapper frameworks, please share your experience.</p> <p>Thanks in advance.</p>
[ { "answer_id": 10635155, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 1, "selected": false, "text": "JdbcSession String name = new JdbcSession(source)\n .sql(\"SELECT name FROM foo WHERE id = ?\")\n .set(123)\n .select(new SingleOutcome<String>(String.class));\n" }, { "answer_id": 12846227, "author": "egaga", "author_id": 103014, "author_profile": "https://Stackoverflow.com/users/103014", "pm_score": 2, "selected": false, "text": "List<Department> departments = db.findAll(Department.class,\n \"select id, name from department\");\n public final class Department {\n private final int id;\n private final String name;\n\n public Department(int id, String name) {\n this.id = id;\n this.name = name;\n }\n}\n" }, { "answer_id": 59501597, "author": "Amir Fo", "author_id": 7580839, "author_profile": "https://Stackoverflow.com/users/7580839", "pm_score": 0, "selected": false, "text": "import static com.pwwiur.util.database.Jedoo.database;\n if(database.count(\"users\") < 100) {\n long id = database.insert(\"users\", new Object[][]{\n {\"name\", \"Amir\"},\n {\"username\", \"amirfo\"}\n });\n \n database.setString(\"users\", \"name\", \"Amir Forsati\", id);\n\n try(ResultSetHandler rsh = database.all(\"users\")) {\n while(rsh.next()) {\n System.out.println(\"User ID:\" + rsh.getLong(\"id\"));\n System.out.println(\"User Name:\" + rsh.getString(\"name\"));\n }\n }\n}\n" }, { "answer_id": 61875706, "author": "Anatoly", "author_id": 12378936, "author_profile": "https://Stackoverflow.com/users/12378936", "pm_score": 0, "selected": false, "text": "<dependency>\n <groupId>com.github.buckelieg</groupId>\n <artifactId>jdbc-fn</artifactId>\n <version>0.2</version>\n</dependency>\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15894/" ]
299,604
<p>My current project involves deploying an upgraded .exe file that runs as a Windows Service. In order to overwrite the existing .exe with the new version, I currently need to:</p> <ol> <li>Stop the service</li> <li>Uninstall the service</li> <li>Reboot the system (so Windows releases it's hold on the file)</li> <li>Deploy the new .exe</li> <li>Reinstall the service</li> <li>Start the upgraded service.</li> </ol> <p>I'd like to avoid the reboot, so that this can be a fully scripted/automated upgrade.</p> <p>Is there any way to avoid rebooting? Maybe a command-line tool that will force Windows to give up it's death grip on the old .exe?</p>
[ { "answer_id": 299614, "author": "Jonathan S.", "author_id": 2034, "author_profile": "https://Stackoverflow.com/users/2034", "pm_score": 4, "selected": false, "text": "net stop <service name>\nnet start <service name>\n" }, { "answer_id": 301930, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 7, "selected": true, "text": "sc delete \"service name\"\n" }, { "answer_id": 11399062, "author": "cxxl", "author_id": 1045800, "author_profile": "https://Stackoverflow.com/users/1045800", "pm_score": 4, "selected": false, "text": "NetServiceControl(NULL, service_name, 3, 0, 0)" }, { "answer_id": 23126372, "author": "MSkuta", "author_id": 897609, "author_profile": "https://Stackoverflow.com/users/897609", "pm_score": 0, "selected": false, "text": "installutil MyService.HostService.exe /u /u C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\InstallUtil.exe \"C:\\MyServiceFolder\\MyService.HostService.exe\" /u" }, { "answer_id": 59669625, "author": "Chris Robertson", "author_id": 2800385, "author_profile": "https://Stackoverflow.com/users/2800385", "pm_score": 0, "selected": false, "text": "@echo off\ntitle Service Uninstaller\ncolor 0A\nset blank=\nset service=blank\n:start\necho.&echo.&echo.\nSET /P service=Enter the name of the service you want to uninstall: \n\nIF \"%service%\"==\"\" (ECHO Nothing is entered\nGoTo :start)\ncls\necho.&echo.&echo We will delete the service: %service%\nping -n 5 -w 1 127.0.0.1>nul\n::net stop %service%\nping -n 2 -w 1 127.0.0.1>nul\nsc delete %service%\npause\n:end\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38657/" ]
299,606
<p>What is the most direct and/or efficient way to convert a <code>char[]</code> into a <code>CharSequence</code>? </p>
[ { "answer_id": 299609, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 3, "selected": false, "text": "String CharSequence String char[] CharSequence seq = new String(arr);\n" }, { "answer_id": 299624, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "CharSequence seq = java.nio.CharBuffer.wrap(array);\n new String(array)" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
299,608
<p>In addition to informing the user, we want to collect information for our debugging purposes. Our system is a niche system for only about 1400 customers, and therefore we are not as well-financed as we would hope, so bugs are more common than we would like. We currently have a window that shows the first line of the error message in larger print with a yellow background to draw the user's eye, with the scary part in a textbox below it with a gray background. There is also a button that will put all of it in the copy buffer for sending to customer support. The message that we're trying to go to consists of the exception.Message, the last five parts of the stack trace, and the name of the method that caused the error (Reflection.MethodBase). We are planning to add the ability for the user to say what he was doing at the time, and maybe a radio button indicating how often this happens, and write it to a log file. What other other useful information should we include? </p> <p>We are also considering emailing it to customer support but not stressing if the email fails. There are other considerations with the email - customer support might drown in it, users might object because we'd be sending system info as well, etc.</p> <p>I found two similar questions on SO, but they aren't really focussed on what I'm interested in. <a href="https://stackoverflow.com/questions/117083/error-message-text-best-practices">Error Message Text - Best Practices</a> deals with how to make useful messages for the user, and <a href="https://stackoverflow.com/questions/116542/best-way-to-handle-error-messages">Best way to handle error messages</a> deals with where to keep error IDs vs error text. I'm more interested in debugging (because unfortunately our system DOES have lots of errors).</p>
[ { "answer_id": 299609, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 3, "selected": false, "text": "String CharSequence String char[] CharSequence seq = new String(arr);\n" }, { "answer_id": 299624, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": true, "text": "CharSequence seq = java.nio.CharBuffer.wrap(array);\n new String(array)" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
299,610
<p>I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?</p>
[ { "answer_id": 299751, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 2, "selected": false, "text": "http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz $var" }, { "answer_id": 424060, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);\nmyAjax.send(myObject.toQueryString());\n echo $_POST['arrayItems'] ; \n" }, { "answer_id": 3995907, "author": "Dragouf", "author_id": 210456, "author_profile": "https://Stackoverflow.com/users/210456", "pm_score": 5, "selected": false, "text": "var myJavascriptArray = new Array('jj', 'kk', 'oo');\n\n$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){\n // do something with received data!\n});\n" }, { "answer_id": 10412440, "author": "kishanio", "author_id": 1263709, "author_profile": "https://Stackoverflow.com/users/1263709", "pm_score": 1, "selected": false, "text": "jQuery.ajaxSetting.traditional = true;\n $.ajax({ \n traditional: true,\n type: \"post\",\n url: myURL,\n dataType: \"text\", \n data: dataToSend, //this will be an array eg. \n success: function(request) {\n $('#results').html(request);\n } // End success\n }); // End ajax method\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17600/" ]
299,619
<p>I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.</p> <p>This is what I do now:</p> <pre><code>IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput(). getAdapter(IFile.class); </code></pre> <p>Now I have an IFile object, and I can retrieve it's path:</p> <pre><code>file.getFullPath().toOSString(); </code></pre> <p>However this still only gives me the path relative to the workspace. How can I get the absolute path from that?</p>
[ { "answer_id": 299633, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "IResource.getRawLocation() IPath makeAbsolute()" }, { "answer_id": 302689, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "file.getLocation().toOSString()\n" }, { "answer_id": 349698, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "IWorkspace ws = ResourcesPlugin.getWorkspace(); \nIProject project = ws.getRoot().getProject(\"*project_name*\");\n\nIPath location = new Path(editor.getTitleToolTip()); \nIFile file = project.getFile(location.lastSegment());\n\ninto file.getLocationURI() it's the absolute path\n" }, { "answer_id": 1370758, "author": "James E. Ervin", "author_id": 162999, "author_profile": "https://Stackoverflow.com/users/162999", "pm_score": 3, "selected": false, "text": "IResource.getLocation().toFile()\n (org.eclipse.ui.ide.IDE)" }, { "answer_id": 9299638, "author": "ChrisJF", "author_id": 156210, "author_profile": "https://Stackoverflow.com/users/156210", "pm_score": 3, "selected": false, "text": "// Get the currently selected file from the editor\nIWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); \nIFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);\nif (file == null) throw new FileNotFoundException();\nString path = file.getRawLocation().toOSString();\nSystem.out.println(\"path: \" + path);\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ]
299,628
<p>When issuing an HTTP DELETE request, the request URI should completely identify the resource to delete. However, is it allowable to add extra meta-data as part of the entity body of the request?</p>
[ { "answer_id": 299696, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 11, "selected": true, "text": "Content-Length Transfer-Encoding" }, { "answer_id": 18141127, "author": "Neil McGuigan", "author_id": 223478, "author_profile": "https://Stackoverflow.com/users/223478", "pm_score": 6, "selected": false, "text": "GET /some-resource/1\n200 OK { id:1, status:\"unimportant\", version:1 }\n GET /some-resource/1\n200 OK { id:1, status:\"unimportant\", version:1 }\n PUT /some-resource/1 { id:1, status:\"important\", version:1 }\n200 OK { id:1, status:\"important\", version:2 }\n DELETE /some-resource/1 { id:1, version:1 }\n409 Conflict\n DELETE /messages\n[{id:1, version:2},\n{id:99, version:3}]\n204 No Content\n @RestController\npublic class TestController {\n\n @RequestMapping(value=\"/echo-delete\", method = RequestMethod.DELETE)\n SomeBean echoDelete(@RequestBody SomeBean someBean) {\n return someBean;\n }\n}\n" }, { "answer_id": 54735278, "author": "Evert", "author_id": 80911, "author_profile": "https://Stackoverflow.com/users/80911", "pm_score": 4, "selected": false, "text": "DELETE DELETE DELETE" }, { "answer_id": 72596867, "author": "Moshe Katz", "author_id": 829970, "author_profile": "https://Stackoverflow.com/users/829970", "pm_score": 3, "selected": false, "text": "DELETE" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598/" ]
299,659
<p>What's the difference between <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/WeakReference.html" rel="noreferrer"><code>java.lang.ref.WeakReference</code></a> and <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/SoftReference.html" rel="noreferrer"><code>java.lang.ref.SoftReference</code></a> ?</p>
[ { "answer_id": 299665, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 5, "selected": false, "text": "SoftReference WeakReference SoftReference -Xmx SoftReference OutOfMemoryError" }, { "answer_id": 299702, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 11, "selected": true, "text": "WeakReference weakWidget = new WeakReference(widget);\n weakWidget.get() Widget weakWidget.get() null WeakReferences SoftReferences WeakReferences" }, { "answer_id": 19417545, "author": "Thalaivar", "author_id": 337128, "author_profile": "https://Stackoverflow.com/users/337128", "pm_score": 6, "selected": false, "text": "weak reference reference weak reference Map import java.util.HashMap; \npublic class Test {\n\n public static void main(String args[]) {\n HashMap<Employee, EmployeeVal> aMap = new \n HashMap<Employee, EmployeeVal>();\n\n Employee emp = new Employee(\"Vinoth\");\n EmployeeVal val = new EmployeeVal(\"Programmer\");\n\n aMap.put(emp, val);\n\n emp = null;\n\n System.gc();\n System.out.println(\"Size of Map\" + aMap.size());\n\n }\n}\n emp = null Map null WeakHashMap key-to-value mappings Map import java.util.WeakHashMap;\n\npublic class Test {\n\n public static void main(String args[]) {\n WeakHashMap<Employee, EmployeeVal> aMap = \n new WeakHashMap<Employee, EmployeeVal>();\n\n Employee emp = new Employee(\"Vinoth\");\n EmployeeVal val = new EmployeeVal(\"Programmer\");\n\n aMap.put(emp, val);\n\n emp = null;\n\n System.gc();\n int count = 0;\n while (0 != aMap.size()) {\n ++count;\n System.gc();\n }\n System.out.println(\"Took \" + count\n + \" calls to System.gc() to result in weakHashMap size of : \"\n + aMap.size());\n }\n}\n 20 calls to System.gc() aMap size WeakHashMap Map WeakHashMap import java.lang.ref.WeakReference;\nimport java.util.HashMap;\n\npublic class Test {\n\n public static void main(String args[]) {\n HashMap<Employee, EmployeeVal> map = \n new HashMap<Employee, EmployeeVal>();\n WeakReference<HashMap<Employee, EmployeeVal>> aMap = \n new WeakReference<HashMap<Employee, EmployeeVal>>(\n map);\n\n map = null;\n\n while (null != aMap.get()) {\n aMap.get().put(new Employee(\"Vinoth\"),\n new EmployeeVal(\"Programmer\"));\n System.out.println(\"Size of aMap \" + aMap.get().size());\n System.gc();\n }\n System.out.println(\"Its garbage collected\");\n }\n}\n Soft Reference OutOfMemoryError" }, { "answer_id": 31785221, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 8, "selected": false, "text": "OutOfMemoryError" }, { "answer_id": 46291143, "author": "Pacerier", "author_id": 632951, "author_profile": "https://Stackoverflow.com/users/632951", "pm_score": 3, "selected": false, "text": "weak_ref.get() null" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24982/" ]
299,679
<p>In my web app, when a user logs in, I add his Id to a vector of valid Ids in the servlet, when he logs out, I remove his Id from the vector, so I can see how many current users are active, if a user forgets to log out, my servelt generated html has : </p> <pre><code>&lt;meta http-equiv="Refresh" content="30; url=My_Servlet?User_Action=logout&amp;User_Id=1111"&gt; </code></pre> <p>in the tag to automatically log him out.</p> <p>But I've noticed many users are there for ever, never logged out. I found out why, by closing their browsers, they never manually or automatically logged out, so their user Ids will never be removed from the valid user Ids vector.</p> <p>So, my question is : how do I detect users closing their browsers, so my servlet can remove their Ids from the vector ?</p> <hr> <p>I see some light at the end of the tunnel, but there is still a problem, my program has something like this : </p> <p>Active User List :</p> <pre><code>User_1 : Machine_1 [ IP_1 address ] User_2 : Machine_2 [ IP_2 address ] User_3 : Machine_3 [ IP_3 address ] ... </code></pre> <p>How do I know, from the session listener, which user's session has ended and therefore remove him from my list?</p> <p>I was hoping when the session ends, the HttpServlet's <code>destroy()</code> method would be called and I can remove the user Id in there, but it never gets called when user closes his browser, why? And is there any other method in the HttpServlet that gets called when a session closes?</p>
[ { "answer_id": 299697, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "onbeforeclose" }, { "answer_id": 299700, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "HttpSessionListener sessionDestroyed()" }, { "answer_id": 299733, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": true, "text": "HttpSessionListener" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32834/" ]
299,695
<p>I'm trying to put in an exception in my web.config so that one page does not require authentication. However, it still redirects to the login page.</p> <p><strong>The question isn't how to setup the web.config</strong>. Why? Our system (for better or worse) has a bunch of instrumentation besides the web.config. We have global.asax and custom HttpHandlers. The code base isn't huge, but there's a lot of potential causes for the redirect.</p> <p>What I do want to know is <strong>how to best determine the cause of the redirect</strong>. Is there some way to find out what code triggered the redirect?</p>
[ { "answer_id": 299713, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 0, "selected": false, "text": "<system.web>\n...\n</system.web>\n\n<location path=\"NoAuthNeeded.aspx\">\n <system.web>\n <authorization>\n <allow roles=\"*\" />\n <allow roles=\"?\" />\n </authorization>\n </system.web>\n</location>\n" }, { "answer_id": 299808, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 1, "selected": false, "text": "<system.web>\n...\n</system.web>\n\n<location path=\"NoAuthNeeded.aspx\">\n <system.web>\n <authorization>\n <allow roles=\"*\" />\n <allow roles=\"?\" />\n </authorization>\n </system.web>\n</location>\n" }, { "answer_id": 299900, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 1, "selected": false, "text": ".loadby sos mscorwks sxe clr g !printexception ~*e!clrstack" }, { "answer_id": 68066531, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": 0, "selected": false, "text": "authorization" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
299,703
<p>Once it is compiled, is there a difference between:</p> <pre><code>delegate { x = 0; } </code></pre> <p>and</p> <pre><code>() =&gt; { x = 0 } </code></pre> <p>?</p>
[ { "answer_id": 299712, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 8, "selected": true, "text": "Func Action" }, { "answer_id": 299752, "author": "Olmo", "author_id": 38670, "author_profile": "https://Stackoverflow.com/users/38670", "pm_score": 2, "selected": false, "text": "() => { x = 0 }\n () => { x = 0; } // Lambda statement body\n() => x = 0 // Lambda expression body, could be an expression tree. \n" }, { "answer_id": 299858, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "out using System;\nusing System.Linq.Expressions;\n\npublic class Test\n{\n static void Main()\n {\n int x = 0;\n Foo( () => x );\n Foo( delegate { return x; } );\n }\n\n static void Foo(Func<int, int> action)\n {\n Console.WriteLine(\"I suspect the anonymous method...\");\n }\n\n static void Foo(Expression<Func<int>> func)\n {\n Console.WriteLine(\"I suspect the lambda expression...\");\n }\n}\n using System;\nusing System.Linq.Expressions;\n\npublic class Base\n{\n public void Foo(Action action)\n {\n Console.WriteLine(\"I suspect the lambda expression...\");\n }\n}\n\npublic class Derived : Base\n{\n public void Foo(Action<int> action)\n {\n Console.WriteLine(\"I suspect the anonymous method...\");\n }\n}\n\nclass Test\n{\n static void Main()\n {\n Derived d = new Derived();\n int x = 0;\n d.Foo( () => { x = 0; } );\n d.Foo( delegate { x = 0; } );\n }\n}\n" }, { "answer_id": 10747491, "author": "Án Bình Trọng", "author_id": 972264, "author_profile": "https://Stackoverflow.com/users/972264", "pm_score": -1, "selected": false, "text": "var mytask = Task.Factory.StartNew(() =>\n{\n Thread.Sleep(5000);\n return 2712;\n});\nmytask.ContinueWith(delegate\n{\n _backgroundTask.ContinueTask(() =>lblPercent.Content = mytask.Result.ToString(CultureInfo.InvariantCulture));\n}); \n var mytask = Task.Factory.StartNew(() =>\n{\n Thread.Sleep(5000);\n return 2712;\n});\nmytask.ContinueWith(()=>\n{\n _backgroundTask.ContinueTask(() =>lblPercent.Content = mytask.Result.ToString(CultureInfo.InvariantCulture));\n});\n" }, { "answer_id": 50313654, "author": "Yogesh Prajapati", "author_id": 4959238, "author_profile": "https://Stackoverflow.com/users/4959238", "pm_score": -1, "selected": false, "text": "(string testString) => { Console.WriteLine(testString); };\n delegate void PrintTestString(string testString); // declare a delegate\n\nPrintTestString print = (string testString) => { Console.WriteLine(testString); }; \nprint();\n s => s.Age > someValue && s.Age < someValue // will return true/false\n Func< Student,bool> checkStudentAge = s => s.Age > someValue && s.Age < someValue ;\n\nbool result = checkStudentAge ( Student Object);\n" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93/" ]
299,704
<p>I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?</p>
[ { "answer_id": 300173, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "doctest.testmod() if __name__==\"__main__\" assert print()" }, { "answer_id": 300361, "author": "Michael Kuhn", "author_id": 33996, "author_profile": "https://Stackoverflow.com/users/33996", "pm_score": 3, "selected": false, "text": "if answer == 42:\n 1/0 \n" }, { "answer_id": 300366, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "page = grabpage(url)\nprint \"Page content:\", page\nprint \"page type():\", type(page)\n debug = True\nif debug: print \"page content\", page\n pdb winpdb myscript --arg 4 -b 4 rpdb2" }, { "answer_id": 4613364, "author": "Eric O Lebigot", "author_id": 42973, "author_profile": "https://Stackoverflow.com/users/42973", "pm_score": 0, "selected": false, "text": "%pdb %run" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
299,719
<p>In the Linux kernel, given the <code>task_struct</code>'s <code>mm</code> I can access the process's list of <code>vm_area_struct</code>s. Given these <code>vm_area_struct</code>s, how do I get the <code>struct page</code>s which actually correspond to this vma? </p> <p>I tried looking for functions in mm/memory.c and the like, but I was at a loss.</p> <p>Edit: the idea is to find which pages in the vma are currently in memory and which are not. But I <strong>don't</strong> want someone telling me how to do this bit, as that's a small part of a homework assignment that I need to figure out on my own. But I can't seem to figure out how to find the pages that correspond to this vma. If I can find the pages, I figure I can check to see if they have a valid pfn or not.</p>
[ { "answer_id": 299875, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 1, "selected": false, "text": "get_user_pages() copy_from_user copy_to_user" } ]
2008/11/18
[ "https://Stackoverflow.com/questions/299719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2132/" ]