qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
94,305
<p>Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type:</p> <p>Which is quicker and why?</p> <pre><code>switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } </code></pre> <p><strong>Update:</strong> The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements?</p> <p><strong>Caveat:</strong> I am post-optimising. This method is called <em>many</em> times in a slow part of the app.</p>
[ { "answer_id": 94319, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "<p>The switch() will compile out to code equivalent to a set of else ifs. The string comparisons will be much slower than the type comparisons.</p>\n" }, { "answer_id": 94336, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 2, "selected": false, "text": "<p>Unless you've already written this and find you have a performance problem I wouldn't worry about which is quicker. Go with the one that's more readable. Remember, \"Premature optimization is the root of all evil.\" - Donald Knuth</p>\n" }, { "answer_id": 94343, "author": "Magsol", "author_id": 13604, "author_profile": "https://Stackoverflow.com/users/13604", "pm_score": 0, "selected": false, "text": "<p>String comparison will always rely completely on the runtime environment (unless the strings are statically allocated, though the need to compare those to each other is debatable). Type comparison, however, can be done through dynamic or static binding, and either way it's more efficient for the runtime environment than comparing individual characters in a string.</p>\n" }, { "answer_id": 94356, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>Surely the switch on String would compile down to a String comparison (one per case) which is slower than a type comparison (and far slower than the typical integer compare that is used for switch/case)?</p>\n" }, { "answer_id": 94408, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": -1, "selected": false, "text": "<p>I may be missing something, but couldn't you do a switch statement on the type instead of the String? That is, </p>\n\n<pre><code>switch(childNode.Type)\n{\ncase Bob:\n break;\ncase Jill:\n break;\ncase Marko:\n break;\n}\n</code></pre>\n" }, { "answer_id": 94438, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 4, "selected": false, "text": "<p>Switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.</p>\n" }, { "answer_id": 94460, "author": "Gary Kephart", "author_id": 17967, "author_profile": "https://Stackoverflow.com/users/17967", "pm_score": 3, "selected": false, "text": "<p>If you've got the classes made, I'd suggest using a Strategy design pattern instead of switch or elseif.</p>\n" }, { "answer_id": 94497, "author": "Metro Smurf", "author_id": 9664, "author_profile": "https://Stackoverflow.com/users/9664", "pm_score": 2, "selected": false, "text": "<p>I recall reading in several reference books that the if/else branching is quicker than the switch statement. However, a bit of research on Blackwasp shows that the switch statement is actually faster:\n<a href=\"http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx</a></p>\n\n<p>In reality, if you're comparing the typical 3 to 10 (or so) statements, I seriously doubt there's any real performance gain using one or the other.</p>\n\n<p>As Chris has already said, go for readability:\n<a href=\"https://stackoverflow.com/questions/94305/what-is-quicker-switch-on-string-or-elseif-on-type#94336\">What is quicker, switch on string or elseif on type?</a></p>\n" }, { "answer_id": 94615, "author": "SaguiItay", "author_id": 6980, "author_profile": "https://Stackoverflow.com/users/6980", "pm_score": 2, "selected": false, "text": "<p>I think the main performance issue here is, that in the switch block, you compare strings, and that in the if-else block, you check for types... Those two are not the same, and therefore, I'd say you're \"comparing potatoes to bananas\".</p>\n\n<p>I'd start by comparing this:</p>\n\n<pre><code>switch(childNode.Name)\n{\n case \"Bob\":\n break;\n case \"Jill\":\n break;\n case \"Marko\":\n break;\n}\n\nif(childNode.Name == \"Bob\")\n{}\nelse if(childNode.Name == \"Jill\")\n{}\nelse if(childNode.Name == \"Marko\")\n{}\n</code></pre>\n" }, { "answer_id": 94624, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One of the issues you have with the switch is using strings, like \"Bob\", this will cause a lot more cycles and lines in the compiled code. The IL that is generated will have to declare a string, set it to \"Bob\" then use it in the comparison. So with that in mind your IF statements will run faster.</p>\n\n<p>PS. Aeon's example wont work because you can't switch on Types. (No I don't know why exactly, but we've tried it an it doesn't work. It has to do with the type being variable)</p>\n\n<p>If you want to test this, just build a separate application and build two simple Methods that do what is written up above and use something like Ildasm.exe to see the IL. You'll notice a lot less lines in the IF statement Method's IL.</p>\n\n<p>Ildasm comes with VisualStudio... </p>\n\n<p>ILDASM page - <a href=\"http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/f7dy01k1(VS.80).aspx</a></p>\n\n<p>ILDASM Tutorial - <a href=\"http://msdn.microsoft.com/en-us/library/aa309387(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa309387(VS.71).aspx</a></p>\n" }, { "answer_id": 94664, "author": "user17983", "author_id": 17983, "author_profile": "https://Stackoverflow.com/users/17983", "pm_score": 2, "selected": false, "text": "<p>A SWITCH construct was originally intended for integer data; it's intent was to use the argument directly as a index into a \"dispatch table\", a table of pointers. As such, there would be a single test, then launch directly to the relevant code, rather than a series of tests.</p>\n\n<p>The difficulty here is that it's use has been generalized to \"string\" types, which obviously cannot be used as an index, and all advantage of the SWITCH construct is lost.</p>\n\n<p>If speed is your intended goal, the problem is NOT your code, but your data structure. If the \"name\" space is as simple as you show it, better to code it into an integer value (when data is created, for example), and use this integer in the \"many times in a slow part of the app\".</p>\n" }, { "answer_id": 94710, "author": "Ted Elliott", "author_id": 16501, "author_profile": "https://Stackoverflow.com/users/16501", "pm_score": 2, "selected": false, "text": "<p>If the types you're switching on are primitive .NET types you can use Type.GetTypeCode(Type), but if they're custom types they will all come back as TypeCode.Object. </p>\n\n<p>A dictionary with delegates or handler classes might work as well.</p>\n\n<pre><code>Dictionary&lt;Type, HandlerDelegate&gt; handlers = new Dictionary&lt;Type, HandlerDelegate&gt;();\nhandlers[typeof(Bob)] = this.HandleBob;\nhandlers[typeof(Jill)] = this.HandleJill;\nhandlers[typeof(Marko)] = this.HandleMarko;\n\nhandlers[childNode.GetType()](childNode);\n/// ...\n\nprivate void HandleBob(Node childNode) {\n // code to handle Bob\n}\n</code></pre>\n" }, { "answer_id": 94904, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 0, "selected": false, "text": "<p>Three thoughts:</p>\n\n<p>1) If you're going to do something different based on the types of the objects, it might make sense to move that behavior into those classes. Then instead of switch or if-else, you'd just call childNode.DoSomething(). </p>\n\n<p>2) Comparing types will be much faster than string comparisons.</p>\n\n<p>3) In the if-else design, you might be able to take advantage of reordering the tests. If \"Jill\" objects make up 90% of the objects going through there, test for them first.</p>\n" }, { "answer_id": 95012, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": 4, "selected": false, "text": "<p>I just implemented a quick test application and profiled it with ANTS 4.<br>\nSpec: .Net 3.5 sp1 in 32bit Windows XP, code built in release mode.</p>\n\n<p>3 million tests: </p>\n\n<ul>\n<li>Switch: 1.842 seconds</li>\n<li>If: 0.344 seconds.</li>\n</ul>\n\n<p>Furthermore, the switch statement results reveal (unsurprisingly) that longer names take longer.</p>\n\n<p>1 million tests </p>\n\n<ul>\n<li>Bob: 0.612 seconds. </li>\n<li>Jill: 0.835 seconds. </li>\n<li>Marko: 1.093 seconds.</li>\n</ul>\n\n<p>I looks like the \"If Else\" is faster, at least the the scenario I created. </p>\n\n<pre><code>class Program\n{\n static void Main( string[] args )\n {\n Bob bob = new Bob();\n Jill jill = new Jill();\n Marko marko = new Marko();\n\n for( int i = 0; i &lt; 1000000; i++ )\n {\n Test( bob );\n Test( jill );\n Test( marko );\n }\n }\n\n public static void Test( ChildNode childNode )\n { \n TestSwitch( childNode );\n TestIfElse( childNode );\n }\n\n private static void TestIfElse( ChildNode childNode )\n {\n if( childNode is Bob ){}\n else if( childNode is Jill ){}\n else if( childNode is Marko ){}\n }\n\n private static void TestSwitch( ChildNode childNode )\n {\n switch( childNode.Name )\n {\n case \"Bob\":\n break;\n case \"Jill\":\n break;\n case \"Marko\":\n break;\n }\n }\n}\n\nclass ChildNode { public string Name { get; set; } }\n\nclass Bob : ChildNode { public Bob(){ this.Name = \"Bob\"; }}\n\nclass Jill : ChildNode{public Jill(){this.Name = \"Jill\";}}\n\nclass Marko : ChildNode{public Marko(){this.Name = \"Marko\";}}\n</code></pre>\n" }, { "answer_id": 95028, "author": "Rick Minerich", "author_id": 9251, "author_profile": "https://Stackoverflow.com/users/9251", "pm_score": 2, "selected": false, "text": "<p>Try using enumerations for each object, you can switch on enums quickly and easily.</p>\n" }, { "answer_id": 95091, "author": "Eddie Velasquez", "author_id": 12851, "author_profile": "https://Stackoverflow.com/users/12851", "pm_score": 0, "selected": false, "text": "<p>Remember, the profiler is your friend. Any guesswork is a waste of time most of the time.\nBTW, I have had a good experience with JetBrains' <a href=\"http://www.jetbrains.com/profiler/\" rel=\"nofollow noreferrer\">dotTrace</a> profiler. </p>\n" }, { "answer_id": 95099, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 0, "selected": false, "text": "<p>Switch on string basically gets compiled into a if-else-if ladder. Try decompiling a simple one. In any case, testing string equailty should be cheaper since they are interned and all that would be needed is a reference check. Do what makes sense in terms of maintainability; if you are compring strings, do the string switch. If you are selecting based on type, a type ladder is the more appropriate.</p>\n" }, { "answer_id": 95118, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 4, "selected": false, "text": "<p>Firstly, you're comparing apples and oranges. You'd first need to compare switch on type vs switch on string, and then if on type vs if on string, and then compare the winners.</p>\n\n<p>Secondly, this is the kind of thing OO was designed for. In languages that support OO, switching on type (of any kind) is a code smell that points to poor design. The solution is to derive from a common base with an abstract or virtual method (or a similar construct, depending on your language)</p>\n\n<p>eg.</p>\n\n<pre><code>class Node\n{\n public virtual void Action()\n {\n // Perform default action\n }\n}\n\nclass Bob : Node\n{\n public override void Action()\n {\n // Perform action for Bill\n }\n}\n\nclass Jill : Node\n{\n public override void Action()\n {\n // Perform action for Jill\n }\n}\n</code></pre>\n\n<p>Then, instead of doing the switch statement, you just call childNode.Action()</p>\n" }, { "answer_id": 126507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<p>Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data.</p>\n\n<p>The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer.</p>\n\n<p>The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well.</p>\n\n<p>if I execute the following:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int value = 25124;\nif(value == 0) ...\nelse if (value == 1) ...\nelse if (value == 2) ...\n...\nelse if (value == 25124) ... \n</code></pre>\n\n<p>each of the previous if conditions must be evaluated before the correct block is entered. On the other hand</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>switch(value) {\n case 0:...break;\n case 1:...break;\n case 2:...break;\n ...\n case 25124:...break;\n}\n</code></pre>\n\n<p>will perform one simple jump to the correct bit of code.</p>\n\n<p>Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. </p>\n\n<p>If the switch statement is \"small enough\" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>switch(someString) {\n case \"Foo\": DoFoo(); break;\n case \"Bar\": DoBar(); break;\n default: DoOther; break;\n}\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if(someString == \"Foo\") {\n DoFoo();\n} else if(someString == \"Bar\") {\n DoBar();\n} else {\n DoOther();\n}\n</code></pre>\n\n<p>Once the list of items in the dictionary gets \"big enough\" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index.</p>\n\n<p>It looks something like this (Just imagine more entries than I am going to bother to type)</p>\n\n<p>A static field is defined in a \"hidden\" location that is associated with the class containing the switch statement of type <code>Dictionary&lt;string, int&gt;</code> and given a mangled name </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>//Make sure the dictionary is loaded\nif(theDictionary == null) { \n //This is simplified for clarity, the actual implementation is more complex \n // in order to ensure thread safety\n theDictionary = new Dictionary&lt;string,int&gt;();\n theDictionary[\"Foo\"] = 0;\n theDictionary[\"Bar\"] = 1;\n}\n\nint switchIndex;\nif(theDictionary.TryGetValue(someString, out switchIndex)) {\n switch(switchIndex) {\n case 0: DoFoo(); break;\n case 1: DoBar(); break;\n }\n} else {\n DoOther();\n}\n</code></pre>\n\n<p>In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast.</p>\n\n<p>If you are going to be switching on a large number of types, I would suggest a 3rd method:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private delegate void NodeHandler(ChildNode node);\n\nstatic Dictionary&lt;RuntimeTypeHandle, NodeHandler&gt; TypeHandleSwitcher = CreateSwitcher();\n\nprivate static Dictionary&lt;RuntimeTypeHandle, NodeHandler&gt; CreateSwitcher()\n{\n var ret = new Dictionary&lt;RuntimeTypeHandle, NodeHandler&gt;();\n\n ret[typeof(Bob).TypeHandle] = HandleBob;\n ret[typeof(Jill).TypeHandle] = HandleJill;\n ret[typeof(Marko).TypeHandle] = HandleMarko;\n\n return ret;\n}\n\nvoid HandleChildNode(ChildNode node)\n{\n NodeHandler handler;\n if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler))\n {\n handler(node);\n }\n else\n {\n //Unexpected type...\n }\n}\n</code></pre>\n\n<p>This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection.</p>\n\n<p>Here are some quick timings on my machine:</p>\n\n<pre>\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 5 types\nMethod Time % of optimal\nIf/Else 179.67 100.00\nTypeHandleDictionary 321.33 178.85\nTypeDictionary 377.67 210.20\nSwitch 492.67 274.21\n\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 10 types\nMethod Time % of optimal\nIf/Else 271.33 100.00\nTypeHandleDictionary 312.00 114.99\nTypeDictionary 374.33 137.96\nSwitch 490.33 180.71\n\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 15 types\nMethod Time % of optimal\nTypeHandleDictionary 312.00 100.00\nIf/Else 369.00 118.27\nTypeDictionary 371.67 119.12\nSwitch 491.67 157.59\n\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 20 types\nMethod Time % of optimal\nTypeHandleDictionary 335.33 100.00\nTypeDictionary 373.00 111.23\nIf/Else 462.67 137.97\nSwitch 490.33 146.22\n\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 25 types\nMethod Time % of optimal\nTypeHandleDictionary 319.33 100.00\nTypeDictionary 371.00 116.18\nSwitch 483.00 151.25\nIf/Else 562.00 175.99\n\nTesting 3 iterations with 5,000,000 data elements (mode=Random) and 50 types\nMethod Time % of optimal\nTypeHandleDictionary 319.67 100.00\nTypeDictionary 376.67 117.83\nSwitch 453.33 141.81\nIf/Else 1,032.67 323.04\n\n</pre>\n\n<p>On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution\nof the types used as input to the method is random. </p>\n\n<p>If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is <em>much</em> faster:</p>\n\n<pre>\nTesting 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types\nMethod Time % of optimal\nIf/Else 39.00 100.00\nTypeHandleDictionary 317.33 813.68\nTypeDictionary 396.00 1,015.38\nSwitch 403.00 1,033.33\n</pre>\n\n<p>Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect:</p>\n\n<pre>\nTesting 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types\nMethod Time % of optimal\nTypeHandleDictionary 317.67 100.00\nSwitch 354.33 111.54\nTypeDictionary 377.67 118.89\nIf/Else 1,907.67 600.52\n</pre>\n\n<p>If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.</p>\n" }, { "answer_id": 14132144, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "<p>I'm not sure how faster it could be the right design would be to go for polymorphism. </p>\n\n<pre><code>interface INode\n{\n void Action;\n}\n\nclass Bob : INode\n{\n public void Action\n {\n\n }\n}\n\nclass Jill : INode\n{\n public void Action\n {\n\n }\n}\n\nclass Marko : INode\n{\n public void Action\n {\n\n }\n}\n\n//Your function:\nvoid Do(INode childNode)\n{\n childNode.Action();\n}\n</code></pre>\n\n<p>Seeing what your switch statement does will help better. If your function is not really anything about an action on the type, may be you could define an enum on each type.</p>\n\n<pre><code>enum NodeType { Bob, Jill, Marko, Default }\n\ninterface INode\n{\n NodeType Node { get; };\n}\n\nclass Bob : INode\n{\n public NodeType Node { get { return NodeType.Bob; } }\n}\n\nclass Jill : INode\n{\n public NodeType Node { get { return NodeType.Jill; } }\n}\n\nclass Marko : INode\n{\n public NodeType Node { get { return NodeType.Marko; } }\n}\n\n//Your function:\nvoid Do(INode childNode)\n{\n switch(childNode.Node)\n {\n case Bob:\n break;\n case Jill:\n break;\n case Marko:\n break;\n Default:\n throw new ArgumentException();\n }\n}\n</code></pre>\n\n<p>I assume this has to be faster than both approaches in question. You might want to try abstract class route <a href=\"http://www.dotnetperls.com/interface-virtual-performance\" rel=\"nofollow\">if nanoseconds does matter for you</a>.</p>\n" }, { "answer_id": 48439960, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 0, "selected": false, "text": "<p>I kind of do it a bit different, \nThe strings you're switching on are going to be constants, so you can predict the values at compile time. </p>\n\n<p>in your case i'd use the hash values, this is an int switch, you have 2 options, use compile time constants or calculate at run-time.</p>\n\n<pre><code>//somewhere in your code\nstatic long _bob = \"Bob\".GetUniqueHashCode();\nstatic long _jill = \"Jill\".GetUniqueHashCode();\nstatic long _marko = \"Marko\".GeUniquetHashCode();\n\nvoid MyMethod()\n{\n ...\n if(childNode.Tag==0)\n childNode.Tag= childNode.Name.GetUniquetHashCode()\n\n switch(childNode.Tag)\n {\n case _bob :\n break;\n case _jill :\n break;\n case _marko :\n break;\n }\n}\n</code></pre>\n\n<p>The extension method for GetUniquetHashCode can be something like this:</p>\n\n<pre><code>public static class StringExtentions\n {\n /// &lt;summary&gt;\n /// Return unique Int64 value for input string\n /// &lt;/summary&gt;\n /// &lt;param name=\"strText\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static Int64 GetUniquetHashCode(this string strText)\n {\n Int64 hashCode = 0;\n if (!string.IsNullOrEmpty(strText))\n {\n //Unicode Encode Covering all character-set\n byte[] byteContents = Encoding.Unicode.GetBytes(strText);\n System.Security.Cryptography.SHA256 hash = new System.Security.Cryptography.SHA256CryptoServiceProvider();\n byte[] hashText = hash.ComputeHash(byteContents);\n //32Byte hashText separate\n //hashCodeStart = 0~7 8Byte\n //hashCodeMedium = 8~23 8Byte\n //hashCodeEnd = 24~31 8Byte\n //and Fold\n Int64 hashCodeStart = BitConverter.ToInt64(hashText, 0);\n Int64 hashCodeMedium = BitConverter.ToInt64(hashText, 8);\n Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24);\n hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;\n }\n return (hashCode);\n }\n\n\n }\n</code></pre>\n\n<p>The source of this code was published <a href=\"https://www.codeproject.com/Articles/34309/Convert-String-to-bit-Integer\" rel=\"nofollow noreferrer\">here</a>\nPlease note that using Cryptography is slow, you would typically warm-up the supported string on application start, i do this my saving them at static fields as will not change and are not instance relevant. please note that I set the tag value of the node object, I could use any property or add one, just make sure that these are in sync with the actual text. </p>\n\n<p>I work on low latency systems and all my codes come as a string of command:value,command:value.... </p>\n\n<p>now the command are all known as 64 bit integer values so switching like this saves some CPU time. </p>\n" }, { "answer_id": 48475161, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 2, "selected": false, "text": "<p>I created a little console to show my solution, just to highlight the speed difference. I used a different string hash algorithm as the certificate version is to slow for me on runtime and duplicates are unlikely and if so my switch statement would fail (never happened till now). My unique hash extension method is included in the code below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/88P5E.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/88P5E.png\" alt=\"Core 2 console app with output\"></a></p>\n\n<p>I will take 29 ticks over 695 ticks any time, specially when using critical code.</p>\n\n<p>With a set of strings from a given database you can create a small application to create the constant in a given file for you to use in your code, if values are added you just re-run your batch and constants are generated and picked up by the solution.</p>\n\n<pre><code> public static class StringExtention\n {\n public static long ToUniqueHash(this string text)\n {\n long value = 0;\n var array = text.ToCharArray();\n unchecked\n {\n for (int i = 0; i &lt; array.Length; i++)\n {\n value = (value * 397) ^ array[i].GetHashCode();\n value = (value * 397) ^ i;\n }\n return value;\n }\n }\n }\n\n public class AccountTypes\n {\n\n static void Main()\n {\n var sb = new StringBuilder();\n\n sb.AppendLine($\"const long ACCOUNT_TYPE = {\"AccountType\".ToUniqueHash()};\");\n sb.AppendLine($\"const long NET_LIQUIDATION = {\"NetLiquidation\".ToUniqueHash()};\");\n sb.AppendLine($\"const long TOTAL_CASH_VALUE = {\"TotalCashValue\".ToUniqueHash()};\");\n sb.AppendLine($\"const long SETTLED_CASH = {\"SettledCash\".ToUniqueHash()};\");\n sb.AppendLine($\"const long ACCRUED_CASH = {\"AccruedCash\".ToUniqueHash()};\");\n sb.AppendLine($\"const long BUYING_POWER = {\"BuyingPower\".ToUniqueHash()};\");\n sb.AppendLine($\"const long EQUITY_WITH_LOAN_VALUE = {\"EquityWithLoanValue\".ToUniqueHash()};\");\n sb.AppendLine($\"const long PREVIOUS_EQUITY_WITH_LOAN_VALUE = {\"PreviousEquityWithLoanValue\".ToUniqueHash()};\");\n sb.AppendLine($\"const long GROSS_POSITION_VALUE ={ \"GrossPositionValue\".ToUniqueHash()};\");\n sb.AppendLine($\"const long REQT_EQUITY = {\"ReqTEquity\".ToUniqueHash()};\");\n sb.AppendLine($\"const long REQT_MARGIN = {\"ReqTMargin\".ToUniqueHash()};\");\n sb.AppendLine($\"const long SPECIAL_MEMORANDUM_ACCOUNT = {\"SMA\".ToUniqueHash()};\");\n sb.AppendLine($\"const long INIT_MARGIN_REQ = { \"InitMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long MAINT_MARGIN_REQ = {\"MaintMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long AVAILABLE_FUNDS = {\"AvailableFunds\".ToUniqueHash()};\");\n sb.AppendLine($\"const long EXCESS_LIQUIDITY = {\"ExcessLiquidity\".ToUniqueHash()};\");\n sb.AppendLine($\"const long CUSHION = {\"Cushion\".ToUniqueHash()};\");\n sb.AppendLine($\"const long FULL_INIT_MARGIN_REQ = {\"FullInitMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long FULL_MAINTMARGIN_REQ ={ \"FullMaintMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long FULL_AVAILABLE_FUNDS = {\"FullAvailableFunds\".ToUniqueHash()};\");\n sb.AppendLine($\"const long FULL_EXCESS_LIQUIDITY ={ \"FullExcessLiquidity\".ToUniqueHash()};\");\n sb.AppendLine($\"const long LOOK_AHEAD_INIT_MARGIN_REQ = {\"LookAheadInitMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long LOOK_AHEAD_MAINT_MARGIN_REQ = {\"LookAheadMaintMarginReq\".ToUniqueHash()};\");\n sb.AppendLine($\"const long LOOK_AHEAD_AVAILABLE_FUNDS = {\"LookAheadAvailableFunds\".ToUniqueHash()};\");\n sb.AppendLine($\"const long LOOK_AHEAD_EXCESS_LIQUIDITY = {\"LookAheadExcessLiquidity\".ToUniqueHash()};\");\n sb.AppendLine($\"const long HIGHEST_SEVERITY = {\"HighestSeverity\".ToUniqueHash()};\");\n sb.AppendLine($\"const long DAY_TRADES_REMAINING = {\"DayTradesRemaining\".ToUniqueHash()};\");\n sb.AppendLine($\"const long LEVERAGE = {\"Leverage\".ToUniqueHash()};\");\n Console.WriteLine(sb.ToString());\n\n Test(); \n } \n\n public static void Test()\n {\n //generated constant values\n const long ACCOUNT_TYPE = -3012481629590703298;\n const long NET_LIQUIDATION = 5886477638280951639;\n const long TOTAL_CASH_VALUE = 2715174589598334721;\n const long SETTLED_CASH = 9013818865418133625;\n const long ACCRUED_CASH = -1095823472425902515;\n const long BUYING_POWER = -4447052054809609098;\n const long EQUITY_WITH_LOAN_VALUE = -4088154623329785565;\n const long PREVIOUS_EQUITY_WITH_LOAN_VALUE = 6224054330592996694;\n const long GROSS_POSITION_VALUE = -7316842993788269735;\n const long REQT_EQUITY = -7457439202928979430;\n const long REQT_MARGIN = -7525806483981945115;\n const long SPECIAL_MEMORANDUM_ACCOUNT = -1696406879233404584;\n const long INIT_MARGIN_REQ = 4495254338330797326;\n const long MAINT_MARGIN_REQ = 3923858659879350034;\n const long AVAILABLE_FUNDS = 2736927433442081110;\n const long EXCESS_LIQUIDITY = 5975045739561521360;\n const long CUSHION = 5079153439662500166;\n const long FULL_INIT_MARGIN_REQ = -6446443340724968443;\n const long FULL_MAINTMARGIN_REQ = -8084126626285123011;\n const long FULL_AVAILABLE_FUNDS = 1594040062751632873;\n const long FULL_EXCESS_LIQUIDITY = -2360941491690082189;\n const long LOOK_AHEAD_INIT_MARGIN_REQ = 5230305572167766821;\n const long LOOK_AHEAD_MAINT_MARGIN_REQ = 4895875570930256738;\n const long LOOK_AHEAD_AVAILABLE_FUNDS = -7687608210548571554;\n const long LOOK_AHEAD_EXCESS_LIQUIDITY = -4299898188451362207;\n const long HIGHEST_SEVERITY = 5831097798646393988;\n const long DAY_TRADES_REMAINING = 3899479916235857560;\n const long LEVERAGE = 1018053116254258495;\n\n bool found = false;\n var sValues = new string[] {\n \"AccountType\"\n ,\"NetLiquidation\"\n ,\"TotalCashValue\"\n ,\"SettledCash\"\n ,\"AccruedCash\"\n ,\"BuyingPower\"\n ,\"EquityWithLoanValue\"\n ,\"PreviousEquityWithLoanValue\"\n ,\"GrossPositionValue\"\n ,\"ReqTEquity\"\n ,\"ReqTMargin\"\n ,\"SMA\"\n ,\"InitMarginReq\"\n ,\"MaintMarginReq\"\n ,\"AvailableFunds\"\n ,\"ExcessLiquidity\"\n ,\"Cushion\"\n ,\"FullInitMarginReq\"\n ,\"FullMaintMarginReq\"\n ,\"FullAvailableFunds\"\n ,\"FullExcessLiquidity\"\n ,\"LookAheadInitMarginReq\"\n ,\"LookAheadMaintMarginReq\"\n ,\"LookAheadAvailableFunds\"\n ,\"LookAheadExcessLiquidity\"\n ,\"HighestSeverity\"\n ,\"DayTradesRemaining\"\n ,\"Leverage\"\n };\n\n long t1, t2;\n var sw = System.Diagnostics.Stopwatch.StartNew();\n foreach (var name in sValues)\n {\n switch (name)\n {\n case \"AccountType\": found = true; break;\n case \"NetLiquidation\": found = true; break;\n case \"TotalCashValue\": found = true; break;\n case \"SettledCash\": found = true; break;\n case \"AccruedCash\": found = true; break;\n case \"BuyingPower\": found = true; break;\n case \"EquityWithLoanValue\": found = true; break;\n case \"PreviousEquityWithLoanValue\": found = true; break;\n case \"GrossPositionValue\": found = true; break;\n case \"ReqTEquity\": found = true; break;\n case \"ReqTMargin\": found = true; break;\n case \"SMA\": found = true; break;\n case \"InitMarginReq\": found = true; break;\n case \"MaintMarginReq\": found = true; break;\n case \"AvailableFunds\": found = true; break;\n case \"ExcessLiquidity\": found = true; break;\n case \"Cushion\": found = true; break;\n case \"FullInitMarginReq\": found = true; break;\n case \"FullMaintMarginReq\": found = true; break;\n case \"FullAvailableFunds\": found = true; break;\n case \"FullExcessLiquidity\": found = true; break;\n case \"LookAheadInitMarginReq\": found = true; break;\n case \"LookAheadMaintMarginReq\": found = true; break;\n case \"LookAheadAvailableFunds\": found = true; break;\n case \"LookAheadExcessLiquidity\": found = true; break;\n case \"HighestSeverity\": found = true; break;\n case \"DayTradesRemaining\": found = true; break;\n case \"Leverage\": found = true; break;\n default: found = false; break;\n }\n\n if (!found)\n throw new NotImplementedException();\n }\n t1 = sw.ElapsedTicks;\n sw.Restart();\n foreach (var name in sValues)\n {\n switch (name.ToUniqueHash())\n {\n case ACCOUNT_TYPE:\n found = true;\n break;\n case NET_LIQUIDATION:\n found = true;\n break;\n case TOTAL_CASH_VALUE:\n found = true;\n break;\n case SETTLED_CASH:\n found = true;\n break;\n case ACCRUED_CASH:\n found = true;\n break;\n case BUYING_POWER:\n found = true;\n break;\n case EQUITY_WITH_LOAN_VALUE:\n found = true;\n break;\n case PREVIOUS_EQUITY_WITH_LOAN_VALUE:\n found = true;\n break;\n case GROSS_POSITION_VALUE:\n found = true;\n break;\n case REQT_EQUITY:\n found = true;\n break;\n case REQT_MARGIN:\n found = true;\n break;\n case SPECIAL_MEMORANDUM_ACCOUNT:\n found = true;\n break;\n case INIT_MARGIN_REQ:\n found = true;\n break;\n case MAINT_MARGIN_REQ:\n found = true;\n break;\n case AVAILABLE_FUNDS:\n found = true;\n break;\n case EXCESS_LIQUIDITY:\n found = true;\n break;\n case CUSHION:\n found = true;\n break;\n case FULL_INIT_MARGIN_REQ:\n found = true;\n break;\n case FULL_MAINTMARGIN_REQ:\n found = true;\n break;\n case FULL_AVAILABLE_FUNDS:\n found = true;\n break;\n case FULL_EXCESS_LIQUIDITY:\n found = true;\n break;\n case LOOK_AHEAD_INIT_MARGIN_REQ:\n found = true;\n break;\n case LOOK_AHEAD_MAINT_MARGIN_REQ:\n found = true;\n break;\n case LOOK_AHEAD_AVAILABLE_FUNDS:\n found = true;\n break;\n case LOOK_AHEAD_EXCESS_LIQUIDITY:\n found = true;\n break;\n case HIGHEST_SEVERITY:\n found = true;\n break;\n case DAY_TRADES_REMAINING:\n found = true;\n break;\n case LEVERAGE:\n found = true;\n break;\n default:\n found = false;\n break;\n }\n\n if (!found)\n throw new NotImplementedException();\n }\n t2 = sw.ElapsedTicks;\n sw.Stop();\n Console.WriteLine($\"String switch:{t1:N0} long switch:{t2:N0}\");\n var faster = (t1 &gt; t2) ? \"Slower\" : \"faster\";\n Console.WriteLine($\"String switch: is {faster} than long switch: by {Math.Abs(t1-t2)} Ticks\");\n Console.ReadLine();\n\n }\n</code></pre>\n" }, { "answer_id": 48697861, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I was just reading through the list of answers here, and wanted to share <a href=\"http://cc.davelozinski.com/c-sharp/what-is-the-fastest-conditional-statement\" rel=\"nofollow noreferrer\" title=\"http://cc.davelozinski.com/c-sharp/what-is-the-fastest-conditional-statement\">this benchmark test</a> which compares the <code>switch</code> construct with the <code>if-else</code> and ternary <code>?</code> operators.</p>\n\n<p>What I like about <a href=\"http://cc.davelozinski.com/c-sharp/what-is-the-fastest-conditional-statement\" rel=\"nofollow noreferrer\" title=\"http://cc.davelozinski.com/c-sharp/what-is-the-fastest-conditional-statement\">that post</a> is it not only compares single-left constructs (eg, <code>if-else</code>) but double and triple level constructs (eg, <code>if-else-if-else</code>).</p>\n\n<p>According to the results, the <code>if-else</code> construct was the fastest in 8/9 test cases; the <code>switch</code> construct tied for the fastest in 5/9 test cases. </p>\n\n<p>So if you're looking for speed <code>if-else</code> appears to be the fastest way to go.</p>\n" }, { "answer_id": 71854518, "author": "user889030", "author_id": 889030, "author_profile": "https://Stackoverflow.com/users/889030", "pm_score": 1, "selected": false, "text": "<p>well it depend on language you need to test yourself to see timing that which one is fast. like in <strong>php</strong> web language <code>if / else if</code> is fast compare to <code>switch</code> so you need to find it out by running some bench basic code in your desire language.\npersonally i prefer <code>if / else if</code> for code reading as switch statements can be nightmare to read where there is big code blocks in each condition as you will have to look for break keywords it each end point manually while with <code>if / else if</code> due to the start and end braces its easy to trace code blocks.</p>\n<p><strong>php</strong>\n<a href=\"https://i.stack.imgur.com/r9kYB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/r9kYB.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1143/" ]
Lets say I have the option of identifying a code path to take on the basis of a string comparison or else iffing the type: Which is quicker and why? ``` switch(childNode.Name) { case "Bob": break; case "Jill": break; case "Marko": break; } if(childNode is Bob) { } elseif(childNode is Jill) { } else if(childNode is Marko) { } ``` **Update:** The main reason I ask this is because the switch statement is perculiar about what counts as a case. For example it wont allow you to use variables, only constants which get moved to the main assembly. I assumed it had this restriction due to some funky stuff it was doing. If it is only translating to elseifs (as one poster commented) then why are we not allowed variables in case statements? **Caveat:** I am post-optimising. This method is called *many* times in a slow part of the app.
Greg's profile results are great for the exact scenario he covered, but interestingly, the relative costs of the different methods change dramatically when considering a number of different factors including the number of types being compared, and the relative frequency and any patterns in the underlying data. The simple answer is that nobody can tell you what the performance difference is going to be in your specific scenario, you will need to measure the performance in different ways yourself in your own system to get an accurate answer. The If/Else chain is an effective approach for a small number of type comparisons, or if you can reliably predict which few types are going to make up the majority of the ones that you see. The potential problem with the approach is that as the number of types increases, the number of comparisons that must be executed increases as well. if I execute the following: ```cs int value = 25124; if(value == 0) ... else if (value == 1) ... else if (value == 2) ... ... else if (value == 25124) ... ``` each of the previous if conditions must be evaluated before the correct block is entered. On the other hand ```cs switch(value) { case 0:...break; case 1:...break; case 2:...break; ... case 25124:...break; } ``` will perform one simple jump to the correct bit of code. Where it gets more complicated in your example is that your other method uses a switch on strings rather than integers which gets a little more complicated. At a low level, strings can't be switched on in the same way that integer values can so the C# compiler does some magic to make this work for you. If the switch statement is "small enough" (where the compiler does what it thinks is best automatically) switching on strings generates code that is the same as an if/else chain. ```cs switch(someString) { case "Foo": DoFoo(); break; case "Bar": DoBar(); break; default: DoOther; break; } ``` is the same as: ```cs if(someString == "Foo") { DoFoo(); } else if(someString == "Bar") { DoBar(); } else { DoOther(); } ``` Once the list of items in the dictionary gets "big enough" the compiler will automatically create an internal dictionary that maps from the strings in the switch to an integer index and then a switch based on that index. It looks something like this (Just imagine more entries than I am going to bother to type) A static field is defined in a "hidden" location that is associated with the class containing the switch statement of type `Dictionary<string, int>` and given a mangled name ```cs //Make sure the dictionary is loaded if(theDictionary == null) { //This is simplified for clarity, the actual implementation is more complex // in order to ensure thread safety theDictionary = new Dictionary<string,int>(); theDictionary["Foo"] = 0; theDictionary["Bar"] = 1; } int switchIndex; if(theDictionary.TryGetValue(someString, out switchIndex)) { switch(switchIndex) { case 0: DoFoo(); break; case 1: DoBar(); break; } } else { DoOther(); } ``` In some quick tests that I just ran, the If/Else method is about 3x as fast as the switch for 3 different types (where the types are randomly distributed). At 25 types the switch is faster by a small margin (16%) at 50 types the switch is more than twice as fast. If you are going to be switching on a large number of types, I would suggest a 3rd method: ```cs private delegate void NodeHandler(ChildNode node); static Dictionary<RuntimeTypeHandle, NodeHandler> TypeHandleSwitcher = CreateSwitcher(); private static Dictionary<RuntimeTypeHandle, NodeHandler> CreateSwitcher() { var ret = new Dictionary<RuntimeTypeHandle, NodeHandler>(); ret[typeof(Bob).TypeHandle] = HandleBob; ret[typeof(Jill).TypeHandle] = HandleJill; ret[typeof(Marko).TypeHandle] = HandleMarko; return ret; } void HandleChildNode(ChildNode node) { NodeHandler handler; if (TaskHandleSwitcher.TryGetValue(Type.GetRuntimeType(node), out handler)) { handler(node); } else { //Unexpected type... } } ``` This is similar to what Ted Elliot suggested, but the usage of runtime type handles instead of full type objects avoids the overhead of loading the type object through reflection. Here are some quick timings on my machine: ``` Testing 3 iterations with 5,000,000 data elements (mode=Random) and 5 types Method Time % of optimal If/Else 179.67 100.00 TypeHandleDictionary 321.33 178.85 TypeDictionary 377.67 210.20 Switch 492.67 274.21 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 10 types Method Time % of optimal If/Else 271.33 100.00 TypeHandleDictionary 312.00 114.99 TypeDictionary 374.33 137.96 Switch 490.33 180.71 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 15 types Method Time % of optimal TypeHandleDictionary 312.00 100.00 If/Else 369.00 118.27 TypeDictionary 371.67 119.12 Switch 491.67 157.59 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 20 types Method Time % of optimal TypeHandleDictionary 335.33 100.00 TypeDictionary 373.00 111.23 If/Else 462.67 137.97 Switch 490.33 146.22 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 25 types Method Time % of optimal TypeHandleDictionary 319.33 100.00 TypeDictionary 371.00 116.18 Switch 483.00 151.25 If/Else 562.00 175.99 Testing 3 iterations with 5,000,000 data elements (mode=Random) and 50 types Method Time % of optimal TypeHandleDictionary 319.67 100.00 TypeDictionary 376.67 117.83 Switch 453.33 141.81 If/Else 1,032.67 323.04 ``` On my machine at least, the type handle dictionary approach beats all of the others for anything over 15 different types when the distribution of the types used as input to the method is random. If on the other hand, the input is composed entirely of the type that is checked first in the if/else chain that method is *much* faster: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformFirst) and 50 types Method Time % of optimal If/Else 39.00 100.00 TypeHandleDictionary 317.33 813.68 TypeDictionary 396.00 1,015.38 Switch 403.00 1,033.33 ``` Conversely, if the input is always the last thing in the if/else chain, it has the opposite effect: ``` Testing 3 iterations with 5,000,000 data elements (mode=UniformLast) and 50 types Method Time % of optimal TypeHandleDictionary 317.67 100.00 Switch 354.33 111.54 TypeDictionary 377.67 118.89 If/Else 1,907.67 600.52 ``` If you can make some assumptions about your input, you might get the best performance from a hybrid approach where you perform if/else checks for the few types that are most common, and then fall back to a dictionary-driven approach if those fail.
94,331
<p>I use the recent Ganymede release of Eclipse, specifically the distro for Java EE and web developers. I have installed a few additional plugins (e.g. Subclipse, Spring, FindBugs) and removed all the Mylyn plugins. </p> <p>I don't do anything particularly heavy-duty within Eclipse such as starting an app server or connecting to databases, yet for some reason, after several hours use I see that Eclipse is using close to 500MB of memory.</p> <p>Does anybody know why Eclipse uses so much memory (leaky?), and more importantly, if there's anything I can do to improve this?</p>
[ { "answer_id": 94376, "author": "Magsol", "author_id": 13604, "author_profile": "https://Stackoverflow.com/users/13604", "pm_score": 2, "selected": false, "text": "<p>Eclipse by itself is pretty bloated, and the more plugins you add only exacerbates the situation. It's still my favorite IDE, as it certainly isn't short on functionality, but if you're looking for a lightweight IDE then I'd suggest ditching Eclipse; it's pretty normal to run up half a gig of memory if you leave it running for awhile.</p>\n" }, { "answer_id": 94399, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 0, "selected": false, "text": "<p>Well, you don't specify on which platform this occurs. The memory management may vary if you're using Windows XP, Vista, Linux, OS X, ...</p>\n\n<p>Usually, on my computer (WinXP with 1Gb of Ram), Eclipse take rarely more than 200Mb, depengin of the size of the opened projects, the loaded plugins and the ongoing action.</p>\n" }, { "answer_id": 94435, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 1, "selected": false, "text": "<p>RAM is relatively cheap (not that this is an excuse for poor memory managmentment). Unused memory is essentially WASTED memory. If you're hitting limits and the IDE is the problem consider less multitasking, adjusting your memory reqs, or buy more. I wouldn't cripple Eclipse if that's your bread-and-butter IDE.</p>\n" }, { "answer_id": 94459, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>The Ganymede Java EE plugins are absolutely huge when running in memory. Also, I've had bad experiences with FindBugs and its reliability over a long coding session.</p>\n\n<p>If you can't live without these plugins though, then your only recourse is to start closing projects. If you limit the number of <em>open</em> projects in your workspace, the compiler (and FindBugs) will have less to worry about and your memory usage will drop tremendously.</p>\n\n<p>I usually split up my workspaces by customer and then only keep the bare-minimum projects open within each workspace. Note that if you have a particularly large projects (especially ones with a lot of files checked by WST), that will not only chew through your memory, but also cause a noticeable pause in responsiveness when compiling.</p>\n" }, { "answer_id": 94467, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Eclipse is a pretty bloated IDE. You can minimize it by turning of the automatic project building under Project -> Build Automatically. It also can be helped by closing any open project you are not currently working on.</p>\n" }, { "answer_id": 94555, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 2, "selected": false, "text": "<p>I'd call it bloated, but not leaky. (If it was leaky it would climb and climb until something crashed.) As others have said, memory is <strong><em>cheap!</em></strong> It seems like a simple decision to me: spend a tiny bit on more memory vs. lose productivity because you don't have the memory budget to run Eclipse @ 500MB.</p>\n\n<p><em>Summarized rhetorical question:</em> What is more valuable: </p>\n\n<ol>\n<li>The productivity gained from using an IDE you know with the plug-ins you want, or </li>\n<li>Spending $50-200 on some memory?</li>\n</ol>\n" }, { "answer_id": 94807, "author": "Henrik Heimbuerger", "author_id": 6278, "author_profile": "https://Stackoverflow.com/users/6278", "pm_score": 2, "selected": false, "text": "<p>I don't think the JVM does a lot of garbage collection unless it has to (i.e. it's getting to its limits). Therefore it grabs all the memory it can get, probably up to the limit set in the eclipse.ini (the -Xmx argument, set to 512MiB here).</p>\n\n<p>You can get a visual representation of the current heap status by checking 'Preferences' -> 'General' -> 'Show heap status'. It will create a small gauge in the status bar which also has a 'trash can' button you can use to trigger a manual garbage collection.</p>\n" }, { "answer_id": 96330, "author": "Johannes K. Lehnert", "author_id": 2367, "author_profile": "https://Stackoverflow.com/users/2367", "pm_score": 0, "selected": false, "text": "<p>I usually give Eclipse 512 MB of RAM (using the -Xmx option of the JVM) and I don't have any memory problems with Ganymede. I upgraded to two GB of RAM a few months ago, and I can really recommend it. It makes a huge difference.</p>\n" }, { "answer_id": 101193, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "<p>Just for information, </p>\n\n<ul>\n<li><p>you can add </p>\n\n<p>-Dcom.sun.management.jmxremote</p></li>\n</ul>\n\n<p>to your eclise.ini file, launch eclipse and then monitor its memory usage through 'jconsole.exe' found in your jdk installation.</p>\n\n<pre><code>C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n</code></pre>\n\n<p>Choose 'Connection / New connection / 'eclipse' to monitor the memory used by eclipse</p>\n\n<ul>\n<li>always use the latest jvm to launch your eclipse (that does not prevent you to use any other jfk to compile your project within eclipse)</li>\n</ul>\n" }, { "answer_id": 101995, "author": "GKelly", "author_id": 18744, "author_profile": "https://Stackoverflow.com/users/18744", "pm_score": 5, "selected": false, "text": "<p>I don't know about Eclipse specifically, I use IntelliJ which also suffers from memory growth (whether you're actively using it or not!). Anyway, in IntelliJ, I couldn't eliminate the problem, but I did slow down the memory growth by playing with the runtime VM options. You could try resetting these in Eclipse and see if they make a difference.</p>\n\n<p>You can edit the VM options in the eclipse.ini file in your eclipse folder.</p>\n\n<p>I found that (in IntelliJ) the garbage collector settings had the most effect on how fast the memory grows. </p>\n\n<p>My settings are:</p>\n\n<pre><code>-Xms128m\n-Xmx512m\n-XX:MaxPermSize=120m\n-XX:MaxGCPauseMillis=10\n-XX:MaxHeapFreeRatio=70\n-XX:+UseConcMarkSweepGC\n-XX:+CMSIncrementalMode\n-XX:+CMSIncrementalPacing\n</code></pre>\n\n<p>(See <a href=\"http://piotrga.wordpress.com/2006/12/12/intellij-and-garbage-collection/\" rel=\"noreferrer\">http://piotrga.wordpress.com/2006/12/12/intellij-and-garbage-collection/</a> for an explanation of the individual settings). As you can see, I'm more concerned with avoiding long pauses during editting than actuial memory usage but you could use this as a start.</p>\n" }, { "answer_id": 218880, "author": "kohlerm", "author_id": 26056, "author_profile": "https://Stackoverflow.com/users/26056", "pm_score": 1, "selected": false, "text": "<p>Instead of whining about how much memory Eclipse takes, just go ahead and analyze where the problem is. I might be just one plugin. </p>\n\n<p>Check the blog here :\n<a href=\"http://kohlerm.blogspot.com/2008/05/analyzing-memory-consumption-of-eclipse.html\" rel=\"nofollow noreferrer\">\"analyzing memory consumption of eclipse\"</a></p>\n\n<p>Regards,\nMarkus</p>\n" }, { "answer_id": 2538048, "author": "Thorbjørn Ravn Andersen", "author_id": 53897, "author_profile": "https://Stackoverflow.com/users/53897", "pm_score": -1, "selected": false, "text": "<p>Eclipse generally keeps a lot of meta-data in memory to allow for all kinds of IDE gymnastics.</p>\n\n<p>I have found that the default configuration of Eclipse works well for most purposes and that includes a limit (either given explicitly or implictly by the JVM) to how much memory can be consumed, and Eclipse will stay within that.</p>\n\n<p>Is there any particular reason you are concerned about memory usage?</p>\n" }, { "answer_id": 6775562, "author": "Arkadiusz Jamrocha", "author_id": 855852, "author_profile": "https://Stackoverflow.com/users/855852", "pm_score": 1, "selected": false, "text": "<p>I had problem with java-based programs memory consumption. I found that it could be related to the chosen jvm (in my case it was). Try to run eclipse with -client switch.</p>\n\n<p>In some operating systems (most of linux distros I believe), the default option is server vm, which will consume noticeable more memory when running applications with gui.</p>\n\n<p>In my case initial memory footprint went down from 300MB to 80MB.</p>\n\n<p>Sorry for my crappy English. I hope I helped.</p>\n\n<p>All Regards\nArkadiusz Jamrocha</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I use the recent Ganymede release of Eclipse, specifically the distro for Java EE and web developers. I have installed a few additional plugins (e.g. Subclipse, Spring, FindBugs) and removed all the Mylyn plugins. I don't do anything particularly heavy-duty within Eclipse such as starting an app server or connecting to databases, yet for some reason, after several hours use I see that Eclipse is using close to 500MB of memory. Does anybody know why Eclipse uses so much memory (leaky?), and more importantly, if there's anything I can do to improve this?
I don't know about Eclipse specifically, I use IntelliJ which also suffers from memory growth (whether you're actively using it or not!). Anyway, in IntelliJ, I couldn't eliminate the problem, but I did slow down the memory growth by playing with the runtime VM options. You could try resetting these in Eclipse and see if they make a difference. You can edit the VM options in the eclipse.ini file in your eclipse folder. I found that (in IntelliJ) the garbage collector settings had the most effect on how fast the memory grows. My settings are: ``` -Xms128m -Xmx512m -XX:MaxPermSize=120m -XX:MaxGCPauseMillis=10 -XX:MaxHeapFreeRatio=70 -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing ``` (See <http://piotrga.wordpress.com/2006/12/12/intellij-and-garbage-collection/> for an explanation of the individual settings). As you can see, I'm more concerned with avoiding long pauses during editting than actuial memory usage but you could use this as a start.
94,342
<p>I have a string which contain tags in the form <code>&lt; tag &gt;</code>. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like <code>"&lt; tab &gt;"</code> with the ascii equivelent of <code>'/t'</code>?</p>
[ { "answer_id": 94350, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 1, "selected": false, "text": "<p>Regex patterns should do the trick.</p>\n" }, { "answer_id": 94366, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": true, "text": "<pre><code>string s = \"...&lt;tab&gt;...\";\ns = s.Replace(\"&lt;tab&gt;\", \"\\t\");\n</code></pre>\n" }, { "answer_id": 94367, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "<pre><code>using System.Text.RegularExpressions;\n\nRegex.Replace(s, \"TAB\", \"\\t\");//s is your string and TAB is a tab.\n</code></pre>\n" }, { "answer_id": 94387, "author": "ddc0660", "author_id": 16027, "author_profile": "https://Stackoverflow.com/users/16027", "pm_score": 2, "selected": false, "text": "<pre><code>public static Regex regex = new Regex(\"&lt; tab &gt;\", RegexOptions.CultureInvariant | RegexOptions.Compiled);\npublic static string regexReplace = \"\\t\";\nstring result = regex.Replace(InputText,regexReplace);\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
I have a string which contain tags in the form `< tag >`. Is there an easy way for me to programmatically replace instances of these tags with special ascii characters? e.g. replace a tag like `"< tab >"` with the ascii equivelent of `'/t'`?
``` string s = "...<tab>..."; s = s.Replace("<tab>", "\t"); ```
94,372
<p>I am building a quiz and i need to calculate the total time taken to do the quiz. and i need to display the time taken in HH::MM::SS..any pointers?</p>
[ { "answer_id": 94427, "author": "Brian", "author_id": 1750627, "author_profile": "https://Stackoverflow.com/users/1750627", "pm_score": 3, "selected": true, "text": "<p>new Date().time returns the time in milliseconds.</p>\n\n<pre><code>var nStart:Number = new Date().time;\n\n// Some time passes\n\nvar nMillisElapsed:Number = new Date().time - nStart;\n\nvar strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + \"::\" + \n (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + \"::\" + \n (Math.floor(nMillisElapsed / (1000)) % 60);\n</code></pre>\n" }, { "answer_id": 4458977, "author": "mica", "author_id": 544503, "author_profile": "https://Stackoverflow.com/users/544503", "pm_score": 1, "selected": false, "text": "<p>Fill with zero when number is less than 10 (Thanks brian)</p>\n\n<pre><code>var now:Date; //\nvar startDate:Date;\nvar startTime:Number; \n// initialize timer and start it\nfunction initTimer():void{\n startDate = new Date();\n startTime = startDate.getTime();\n //\n var timer:Timer = new Timer(1000,0); // set a new break\n timer.addEventListener(TimerEvent.TIMER, onTimer); // add timer listener\n //\n function onTimer():void{\n now=new Date();\n var nowTime:Number = now.getTime();\n var diff:Number = nowTime-startTime;\n var strTime:String = Math.floor(diff / (1000 * 60 * 60)) + \":\" + \n zeroFill(Math.floor(diff / (1000 * 60)) % 60) + \":\" + \n zeroFill(Math.floor(diff / (1000)) % 60);\n // display where you want\n trace('time elapsed : ' + strTime);\n }\n // fill with zero when number is less than 10\n function zeroFill(myNumber:Number):String{\n var zeroFilledNumber:String=myNumber.toString();\n if(myNumber&lt;10){\n zeroFilledNumber = '0'+zeroFilledNumber;\n }\n return zeroFilledNumber;\n }\n\n // start TIMER\n timer.start();\n\n}\ninitTimer();\n</code></pre>\n" }, { "answer_id": 15896624, "author": "Jonathan Graef", "author_id": 1045086, "author_profile": "https://Stackoverflow.com/users/1045086", "pm_score": 2, "selected": false, "text": "<p>I resurrect this question to say that both Brian and mica are wrong. Creating a new Date() gives you the time according to the computer's clock. All someone has to do is set their clock back several minutes, and that would cause the quiz timer to go back several minutes as well. Or worse, they could set their clock back to a time before they started the quiz, and your app would think they spent a negative amount of time taking the quiz. o.O</p>\n\n<p>The solution is to use flash.utils.getTimer(). It returns the number of milliseconds since the swf started playing, regardless of what the computer's clock says.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>var startTime:Number = getTimer();\n\n// then after some time passes:\n\nvar elapsedMilliseconds:Number = getTimer() - startTime;\n</code></pre>\n\n<p>Then you can use Brian's code to format the time for display:</p>\n\n<pre><code>var strTime:String = Math.floor(elapsedMilliseconds / (1000 * 60 * 60)) + \"::\" + \n(Math.floor(elapsedMilliseconds / (1000 * 60)) % 60) + \"::\" + \n(Math.floor(elapsedMilliseconds / (1000)) % 60);\n</code></pre>\n" }, { "answer_id": 20033764, "author": "Chakroun Yesser", "author_id": 2898474, "author_profile": "https://Stackoverflow.com/users/2898474", "pm_score": 0, "selected": false, "text": "<pre><code>var countdown:Timer = new Timer(1000);\ncountdown.addEventListener(TimerEvent.TIMER, timerHandler);\ncountdown.start();\n\nfunction timerHandler(e:TimerEvent):void\n{ \n var minute = Math.floor(countdown.currentCount / 60);\n if(minute &lt; 10)\n minute = '0'+minute;\n\n var second = countdown.currentCount % 60;\n if(second &lt; 10)\n second = '0'+second;\n\n\n var timeElapsed = minute +':'+second;\n trace(timeElapsed);\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16458/" ]
I am building a quiz and i need to calculate the total time taken to do the quiz. and i need to display the time taken in HH::MM::SS..any pointers?
new Date().time returns the time in milliseconds. ``` var nStart:Number = new Date().time; // Some time passes var nMillisElapsed:Number = new Date().time - nStart; var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" + (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" + (Math.floor(nMillisElapsed / (1000)) % 60); ```
94,382
<p>I'm using gvim on Windows.</p> <p>In my _vimrc I've added:</p> <pre><code>set shell=powershell.exe set shellcmdflag=-c set shellpipe=&gt; set shellredir=&gt; function! Test() echo system("dir -name") endfunction command! -nargs=0 Test :call Test() </code></pre> <p>If I execute this function (:Test) I see nonsense characters (non number/letter ASCII characters).</p> <p>If I use cmd as the shell, it works (without the -name), so the problem seems to be with getting output from powershell into vim. </p> <p>Interestingly, this works great:</p> <pre><code>:!dir -name </code></pre> <p>As does this:</p> <pre><code>:r !dir -name </code></pre> <p><strong>UPDATE:</strong> confirming behavior mentioned by <a href="https://stackoverflow.com/questions/94382/vim-with-powershell#101743">David</a></p> <p>If you execute the set commands mentioned above in the _vimrc, :Test outputs nonsense. However, if you execute them directly in vim instead of in the _vimrc, :Test works as expected.</p> <p>Also, I've tried using iconv in case it was an encoding problem:</p> <pre><code>:echo iconv( system("dir -name"), "unicode", &amp;enc ) </code></pre> <p>But this didn't make any difference. I could be using the wrong encoding types though.</p> <p>Anyone know how to make this work?</p>
[ { "answer_id": 94697, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 2, "selected": false, "text": "<p>Try replacing </p>\n\n<pre><code>\"dir \\*vim\\*\"\n</code></pre>\n\n<p>with </p>\n\n<pre><code> \" -command { dir \\*vim\\* }\"\n</code></pre>\n\n<p><strong>EDIT:</strong> Try using cmd.exe as the shell and put \"powershell.exe\" before \"-command\"</p>\n" }, { "answer_id": 95038, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I don't use VIM but Powershell's default output is Unicode. Notepad can read unicode, you could use it to see if you are getting the output you expect.</p>\n" }, { "answer_id": 101743, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 2, "selected": false, "text": "<p>Interesting question - here is something else to add to the confusion. Without making any changes to my .vimrc file, if I then run the following commands in gvim:</p>\n\n<pre><code>:set shell=powershell.exe\n:set shellcmdflag=-noprofile\n:echo system(\"dir -name\")\n</code></pre>\n\n<p>It behaves as expected! </p>\n\n<p>If I make the same changes to my .vimrc file, though (the shell and shellcmdflag options), running :echo system(\"dir -name\") returns the nonsense characters!</p>\n" }, { "answer_id": 1670172, "author": "Raoul Supercopter", "author_id": 57123, "author_profile": "https://Stackoverflow.com/users/57123", "pm_score": 0, "selected": false, "text": "<p>I propose an hackish solution. It doesn't really solve the problem, but it get the job done somehow.</p>\n\n<p>This <a href=\"http://www.vim.org/scripts/script.php?script_id=2837\" rel=\"nofollow noreferrer\">Vim plugin</a> automate the creation of a temporary script file, powershell call through cmd.exe and paste of the result. It's not as nice as a proper powershell handling by vim, but it works.</p>\n" }, { "answer_id": 1999496, "author": "Adrian", "author_id": 108753, "author_profile": "https://Stackoverflow.com/users/108753", "pm_score": 2, "selected": false, "text": "<p>I suspect that the problem is that Powershell uses the native String encoding for .NET, which is UTF-16 plus a byte-order-mark.</p>\n\n<p>When it's piping objects between commands it's not a problem. It's a total PITA for external programs though.</p>\n\n<p>You can pipe the output through out-file, which does support changing the encoding, but still formats the output for the terminal that it's in by default (arrgh!), so things like \"Get-Process\" will truncate with ellipses, etc. You can specify the width of the virtual terminal that Out-File uses though.</p>\n\n<p>Not sure how useful this information is, but it does illuminate the problem a bit more.</p>\n" }, { "answer_id": 2539941, "author": "Dan Fitch", "author_id": 27614, "author_profile": "https://Stackoverflow.com/users/27614", "pm_score": 2, "selected": false, "text": "<p>The initial example code works fine for me when I plop it in vimrc.</p>\n\n<p>So now I'm trying to figure out what in my vimrc is making it function. Possibly:</p>\n\n<pre><code>set encoding=utf8\n</code></pre>\n\n<p><strong>Edit</strong>: Yep, that appears to do it. You probably want to have VIM defaulting to unicode anyway, these days...</p>\n" }, { "answer_id": 3419406, "author": "Nathan Hartley", "author_id": 80161, "author_profile": "https://Stackoverflow.com/users/80161", "pm_score": 6, "selected": true, "text": "<p>It is a bit of a hack, but the following works in Vim 7.2. Notice, I am running Powershell within a CMD session.</p>\n\n<pre><code>if has(\"win32\")\n set shell=cmd.exe\n set shellcmdflag=/c\\ powershell.exe\\ -NoLogo\\ -NoProfile\\ -NonInteractive\\ -ExecutionPolicy\\ RemoteSigned\n set shellpipe=|\n set shellredir=&gt;\nendif\n\nfunction! Test()\n echo system(\"dir -name\")\nendfunction\n</code></pre>\n\n<p>Tested with the following...</p>\n\n<ul>\n<li><code>:!dir -name</code></li>\n<li><code>:call Test()</code></li>\n</ul>\n" }, { "answer_id": 7830735, "author": "actf", "author_id": 205836, "author_profile": "https://Stackoverflow.com/users/205836", "pm_score": 4, "selected": false, "text": "<p>I ran into a similar problem described by many here.</p>\n\n<p>Specifically, calling </p>\n\n<pre><code>:set shell=powershell\n</code></pre>\n\n<p>manually from within vim would cause powershell to work fine, but as soon as I added:</p>\n\n<pre><code>set shell=powershell\n</code></pre>\n\n<p>to my vimrc file I would get the error \"Unable to open temp file .... \"</p>\n\n<p>The problem is that by default when shell is modified, vim automatically sets shellxquote to \" which means that shell commands will look like the following:</p>\n\n<pre><code> powershell -c \"cmd &gt; tmpfile\"\n</code></pre>\n\n<p>Where as this command needs to look like this, in order for vim to read the temp file:</p>\n\n<pre><code> powershell -c \"cmd\" &gt; tmpfile\n</code></pre>\n\n<p>Setting shellquote to \" in my vimrc file and unsetting shellxquote (i.e. setting it to a blank space) seem to fix all my problems:</p>\n\n<pre><code>set shell=powershell\nset shellcmdflag=-c\nset shellquote=\\\"\nset shellxquote=\n</code></pre>\n\n<p>I've also tried taking this further and scripting vim a bit using the system() call:\n<a href=\"https://stackoverflow.com/questions/7605917/system-with-powershell-in-vim\">system() with powershell in vim</a></p>\n" }, { "answer_id": 27499996, "author": "Enno", "author_id": 3528522, "author_profile": "https://Stackoverflow.com/users/3528522", "pm_score": 0, "selected": false, "text": "<p>Try instead\n<code>\nset shellcmdflag=\\ -c\n</code></p>\n\n<hr>\n\n<p>Explanation:</p>\n\n<p>Vim uses tempname() to generate a temp file path that system() reads. </p>\n\n<p>If &amp;shell contains 'sh' and &amp;shellcmdflag starts with '-' \nthen tempname() generates a temp file path with forward slashes.</p>\n\n<p>Thus, if\n<code>\nset shell=powershell\nset shellcmdflag=-c\n</code>\nthen Vim will try to read a temp file with forward slashes that \ncannot be found.</p>\n\n<p>A remedy is to set instead\n<code>\nset shellcmdflag=\\ -c\n</code>\nthat is, add a whitespace to &amp;shellcmdflag so that the first character\nis no longer '-' and tempname() produces a temp file path with backward \nslashes that can be found by system().</p>\n\n<hr>\n\n<p>I remarked on the vim_dev mailing list ( <a href=\"https://groups.google.com/forum/#!topic/vim_dev/vTR05EZyfE0\" rel=\"nofollow\">https://groups.google.com/forum/#!topic/vim_dev/vTR05EZyfE0</a> ) that this deserves better documentation.</p>\n" }, { "answer_id": 33745531, "author": "Mark Stanfill", "author_id": 5460180, "author_profile": "https://Stackoverflow.com/users/5460180", "pm_score": 1, "selected": false, "text": "<p>None of the answers on this page were working for me until I found this hint from <a href=\"https://github.com/dougireton/mirror_pond/blob/master/vimrc\" rel=\"nofollow\">https://github.com/dougireton/mirror_pond/blob/master/vimrc</a> - set shellxquote= [space character] was the missing piece.</p>\n\n<pre><code>if has(\"win32\") || has(\"gui_win32\") \n if executable(\"PowerShell\") \n \" Set PowerShell as the shell for running external ! commands \n \" http://stackoverflow.com/questions/7605917/system-with-powershell-in-vim \n set shell=PowerShell \n set shellcmdflag=-ExecutionPolicy\\ RemoteSigned\\ -Command \n set shellquote=\\\" \n \" shellxquote must be a literal space character. \n set shellxquote= \n endif \nendif \n</code></pre>\n" }, { "answer_id": 41980093, "author": "Lobo", "author_id": 2968792, "author_profile": "https://Stackoverflow.com/users/2968792", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/205836/actf\">actf</a> answer works for me, but because of Powershell built in DIFF (which is different from the Linux one) you must add this line to your Powershell profile to have diff working again in VIM:</p>\n\n<pre><code>Remove-Item Alias:diff -force\n</code></pre>\n" }, { "answer_id": 59870353, "author": "Rafael Kitover", "author_id": 262458, "author_profile": "https://Stackoverflow.com/users/262458", "pm_score": 1, "selected": false, "text": "<p>Combining the answers in this and the related thread, add the following to your <code>$profile</code> assuming you installed <code>diffutils</code> from chocolatey:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>Remove-Item Alias:diff -force\n</code></pre>\n\n<p>And add the following to your <code>~/.vimrc</code>:</p>\n\n<pre><code>if (has('win32') || has('gui_win32')) &amp;&amp; executable('pwsh')\n set shell=pwsh\n set shellcmdflag=\\ -ExecutionPolicy\\ RemoteSigned\\ -NoProfile\\ -Nologo\\ -NonInteractive\\ -Command\nendif\n</code></pre>\n\n<p><strong>make sure <code>shellcmdflag</code> is exactly as shown</strong></p>\n\n<p>All credit for these solutions to their respective contributors, this is merely an aggregation post.</p>\n" }, { "answer_id": 66261005, "author": "CRTejaswi", "author_id": 7794299, "author_profile": "https://Stackoverflow.com/users/7794299", "pm_score": 0, "selected": false, "text": "<p>I'm running GVim v8.2 (Windows).</p>\n<p>Using the fullpath to the executable works for me:</p>\n<pre><code>set shell=C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4407/" ]
I'm using gvim on Windows. In my \_vimrc I've added: ``` set shell=powershell.exe set shellcmdflag=-c set shellpipe=> set shellredir=> function! Test() echo system("dir -name") endfunction command! -nargs=0 Test :call Test() ``` If I execute this function (:Test) I see nonsense characters (non number/letter ASCII characters). If I use cmd as the shell, it works (without the -name), so the problem seems to be with getting output from powershell into vim. Interestingly, this works great: ``` :!dir -name ``` As does this: ``` :r !dir -name ``` **UPDATE:** confirming behavior mentioned by [David](https://stackoverflow.com/questions/94382/vim-with-powershell#101743) If you execute the set commands mentioned above in the \_vimrc, :Test outputs nonsense. However, if you execute them directly in vim instead of in the \_vimrc, :Test works as expected. Also, I've tried using iconv in case it was an encoding problem: ``` :echo iconv( system("dir -name"), "unicode", &enc ) ``` But this didn't make any difference. I could be using the wrong encoding types though. Anyone know how to make this work?
It is a bit of a hack, but the following works in Vim 7.2. Notice, I am running Powershell within a CMD session. ``` if has("win32") set shell=cmd.exe set shellcmdflag=/c\ powershell.exe\ -NoLogo\ -NoProfile\ -NonInteractive\ -ExecutionPolicy\ RemoteSigned set shellpipe=| set shellredir=> endif function! Test() echo system("dir -name") endfunction ``` Tested with the following... * `:!dir -name` * `:call Test()`
94,445
<p>I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL:</p> <blockquote> <p>unable to write 'random state'</p> </blockquote> <p>What does this mean?</p> <p>This is on an Ubuntu server. I have upgraded libssl to fix <a href="http://www.ubuntu.com/usn/usn-612-1">the recent security vulnerability</a>.</p>
[ { "answer_id": 94458, "author": "Ville Laurikari", "author_id": 7446, "author_profile": "https://Stackoverflow.com/users/7446", "pm_score": 10, "selected": true, "text": "<p>In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix:</p>\n\n<pre><code>sudo rm ~/.rnd\n</code></pre>\n\n<p>For more information, here's the entry from the <a href=\"http://www.openssl.org/support/faq.html#USER2\" rel=\"noreferrer\">OpenSSL FAQ</a>:</p>\n\n<blockquote>\n <p>Sometimes the openssl command line utility does not abort with a \"PRNG not seeded\" error message, but complains that it is \"unable to write 'random state'\". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file \".rnd\" in the current directory in this case, but this has changed with 0.9.6a.) </p>\n</blockquote>\n\n<p>So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.</p>\n\n<p>If everything seems to be in order, you could try running with <a href=\"http://en.wikipedia.org/wiki/Strace\" rel=\"noreferrer\">strace</a> and see what exactly is going on.</p>\n" }, { "answer_id": 94537, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 4, "selected": false, "text": "<p>Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.</p>\n" }, { "answer_id": 5537205, "author": "Zds", "author_id": 639119, "author_profile": "https://Stackoverflow.com/users/639119", "pm_score": 3, "selected": false, "text": "<p>The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.</p>\n" }, { "answer_id": 6484589, "author": "Jusuf", "author_id": 816211, "author_profile": "https://Stackoverflow.com/users/816211", "pm_score": 4, "selected": false, "text": "<p>I had the same thing on windows server. Then I figured out by changing the <code>vars.bat</code> which is:</p>\n\n<pre><code>set HOME=C:\\Program Files (x86)\\OpenVPN\\easy-rsa\n</code></pre>\n\n<p>then redo from beginning and everything should be fine.</p>\n" }, { "answer_id": 8216589, "author": "Beachhouse", "author_id": 783004, "author_profile": "https://Stackoverflow.com/users/783004", "pm_score": 8, "selected": false, "text": "<p>I know this question is on Linux, but on windows I had the same issue. Turns out you have to start the command prompt in \"Run As Administrator\" mode for it to work. Otherwise you get the same: unable to write 'random state' error.</p>\n" }, { "answer_id": 10316620, "author": "joel", "author_id": 1356315, "author_profile": "https://Stackoverflow.com/users/1356315", "pm_score": 6, "selected": false, "text": "<p>One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!</p>\n\n<p>I don't know how many times this has bitten me...</p>\n" }, { "answer_id": 48290001, "author": "Gangnus", "author_id": 715269, "author_profile": "https://Stackoverflow.com/users/715269", "pm_score": 3, "selected": false, "text": "<p>You should set the $RANDFILE environment variable and/or create $HOME/.rnd file. (<a href=\"https://www.openssl.org/docs/faq.html#LEGAL2\" rel=\"noreferrer\">OpenSSL FAQ</a>). <em>(Of course, you should have rights to that file. Others answers here are about that. But first you should have the file and a reference to it.)</em></p>\n\n<p>Up to version 0.9.6 OpenSSL wrote the seeding file in the current directory in the file \".rnd\". At version 0.9.6a you have no default seeding file. OpenSSL 0.9.6b and later will behave similarly to 0.9.6a, but will use a default of \"C:\\\" for HOME on Windows systems if the environment variable has not been set. </p>\n\n<p>If the default seeding file does not exist or is too short, the \"PRNG not seeded\" error message may occur. </p>\n\n<p>The $RANDFILE environment variable and $HOME/.rnd are only used by the OpenSSL command line tools. Applications using the OpenSSL library provide their own configuration options to specify the entropy source, please check out the documentation coming the with application.</p>\n" }, { "answer_id": 59715423, "author": "Guilherme Mussi", "author_id": 2037710, "author_profile": "https://Stackoverflow.com/users/2037710", "pm_score": 3, "selected": false, "text": "<p>I have come accross this problem today on AWS Lambda. I created an environment variable RANDFILE = /tmp/.random </p>\n\n<p>That did the trick.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ]
I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL: > > unable to write 'random state' > > > What does this mean? This is on an Ubuntu server. I have upgraded libssl to fix [the recent security vulnerability](http://www.ubuntu.com/usn/usn-612-1).
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix: ``` sudo rm ~/.rnd ``` For more information, here's the entry from the [OpenSSL FAQ](http://www.openssl.org/support/faq.html#USER2): > > Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.) > > > So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem. If everything seems to be in order, you could try running with [strace](http://en.wikipedia.org/wiki/Strace) and see what exactly is going on.
94,456
<p>I have an instance of a <code>System.Drawing.Bitmap</code> and would like to make it available to my WPF app in the form of a <code>System.Windows.Media.Imaging.BitmapImage</code>.</p> <p>What would be the best approach for this?</p>
[ { "answer_id": 94474, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "<p>The easiest thing is if you can make the WPF bitmap from a file directly.</p>\n\n<p>Otherwise you will have to use System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap.</p>\n" }, { "answer_id": 94495, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>I work at an imaging vendor and wrote an adapter for WPF to our image format which is similar to a System.Drawing.Bitmap.</p>\n\n<p>I wrote this KB to explain it to our customers:</p>\n\n<p><a href=\"http://www.atalasoft.com/kb/article.aspx?id=10156\" rel=\"noreferrer\">http://www.atalasoft.com/kb/article.aspx?id=10156</a></p>\n\n<p>And there is code there that does it. You need to replace AtalaImage with Bitmap and do the equivalent thing that we are doing -- it should be pretty straightforward.</p>\n" }, { "answer_id": 96470, "author": "Kevin", "author_id": 2723, "author_profile": "https://Stackoverflow.com/users/2723", "pm_score": 7, "selected": true, "text": "<p>Thanks to Hallgrim, here is the code I ended up with:</p>\n\n<pre><code>ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n bmp.GetHbitmap(), \n IntPtr.Zero, \n System.Windows.Int32Rect.Empty, \n BitmapSizeOptions.FromWidthAndHeight(width, height));\n</code></pre>\n\n<p>I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question</p>\n" }, { "answer_id": 1069509, "author": "Pawel Lesnikowski", "author_id": 80894, "author_profile": "https://Stackoverflow.com/users/80894", "pm_score": 8, "selected": false, "text": "<p>How about loading it from MemoryStream?</p>\n\n<pre><code>using(MemoryStream memory = new MemoryStream())\n{\n bitmap.Save(memory, ImageFormat.Png);\n memory.Position = 0;\n BitmapImage bitmapImage = new BitmapImage();\n bitmapImage.BeginInit();\n bitmapImage.StreamSource = memory;\n bitmapImage.CacheOption = BitmapCacheOption.OnLoad;\n bitmapImage.EndInit();\n}\n</code></pre>\n" }, { "answer_id": 1470182, "author": "Alastair Pitts", "author_id": 120243, "author_profile": "https://Stackoverflow.com/users/120243", "pm_score": 6, "selected": false, "text": "<p>I know this has been answered, but here are a couple of extension methods (for .NET 3.0+) that do the conversion. :)</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Converts a &lt;see cref=\"System.Drawing.Image\"/&gt; into a WPF &lt;see cref=\"BitmapSource\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"source\"&gt;The source image.&lt;/param&gt;\n /// &lt;returns&gt;A BitmapSource&lt;/returns&gt;\n public static BitmapSource ToBitmapSource(this System.Drawing.Image source)\n {\n System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);\n\n var bitSrc = bitmap.ToBitmapSource();\n\n bitmap.Dispose();\n bitmap = null;\n\n return bitSrc;\n }\n\n /// &lt;summary&gt;\n /// Converts a &lt;see cref=\"System.Drawing.Bitmap\"/&gt; into a WPF &lt;see cref=\"BitmapSource\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.\n /// &lt;/remarks&gt;\n /// &lt;param name=\"source\"&gt;The source bitmap.&lt;/param&gt;\n /// &lt;returns&gt;A BitmapSource&lt;/returns&gt;\n public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)\n {\n BitmapSource bitSrc = null;\n\n var hBitmap = source.GetHbitmap();\n\n try\n {\n bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n hBitmap,\n IntPtr.Zero,\n Int32Rect.Empty,\n BitmapSizeOptions.FromEmptyOptions());\n }\n catch (Win32Exception)\n {\n bitSrc = null;\n }\n finally\n {\n NativeMethods.DeleteObject(hBitmap);\n }\n\n return bitSrc;\n }\n</code></pre>\n\n<p>and the NativeMethods class (to appease FxCop)</p>\n\n<pre><code> /// &lt;summary&gt;\n/// FxCop requires all Marshalled functions to be in a class called NativeMethods.\n/// &lt;/summary&gt;\ninternal static class NativeMethods\n{\n [DllImport(\"gdi32.dll\")]\n [return: MarshalAs(UnmanagedType.Bool)]\n internal static extern bool DeleteObject(IntPtr hObject);\n}\n</code></pre>\n" }, { "answer_id": 6775114, "author": "Daniel Wolf", "author_id": 52041, "author_profile": "https://Stackoverflow.com/users/52041", "pm_score": 5, "selected": false, "text": "<p>It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:</p>\n\n<pre><code>using System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Windows.Media.Imaging;\n\npublic static class BitmapConversion {\n\n public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {\n using (MemoryStream stream = new MemoryStream()) {\n BitmapEncoder enc = new BmpBitmapEncoder();\n enc.Frames.Add(BitmapFrame.Create(bitmapsource));\n enc.Save(stream);\n\n using (var tempBitmap = new Bitmap(stream)) {\n // According to MSDN, one \"must keep the stream open for the lifetime of the Bitmap.\"\n // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.\n return new Bitmap(tempBitmap);\n }\n }\n }\n\n public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {\n using (MemoryStream stream = new MemoryStream()) {\n bitmap.Save(stream, ImageFormat.Bmp);\n\n stream.Position = 0;\n BitmapImage result = new BitmapImage();\n result.BeginInit();\n // According to MSDN, \"The default OnDemand cache option retains access to the stream until the image is needed.\"\n // Force the bitmap to load right now so we can dispose the stream.\n result.CacheOption = BitmapCacheOption.OnLoad;\n result.StreamSource = stream;\n result.EndInit();\n result.Freeze();\n return result;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 7375570, "author": "Roland", "author_id": 480894, "author_profile": "https://Stackoverflow.com/users/480894", "pm_score": 2, "selected": false, "text": "<p>I came to this question because I was trying to do the same, but in my case the Bitmap is from a resource/file. I found the best solution is as described in the following link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx</a></p>\n\n<pre><code>// Create the image element.\nImage simpleImage = new Image(); \nsimpleImage.Width = 200;\nsimpleImage.Margin = new Thickness(5);\n\n// Create source.\nBitmapImage bi = new BitmapImage();\n// BitmapImage.UriSource must be in a BeginInit/EndInit block.\nbi.BeginInit();\nbi.UriSource = new Uri(@\"/sampleImages/cherries_larger.jpg\",UriKind.RelativeOrAbsolute);\nbi.EndInit();\n// Set the image source.\nsimpleImage.Source = bi;\n</code></pre>\n" }, { "answer_id": 7390373, "author": "Tony", "author_id": 194717, "author_profile": "https://Stackoverflow.com/users/194717", "pm_score": 3, "selected": false, "text": "<pre><code>// at class level;\n[System.Runtime.InteropServices.DllImport(\"gdi32.dll\")]\npublic static extern bool DeleteObject(IntPtr hObject); // https://stackoverflow.com/a/1546121/194717\n\n\n/// &lt;summary&gt; \n/// Converts a &lt;see cref=\"System.Drawing.Bitmap\"/&gt; into a WPF &lt;see cref=\"BitmapSource\"/&gt;. \n/// &lt;/summary&gt; \n/// &lt;remarks&gt;Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. \n/// &lt;/remarks&gt; \n/// &lt;param name=\"source\"&gt;The source bitmap.&lt;/param&gt; \n/// &lt;returns&gt;A BitmapSource&lt;/returns&gt; \npublic static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)\n{\n var hBitmap = source.GetHbitmap();\n var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());\n\n DeleteObject(hBitmap);\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 29917964, "author": "weston", "author_id": 360211, "author_profile": "https://Stackoverflow.com/users/360211", "pm_score": 2, "selected": false, "text": "<p>My take on this built from a number of resources. <a href=\"https://stackoverflow.com/a/7035036\">https://stackoverflow.com/a/7035036</a> <a href=\"https://stackoverflow.com/a/1470182/360211\">https://stackoverflow.com/a/1470182/360211</a></p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Runtime.ConstrainedExecution;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Windows;\nusing System.Windows.Interop;\nusing System.Windows.Media.Imaging;\nusing Microsoft.Win32.SafeHandles;\n\nnamespace WpfHelpers\n{\n public static class BitmapToBitmapSource\n {\n public static BitmapSource ToBitmapSource(this Bitmap source)\n {\n using (var handle = new SafeHBitmapHandle(source))\n {\n return Imaging.CreateBitmapSourceFromHBitmap(handle.DangerousGetHandle(),\n IntPtr.Zero, Int32Rect.Empty,\n BitmapSizeOptions.FromEmptyOptions());\n }\n }\n\n [DllImport(\"gdi32\")]\n private static extern int DeleteObject(IntPtr o);\n\n private sealed class SafeHBitmapHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n [SecurityCritical]\n public SafeHBitmapHandle(Bitmap bitmap)\n : base(true)\n {\n SetHandle(bitmap.GetHbitmap());\n }\n\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n protected override bool ReleaseHandle()\n {\n return DeleteObject(handle) &gt; 0;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 32841840, "author": "Andreas", "author_id": 690656, "author_profile": "https://Stackoverflow.com/users/690656", "pm_score": 3, "selected": false, "text": "<p>You can just share the pixeldata between a both namespaces ( Media and Drawing) by writing a custom bitmapsource. The conversion will happen immediately and no additional memory will be allocated. If you do not want to explicitly create a copy of your Bitmap this is the method you want. </p>\n\n<pre><code>class SharedBitmapSource : BitmapSource, IDisposable\n{\n #region Public Properties\n\n /// &lt;summary&gt;\n /// I made it public so u can reuse it and get the best our of both namespaces\n /// &lt;/summary&gt;\n public Bitmap Bitmap { get; private set; }\n\n public override double DpiX { get { return Bitmap.HorizontalResolution; } }\n\n public override double DpiY { get { return Bitmap.VerticalResolution; } }\n\n public override int PixelHeight { get { return Bitmap.Height; } }\n\n public override int PixelWidth { get { return Bitmap.Width; } }\n\n public override System.Windows.Media.PixelFormat Format { get { return ConvertPixelFormat(Bitmap.PixelFormat); } }\n\n public override BitmapPalette Palette { get { return null; } }\n\n #endregion\n\n #region Constructor/Destructor\n\n public SharedBitmapSource(int width, int height,System.Drawing.Imaging.PixelFormat sourceFormat)\n :this(new Bitmap(width,height, sourceFormat) ) { }\n\n public SharedBitmapSource(Bitmap bitmap)\n {\n Bitmap = bitmap;\n }\n\n // Use C# destructor syntax for finalization code.\n ~SharedBitmapSource()\n {\n // Simply call Dispose(false).\n Dispose(false);\n }\n\n #endregion\n\n #region Overrides\n\n public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)\n {\n BitmapData sourceData = Bitmap.LockBits(\n new Rectangle(sourceRect.X, sourceRect.Y, sourceRect.Width, sourceRect.Height),\n ImageLockMode.ReadOnly,\n Bitmap.PixelFormat);\n\n var length = sourceData.Stride * sourceData.Height;\n\n if (pixels is byte[])\n {\n var bytes = pixels as byte[];\n Marshal.Copy(sourceData.Scan0, bytes, 0, length);\n }\n\n Bitmap.UnlockBits(sourceData);\n }\n\n protected override Freezable CreateInstanceCore()\n {\n return (Freezable)Activator.CreateInstance(GetType());\n }\n\n #endregion\n\n #region Public Methods\n\n public BitmapSource Resize(int newWidth, int newHeight)\n {\n Image newImage = new Bitmap(newWidth, newHeight);\n using (Graphics graphicsHandle = Graphics.FromImage(newImage))\n {\n graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;\n graphicsHandle.DrawImage(Bitmap, 0, 0, newWidth, newHeight);\n }\n return new SharedBitmapSource(newImage as Bitmap);\n }\n\n public new BitmapSource Clone()\n {\n return new SharedBitmapSource(new Bitmap(Bitmap));\n }\n\n //Implement IDisposable.\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n #endregion\n\n #region Protected/Private Methods\n\n private static System.Windows.Media.PixelFormat ConvertPixelFormat(System.Drawing.Imaging.PixelFormat sourceFormat)\n {\n switch (sourceFormat)\n {\n case System.Drawing.Imaging.PixelFormat.Format24bppRgb:\n return PixelFormats.Bgr24;\n\n case System.Drawing.Imaging.PixelFormat.Format32bppArgb:\n return PixelFormats.Pbgra32;\n\n case System.Drawing.Imaging.PixelFormat.Format32bppRgb:\n return PixelFormats.Bgr32;\n\n }\n return new System.Windows.Media.PixelFormat();\n }\n\n private bool _disposed = false;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n // Free other state (managed objects).\n }\n // Free your own state (unmanaged objects).\n // Set large fields to null.\n _disposed = true;\n }\n }\n\n #endregion\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ]
I have an instance of a `System.Drawing.Bitmap` and would like to make it available to my WPF app in the form of a `System.Windows.Media.Imaging.BitmapImage`. What would be the best approach for this?
Thanks to Hallgrim, here is the code I ended up with: ``` ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(width, height)); ``` I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question
94,488
<p>More specifically, when the exception contains custom objects which may or may not themselves be serializable.</p> <p>Take this example:</p> <pre><code>public class MyException : Exception { private readonly string resourceName; private readonly IList&lt;string&gt; validationErrors; public MyException(string resourceName, IList&lt;string&gt; validationErrors) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public string ResourceName { get { return this.resourceName; } } public IList&lt;string&gt; ValidationErrors { get { return this.validationErrors; } } } </code></pre> <p>If this Exception is serialized and de-serialized, the two custom properties (<code>ResourceName</code> and <code>ValidationErrors</code>) will not be preserved. The properties will return <code>null</code>.</p> <p><strong>Is there a common code pattern for implementing serialization for custom exception?</strong></p>
[ { "answer_id": 94511, "author": "David Hill", "author_id": 1181217, "author_profile": "https://Stackoverflow.com/users/1181217", "pm_score": 0, "selected": false, "text": "<p>Mark the class with [Serializable], although I'm not sure how well a IList member will be handled by the serializer.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The post below is correct, because your custom exception has constructor that takes parameters, you must implement ISerializable.</p>\n\n<p>If you used a default constructor and exposed the two custom members with getter/setter properties, you could get away with just setting the attribute.</p>\n" }, { "answer_id": 94524, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Implement ISerializable, and follow the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable%28VS.71%29.aspx\" rel=\"noreferrer\">normal pattern</a> for doing this.</p>\n\n<p>You need to tag the class with the [Serializable] attribute, and add support for that interface, and also add the implied constructor (described on that page, search for <em>implies a constructor</em>). You can see an example of its implementation in the code below the text.</p>\n" }, { "answer_id": 94549, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": -1, "selected": false, "text": "<p>I have to think that wanting to serialize an exception is a strong indication that you're taking the wrong approach to something. What's the ultimate goal, here? If you're passing the exception between two processes, or between separate runs of the same process, then most of the properties of the exception aren't going to be valid in the other process anyway.</p>\n\n<p>It would probably make more sense to extract the state information you want at the catch() statement, and archive that.</p>\n" }, { "answer_id": 94625, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 5, "selected": false, "text": "<p>Exception is already serializable, but you need to override the <code>GetObjectData</code> method to store your variables and provide a constructor which can be called when re-hydrating your object.</p>\n\n<p>So your example becomes:</p>\n\n<pre><code>[Serializable]\npublic class MyException : Exception\n{\n private readonly string resourceName;\n private readonly IList&lt;string&gt; validationErrors;\n\n public MyException(string resourceName, IList&lt;string&gt; validationErrors)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n public string ResourceName\n {\n get { return this.resourceName; }\n }\n\n public IList&lt;string&gt; ValidationErrors\n {\n get { return this.validationErrors; }\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]\n protected MyException(SerializationInfo info, StreamingContext context) : base (info, context)\n {\n this.resourceName = info.GetString(\"MyException.ResourceName\");\n this.validationErrors = info.GetValue(\"MyException.ValidationErrors\", typeof(IList&lt;string&gt;));\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)]\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n base.GetObjectData(info, context);\n\n info.AddValue(\"MyException.ResourceName\", this.ResourceName);\n\n // Note: if \"List&lt;T&gt;\" isn't serializable you may need to work out another\n // method of adding your list, this is just for show...\n info.AddValue(\"MyException.ValidationErrors\", this.ValidationErrors, typeof(IList&lt;string&gt;));\n }\n\n}\n</code></pre>\n" }, { "answer_id": 95586, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": false, "text": "<p>There used to be an excellent article from Eric Gunnerson on MSDN \"The well-tempered exception\" but it seems to have been pulled. The URL was:</p>\n\n<p><a href=\"http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp08162001.asp\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp08162001.asp</a></p>\n\n<p>Aydsman's answer is correct, more info here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms229064.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms229064.aspx</a></p>\n\n<p>I can't think of any use-case for an Exception with non-serializable members, but if you avoid attempting to serialize/deserialize them in GetObjectData and the deserialization constructor you should be OK. Also mark them with the [NonSerialized] attribute, more as documentation than anything else, since you are implementing the serialization yourself.</p>\n" }, { "answer_id": 100369, "author": "Daniel Fortunov", "author_id": 5975, "author_profile": "https://Stackoverflow.com/users/5975", "pm_score": 10, "selected": true, "text": "<h2>Base implementation, without custom properties</h2>\n\n<p><strong><em>SerializableExceptionWithoutCustomProperties.cs:</em></strong></p>\n\n<pre><code>namespace SerializableExceptions\n{\n using System;\n using System.Runtime.Serialization;\n\n [Serializable]\n // Important: This attribute is NOT inherited from Exception, and MUST be specified \n // otherwise serialization will fail with a SerializationException stating that\n // \"Type X in Assembly Y is not marked as serializable.\"\n public class SerializableExceptionWithoutCustomProperties : Exception\n {\n public SerializableExceptionWithoutCustomProperties()\n {\n }\n\n public SerializableExceptionWithoutCustomProperties(string message) \n : base(message)\n {\n }\n\n public SerializableExceptionWithoutCustomProperties(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n\n // Without this constructor, deserialization will fail\n protected SerializableExceptionWithoutCustomProperties(SerializationInfo info, StreamingContext context) \n : base(info, context)\n {\n }\n }\n}\n</code></pre>\n\n<h2>Full implementation, with custom properties</h2>\n\n<p>Complete implementation of a custom serializable exception (<code>MySerializableException</code>), and a derived <code>sealed</code> exception (<code>MyDerivedSerializableException</code>).</p>\n\n<p>The main points about this implementation are summarized here:</p>\n\n<ol>\n<li>You <strong>must decorate each derived class with the <code>[Serializable]</code> attribute</strong> —\nThis attribute is not inherited from the base class, and if it is not specified, serialization will fail with a <code>SerializationException</code> stating that <em>\"Type X in Assembly Y is not marked as serializable.\"</em></li>\n<li>You <strong>must implement custom serialization</strong>. The <code>[Serializable]</code> attribute alone is not enough — <code>Exception</code> implements <code>ISerializable</code> which means your derived classes must also implement custom serialization. This involves two steps:\n\n<ol>\n<li><strong>Provide a serialization constructor</strong>. This constructor should be <code>private</code> if your class is <code>sealed</code>, otherwise it should be <code>protected</code> to allow access to derived classes.</li>\n<li><strong>Override GetObjectData()</strong> and make sure you call through to <code>base.GetObjectData(info, context)</code> at the end, in order to let the base class save its own state.</li>\n</ol></li>\n</ol>\n\n<p><strong><em>SerializableExceptionWithCustomProperties.cs:</em></strong></p>\n\n<pre><code>namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.Runtime.Serialization;\n using System.Security.Permissions;\n\n [Serializable]\n // Important: This attribute is NOT inherited from Exception, and MUST be specified \n // otherwise serialization will fail with a SerializationException stating that\n // \"Type X in Assembly Y is not marked as serializable.\"\n public class SerializableExceptionWithCustomProperties : Exception\n {\n private readonly string resourceName;\n private readonly IList&lt;string&gt; validationErrors;\n\n public SerializableExceptionWithCustomProperties()\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message) \n : base(message)\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message, Exception innerException)\n : base(message, innerException)\n {\n }\n\n public SerializableExceptionWithCustomProperties(string message, string resourceName, IList&lt;string&gt; validationErrors)\n : base(message)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n public SerializableExceptionWithCustomProperties(string message, string resourceName, IList&lt;string&gt; validationErrors, Exception innerException)\n : base(message, innerException)\n {\n this.resourceName = resourceName;\n this.validationErrors = validationErrors;\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n // Constructor should be protected for unsealed classes, private for sealed classes.\n // (The Serializer invokes this constructor through reflection, so it can be private)\n protected SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n this.resourceName = info.GetString(\"ResourceName\");\n this.validationErrors = (IList&lt;string&gt;)info.GetValue(\"ValidationErrors\", typeof(IList&lt;string&gt;));\n }\n\n public string ResourceName\n {\n get { return this.resourceName; }\n }\n\n public IList&lt;string&gt; ValidationErrors\n {\n get { return this.validationErrors; }\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (info == null)\n {\n throw new ArgumentNullException(\"info\");\n }\n\n info.AddValue(\"ResourceName\", this.ResourceName);\n\n // Note: if \"List&lt;T&gt;\" isn't serializable you may need to work out another\n // method of adding your list, this is just for show...\n info.AddValue(\"ValidationErrors\", this.ValidationErrors, typeof(IList&lt;string&gt;));\n\n // MUST call through to the base class to let it save its own state\n base.GetObjectData(info, context);\n }\n }\n}\n</code></pre>\n\n<p><strong><em>DerivedSerializableExceptionWithAdditionalCustomProperties.cs:</em></strong></p>\n\n<pre><code>namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.Runtime.Serialization;\n using System.Security.Permissions;\n\n [Serializable]\n public sealed class DerivedSerializableExceptionWithAdditionalCustomProperty : SerializableExceptionWithCustomProperties\n {\n private readonly string username;\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty()\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message)\n : base(message)\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, Exception innerException) \n : base(message, innerException)\n {\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList&lt;string&gt; validationErrors) \n : base(message, resourceName, validationErrors)\n {\n this.username = username;\n }\n\n public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList&lt;string&gt; validationErrors, Exception innerException) \n : base(message, resourceName, validationErrors, innerException)\n {\n this.username = username;\n }\n\n [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]\n // Serialization constructor is private, as this class is sealed\n private DerivedSerializableExceptionWithAdditionalCustomProperty(SerializationInfo info, StreamingContext context)\n : base(info, context)\n {\n this.username = info.GetString(\"Username\");\n }\n\n public string Username\n {\n get { return this.username; }\n }\n\n public override void GetObjectData(SerializationInfo info, StreamingContext context)\n {\n if (info == null)\n {\n throw new ArgumentNullException(\"info\");\n }\n info.AddValue(\"Username\", this.username);\n base.GetObjectData(info, context);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Unit Tests</h2>\n\n<p>MSTest unit tests for the three exception types defined above.</p>\n\n<p><strong><em>UnitTests.cs:</em></strong></p>\n\n<pre><code>namespace SerializableExceptions\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Runtime.Serialization.Formatters.Binary;\n using Microsoft.VisualStudio.TestTools.UnitTesting;\n\n [TestClass]\n public class UnitTests\n {\n private const string Message = \"The widget has unavoidably blooped out.\";\n private const string ResourceName = \"Resource-A\";\n private const string ValidationError1 = \"You forgot to set the whizz bang flag.\";\n private const string ValidationError2 = \"Wally cannot operate in zero gravity.\";\n private readonly List&lt;string&gt; validationErrors = new List&lt;string&gt;();\n private const string Username = \"Barry\";\n\n public UnitTests()\n {\n validationErrors.Add(ValidationError1);\n validationErrors.Add(ValidationError2);\n }\n\n [TestMethod]\n public void TestSerializableExceptionWithoutCustomProperties()\n {\n Exception ex =\n new SerializableExceptionWithoutCustomProperties(\n \"Message\", new Exception(\"Inner exception.\"));\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (SerializableExceptionWithoutCustomProperties)bf.Deserialize(ms);\n }\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n\n [TestMethod]\n public void TestSerializableExceptionWithCustomProperties()\n {\n SerializableExceptionWithCustomProperties ex = \n new SerializableExceptionWithCustomProperties(Message, ResourceName, validationErrors);\n\n // Sanity check: Make sure custom properties are set before serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (SerializableExceptionWithCustomProperties)bf.Deserialize(ms);\n }\n\n // Make sure custom properties are preserved after serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n\n [TestMethod]\n public void TestDerivedSerializableExceptionWithAdditionalCustomProperty()\n {\n DerivedSerializableExceptionWithAdditionalCustomProperty ex = \n new DerivedSerializableExceptionWithAdditionalCustomProperty(Message, Username, ResourceName, validationErrors);\n\n // Sanity check: Make sure custom properties are set before serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n Assert.AreEqual(Username, ex.Username);\n\n // Save the full ToString() value, including the exception message and stack trace.\n string exceptionToString = ex.ToString();\n\n // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter\n BinaryFormatter bf = new BinaryFormatter();\n using (MemoryStream ms = new MemoryStream())\n {\n // \"Save\" object state\n bf.Serialize(ms, ex);\n\n // Re-use the same stream for de-serialization\n ms.Seek(0, 0);\n\n // Replace the original exception with de-serialized one\n ex = (DerivedSerializableExceptionWithAdditionalCustomProperty)bf.Deserialize(ms);\n }\n\n // Make sure custom properties are preserved after serialization\n Assert.AreEqual(Message, ex.Message, \"Message\");\n Assert.AreEqual(ResourceName, ex.ResourceName, \"ex.ResourceName\");\n Assert.AreEqual(2, ex.ValidationErrors.Count, \"ex.ValidationErrors.Count\");\n Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], \"ex.ValidationErrors[0]\");\n Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], \"ex.ValidationErrors[1]\");\n Assert.AreEqual(Username, ex.Username);\n\n // Double-check that the exception message and stack trace (owned by the base Exception) are preserved\n Assert.AreEqual(exceptionToString, ex.ToString(), \"ex.ToString()\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 26895291, "author": "Uwe Keim", "author_id": 107625, "author_profile": "https://Stackoverflow.com/users/107625", "pm_score": 4, "selected": false, "text": "<p>To add to the correct answers above, I discovered that I can avoid doing this custom serialization stuff if I store my custom properties in the <a href=\"http://msdn.microsoft.com/en-us/library/system.exception.data\" rel=\"noreferrer\"><code>Data</code> collection</a> of the <code>Exception</code> class.</p>\n\n<p>E.g.:</p>\n\n<pre><code>[Serializable]\npublic class JsonReadException : Exception\n{\n // ...\n\n public string JsonFilePath\n {\n get { return Data[@\"_jsonFilePath\"] as string; }\n private set { Data[@\"_jsonFilePath\"] = value; }\n }\n\n public string Json\n {\n get { return Data[@\"_json\"] as string; }\n private set { Data[@\"_json\"] = value; }\n }\n\n // ...\n}\n</code></pre>\n\n<p>Probably this is less efficient in terms of performance than <a href=\"https://stackoverflow.com/a/100369/107625\">the solution provided by Daniel</a> and probably only works for \"integral\" types like strings and integers and the like.</p>\n\n<p>Still it was very easy and very understandable for me.</p>\n" }, { "answer_id": 66713266, "author": "user2205317", "author_id": 2205317, "author_profile": "https://Stackoverflow.com/users/2205317", "pm_score": 2, "selected": false, "text": "<p>In .NET Core, .Net 5.0 and above do not use Serializable because Microsoft follows the security threat practices found in <a href=\"https://aka.ms/binaryformatter\" rel=\"nofollow noreferrer\">BinaryFormatter</a>.</p>\n<p>Use the example storing in Data Collection</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5975/" ]
More specifically, when the exception contains custom objects which may or may not themselves be serializable. Take this example: ``` public class MyException : Exception { private readonly string resourceName; private readonly IList<string> validationErrors; public MyException(string resourceName, IList<string> validationErrors) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public string ResourceName { get { return this.resourceName; } } public IList<string> ValidationErrors { get { return this.validationErrors; } } } ``` If this Exception is serialized and de-serialized, the two custom properties (`ResourceName` and `ValidationErrors`) will not be preserved. The properties will return `null`. **Is there a common code pattern for implementing serialization for custom exception?**
Base implementation, without custom properties ---------------------------------------------- ***SerializableExceptionWithoutCustomProperties.cs:*** ``` namespace SerializableExceptions { using System; using System.Runtime.Serialization; [Serializable] // Important: This attribute is NOT inherited from Exception, and MUST be specified // otherwise serialization will fail with a SerializationException stating that // "Type X in Assembly Y is not marked as serializable." public class SerializableExceptionWithoutCustomProperties : Exception { public SerializableExceptionWithoutCustomProperties() { } public SerializableExceptionWithoutCustomProperties(string message) : base(message) { } public SerializableExceptionWithoutCustomProperties(string message, Exception innerException) : base(message, innerException) { } // Without this constructor, deserialization will fail protected SerializableExceptionWithoutCustomProperties(SerializationInfo info, StreamingContext context) : base(info, context) { } } } ``` Full implementation, with custom properties ------------------------------------------- Complete implementation of a custom serializable exception (`MySerializableException`), and a derived `sealed` exception (`MyDerivedSerializableException`). The main points about this implementation are summarized here: 1. You **must decorate each derived class with the `[Serializable]` attribute** — This attribute is not inherited from the base class, and if it is not specified, serialization will fail with a `SerializationException` stating that *"Type X in Assembly Y is not marked as serializable."* 2. You **must implement custom serialization**. The `[Serializable]` attribute alone is not enough — `Exception` implements `ISerializable` which means your derived classes must also implement custom serialization. This involves two steps: 1. **Provide a serialization constructor**. This constructor should be `private` if your class is `sealed`, otherwise it should be `protected` to allow access to derived classes. 2. **Override GetObjectData()** and make sure you call through to `base.GetObjectData(info, context)` at the end, in order to let the base class save its own state. ***SerializableExceptionWithCustomProperties.cs:*** ``` namespace SerializableExceptions { using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] // Important: This attribute is NOT inherited from Exception, and MUST be specified // otherwise serialization will fail with a SerializationException stating that // "Type X in Assembly Y is not marked as serializable." public class SerializableExceptionWithCustomProperties : Exception { private readonly string resourceName; private readonly IList<string> validationErrors; public SerializableExceptionWithCustomProperties() { } public SerializableExceptionWithCustomProperties(string message) : base(message) { } public SerializableExceptionWithCustomProperties(string message, Exception innerException) : base(message, innerException) { } public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors) : base(message) { this.resourceName = resourceName; this.validationErrors = validationErrors; } public SerializableExceptionWithCustomProperties(string message, string resourceName, IList<string> validationErrors, Exception innerException) : base(message, innerException) { this.resourceName = resourceName; this.validationErrors = validationErrors; } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] // Constructor should be protected for unsealed classes, private for sealed classes. // (The Serializer invokes this constructor through reflection, so it can be private) protected SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context) : base(info, context) { this.resourceName = info.GetString("ResourceName"); this.validationErrors = (IList<string>)info.GetValue("ValidationErrors", typeof(IList<string>)); } public string ResourceName { get { return this.resourceName; } } public IList<string> ValidationErrors { get { return this.validationErrors; } } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("ResourceName", this.ResourceName); // Note: if "List<T>" isn't serializable you may need to work out another // method of adding your list, this is just for show... info.AddValue("ValidationErrors", this.ValidationErrors, typeof(IList<string>)); // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } } } ``` ***DerivedSerializableExceptionWithAdditionalCustomProperties.cs:*** ``` namespace SerializableExceptions { using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Security.Permissions; [Serializable] public sealed class DerivedSerializableExceptionWithAdditionalCustomProperty : SerializableExceptionWithCustomProperties { private readonly string username; public DerivedSerializableExceptionWithAdditionalCustomProperty() { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message) : base(message) { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, Exception innerException) : base(message, innerException) { } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors) : base(message, resourceName, validationErrors) { this.username = username; } public DerivedSerializableExceptionWithAdditionalCustomProperty(string message, string username, string resourceName, IList<string> validationErrors, Exception innerException) : base(message, resourceName, validationErrors, innerException) { this.username = username; } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] // Serialization constructor is private, as this class is sealed private DerivedSerializableExceptionWithAdditionalCustomProperty(SerializationInfo info, StreamingContext context) : base(info, context) { this.username = info.GetString("Username"); } public string Username { get { return this.username; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("Username", this.username); base.GetObjectData(info, context); } } } ``` --- Unit Tests ---------- MSTest unit tests for the three exception types defined above. ***UnitTests.cs:*** ``` namespace SerializableExceptions { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class UnitTests { private const string Message = "The widget has unavoidably blooped out."; private const string ResourceName = "Resource-A"; private const string ValidationError1 = "You forgot to set the whizz bang flag."; private const string ValidationError2 = "Wally cannot operate in zero gravity."; private readonly List<string> validationErrors = new List<string>(); private const string Username = "Barry"; public UnitTests() { validationErrors.Add(ValidationError1); validationErrors.Add(ValidationError2); } [TestMethod] public void TestSerializableExceptionWithoutCustomProperties() { Exception ex = new SerializableExceptionWithoutCustomProperties( "Message", new Exception("Inner exception.")); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (SerializableExceptionWithoutCustomProperties)bf.Deserialize(ms); } // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } [TestMethod] public void TestSerializableExceptionWithCustomProperties() { SerializableExceptionWithCustomProperties ex = new SerializableExceptionWithCustomProperties(Message, ResourceName, validationErrors); // Sanity check: Make sure custom properties are set before serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (SerializableExceptionWithCustomProperties)bf.Deserialize(ms); } // Make sure custom properties are preserved after serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } [TestMethod] public void TestDerivedSerializableExceptionWithAdditionalCustomProperty() { DerivedSerializableExceptionWithAdditionalCustomProperty ex = new DerivedSerializableExceptionWithAdditionalCustomProperty(Message, Username, ResourceName, validationErrors); // Sanity check: Make sure custom properties are set before serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); Assert.AreEqual(Username, ex.Username); // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = ex.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { // "Save" object state bf.Serialize(ms, ex); // Re-use the same stream for de-serialization ms.Seek(0, 0); // Replace the original exception with de-serialized one ex = (DerivedSerializableExceptionWithAdditionalCustomProperty)bf.Deserialize(ms); } // Make sure custom properties are preserved after serialization Assert.AreEqual(Message, ex.Message, "Message"); Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName"); Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count"); Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]"); Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]"); Assert.AreEqual(Username, ex.Username); // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()"); } } } ```
94,490
<p>I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).</p> <p>I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.</p>
[ { "answer_id": 94491, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 4, "selected": true, "text": "<p>Here's how I did it (grabbing all files ending in \".ranks\"):</p>\n\n<pre><code>import urllib2, cStringIO, zipfile\n\ntry:\n remotezip = urllib2.urlopen(url)\n zipinmemory = cStringIO.StringIO(remotezip.read())\n zip = zipfile.ZipFile(zipinmemory)\n for fn in zip.namelist():\n if fn.endswith(\".ranks\"):\n ranks_data = zip.read(fn)\n for line in ranks_data.split(\"\\n\"):\n # do something with each line\nexcept urllib2.HTTPError:\n # handle exception\n</code></pre>\n" }, { "answer_id": 94516, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>Bear in mind that merely decompressing a ZIP file may result in <a href=\"http://en.wikipedia.org/wiki/Decompression_bomb\" rel=\"nofollow noreferrer\">a security vulnerability</a>.</p>\n" }, { "answer_id": 952834, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 2, "selected": false, "text": "<p>Thanks Marcel for your question and answer (I had the same problem in a different context and encountered the same difficulty with file-like objects not really being file-like)! Just as an update: For Python 3.0, your code needs to be modified slightly:</p>\n\n<pre><code>import urllib.request, io, zipfile\n\ntry:\n remotezip = urllib.request.urlopen(url)\n zipinmemory = io.BytesIO(remotezip.read())\n zip = zipfile.ZipFile(zipinmemory)\n for fn in zip.namelist():\n if fn.endswith(\".ranks\"):\n ranks_data = zip.read(fn)\n for line in ranks_data.split(\"\\n\"):\n # do something with each line\nexcept urllib.request.HTTPError:\n # handle exception\n</code></pre>\n" }, { "answer_id": 14461148, "author": "Filipe Varela", "author_id": 2000700, "author_profile": "https://Stackoverflow.com/users/2000700", "pm_score": 2, "selected": false, "text": "<p>This will do the job without downloading the entire zip file!</p>\n\n<p><a href=\"http://pypi.python.org/pypi/pyremotezip\" rel=\"nofollow\">http://pypi.python.org/pypi/pyremotezip</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676/" ]
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory). I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.
Here's how I did it (grabbing all files ending in ".ranks"): ``` import urllib2, cStringIO, zipfile try: remotezip = urllib2.urlopen(url) zipinmemory = cStringIO.StringIO(remotezip.read()) zip = zipfile.ZipFile(zipinmemory) for fn in zip.namelist(): if fn.endswith(".ranks"): ranks_data = zip.read(fn) for line in ranks_data.split("\n"): # do something with each line except urllib2.HTTPError: # handle exception ```
94,502
<p>I have a simple database table called "Entries":</p> <pre><code>class CreateEntries &lt; ActiveRecord::Migration def self.up create_table :entries do |t| t.string :firstName t.string :lastName #etc. t.timestamps end end def self.down drop_table :entries end end </code></pre> <p>How do I write a handler that will return the contents of the Entries table as a CSV file (ideally in a way that it will automatically open in Excel)?</p> <pre><code>class EntriesController &lt; ApplicationController def getcsv @entries = Entry.find( :all ) # ??? NOW WHAT ???? end end </code></pre>
[ { "answer_id": 94519, "author": "Brian", "author_id": 15901, "author_profile": "https://Stackoverflow.com/users/15901", "pm_score": 6, "selected": true, "text": "<p>There is a plugin called FasterCSV that handles this wonderfully.</p>\n" }, { "answer_id": 94520, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 3, "selected": false, "text": "<p>Take a look into the <a href=\"http://fastercsv.rubyforge.org/classes/FasterCSV.html\" rel=\"nofollow noreferrer\">FasterCSV</a> gem.</p>\n\n<p>If all you need is excel support, you might also look into generating a xls directly. (See Spreadsheet::Excel)</p>\n\n<pre><code>gem install fastercsv\ngem install spreadsheet-excel\n</code></pre>\n\n<p>I find these options good for opening the csv file in Windows Excel:</p>\n\n<pre><code>FasterCSV.generate(:col_sep =&gt; \";\", :row_sep =&gt; \"\\r\\n\") { |csv| ... }\n</code></pre>\n\n<p>As for the ActiveRecord part, something like this would do:</p>\n\n<pre><code>CSV_FIELDS = %w[ title created_at etc ]\nFasterCSV.generate do |csv|\n Entry.all.map { |r| CSV_FIELDS.map { |m| r.send m } }.each { |row| csv &lt;&lt; row }\nend\n</code></pre>\n" }, { "answer_id": 94577, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 2, "selected": false, "text": "<p>You need to set the Content-Type header in your response, then send the data. Content_Type: application/vnd.ms-excel should do the trick.</p>\n\n<p>You may also want to set the Content-Disposition header so that it looks like an Excel document, and the browser picks a reasonable default file name; that's something like Content-Disposition: attachment; filename=\"#{suggested_name}.xls\"</p>\n\n<p>I suggest using the fastercsv ruby gem to generate your CSV, but there's also a builtin csv. The fastercsv sample code (from the gem's documentation) looks like this:</p>\n\n<pre><code>csv_string = FasterCSV.generate do |csv|\n csv &lt;&lt; [\"row\", \"of\", \"CSV\", \"data\"]\n csv &lt;&lt; [\"another\", \"row\"]\n# ...\nend\n</code></pre>\n" }, { "answer_id": 94626, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://fastercsv.rubyforge.org/classes/FasterCSV.html\" rel=\"noreferrer\">FasterCSV</a> is definitely the way to go, but if you want to serve it directly from your Rails app, you'll want to set up some response headers, too.</p>\n\n<p>I keep a method around to set up the filename and necessary headers:</p>\n\n<pre><code>def render_csv(filename = nil)\n filename ||= params[:action]\n filename += '.csv'\n\n if request.env['HTTP_USER_AGENT'] =~ /msie/i\n headers['Pragma'] = 'public'\n headers[\"Content-type\"] = \"text/plain\" \n headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'\n headers['Content-Disposition'] = \"attachment; filename=\\\"#{filename}\\\"\" \n headers['Expires'] = \"0\" \n else\n headers[\"Content-Type\"] ||= 'text/csv'\n headers[\"Content-Disposition\"] = \"attachment; filename=\\\"#{filename}\\\"\" \n end\n\n render :layout =&gt; false\nend\n</code></pre>\n\n<p>Using that makes it easy to have something like this in my controller:</p>\n\n<pre><code>respond_to do |wants|\n wants.csv do\n render_csv(\"users-#{Time.now.strftime(\"%Y%m%d\")}\")\n end\nend\n</code></pre>\n\n<p>And have a view that looks like this: (<code>generate_csv</code> is from FasterCSV)</p>\n\n<pre><code>UserID,Email,Password,ActivationURL,Messages\n&lt;%= generate_csv do |csv|\n @users.each do |user|\n csv &lt;&lt; [ user[:id], user[:email], user[:password], user[:url], user[:message] ]\n end\nend %&gt;\n</code></pre>\n" }, { "answer_id": 94654, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 5, "selected": false, "text": "<p>I accepted (and voted up!) @Brian's answer, for first pointing me to FasterCSV. Then when I googled to find the gem, I also found a fairly complete example at <a href=\"http://wiki.rubyonrails.org/rails/pages/HowtoExportDataAsCSV\" rel=\"noreferrer\">this wiki page</a>. Putting them together, I settled on the following code.</p>\n\n<p>By the way, the command to install the gem is:\n sudo gem install fastercsv\n(all lower case)</p>\n\n<pre><code>require 'fastercsv'\n\nclass EntriesController &lt; ApplicationController\n\n def getcsv\n entries = Entry.find(:all)\n csv_string = FasterCSV.generate do |csv| \n csv &lt;&lt; [\"first\",\"last\"]\n entries.each do |e|\n csv &lt;&lt; [e.firstName,e.lastName]\n end\n end\n send_data csv_string, :type =&gt; \"text/plain\", \n :filename=&gt;\"entries.csv\",\n :disposition =&gt; 'attachment'\n\n end\n\n\nend\n</code></pre>\n" }, { "answer_id": 222698, "author": "rwc9u", "author_id": 7778, "author_profile": "https://Stackoverflow.com/users/7778", "pm_score": 5, "selected": false, "text": "<p>Another way to do this without using FasterCSV:</p>\n\n<p>Require ruby's csv library in an initializer file like config/initializers/dependencies.rb</p>\n\n<pre><code>require \"csv\"\n</code></pre>\n\n<p>As some background the following code is based off of <a href=\"http://railscasts.com/episodes/111\" rel=\"noreferrer\">Ryan Bate's Advanced Search Form</a> that creates a search resource. In my case the show method of the search resource will return the results of a previously saved search. It also responds to csv, and uses a view template to format the desired output.</p>\n\n<pre><code> def show\n @advertiser_search = AdvertiserSearch.find(params[:id])\n @advertisers = @advertiser_search.search(params[:page])\n respond_to do |format|\n format.html # show.html.erb\n format.csv # show.csv.erb\n end\n end\n</code></pre>\n\n<p>The show.csv.erb file looks like the following:</p>\n\n<pre><code>&lt;%- headers = [\"Id\", \"Name\", \"Account Number\", \"Publisher\", \"Product Name\", \"Status\"] -%&gt;\n&lt;%= CSV.generate_line headers %&gt;\n&lt;%- @advertiser_search.advertisers.each do |advertiser| -%&gt;\n&lt;%- advertiser.subscriptions.each do |subscription| -%&gt;\n&lt;%- row = [ advertiser.id,\n advertiser.name,\n advertiser.external_id,\n advertiser.publisher.name,\n publisher_product_name(subscription),\n subscription.state ] -%&gt;\n&lt;%= CSV.generate_line row %&gt;\n&lt;%- end -%&gt;\n&lt;%- end -%&gt;\n</code></pre>\n\n<p>On the html version of the report page I have a link to export the report that the user is viewing. The following is the link_to that returns the csv version of the report:</p>\n\n<pre><code>&lt;%= link_to \"Export Report\", formatted_advertiser_search_path(@advertiser_search, :csv) %&gt;\n</code></pre>\n" }, { "answer_id": 11148546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following approached worked well for my case and causes the browser to open the appropriate application for the CSV type after downloading.</p>\n\n<pre><code>def index\n respond_to do |format|\n format.csv { return index_csv }\n end\nend\n\ndef index_csv\n send_data(\n method_that_returns_csv_data(...),\n :type =&gt; 'text/csv',\n :filename =&gt; 'export.csv',\n :disposition =&gt; 'attachment'\n )\nend\n</code></pre>\n" }, { "answer_id": 11517465, "author": "Henry Jacob", "author_id": 1528174, "author_profile": "https://Stackoverflow.com/users/1528174", "pm_score": 1, "selected": false, "text": "<p>try a nice gem to generate CSV from Rails\n<a href=\"https://github.com/crafterm/comma\" rel=\"nofollow\">https://github.com/crafterm/comma</a></p>\n" }, { "answer_id": 11656937, "author": "paul", "author_id": 155753, "author_profile": "https://Stackoverflow.com/users/155753", "pm_score": 0, "selected": false, "text": "<p>Take a look at the CSV Shaper gem.</p>\n\n<p><a href=\"http://github.com/paulspringett/csv_shaper\" rel=\"nofollow\">https://github.com/paulspringett/csv_shaper</a></p>\n\n<p>It has a nice DSL and works really well with Rails models. It also handles the response headers and allows filename customisation.</p>\n" }, { "answer_id": 17736685, "author": "boulder_ruby", "author_id": 1276506, "author_profile": "https://Stackoverflow.com/users/1276506", "pm_score": 0, "selected": false, "text": "<p>If you're simply wanting to get the csv database yourself from the console you can do so in a few lines</p>\n\n<pre><code>tags = [Model.column_names]\nrows = tags + Model.all.map(&amp;:attributes).map(&amp;:to_a).map { |m| m.inject([]) { |data, pair| data &lt;&lt; pair.last } }\nFile.open(\"ss.csv\", \"w\") {|f| f.write(rows.inject([]) { |csv, row| csv &lt;&lt; CSV.generate_line(row) }.join(\"\"))}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
I have a simple database table called "Entries": ``` class CreateEntries < ActiveRecord::Migration def self.up create_table :entries do |t| t.string :firstName t.string :lastName #etc. t.timestamps end end def self.down drop_table :entries end end ``` How do I write a handler that will return the contents of the Entries table as a CSV file (ideally in a way that it will automatically open in Excel)? ``` class EntriesController < ApplicationController def getcsv @entries = Entry.find( :all ) # ??? NOW WHAT ???? end end ```
There is a plugin called FasterCSV that handles this wonderfully.
94,528
<p>In other words may one use <code>/&lt;tag[^&gt;]*&gt;.*?&lt;\/tag&gt;/</code> regex to match the <code>tag</code> html element which does not contain nested <code>tag</code> elements?</p> <p>For example (lt.html):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;greater than sign in attribute value&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;1&lt;/div&gt; &lt;div title="&gt;"&gt;2&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Regex:</p> <pre><code>$ perl -nE"say $1 if m~&lt;div[^&gt;]*&gt;(.*?)&lt;/div&gt;~" lt.html </code></pre> <p>And screen-scraper:</p> <pre><code>#!/usr/bin/env python import sys import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(sys.stdin) for div in soup.findAll('div'): print div.string $ python lt.py &lt;lt.html </code></pre> <p>Both give the same output:</p> <pre><code>1 "&gt;2 </code></pre> <p>Expected output:</p> <pre><code>1 2 </code></pre> <p><a href="http://www.w3.org/TR/html5/syntax.html#attributes2" rel="noreferrer" title="html attribute syntax">w3c</a> says:</p> <blockquote> <p>Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.</p> </blockquote>
[ { "answer_id": 94544, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<pre><code>yeah except /&lt;tag[^&gt;]*&gt;.*?&lt;\\/tag&gt;/\n</code></pre>\n\n<p>Will not match a single tag, but match the first start-tag and the last end-tag for a given tag. Just like your first non-greedy tag-match, your in-between should be written non-greedy as well.</p>\n" }, { "answer_id": 94545, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>see if you get the same result using &amp;gt; instead of &gt;</p>\n" }, { "answer_id": 94552, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": false, "text": "<p>After reading the following:</p>\n\n<p><a href=\"http://www.w3.org/International/questions/qa-escapes\" rel=\"nofollow noreferrer\">http://www.w3.org/International/questions/qa-escapes</a></p>\n\n<p>it looks like entity escapes are suggested everywhere (including in attributes) for &lt; > and &amp;</p>\n" }, { "answer_id": 94559, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>I believe that's valid, and the W3C validator agrees, but the authoritative source for this information is the ISO 8879:1986 standard, which costs ~150EUR/210USD. Regardless, it is not wrong to encode them, so if in doubt, encode. Additionally, if you are using an XML-based document type, you need to encode greater-than signs in the sequence <code>]]&gt;</code>.</p>\n" }, { "answer_id": 94721, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": "<p>Literal <code>&gt;</code> is legal everywhere in html content, both inside attribute values and as text within an element.</p>\n" }, { "answer_id": 131131, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 2, "selected": false, "text": "<p>If you insist on using regular expressions (which is appropriate for basic string operations) try using <code>&lt;tag((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\"&gt;\\s]+))?)+\\s*|\\s*)&gt;.*?&lt;\\/tag&gt;</code>. It should match attributes perfectly and therefore allowing you to access the inner content (although you need to put it in a capture group).</p>\n\n<p>You may also use the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\" title=\"Html Agility Pack project page on CodePlex\">Html Agility Pack</a> for parsing HTML, which I would recommend if you are going to do a lot of parsing. Maintaining large regular expressions can easily become a headache, but in the meanwhile they are also much more effective if you are able to do so.</p>\n" }, { "answer_id": 217136, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 5, "selected": true, "text": "<p>Yes, it is allowed (W3C Validator accepts it, only issues a warning).</p>\n\n<p>Unescaped <code>&lt;</code> and <code>&gt;</code> are also allowed inside comments, so such simple regexp can be fooled.</p>\n\n<p>If BeautifulSoup doesn't handle this, it could be a bug or perhaps a conscious design decision to make it more resilient to missing closing quotes in attributes. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
In other words may one use `/<tag[^>]*>.*?<\/tag>/` regex to match the `tag` html element which does not contain nested `tag` elements? For example (lt.html): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>greater than sign in attribute value</title> </head> <body> <div>1</div> <div title=">">2</div> </body> </html> ``` Regex: ``` $ perl -nE"say $1 if m~<div[^>]*>(.*?)</div>~" lt.html ``` And screen-scraper: ``` #!/usr/bin/env python import sys import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(sys.stdin) for div in soup.findAll('div'): print div.string $ python lt.py <lt.html ``` Both give the same output: ``` 1 ">2 ``` Expected output: ``` 1 2 ``` [w3c](http://www.w3.org/TR/html5/syntax.html#attributes2 "html attribute syntax") says: > > Attribute values are a mixture of text > and character references, except with > the additional restriction that the > text cannot contain an ambiguous > ampersand. > > >
Yes, it is allowed (W3C Validator accepts it, only issues a warning). Unescaped `<` and `>` are also allowed inside comments, so such simple regexp can be fooled. If BeautifulSoup doesn't handle this, it could be a bug or perhaps a conscious design decision to make it more resilient to missing closing quotes in attributes.
94,542
<p>I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it.</p> <p>I'd like to have a modelContext.xml file and another for my ui.xml, etc.</p> <p>Can I do this?</p>
[ { "answer_id": 94586, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 2, "selected": false, "text": "<p>Yes, you can do this via the import element.</p>\n\n<pre><code>&lt;import resource=\"services.xml\"/&gt;\n</code></pre>\n\n<p>Each element's resource attribute is a valid path (e.g. classpath:foo.xml)</p>\n" }, { "answer_id": 94588, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 5, "selected": true, "text": "<p>From the <a href=\"http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition\" rel=\"noreferrer\">Spring Docs (v 2.5.5 Section 3.2.2.1.)</a>:</p>\n\n<blockquote>\n <p>It can often be useful to split up\n container definitions into multiple\n XML files. One way to then load an\n application context which is\n configured from all these XML\n fragments is to use the application\n context constructor which takes\n multiple Resource locations. With a\n bean factory, a bean definition reader\n can be used multiple times to read\n definitions from each file in turn.</p>\n \n <p>Generally, the Spring team prefers the\n above approach, since it keeps\n container configuration files unaware\n of the fact that they are being\n combined with others. An alternate\n approach is to use one or more\n occurrences of the element\n to load bean definitions from another\n file (or files). Let's look at a\n sample:</p>\n \n <p></p>\n\n<pre><code>&lt;import resource=\"services.xml\"/&gt;\n&lt;import resource=\"resources/messageSource.xml\"/&gt;\n&lt;import resource=\"/resources/themeSource.xml\"/&gt;\n\n&lt;bean id=\"bean1\" class=\"...\"/&gt;\n&lt;bean id=\"bean2\" class=\"...\"/&gt;\n</code></pre>\n \n <p></p>\n \n <p>In this example, external bean\n definitions are being loaded from 3\n files, services.xml,\n messageSource.xml, and\n themeSource.xml. All location paths\n are considered relative to the\n definition file doing the importing,\n so services.xml in this case must be\n in the same directory or classpath\n location as the file doing the\n importing, while messageSource.xml and\n themeSource.xml must be in a resources\n location below the location of the\n importing file. As you can see, a\n leading slash is actually ignored, but\n given that these are considered\n relative paths, it is probably better\n form not to use the slash at all. The\n contents of the files being imported\n must be valid XML bean definition\n files according to the Spring Schema\n or DTD, including the top level\n element.</p>\n</blockquote>\n" }, { "answer_id": 94788, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "<p>We do this in our projects at work, using the classpath* resource loader in Spring. For a certain app, all appcontext files containing the application id will be loaded:</p>\n\n<pre><code>classpath*:springconfig/spring-appname-*.xml\n</code></pre>\n" }, { "answer_id": 95020, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>Given what Nicholas pointed me to I found this in the docs. It allows me to pick at runtime the bean contexts I'm interested in.</p>\n\n<pre><code>GenericApplicationContext ctx = new GenericApplicationContext();\nXmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"modelContext.xml\"));\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"uiContext.xml\"));\nctx.refresh();\n</code></pre>\n" }, { "answer_id": 96039, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 1, "selected": false, "text": "<p>Here's what I've done for one of my projects. In your <code>web.xml</code> file, you can define the Spring bean files you want your application to use:</p>\n\n<pre><code> &lt;context-param&gt;\n &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;\n &lt;param-value&gt;\n /WEB-INF/applicationContext.xml\n /WEB-INF/modelContext.xml\n /WEB-INF/ui.xml\n &lt;/param-value&gt;\n &lt;/context-param&gt;\n</code></pre>\n\n<p>If this isn't defined in your <code>web.xml</code>, it automatically looks for <code>/WEB-INF/applicationContext.xml</code></p>\n" }, { "answer_id": 96583, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 0, "selected": false, "text": "<p>Another thing to note is that although you can do this, if you aren't a big fan of XML you can do a lot of stuff in Spring 2.5 with annotations. </p>\n" }, { "answer_id": 105496, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 0, "selected": false, "text": "<p>Yes, you can using the tag inside the \"Master\" bean file. But what about the why? Why not listing the files in the contextConfigLocation context param of the wab.xml or als locations array of the bean factory?</p>\n\n<p>I think mutliple files are much easier to handle. You may choose only some of them for a test, simply add rename or remove a part of the application and you may boundle different applications with the same config files (a webapp and a commandline version with some overlapping bean definitions).</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it. I'd like to have a modelContext.xml file and another for my ui.xml, etc. Can I do this?
From the [Spring Docs (v 2.5.5 Section 3.2.2.1.)](http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition): > > It can often be useful to split up > container definitions into multiple > XML files. One way to then load an > application context which is > configured from all these XML > fragments is to use the application > context constructor which takes > multiple Resource locations. With a > bean factory, a bean definition reader > can be used multiple times to read > definitions from each file in turn. > > > Generally, the Spring team prefers the > above approach, since it keeps > container configuration files unaware > of the fact that they are being > combined with others. An alternate > approach is to use one or more > occurrences of the element > to load bean definitions from another > file (or files). Let's look at a > sample: > > > > > ``` > <import resource="services.xml"/> > <import resource="resources/messageSource.xml"/> > <import resource="/resources/themeSource.xml"/> > > <bean id="bean1" class="..."/> > <bean id="bean2" class="..."/> > > ``` > > > In this example, external bean > definitions are being loaded from 3 > files, services.xml, > messageSource.xml, and > themeSource.xml. All location paths > are considered relative to the > definition file doing the importing, > so services.xml in this case must be > in the same directory or classpath > location as the file doing the > importing, while messageSource.xml and > themeSource.xml must be in a resources > location below the location of the > importing file. As you can see, a > leading slash is actually ignored, but > given that these are considered > relative paths, it is probably better > form not to use the slash at all. The > contents of the files being imported > must be valid XML bean definition > files according to the Spring Schema > or DTD, including the top level > element. > > >
94,556
<p>We've got a multiproject we're trying to run Cobertura test coverage reports on as part of our mvn site build. I can get Cobertura to run on the child projects, but it erroneously reports 0% coverage, even though the reports still highlight the lines of code that were hit by the unit tests. </p> <p>We are using mvn 2.0.8. I have tried running <code>mvn clean site</code>, <code>mvn clean site:stage</code> and <code>mvn clean package site</code>. I know the tests are running, they show up in the surefire reports (both the txt/xml and site reports). Am I missing something in the configuration? Does Cobertura not work right with multiprojects?</p> <p>This is in the parent .pom:</p> <pre><code>&lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;inherited&gt;true&lt;/inherited&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;clean&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;clean&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;reporting&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;inherited&gt;true&lt;/inherited&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/reporting&gt; </code></pre> <p>I've tried running it with and without the following in the child .poms:</p> <pre><code> &lt;reporting&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/reporting&gt; </code></pre> <p>I get this in the output of the build:</p> <pre><code>... [INFO] [cobertura:instrument] [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Instrumenting 3 files to C:\workspaces\sandbox\CommonJsf\target\generated-classes\cobertura Cobertura: Saved information on 3 classes. Instrument time: 186ms [INFO] Instrumentation was successful. ... [INFO] Generating "Cobertura Test Coverage" report. [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Cobertura: Loaded information on 3 classes. Report time: 481ms [INFO] Cobertura Report generation was successful. </code></pre> <p>And the report looks like this: <img src="https://i.stack.imgur.com/D7yiM.png" alt="cobertura report"></p>
[ { "answer_id": 94586, "author": "enricopulatzo", "author_id": 9883, "author_profile": "https://Stackoverflow.com/users/9883", "pm_score": 2, "selected": false, "text": "<p>Yes, you can do this via the import element.</p>\n\n<pre><code>&lt;import resource=\"services.xml\"/&gt;\n</code></pre>\n\n<p>Each element's resource attribute is a valid path (e.g. classpath:foo.xml)</p>\n" }, { "answer_id": 94588, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 5, "selected": true, "text": "<p>From the <a href=\"http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition\" rel=\"noreferrer\">Spring Docs (v 2.5.5 Section 3.2.2.1.)</a>:</p>\n\n<blockquote>\n <p>It can often be useful to split up\n container definitions into multiple\n XML files. One way to then load an\n application context which is\n configured from all these XML\n fragments is to use the application\n context constructor which takes\n multiple Resource locations. With a\n bean factory, a bean definition reader\n can be used multiple times to read\n definitions from each file in turn.</p>\n \n <p>Generally, the Spring team prefers the\n above approach, since it keeps\n container configuration files unaware\n of the fact that they are being\n combined with others. An alternate\n approach is to use one or more\n occurrences of the element\n to load bean definitions from another\n file (or files). Let's look at a\n sample:</p>\n \n <p></p>\n\n<pre><code>&lt;import resource=\"services.xml\"/&gt;\n&lt;import resource=\"resources/messageSource.xml\"/&gt;\n&lt;import resource=\"/resources/themeSource.xml\"/&gt;\n\n&lt;bean id=\"bean1\" class=\"...\"/&gt;\n&lt;bean id=\"bean2\" class=\"...\"/&gt;\n</code></pre>\n \n <p></p>\n \n <p>In this example, external bean\n definitions are being loaded from 3\n files, services.xml,\n messageSource.xml, and\n themeSource.xml. All location paths\n are considered relative to the\n definition file doing the importing,\n so services.xml in this case must be\n in the same directory or classpath\n location as the file doing the\n importing, while messageSource.xml and\n themeSource.xml must be in a resources\n location below the location of the\n importing file. As you can see, a\n leading slash is actually ignored, but\n given that these are considered\n relative paths, it is probably better\n form not to use the slash at all. The\n contents of the files being imported\n must be valid XML bean definition\n files according to the Spring Schema\n or DTD, including the top level\n element.</p>\n</blockquote>\n" }, { "answer_id": 94788, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "<p>We do this in our projects at work, using the classpath* resource loader in Spring. For a certain app, all appcontext files containing the application id will be loaded:</p>\n\n<pre><code>classpath*:springconfig/spring-appname-*.xml\n</code></pre>\n" }, { "answer_id": 95020, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>Given what Nicholas pointed me to I found this in the docs. It allows me to pick at runtime the bean contexts I'm interested in.</p>\n\n<pre><code>GenericApplicationContext ctx = new GenericApplicationContext();\nXmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"modelContext.xml\"));\nxmlReader.loadBeanDefinitions(new ClassPathResource(\"uiContext.xml\"));\nctx.refresh();\n</code></pre>\n" }, { "answer_id": 96039, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 1, "selected": false, "text": "<p>Here's what I've done for one of my projects. In your <code>web.xml</code> file, you can define the Spring bean files you want your application to use:</p>\n\n<pre><code> &lt;context-param&gt;\n &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;\n &lt;param-value&gt;\n /WEB-INF/applicationContext.xml\n /WEB-INF/modelContext.xml\n /WEB-INF/ui.xml\n &lt;/param-value&gt;\n &lt;/context-param&gt;\n</code></pre>\n\n<p>If this isn't defined in your <code>web.xml</code>, it automatically looks for <code>/WEB-INF/applicationContext.xml</code></p>\n" }, { "answer_id": 96583, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 0, "selected": false, "text": "<p>Another thing to note is that although you can do this, if you aren't a big fan of XML you can do a lot of stuff in Spring 2.5 with annotations. </p>\n" }, { "answer_id": 105496, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 0, "selected": false, "text": "<p>Yes, you can using the tag inside the \"Master\" bean file. But what about the why? Why not listing the files in the contextConfigLocation context param of the wab.xml or als locations array of the bean factory?</p>\n\n<p>I think mutliple files are much easier to handle. You may choose only some of them for a test, simply add rename or remove a part of the application and you may boundle different applications with the same config files (a webapp and a commandline version with some overlapping bean definitions).</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765/" ]
We've got a multiproject we're trying to run Cobertura test coverage reports on as part of our mvn site build. I can get Cobertura to run on the child projects, but it erroneously reports 0% coverage, even though the reports still highlight the lines of code that were hit by the unit tests. We are using mvn 2.0.8. I have tried running `mvn clean site`, `mvn clean site:stage` and `mvn clean package site`. I know the tests are running, they show up in the surefire reports (both the txt/xml and site reports). Am I missing something in the configuration? Does Cobertura not work right with multiprojects? This is in the parent .pom: ``` <build> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <inherited>true</inherited> <executions> <execution> <id>clean</id> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <inherited>true</inherited> </plugin> </plugins> </reporting> ``` I've tried running it with and without the following in the child .poms: ``` <reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> </plugin> </plugins> </reporting> ``` I get this in the output of the build: ``` ... [INFO] [cobertura:instrument] [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Instrumenting 3 files to C:\workspaces\sandbox\CommonJsf\target\generated-classes\cobertura Cobertura: Saved information on 3 classes. Instrument time: 186ms [INFO] Instrumentation was successful. ... [INFO] Generating "Cobertura Test Coverage" report. [INFO] Cobertura 1.9 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Cobertura: Loaded information on 3 classes. Report time: 481ms [INFO] Cobertura Report generation was successful. ``` And the report looks like this: ![cobertura report](https://i.stack.imgur.com/D7yiM.png)
From the [Spring Docs (v 2.5.5 Section 3.2.2.1.)](http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition): > > It can often be useful to split up > container definitions into multiple > XML files. One way to then load an > application context which is > configured from all these XML > fragments is to use the application > context constructor which takes > multiple Resource locations. With a > bean factory, a bean definition reader > can be used multiple times to read > definitions from each file in turn. > > > Generally, the Spring team prefers the > above approach, since it keeps > container configuration files unaware > of the fact that they are being > combined with others. An alternate > approach is to use one or more > occurrences of the element > to load bean definitions from another > file (or files). Let's look at a > sample: > > > > > ``` > <import resource="services.xml"/> > <import resource="resources/messageSource.xml"/> > <import resource="/resources/themeSource.xml"/> > > <bean id="bean1" class="..."/> > <bean id="bean2" class="..."/> > > ``` > > > In this example, external bean > definitions are being loaded from 3 > files, services.xml, > messageSource.xml, and > themeSource.xml. All location paths > are considered relative to the > definition file doing the importing, > so services.xml in this case must be > in the same directory or classpath > location as the file doing the > importing, while messageSource.xml and > themeSource.xml must be in a resources > location below the location of the > importing file. As you can see, a > leading slash is actually ignored, but > given that these are considered > relative paths, it is probably better > form not to use the slash at all. The > contents of the files being imported > must be valid XML bean definition > files according to the Spring Schema > or DTD, including the top level > element. > > >
94,582
<p>Say I have some javascript that if run in a browser would be typed like this...</p> <pre><code>&lt;script type="text/javascript" src="http://someplace.net/stuff.ashx"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var stuff = null; stuff = new TheStuff('myStuff'); &lt;/script&gt; </code></pre> <p>... and I want to use the javax.script package in java 1.6 to run this code within a jvm (not within an applet) and get the stuff. How do I let the engine know the source of the classes to be constructed is found within the remote .ashx file?</p> <p>For instance, I know to write the java code as...</p> <pre><code>ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); engine.eval( "stuff = new TheStuff('myStuff');" ); Object obj = engine.get("stuff"); </code></pre> <p>...but the "JavaScript" engine doesn't know anything by default about the TheStuff class because that information is in the remote .ashx file. Can I make it look to the above src string for this?</p>
[ { "answer_id": 96911, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 2, "selected": false, "text": "<p>It seems like you're asking:</p>\n\n<blockquote>\n <p>How can I get <code>ScriptEngine</code> to evaluate the contents of a URL instead of just a string?</p>\n</blockquote>\n\n<p>Is that accurate?</p>\n\n<p><code>ScriptEngine</code> doesn't provide a facility for downloading and evaluating the contents of a URL, but it's fairly easy to do. <code>ScriptEngine</code> allows you to pass in a <code>Reader</code> object that it will use to read the script.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>URL url = new URL( \"http://someplace.net/stuff.ashx\" );\nInputStreamReader reader = new InputStreamReader( url.openStream() );\nengine.eval( reader );\n</code></pre>\n" }, { "answer_id": 96916, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>Are you trying to access the javascript object in the browser page from a java 1.6 applet? If so, you're going about it in the wrong way. That's not what the scripting engine's for. It's for running javascript within a jvm, not for an applet to accesses javascript from with in a browser.</p>\n\n<p>Here's a <a href=\"http://www.rgagnon.com/javadetails/java-0184.html\" rel=\"nofollow noreferrer\">blog entry</a> that might get you somewhere, but it doesn't look like there's much support.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17978/" ]
Say I have some javascript that if run in a browser would be typed like this... ``` <script type="text/javascript" src="http://someplace.net/stuff.ashx"></script> <script type="text/javascript"> var stuff = null; stuff = new TheStuff('myStuff'); </script> ``` ... and I want to use the javax.script package in java 1.6 to run this code within a jvm (not within an applet) and get the stuff. How do I let the engine know the source of the classes to be constructed is found within the remote .ashx file? For instance, I know to write the java code as... ``` ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); engine.eval( "stuff = new TheStuff('myStuff');" ); Object obj = engine.get("stuff"); ``` ...but the "JavaScript" engine doesn't know anything by default about the TheStuff class because that information is in the remote .ashx file. Can I make it look to the above src string for this?
It seems like you're asking: > > How can I get `ScriptEngine` to evaluate the contents of a URL instead of just a string? > > > Is that accurate? `ScriptEngine` doesn't provide a facility for downloading and evaluating the contents of a URL, but it's fairly easy to do. `ScriptEngine` allows you to pass in a `Reader` object that it will use to read the script. Try something like this: ``` URL url = new URL( "http://someplace.net/stuff.ashx" ); InputStreamReader reader = new InputStreamReader( url.openStream() ); engine.eval( reader ); ```
94,594
<p>I'm implementing a simple service using datagrams over unix local sockets (AF_UNIX address family, i.e. <strong>not UDP</strong>). The server is bound to a public address, and it receives requests just fine. Unfortunately, when it comes to answering back, <code>sendto</code> fails unless the client is bound too. (the common error is <code>Transport endpoint is not connected</code>).</p> <p>Binding to some random name (filesystem-based or abstract) works. But I'd like to avoid that: who am I to guarantee the names I picked won't collide?</p> <p>The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at <code>connect</code> time if they don't have one already. Is such a feature available for datagram oriented sockets?</p>
[ { "answer_id": 95090, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": -1, "selected": false, "text": "<p>I'm not so sure I understand your question completely, but here is a datagram implementation of an echo server I just wrote. You can see the server is responding to the client on the same IP/PORT it was sent from.</p>\n\n<p>Here's the code</p>\n\n<p>First, the server (listener)</p>\n\n<pre><code>from socket import *\nimport time\nclass Listener:\n def __init__(self, port):\n self.port = port\n self.buffer = 102400\n\n def listen(self):\n\n sock = socket(AF_INET, SOCK_DGRAM)\n sock.bind(('', self.port))\n\n while 1:\n data, addr = sock.recvfrom(self.buffer)\n print \"Received: \" + data\n print \"sending to %s\" % addr[0]\n print \"sending data %s\" % data\n time.sleep(0.25)\n #print addr # will tell you what IP address the request came from and port\n sock.sendto(data, (addr[0], addr[1]))\n print \"sent\"\n sock.close()\n\nif __name__ == \"__main__\":\n l = Listener(1975)\n l.listen()\n</code></pre>\n\n<p>And now, the Client (sender) which receives the response from the Listener</p>\n\n<pre><code>from socket import *\nfrom time import sleep\nclass Sender:\n def __init__(self, server):\n self.port = 1975\n self.server = server\n self.buffer = 102400\n\n def sendPacket(self, packet):\n sock = socket(AF_INET, SOCK_DGRAM)\n sock.settimeout(10.75)\n\n\n sock.sendto(packet, (self.server, int(self.port)))\n\n while 1:\n print \"waiting for response\"\n data, addr = sock.recvfrom(self.buffer)\n sock.close()\n return data\n\n\n\nif __name__ == \"__main__\":\n s = Sender(\"127.0.0.1\")\n response = s.sendPacket(\"Hello, world!\")\n print response\n</code></pre>\n" }, { "answer_id": 107358, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 3, "selected": true, "text": "<p>I assume that you are running Linux; I don't know if this advice applies to SunOS or any UNIX. </p>\n\n<p>First, the answer: after the socket() and before the connect() or first sendto(), try adding this code:</p>\n\n<pre><code>struct sockaddr_un me;\nme.sun_family = AF_UNIX;\nint result = bind(fd, (void*)&amp;me, sizeof(short));\n</code></pre>\n\n<p>Now, the explanation: the the <a href=\"http://www.linuxmanpages.com/man7/unix.7.php\" rel=\"nofollow noreferrer\">unix(7)</a> man page says this:</p>\n\n<blockquote>\n <p>When a socket is connected and it\n doesn’t already have a local address a\n unique address in the abstract\n namespace will be generated\n automatically.</p>\n</blockquote>\n\n<p>Sadly, the man page lies. </p>\n\n<p>Examining the <a href=\"http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L925\" rel=\"nofollow noreferrer\">Linux source code</a>, we see that unix_dgram_connect() only calls unix_autobind() if SOCK_PASSCRED is set in the socket flags. Since I don't know what SOCK_PASSCRED is, and it is now 1:00AM, I need to look for another solution. </p>\n\n<p>Examining <a href=\"http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L765\" rel=\"nofollow noreferrer\">unix_bind</a>, I notice that unix_bind calls unix_autobind if the passed-in size is equal to \"sizeof(short)\". Thus, the solution above.</p>\n\n<p>Good luck, and good morning.</p>\n\n<p>Rob</p>\n" }, { "answer_id": 1284208, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>A bit of a late response, but for whomever finds this using google as I did. Rob Adam's answer helped me get the 'real' answer to this: simply use set (level <code>SO_SOCKET</code>, see <code>man 7 unix</code>) to set <code>SO_PASSCRED</code> to 1. No need for a silly bind.</p>\n\n<p>I used this in PHP, but it doesn't have <code>SO_PASSCRED</code> defined (stupid PHP). It does still work, though, if you define it yourself. On my computer it has the value of 16, and I reckon that it will work quite portably.</p>\n" }, { "answer_id": 8523777, "author": "CapnBry", "author_id": 1100177, "author_profile": "https://Stackoverflow.com/users/1100177", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://linux.die.net/man/7/unix\" rel=\"noreferrer\">unix(7)</a> man page I referenced had this information about autobind UNIX sockets:</p>\n\n<blockquote>\n <p>If a bind(2) call specifies addrlen as sizeof(sa_family_t), or the SO_PASSCRED socket option was specified for a socket that was not explicitly bound to an address, then the socket is autobound to an abstract address.</p>\n</blockquote>\n\n<p>This is why the Linux kernel checks the address length is equal to sizeof(short) because sa_family_t is a short. The other unix(7) man page referenced by Rob's great answer says that client sockets are always autobound on connect, but because SOCK_DGRAM sockets are connectionless (despite calling connect on them) I believe this only applies to SOCK_STREAM sockets.</p>\n\n<p>Also note that when supplying your own abstract namespace socket names, the socket's address in this namespace is given by the additional bytes in sun_path that are covered by the specified length of the address structure.</p>\n\n<pre><code>struct sockaddr_un me;\nconst char name[] = \"\\0myabstractsocket\";\nme.sun_family = AF_UNIX;\n// size-1 because abstract socket names are not null terminated\nmemcpy(me.sun_path, name, sizeof(name) - 1);\nint result = bind(fd, (void*)&amp;me, sizeof(me.sun_family) + sizeof(name) - 1);\n</code></pre>\n\n<p>sendto() should likewise limit the address length, and not pass sizeof(sockaddr_un).</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12274/" ]
I'm implementing a simple service using datagrams over unix local sockets (AF\_UNIX address family, i.e. **not UDP**). The server is bound to a public address, and it receives requests just fine. Unfortunately, when it comes to answering back, `sendto` fails unless the client is bound too. (the common error is `Transport endpoint is not connected`). Binding to some random name (filesystem-based or abstract) works. But I'd like to avoid that: who am I to guarantee the names I picked won't collide? The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at `connect` time if they don't have one already. Is such a feature available for datagram oriented sockets?
I assume that you are running Linux; I don't know if this advice applies to SunOS or any UNIX. First, the answer: after the socket() and before the connect() or first sendto(), try adding this code: ``` struct sockaddr_un me; me.sun_family = AF_UNIX; int result = bind(fd, (void*)&me, sizeof(short)); ``` Now, the explanation: the the [unix(7)](http://www.linuxmanpages.com/man7/unix.7.php) man page says this: > > When a socket is connected and it > doesn’t already have a local address a > unique address in the abstract > namespace will be generated > automatically. > > > Sadly, the man page lies. Examining the [Linux source code](http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L925), we see that unix\_dgram\_connect() only calls unix\_autobind() if SOCK\_PASSCRED is set in the socket flags. Since I don't know what SOCK\_PASSCRED is, and it is now 1:00AM, I need to look for another solution. Examining [unix\_bind](http://lxr.linux.no/linux+v2.6.26.5/net/unix/af_unix.c#L765), I notice that unix\_bind calls unix\_autobind if the passed-in size is equal to "sizeof(short)". Thus, the solution above. Good luck, and good morning. Rob
94,612
<p>To elaborate .. a) A table (BIGTABLE) has a capacity to hold a million rows with a primary Key as the ID. (random and unique) b) What algorithm can be used to arrive at an ID that has not been used so far. This number will be used to insert another row into table BIGTABLE.</p> <p>Updated the question with more details.. C) This table already has about 100 K rows and the primary key is not an set as identity. d) Currently, a random number is generated as the primary key and a row inserted into this table, if the insert fails another random number is generated. the problem is sometimes it goes into a loop and the random numbers generated are pretty random, but unfortunately, They already exist in the table. so if we re try the random number generation number after some time it works. e) The sybase rand() function is used to generate the random number.</p> <p>Hope this addition to the question helps clarify some points.</p>
[ { "answer_id": 94639, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 0, "selected": false, "text": "<p>If ID is purely random, there is no algorithm to find an unused ID in a similarly random fashion without brute forcing. However, as long as the bit-depth of your random unique id is reasonably large (say 64 bits), you're pretty safe from collisions with only a million rows. If it collides on insert, just try again.</p>\n" }, { "answer_id": 94643, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Pick a random number, check if it already exists, if so then keep trying until you hit one that doesn't.</p>\n\n<p>Edit: Or \nbetter yet, skip the check and just try to insert the row with different IDs until it works.</p>\n" }, { "answer_id": 94644, "author": "Per Hornshøj-Schierbeck", "author_id": 11619, "author_profile": "https://Stackoverflow.com/users/11619", "pm_score": 0, "selected": false, "text": "<p>depending on your database you might have the option of either using a sequenser (oracle) or a autoincrement (mysql, ms sql, etc). Or last resort do a select max(id) + 1 as new id - just be carefull of concurrent requests so you don't end up with the same max-id twice - wrap it in a lock with the upcomming insert statement</p>\n" }, { "answer_id": 94651, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>Make the key field UNIQUE and IDENTITY and you wont have to worry about it.</p>\n" }, { "answer_id": 94655, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 2, "selected": false, "text": "<p>Why is the unique ID Random? Why not use IDENTITY?\nHow was the ID chosen for the existing rows.</p>\n\n<p>The simplest thing to do is probably (Select Max(ID) from BIGTABLE) and then make sure your new \"Random\" ID is larger than that...</p>\n\n<p><strong>EDIT</strong>: Based on the added information I'd suggest that you're screwed.</p>\n\n<p>If it's an option: Copy the table, then redefine it and use an Identity Column.</p>\n\n<p>If, as another answer speculated, you do need a truly random Identifier: make your PK two fields. An Identity Field and then a random number.</p>\n\n<p>If you simply can't change the tables structure checking to see if the id exists before trying the insert is probably your only recourse.</p>\n" }, { "answer_id": 94666, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "<p>There isn't really a good algorithm for this. You can use this basic construct to find an unused id:</p>\n\n<pre><code>int id;\ndo {\n id = generateRandomId();\n} while (doesIdAlreadyExist(id));\ndoSomethingWithNewId(id); \n</code></pre>\n" }, { "answer_id": 94670, "author": "Jeff", "author_id": 10157, "author_profile": "https://Stackoverflow.com/users/10157", "pm_score": 1, "selected": false, "text": "<p>If this is something you'll need to do often you will probably want to maintain a live (non-db) data structure to help you quickly answer this question. A 10-way tree would be good. When the app starts it populates the tree by reading the keys from the db, and then keeps it in sync with the various inserts and deletes made in the db. So long as your app is the only one updating the db the tree can be consulted very quickly when verifying that the next large random key is not already in use.</p>\n" }, { "answer_id": 94677, "author": "Ryan Doherty", "author_id": 956, "author_profile": "https://Stackoverflow.com/users/956", "pm_score": 0, "selected": false, "text": "<p>I've seen this done so many times before via brute force, using random number generators, and it's always a bad idea. Generating a random number outside of the db and attempting to see if it exists will put a lot strain on your app and database. And it could lead to 2 processes picking the same id.</p>\n\n<p>Your best option is to use MySQL's autoincrement ability. Other databases have similar functionality. You are guaranteed a unique id and won't have issues with concurrency.</p>\n" }, { "answer_id": 94683, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 0, "selected": false, "text": "<p>It is probably a bad idea to scan every value in that table every time looking for a unique value. I think the way to do this would be to have a value in another table, lock on that table, read the value, calculate the value of the next id, write the value of the next id, release the lock. You can then use the id you read with the confidence your current process is the only one holding that unique value. Not sure how well it scales.</p>\n\n<p>Alternatively use a GUID for your ids, since each newly generated GUID is supposed to be unique.</p>\n" }, { "answer_id": 94731, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "<p>First question: Is this a planned database or a already functional one. If it already has data inside then the answer by bmdhacks is correct. If it is a planned database here is the second question:<br>\nDoes your primary key really <strong>need</strong> to be random? If the answer is yes then use a function to create a random id from with a known seed and a counter to know how many Ids have been created. Each Id created will increment the counter.<br>\nIf you keep the seed secret (i.e., have the seed called and declared private) then no one else should be able to predict the next ID. </p>\n" }, { "answer_id": 94736, "author": "Robert Sanders", "author_id": 16952, "author_profile": "https://Stackoverflow.com/users/16952", "pm_score": 0, "selected": false, "text": "<p>Is it a requirement that the new ID also be random? If so, the best answer is just to loop over (randomize, test for existence) until you find one that doesn't exist.</p>\n\n<p>If the data just <em>happens</em> to be random, but that isn't a strong constraint, you can just use SELECT MAX(idcolumn), increment in a way appropriate to the data, and use that as the primary key for your next record. </p>\n\n<p>You need to do this atomically, so either lock the table or use some other concurrency control appropriate to your DB configuration and schema. Stored procs, table locks, row locks, SELECT...FOR UPDATE, whatever.</p>\n\n<p>Note that in either approach you may need to handle failed transactions. You may theoretically get duplicate key issues in the first (though that's unlikely if your key space is sparsely populated), and you are likely to get deadlocks on some DBs with approaches like SELECT...FOR UPDATE. So be sure to check and restart the transaction on error.</p>\n" }, { "answer_id": 94761, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 2, "selected": false, "text": "<p>Your best bet is to make your key space big enough that the probability of collisions is extremely low, then don't worry about it. As mentioned, GUIDs will do this for you. Or, you can use a pure random number as long as it has enough bits.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Birthday_attack\" rel=\"nofollow noreferrer\">This page has the formula for calculating the collision probability</a>.</p>\n" }, { "answer_id": 94771, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 0, "selected": false, "text": "<p>First check if Max(ID) + 1 is not taken and use that.</p>\n\n<p>If Max(ID) + 1 exceeds the maximum then select an ordered chunk at the top and start looping backwards looking for a hole. Repeat the chunks until you run out of numbers (in which case throw a big error). </p>\n\n<p>if the \"hole\" is found then save the ID in another table and you can use that as the starting point for the next case to save looping.</p>\n" }, { "answer_id": 94812, "author": "Ihar Bury", "author_id": 18001, "author_profile": "https://Stackoverflow.com/users/18001", "pm_score": 0, "selected": false, "text": "<p>Skipping the reasoning of the task itself, the only algorithm that </p>\n\n<ul>\n<li>will give you an ID not in the table</li>\n<li>that will be used to insert a new line in the table</li>\n<li>will result in a table still having random unique IDs</li>\n</ul>\n\n<p>is generating a random number and then checking if it's already used</p>\n" }, { "answer_id": 95065, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 3, "selected": false, "text": "<p>The question is of course: why do you want a random ID?</p>\n\n<p>One case where I encountered a similar requirement, was for client IDs of a webapp: the client identifies himself with his client ID (stored in a cookie), so it has to be hard to brute force guess another client's ID (because that would allow hijacking his data).</p>\n\n<p>The solution I went with, was to combine a sequential int32 with a random int32 to obtain an int64 that I used as the client ID. In PostgreSQL:</p>\n\n<pre><code>CREATE FUNCTION lift(integer, integer) returns bigint AS $$\nSELECT ($1::bigint &lt;&lt; 31) + $2\n$$ LANGUAGE SQL;\n\nCREATE FUNCTION random_pos_int() RETURNS integer AS $$\nselect floor((lift(1,0) - 1)*random())::integer\n$$ LANGUAGE sql;\n\nALTER TABLE client ALTER COLUMN id SET DEFAULT\nlift((nextval('client_id_seq'::regclass))::integer, random_pos_int());\n</code></pre>\n\n<p>The generated IDs are 'half' random, while the other 'half' guarantees you cannot obtain the same ID twice:</p>\n\n<pre><code>select lift(1, random_pos_int()); =&gt; 3108167398\nselect lift(2, random_pos_int()); =&gt; 4673906795\nselect lift(3, random_pos_int()); =&gt; 7414644984\n...\n</code></pre>\n" }, { "answer_id": 95186, "author": "Ray Jenkins", "author_id": 12425, "author_profile": "https://Stackoverflow.com/users/12425", "pm_score": 0, "selected": false, "text": "<p>The best algorithm in that case is to generate a random number and do a select to see if it exists, or just try to add it if your database errs out sanely. Depending on the range of your key, vs, how many records there are, this could be a small amount of time. It also has the ability to spike and isn't consistent at all. </p>\n\n<p>Would it be possible to run some queries on the BigTable and see if there are any ranges that could be exploited? ie. between 100,000 and 234,000 there are no ID's yet, so we could add ID's there?</p>\n" }, { "answer_id": 97021, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 2, "selected": false, "text": "<p>A bit outside of the box.</p>\n\n<p>Why not pre-generate your random numbers ahead of time? That way, when you insert a new row into bigtable, the check has already been made. That would make inserts into bigtable a constant time operation.</p>\n\n<p>You will have to perform the checks eventually, but that could be offloaded to a second process that doesn’t involve the sensitive process of inserting into bigtable.</p>\n\n<p>Or go generate a few billion random numbers, and delete the duplicates, then you won't have to worry for quite some time.</p>\n" }, { "answer_id": 1869954, "author": "Lumpy", "author_id": 190629, "author_profile": "https://Stackoverflow.com/users/190629", "pm_score": 0, "selected": false, "text": "<p>Why not append your random number creator with the current date in seconds. This way the only way to have an identical ID is if two users are created at the same second and are given the same random number by your generator. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17987/" ]
To elaborate .. a) A table (BIGTABLE) has a capacity to hold a million rows with a primary Key as the ID. (random and unique) b) What algorithm can be used to arrive at an ID that has not been used so far. This number will be used to insert another row into table BIGTABLE. Updated the question with more details.. C) This table already has about 100 K rows and the primary key is not an set as identity. d) Currently, a random number is generated as the primary key and a row inserted into this table, if the insert fails another random number is generated. the problem is sometimes it goes into a loop and the random numbers generated are pretty random, but unfortunately, They already exist in the table. so if we re try the random number generation number after some time it works. e) The sybase rand() function is used to generate the random number. Hope this addition to the question helps clarify some points.
The question is of course: why do you want a random ID? One case where I encountered a similar requirement, was for client IDs of a webapp: the client identifies himself with his client ID (stored in a cookie), so it has to be hard to brute force guess another client's ID (because that would allow hijacking his data). The solution I went with, was to combine a sequential int32 with a random int32 to obtain an int64 that I used as the client ID. In PostgreSQL: ``` CREATE FUNCTION lift(integer, integer) returns bigint AS $$ SELECT ($1::bigint << 31) + $2 $$ LANGUAGE SQL; CREATE FUNCTION random_pos_int() RETURNS integer AS $$ select floor((lift(1,0) - 1)*random())::integer $$ LANGUAGE sql; ALTER TABLE client ALTER COLUMN id SET DEFAULT lift((nextval('client_id_seq'::regclass))::integer, random_pos_int()); ``` The generated IDs are 'half' random, while the other 'half' guarantees you cannot obtain the same ID twice: ``` select lift(1, random_pos_int()); => 3108167398 select lift(2, random_pos_int()); => 4673906795 select lift(3, random_pos_int()); => 7414644984 ... ```
94,632
<p>I have an ASP.NET page which has a script manager on it.</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:ScriptManager EnablePageMethods="true" ID="scriptManager2" runat="server"&gt; &lt;/asp:ScriptManager&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The page overrides an abstract property to return the ScriptManager in order to enable the base page to use it:</p> <pre><code>public partial class ReportWebForm : ReportPageBase { protected override ScriptManager ScriptManager { get { return scriptManager2; } } ... } </code></pre> <p>And the base page:</p> <pre><code>public abstract class ReportPageBase : Page { protected abstract ScriptManager ScriptManager { get; } ... } </code></pre> <p>When I run the project, I get the following parser error:</p> <p><strong>Parser Error Message:</strong> The base class includes the field 'scriptManager2', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager).</p> <p>How can I solve this?</p> <p>Update: The script manager part of the designer file is:</p> <pre><code>protected global::System.Web.UI.ScriptManager scriptManager; </code></pre>
[ { "answer_id": 94704, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 4, "selected": true, "text": "<p>I can compile your code sample fine, you should check your designer file to make sure everything is ok.</p>\n\n<p>EDIT: the only other thing I can think of is that this is some sort of reference problem. Is your System.Web.Extensions reference using the correct version for your targeted framework? (should be 3.5.0.0 for .net 3.5 and 1.0.6xxx for 2.0)</p>\n" }, { "answer_id": 94881, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 1, "selected": false, "text": "<p>I found out that my referenced System.Web.Extensions (v3.5.sth) library did not have the same version with the reference in web.config (v.1.0.6sth). Replacing the dll (3.5) with the old version of System.Web.Extensions solved the problem.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have an ASP.NET page which has a script manager on it. ``` <form id="form1" runat="server"> <div> <asp:ScriptManager EnablePageMethods="true" ID="scriptManager2" runat="server"> </asp:ScriptManager> </div> </form> ``` The page overrides an abstract property to return the ScriptManager in order to enable the base page to use it: ``` public partial class ReportWebForm : ReportPageBase { protected override ScriptManager ScriptManager { get { return scriptManager2; } } ... } ``` And the base page: ``` public abstract class ReportPageBase : Page { protected abstract ScriptManager ScriptManager { get; } ... } ``` When I run the project, I get the following parser error: **Parser Error Message:** The base class includes the field 'scriptManager2', but its type (System.Web.UI.ScriptManager) is not compatible with the type of control (System.Web.UI.ScriptManager). How can I solve this? Update: The script manager part of the designer file is: ``` protected global::System.Web.UI.ScriptManager scriptManager; ```
I can compile your code sample fine, you should check your designer file to make sure everything is ok. EDIT: the only other thing I can think of is that this is some sort of reference problem. Is your System.Web.Extensions reference using the correct version for your targeted framework? (should be 3.5.0.0 for .net 3.5 and 1.0.6xxx for 2.0)
94,667
<p>How can I bind an array parameter in the HQL editor of the HibernateTools plugin? The query parameter type list does not include arrays or collections.</p> <p>For example:<br> <code>Select * from Foo f where f.a in (:listOfValues)</code>.<br> How can I bind an array to that listOfValues?</p>
[ { "answer_id": 119294, "author": "boutta", "author_id": 15108, "author_profile": "https://Stackoverflow.com/users/15108", "pm_score": 1, "selected": false, "text": "<p>You probably cannot. Hibernate replaces the objects it gets out of the database with it's own objects (kind of proxies). I would strongly assume Hibernate cannot do that with an array. So if you want to bind the array-data put it into a List on access by Hibernate.</p>\n\n<p>As an example one could do:</p>\n\n<pre><code>select * from Foo f where f.a in f.list\n</code></pre>\n" }, { "answer_id": 6833770, "author": "Shaun Stone", "author_id": 290095, "author_profile": "https://Stackoverflow.com/users/290095", "pm_score": 0, "selected": false, "text": "<p>I am sure you have already got the answer for this but for anyone else viewing this. it appears that the HQL editor for hibernate tools does not support querying collections. you whould have to not use the parameter and hard code it while testing in the Hibernate Tools HQL editor </p>\n\n<pre><code>Select * from Foo f where f.a in (123,1234)\n</code></pre>\n\n<p>The change the query back to what boutta posted when you put it back in your code.</p>\n" }, { "answer_id": 7279391, "author": "Ravi Shankar", "author_id": 575055, "author_profile": "https://Stackoverflow.com/users/575055", "pm_score": 0, "selected": false, "text": "<p>This is how you pass a list to a HQL query. I am not familiar with HQL editor... we are from the Nhibernate world.</p>\n\n<pre><code>select * from Foo f where f.a in (:foolist)\n\nquery.SetParameterList(\"foolist\", list)\n</code></pre>\n" }, { "answer_id": 45482658, "author": "user1659644", "author_id": 1659644, "author_profile": "https://Stackoverflow.com/users/1659644", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/PAS1h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PAS1h.png\" alt=\"Hibernate perspective\" /></a></p>\n<p>In the hibernate perspective, you could see on the left side you can see left panel to enter query parameter, when you enter the :variable in the field and run the query you will get the result</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12905/" ]
How can I bind an array parameter in the HQL editor of the HibernateTools plugin? The query parameter type list does not include arrays or collections. For example: `Select * from Foo f where f.a in (:listOfValues)`. How can I bind an array to that listOfValues?
You probably cannot. Hibernate replaces the objects it gets out of the database with it's own objects (kind of proxies). I would strongly assume Hibernate cannot do that with an array. So if you want to bind the array-data put it into a List on access by Hibernate. As an example one could do: ``` select * from Foo f where f.a in f.list ```
94,674
<p>How come this doesn't work (operating on an empty select list <code>&lt;select id="requestTypes"&gt;&lt;/select&gt;</code></p> <pre><code>$(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { var option = new Option(this.RequestTypeName, this.RequestTypeID); // Use Jquery to get select list element var dropdownList = $("#requestTypes"); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } } ); } </code></pre> <p>But this does:</p> <ul> <li><p>Replace:</p> <p><code>var dropdownList = $("#requestTypes");</code></p></li> <li><p>With plain old javascript:</p> <p><code>var dropdownList = document.getElementById("requestTypes");</code></p></li> </ul>
[ { "answer_id": 94686, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned:</p>\n\n<pre><code> var dropdownList = $(\"#requestTypes\")[0];\n</code></pre>\n" }, { "answer_id": 94716, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "<p><code>$(\"#requestTypes\")</code> returns a jQuery object that contains all the selected elements. You are attempting to call the <code>add()</code> method of an individual element, but instead you are calling the <code>add()</code> method of the jQuery object, which does something very different.</p>\n\n<p>In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using <code>$(\"#requestTypes\")[0]</code>.</p>\n" }, { "answer_id": 97351, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 2, "selected": false, "text": "<p>For stuff like this, I use <a href=\"http://www.texotela.co.uk/code/jquery/select/\" rel=\"nofollow noreferrer\" title=\"jQuery Select box plugin\">texotela's select box plugin</a> with its simple ajaxAddOption function.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
How come this doesn't work (operating on an empty select list `<select id="requestTypes"></select>` ``` $(function() { $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes); } ); function showRequestTypes(data, textStatus) { $.each(data, function() { var option = new Option(this.RequestTypeName, this.RequestTypeID); // Use Jquery to get select list element var dropdownList = $("#requestTypes"); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } } ); } ``` But this does: * Replace: `var dropdownList = $("#requestTypes");` * With plain old javascript: `var dropdownList = document.getElementById("requestTypes");`
`$("#requestTypes")` returns a jQuery object that contains all the selected elements. You are attempting to call the `add()` method of an individual element, but instead you are calling the `add()` method of the jQuery object, which does something very different. In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using `$("#requestTypes")[0]`.
94,689
<p>I am new to asp and have a deadline in the next few days. i receive the following xml from within a webservice response.</p> <pre><code>print("&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;user_data&gt; &lt;execution_status&gt;0&lt;/execution_status&gt; &lt;row_count&gt;1&lt;/row_count&gt; &lt;txn_id&gt;stuetd678&lt;/txn_id&gt; &lt;person_info&gt; &lt;attribute name="firstname"&gt;john&lt;/attribute&gt; &lt;attribute name="lastname"&gt;doe&lt;/attribute&gt; &lt;attribute name="emailaddress"&gt;[email protected]&lt;/attribute&gt; &lt;/person_info&gt; &lt;/user_data&gt;"); </code></pre> <p>How can i parse this xml into asp attributes?</p> <p>Any help is greatly appreciated</p> <p>Thanks Damien</p> <p>On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?</p>
[ { "answer_id": 94712, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 4, "selected": true, "text": "<p>You need to read about MSXML parser. Here is a link to a good all-in-one example <a href=\"http://oreilly.com/pub/h/466\" rel=\"nofollow noreferrer\">http://oreilly.com/pub/h/466</a></p>\n\n<p>Some reading on XPath will help as well. You could get all the information you need in MSDN.</p>\n\n<p>Stealing the code from <a href=\"https://stackoverflow.com/users/17602/luke\">Luke</a> excellent reply for aggregation purposes:</p>\n\n<pre><code>Dim oXML, oNode, sKey, sValue\n\nSet oXML = Server.CreateObject(\"MSXML2.DomDocument.6.0\") 'creating the parser object\noXML.LoadXML(sXML) 'loading the XML from the string\n\nFor Each oNode In oXML.SelectNodes(\"/user_data/person_info/attribute\")\n sKey = oNode.GetAttribute(\"name\")\n sValue = oNode.Text\n Select Case sKey\n Case \"execution_status\"\n ... 'do something with the tag value\n Case else\n ... 'unknown tag\n End Select\nNext\n\nSet oXML = Nothing\n</code></pre>\n" }, { "answer_id": 94726, "author": "Paulj", "author_id": 5433, "author_profile": "https://Stackoverflow.com/users/5433", "pm_score": 0, "selected": false, "text": "<p>You could try loading the xml into the xmldocument object and then parse it using it's methods.</p>\n" }, { "answer_id": 94751, "author": "Luke Bennett", "author_id": 17602, "author_profile": "https://Stackoverflow.com/users/17602", "pm_score": 3, "selected": false, "text": "<p>By ASP I assume you mean Classic ASP? Try:</p>\n\n<pre><code>Dim oXML, oNode, sKey, sValue\n\nSet oXML = Server.CreateObject(\"MSXML2.DomDocument.4.0\")\noXML.LoadXML(sXML)\n\nFor Each oNode In oXML.SelectNodes(\"/user_data/person_info/attribute\")\n sKey = oNode.GetAttribute(\"name\")\n sValue = oNode.Text\n ' Do something with these values here\nNext\n\nSet oXML = Nothing\n</code></pre>\n\n<p>The above code assumes you have your XML in a variable called sXML. If you are consuming this via an ServerXMLHttp request, you should be able to use the ResponseXML property of your object in place of oXML above and skip the LoadXML step altogether.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11612/" ]
I am new to asp and have a deadline in the next few days. i receive the following xml from within a webservice response. ``` print("<?xml version="1.0" encoding="UTF-8"?> <user_data> <execution_status>0</execution_status> <row_count>1</row_count> <txn_id>stuetd678</txn_id> <person_info> <attribute name="firstname">john</attribute> <attribute name="lastname">doe</attribute> <attribute name="emailaddress">[email protected]</attribute> </person_info> </user_data>"); ``` How can i parse this xml into asp attributes? Any help is greatly appreciated Thanks Damien On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?
You need to read about MSXML parser. Here is a link to a good all-in-one example <http://oreilly.com/pub/h/466> Some reading on XPath will help as well. You could get all the information you need in MSDN. Stealing the code from [Luke](https://stackoverflow.com/users/17602/luke) excellent reply for aggregation purposes: ``` Dim oXML, oNode, sKey, sValue Set oXML = Server.CreateObject("MSXML2.DomDocument.6.0") 'creating the parser object oXML.LoadXML(sXML) 'loading the XML from the string For Each oNode In oXML.SelectNodes("/user_data/person_info/attribute") sKey = oNode.GetAttribute("name") sValue = oNode.Text Select Case sKey Case "execution_status" ... 'do something with the tag value Case else ... 'unknown tag End Select Next Set oXML = Nothing ```
94,757
<p>I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts).</p> <p>Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes).</p> <p>So, what is the best way to go about this?</p>
[ { "answer_id": 94808, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 4, "selected": false, "text": "<pre><code>navigator.onLine\n</code></pre>\n\n<p>That should do what you're asking.</p>\n\n<p>You probably want to check that in whatever code you have that updates the page. Eg:</p>\n\n<pre><code>if (navigator.onLine) {\n updatePage();\n} else {\n displayOfflineWarning();\n}\n</code></pre>\n" }, { "answer_id": 94829, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 2, "selected": false, "text": "<p>It seems like you've answered your own question. If the gadgets send an asynch request and it times out, don't update them. If enough of them do so, display the \"page is offline\" message.</p>\n" }, { "answer_id": 94901, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"http://www.w3.org/TR/html5/offline.html#browser0\" rel=\"nofollow noreferrer\">the HTML 5 draft specification</a>. You want <code>navigator.onLine</code>. Not all browsers support it yet. Firefox 3 and Opera 9.5 do.</p>\n\n<p>It sounds as though you are trying to cover up the problem rather than solve it. If a failed request causes your widgets to clear their data, then you should fix your code so that it doesn't attempt to update your widgets unless it receives a response, rather than attempting to figure out whether the request will succeed ahead of time.</p>\n" }, { "answer_id": 94972, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "<p>Hmm actually, now I look into it a bit, it's a bit more complicated than that. Have a read of these links on <a href=\"http://ejohn.org/blog/offline-events/\" rel=\"nofollow noreferrer\">John Resig's blog</a> and the <a href=\"http://developer.mozilla.org/En/Online_and_offline_events\" rel=\"nofollow noreferrer\">Mozilla site</a>. The above poster may also have a good point - you're making requests anyway, so you should be able to work out when they fail.. That might be a much more reliable way to go.</p>\n" }, { "answer_id": 98813, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 3, "selected": true, "text": "<p>One way to handle this might be to extend the XmlHTTPRequest object with an explicit timeout method, then use that to determine if you're working in offline mode (that is, for browsers that don't support navigator.onLine). Here's how I implemented Ajax timeouts on one site (a site that uses the <a href=\"http://prototypejs.org/&quot;Prototype&quot;\" rel=\"nofollow noreferrer\">Prototype</a> library). After 10 seconds (10,000 milliseconds), it aborts the call and calls the onFailure method.</p>\n\n<pre><code>/**\n * Monitor AJAX requests for timeouts\n * Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/\n *\n * Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure\n * method (if it exists), passing an error code to the function.\n *\n */\n\nvar xhr = {\n errorCode: 'timeout',\n callInProgress: function (xmlhttp) {\n switch (xmlhttp.readyState) {\n case 1: case 2: case 3:\n return true;\n // Case 4 and 0\n default:\n return false;\n }\n }\n};\n\n// Register global responders that will occur on all AJAX requests\nAjax.Responders.register({\n onCreate: function (request) {\n request.timeoutId = window.setTimeout(function () {\n // If we have hit the timeout and the AJAX request is active, abort it and let the user know\n if (xhr.callInProgress(request.transport)) {\n var parameters = request.options.parameters;\n request.transport.abort();\n // Run the onFailure method if we set one up when creating the AJAX object\n if (request.options.onFailure) {\n request.options.onFailure(request.transport, xhr.errorCode, parameters);\n }\n }\n },\n // 10 seconds\n 10000);\n },\n onComplete: function (request) {\n // Clear the timeout, the request completed ok\n window.clearTimeout(request.timeoutId);\n }\n});\n</code></pre>\n" }, { "answer_id": 98851, "author": "William Yeung", "author_id": 16371, "author_profile": "https://Stackoverflow.com/users/16371", "pm_score": 1, "selected": false, "text": "<p>I think google gears have such functionality, maybe you could check how they did that.</p>\n" }, { "answer_id": 99313, "author": "matt lohkamp", "author_id": 14026, "author_profile": "https://Stackoverflow.com/users/14026", "pm_score": 2, "selected": false, "text": "<p>Make a call to a reliable destination, or perhaps a series of calls, ones that should go through and return if the user has an active net connection - even something as simple as a token ping to google, yahoo, and msn, or something like that. If at least one comes back green, you know you're connected.</p>\n" }, { "answer_id": 2678386, "author": "thSoft", "author_id": 90874, "author_profile": "https://Stackoverflow.com/users/90874", "pm_score": 1, "selected": false, "text": "<p>Use the relevant HTML5 API: <a href=\"http://www.w3.org/TR/offline-webapps/#related\" rel=\"nofollow noreferrer\">online/offline status/events</a>.</p>\n" }, { "answer_id": 11053207, "author": "anonymous", "author_id": 1358767, "author_profile": "https://Stackoverflow.com/users/1358767", "pm_score": 0, "selected": false, "text": "<p>One possible solution is that if the page and the cached page have a different url to just look and see what url you are on. If you are on the url of the cached page then you are in offline mode. <a href=\"http://remysharp.com/2011/04/19/broken-offline-support/\" rel=\"nofollow\">This</a> blog makes a good point about why navigator.online is broke</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts). Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes). So, what is the best way to go about this?
One way to handle this might be to extend the XmlHTTPRequest object with an explicit timeout method, then use that to determine if you're working in offline mode (that is, for browsers that don't support navigator.onLine). Here's how I implemented Ajax timeouts on one site (a site that uses the [Prototype](http://prototypejs.org/"Prototype") library). After 10 seconds (10,000 milliseconds), it aborts the call and calls the onFailure method. ``` /** * Monitor AJAX requests for timeouts * Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/ * * Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure * method (if it exists), passing an error code to the function. * */ var xhr = { errorCode: 'timeout', callInProgress: function (xmlhttp) { switch (xmlhttp.readyState) { case 1: case 2: case 3: return true; // Case 4 and 0 default: return false; } } }; // Register global responders that will occur on all AJAX requests Ajax.Responders.register({ onCreate: function (request) { request.timeoutId = window.setTimeout(function () { // If we have hit the timeout and the AJAX request is active, abort it and let the user know if (xhr.callInProgress(request.transport)) { var parameters = request.options.parameters; request.transport.abort(); // Run the onFailure method if we set one up when creating the AJAX object if (request.options.onFailure) { request.options.onFailure(request.transport, xhr.errorCode, parameters); } } }, // 10 seconds 10000); }, onComplete: function (request) { // Clear the timeout, the request completed ok window.clearTimeout(request.timeoutId); } }); ```
94,866
<p>Running sp_attach_single_file_db gives this error:</p> <pre><code>The log scan number (10913:125:2) passed to log scan in database 'myDB' is not valid </code></pre> <p>Isn't it supposed to re-create the log file? </p> <p>How else would I be able to attach/repair that .mdf file?</p>
[ { "answer_id": 94947, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 0, "selected": false, "text": "<p>I don't know of an add-on (I use <a href=\"http://www.rememberthemilk.com/\" rel=\"nofollow noreferrer\">Remember The Milk</a> externally), but I think you are onto a good idea there.</p>\n" }, { "answer_id": 211784, "author": "Jason Stangroome", "author_id": 20819, "author_profile": "https://Stackoverflow.com/users/20819", "pm_score": 2, "selected": false, "text": "<p>For semi-immediate programming tasks I use TODO comments in code and ReSharper for Visual Studio to view them.</p>\n\n<p>For longer-term tasks I use Team Foundation Server to record work items.</p>\n\n<p>For non-programming tasks I use Google Calendar.</p>\n" }, { "answer_id": 257576, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 1, "selected": true, "text": "<p>How about the <a href=\"http://our.fogbugz.com/default.asp?W984\" rel=\"nofollow noreferrer\"><strong>FogBugz add-in</a></strong> for Visual Studio 2005 and 2008?</p>\n\n<p>This requires a <a href=\"http://www.fogcreek.com/FogBugz/\" rel=\"nofollow noreferrer\">FogBugz</a> account hosted either locally or by Fog Creek. A free Student and Startup version is <a href=\"https://shop.fogcreek.com/FogBugz/default.asp?sCategory=HOSTEDFB&amp;sStep=stepEnterEmailAddress&amp;HFBnForm=1\" rel=\"nofollow noreferrer\">available</a>.</p>\n" }, { "answer_id": 695462, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 0, "selected": false, "text": "<p>We use Team Foundation Server at work - it is a really superb product, but too expensive for smaller teams.</p>\n\n<p>Out of work I'm looking to use CountersSoft Gemini (<a href=\"http://countersoft.com/home.aspx\" rel=\"nofollow noreferrer\">http://countersoft.com/home.aspx</a>) which has good VS integration and is competitive when looking at the hosted version with unlimited users.</p>\n" }, { "answer_id": 1495132, "author": "Eric Brown - Cal", "author_id": 86431, "author_profile": "https://Stackoverflow.com/users/86431", "pm_score": 2, "selected": false, "text": "<p>Assumed: Visual Studio 2008 + ReSharper</p>\n\n<p>ReSharper->Windows->ToDo Explorer</p>\n\n<p>E-</p>\n" }, { "answer_id": 23052494, "author": "Fütemire", "author_id": 3010927, "author_profile": "https://Stackoverflow.com/users/3010927", "pm_score": 1, "selected": false, "text": "<p>You can modify the task list in Visual Studio by clicking \nTOOLS --> OPTIONS --> ENVIRONMENT --> TASK LIST</p>\n\n<p>In the Token List you can add more tokens specific to what you want to call your tasks.</p>\n\n<p>For example.. I have an EDITING token set up so in any module, class or method that I'm working on I just add the ' EDITING: (Name of whatever method ect..) comment and I can quickly see where I left off and get back too it by double clicking. </p>\n\n<p><img src=\"https://i.stack.imgur.com/E3t3d.png\" alt=\"enter image description here\"></p>\n\n<p>Here are a few other tokens I find useful...\n<img src=\"https://i.stack.imgur.com/XGuHu.png\" alt=\"enter image description here\"></p>\n\n<p>If you would like more advanced project and code tracking you should check out Visual Studio Online. It's free for upto 5 users. \n<a href=\"http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs\" rel=\"nofollow noreferrer\">http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1427/" ]
Running sp\_attach\_single\_file\_db gives this error: ``` The log scan number (10913:125:2) passed to log scan in database 'myDB' is not valid ``` Isn't it supposed to re-create the log file? How else would I be able to attach/repair that .mdf file?
How about the [**FogBugz add-in**](http://our.fogbugz.com/default.asp?W984) for Visual Studio 2005 and 2008? This requires a [FogBugz](http://www.fogcreek.com/FogBugz/) account hosted either locally or by Fog Creek. A free Student and Startup version is [available](https://shop.fogcreek.com/FogBugz/default.asp?sCategory=HOSTEDFB&sStep=stepEnterEmailAddress&HFBnForm=1).
94,906
<p>I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this:</p> <pre><code>select column1, column2, floor(rand() * 10000) as column3 from table1 </code></pre> <p>Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?</p>
[ { "answer_id": 94951, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 1, "selected": false, "text": "<p>You need to use a UDF</p>\n\n<p>first:</p>\n\n<pre><code>CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\n</code></pre>\n\n<p>second:</p>\n\n<pre><code>CREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\n</code></pre>\n\n<p>test:</p>\n\n<pre><code>SELECT dbo.RandNumber(), *\nFROM &lt;table&gt;\n</code></pre>\n\n<p>Above borrowed from <a href=\"http://weblogs.sqlteam.com/jeffs/archive/2004/11/22/2927.aspx\" rel=\"nofollow noreferrer\">Jeff's SQL Server Blog</a></p>\n" }, { "answer_id": 94992, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 1, "selected": false, "text": "<p>For SQLServer, there are a couple of options.<br>\n1. A while loop to update an empty column with one random number at a time<br>\n2. A .net Assembly that contains a function that returns a random number</p>\n" }, { "answer_id": 94995, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 1, "selected": false, "text": "<p><strong>Query</strong></p>\n\n<pre><code>select column1, column2, cast(new_id() as varchar(10)) as column3 \nfrom table1\n</code></pre>\n" }, { "answer_id": 95282, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 2, "selected": false, "text": "<p>Adam's answer works really well, so I marked it as accepted. While I was waiting for an answer though, I also found this blog entry with a few other (slightly less random) methods. Kaboing's method was among them.</p>\n\n<p><a href=\"http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/\" rel=\"nofollow noreferrer\"><a href=\"http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/\" rel=\"nofollow noreferrer\">http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/</a></a></p>\n" }, { "answer_id": 95520, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 1, "selected": false, "text": "<p>You might like to consider generating a UUID instead of a random number using the newid function. These are guaranteed to be unique each time generated whereas there is a significant chance that some duplication will occur with a straightforward random number (and depending on what you're using it for could give you a phenominally hard to debug error at a later point)</p>\n" }, { "answer_id": 96174, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 1, "selected": false, "text": "<p>newid() i believe is very resource intensive. i recall trying that method on a table of a few million records and the performance wasn't nearly as good as rand().</p>\n" }, { "answer_id": 491502, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 6, "selected": true, "text": "<p>I realize this is an older post... but you don't need a view.</p>\n\n<pre><code>select column1, column2, \n ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3 \nfrom table1\n</code></pre>\n" }, { "answer_id": 493703, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 2, "selected": false, "text": "<p><strong>WARNING</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005/94951#94951\">Adam's answer</a> involving the view is very inefficient and for very large sets can take out your database for quite a while, I would strongly recommend against using it on a regular basis or in situations where you need to populate large tables in production. </p>\n\n<p>Instead you could use <a href=\"https://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005/491502#491502\">this answer</a>. </p>\n\n<p>Proof:</p>\n\n<pre><code>CREATE VIEW vRandNumber\nAS\nSELECT RAND() as RandNumber\n\ngo \n\nCREATE FUNCTION RandNumber()\nRETURNS float\nAS\n BEGIN\n RETURN (SELECT RandNumber FROM vRandNumber)\n END\n\ngo \n\ncreate table bigtable(i int)\n\ngo \n\ninsert into bigtable \nselect top 100000 1 from sysobjects a\njoin sysobjects b on 1=1\n\ngo \n\nselect cast(dbo.RandNumber() * 10000 as integer) as r into #t from bigtable \n-- CPU (1607) READS (204639) DURATION (1551)\n\ngo\n\nselect ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as r into #t1 \nfrom bigtable\n-- Runs 15 times faster - CPU (78) READS (809) DURATION (99)\n</code></pre>\n\n<p>Profiler trace: </p>\n\n<p><a href=\"http://img519.imageshack.us/img519/8425/destroydbxu9.png\" rel=\"nofollow noreferrer\">alt text http://img519.imageshack.us/img519/8425/destroydbxu9.png</a></p>\n\n<p>This is proof that stuff is random enough for numbers between 0 to 9999</p>\n\n<pre><code>-- proof that stuff is random enough \nselect avg(r) from #t\n-- 5004\nselect STDEV(r) from #t\n-- 2895.1999 \n\nselect avg(r) from #t1\n-- 4992\nselect STDEV(r) from #t1\n-- 2881.44 \n\n\nselect r,count(r) from #t\ngroup by r \n-- 10000 rows returned \n\nselect r,count(r) from #t1\ngroup by r \n-- 10000 row returned \n</code></pre>\n" }, { "answer_id": 1222744, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>According to my testing, the answer above doesn't generate a value of 10000 ever. This probably isn't much of a problem when you are generating a random between 1 and 10000, but the same algorithm between 1 and 5 would be noticable. Add 1 to your mod.</p>\n" }, { "answer_id": 1731558, "author": "Ken", "author_id": 72966, "author_profile": "https://Stackoverflow.com/users/72966", "pm_score": 1, "selected": false, "text": "<p>This snippet seems to provide a reasonable substitute for <code>rand()</code> in that it returns a float between 0.0 and 1.0. It uses only the last 3 bytes provided by <code>newid()</code> so total randomness may be slightly different than the conversion to <code>VARBINARY</code> then <code>INT</code> then modding from the recommended answer. Have not had a chance to test relative performance but seems fast enough (and random enough) for my purposes.</p>\n\n<pre><code>SELECT CAST(SubString(CONVERT(binary(16), newid()), 14, 3) AS INT) / 16777216.0 AS R\n</code></pre>\n" }, { "answer_id": 4373009, "author": "denis_n", "author_id": 217372, "author_profile": "https://Stackoverflow.com/users/217372", "pm_score": 2, "selected": false, "text": "<pre><code>select RAND(CHECKSUM(NEWID()))\n</code></pre>\n" }, { "answer_id": 16225215, "author": "Cindy Conway", "author_id": 2200446, "author_profile": "https://Stackoverflow.com/users/2200446", "pm_score": 1, "selected": false, "text": "<p>I use c# for dealing with random numbers. It's much cleaner. I have a function I use to return a list of random number and a unique key, then I just join the uniqueKey on the row number. Because I use c#, I can easily specify a range within which the random numbers must fall.</p>\n\n<p>Here are the steps to making the function:\n<a href=\"http://www.sqlwithcindy.com/2013/04/elegant-random-number-list-in-sql-server.html\" rel=\"nofollow\">http://www.sqlwithcindy.com/2013/04/elegant-random-number-list-in-sql-server.html</a></p>\n\n<p>Here is what my query ends up looking like:</p>\n\n<pre><code>SELECT \n rowNumber, \n name, \n randomNumber\nFROM dbo.tvfRandomNumberList(1,10,100) \nINNER JOIN (select ROW_NUMBER() over (order by int_id) as 'rowNumber', name from client \n )as clients\nON clients.rowNumber = uniqueKey\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8409/" ]
I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this: ``` select column1, column2, floor(rand() * 10000) as column3 from table1 ``` Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?
I realize this is an older post... but you don't need a view. ``` select column1, column2, ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 10000 as column3 from table1 ```
94,912
<p>We currently have code like this:</p> <pre><code>Dim xDoc = XDocument.Load(myXMLFilePath) </code></pre> <p>The only way we know how to do it currently is by using a file path and impersonation (since this file is on a secured network path).</p> <p>I've looked at <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load.aspx" rel="nofollow noreferrer">XDocument.Load on MSDN</a>, but I don't see anything.</p>
[ { "answer_id": 94922, "author": "paulwhit", "author_id": 7301, "author_profile": "https://Stackoverflow.com/users/7301", "pm_score": 4, "selected": true, "text": "<p>I would suggest using a WebRequest to get a stream and load the stream into the document.</p>\n" }, { "answer_id": 94993, "author": "Domenic", "author_id": 3191, "author_profile": "https://Stackoverflow.com/users/3191", "pm_score": 2, "selected": false, "text": "<p>That very documentation says that the file parameter is \"A URI string that references the file to load into a new XDocument.\" Furthermore, I have code that does exactly that---uses <code>XDocument.Load</code> with a URI.</p>\n" }, { "answer_id": 9182657, "author": "Shawinder Sekhon", "author_id": 823800, "author_profile": "https://Stackoverflow.com/users/823800", "pm_score": 0, "selected": false, "text": "<pre><code>//Sample XML\n&lt;Product&gt;\n &lt;Name&gt;Product1&lt;/Name&gt;\n &lt;Price&gt;0.00&lt;/Price&gt;\n&lt;/Product&gt;\n\n //Reading XML\n XmlTextReader rdr = new XmlTextReader(\"http://your-url\");\n XDocument loaded = XDocument.Load(rdr);\n\n //View the loaded contents\n //Response.ClearHeaders();\n //Response.ContentType = \"text/xml;charset=UTF-8\";\n //Response.Write(loaded);\n //Response.End();\n\n var data = from c in loaded.Descendants(\"Product\")\n select new\n {\n name = c.Element(\"Name\").Value,\n price = c.Element(\"Price\").Value,\n };\n\n foreach (var element in data)\n {\n //Do something here\n }\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
We currently have code like this: ``` Dim xDoc = XDocument.Load(myXMLFilePath) ``` The only way we know how to do it currently is by using a file path and impersonation (since this file is on a secured network path). I've looked at [XDocument.Load on MSDN](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load.aspx), but I don't see anything.
I would suggest using a WebRequest to get a stream and load the stream into the document.
94,930
<p>I have a table with game scores, allowing multiple rows per account id: <code>scores (id, score, accountid)</code>. I want a list of the top 10 scorer ids and their scores.</p> <p>Can you provide an sql statement to select the top 10 scores, but only one score per account id? </p> <p>Thanks!</p>
[ { "answer_id": 94958, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>select top 10 username, \n max(score) \nfrom usertable \ngroup by username \norder by max(score) desc\n</code></pre>\n" }, { "answer_id": 94982, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "<p>PostgreSQL has the DISTINCT ON clause, that works this way:</p>\n\n<pre><code>SELECT DISTINCT ON (accountid) id, score, accountid\nFROM scoretable\nORDER BY score DESC\nLIMIT 10;\n</code></pre>\n\n<p>I don't think it's standard SQL though, so expect other databases to do it differently.</p>\n" }, { "answer_id": 94985, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 2, "selected": false, "text": "<pre><code>select username, max(score) from usertable group by username order by max(score) desc limit 10;\n</code></pre>\n" }, { "answer_id": 95016, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "<p>First limit the selection to the highest score for each account id.\nThen take the top ten scores.</p>\n\n<pre><code>SELECT TOP 10 AccountId, Score\nFROM Scores s1\nWHERE AccountId NOT IN \n (SELECT AccountId s2 FROM Scores \n WHERE s1.AccountId = s2.AccountId and s1.Score &gt; s2.Score)\nORDER BY Score DESC\n</code></pre>\n" }, { "answer_id": 109662, "author": "John Fiala", "author_id": 9143, "author_profile": "https://Stackoverflow.com/users/9143", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT accountid, MAX(score) as top_score\nFROM Scores\nGROUP BY accountid,\nORDER BY top_score DESC\nLIMIT 0, 10</code></pre>\n\n<p>That should work fine in mysql. It's possible you may need to use 'ORDER BY MAX(score) DESC' instead of that order by - I don't have my SQL reference on hand.</p>\n" }, { "answer_id": 1169549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I believe that PostgreSQL (at least 8.3) will require that the <code>DISTINCT ON</code> expressions must match initial <code>ORDER BY</code> expressions. I.E. you can't use <code>DISTINCT ON (accountid)</code> when you have <code>ORDER BY score DESC</code>. To fix this, add it into the <code>ORDER BY</code>:</p>\n\n<pre><code>SELECT DISTINCT ON (accountid) *\nFROM scoretable\nORDER BY accountid, score DESC\nLIMIT 10;\n</code></pre>\n\n<p>Using this method allows you to select all the columns in a table. It will only return 1 row per accountid even if there are duplicate 'max' values for score.</p>\n\n<p>This was useful for me, as I was not finding the maximum score (which is easy to do with the max() function) but for the most recent time a score was entered for an accountid.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
I have a table with game scores, allowing multiple rows per account id: `scores (id, score, accountid)`. I want a list of the top 10 scorer ids and their scores. Can you provide an sql statement to select the top 10 scores, but only one score per account id? Thanks!
First limit the selection to the highest score for each account id. Then take the top ten scores. ``` SELECT TOP 10 AccountId, Score FROM Scores s1 WHERE AccountId NOT IN (SELECT AccountId s2 FROM Scores WHERE s1.AccountId = s2.AccountId and s1.Score > s2.Score) ORDER BY Score DESC ```
94,932
<p>Our CF server occasionally stops processing mail. This is problematic, as many of our clients depend on it. </p> <p>We found suggestions online that mention zero-byte files in the undeliverable folder, so I created a task that removes them every three minutes. However, the stoppage has occurred again.</p> <p>I am looking for suggestions for diagnosing and fixing this issue.</p> <ul> <li>CF 8 standard </li> <li>Win2k3</li> </ul> <p>Added:</p> <ul> <li>There are no errors in the mail log at the time the queue fails</li> <li>We have not tried to run this without using the queue, due to the large amount of mail we send</li> </ul> <p>Added 2:</p> <ul> <li>It does not seem to be a problem with any of the files in the spool folder. When we restart the mail queue, they all seem to process correctly.</li> </ul> <p>Added 3:</p> <ul> <li>We are not using attachments.</li> </ul>
[ { "answer_id": 95355, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 2, "selected": false, "text": "<p>Have you tried just bypassing the queue altogether? (In CF Admin, under Mail Spool settings, uncheck \"Spool mail messages for delivery.\")</p>\n" }, { "answer_id": 109205, "author": "Dan Roberts", "author_id": 8345, "author_profile": "https://Stackoverflow.com/users/8345", "pm_score": 2, "selected": false, "text": "<p>I have the same problem sometimes and it isn't due to a zero byte file though that problem did crop up in the past. It seems like one or two files (the oldest ones in the folder) will keep the queue from processing. What I do is move all of the messages to a holding folder, restart the mail queue and copy the messages back in a chunk at a time in reverse chronological order, wait for them to go out and move some more over. The messages which were holding up the queue are put in a separate folder to be examined latter.</p>\n\n<p>You can probably programmatically do this by <a href=\"https://stackoverflow.com/questions/94948/restarting-coldfusion-mail-queue\">stopping the queue</a>, moving the oldest file to another folder, then <a href=\"https://stackoverflow.com/questions/94948/restarting-coldfusion-mail-queue\">start the mail queue</a> and see if sending begins successfully by checking folder file counts and dates. If removing the oldest file doesn't work, repeat the previous process until all of the offending mail files are moved and sending continues successfully.</p>\n\n<p>I hope the helps.</p>\n" }, { "answer_id": 130921, "author": "ale", "author_id": 21960, "author_profile": "https://Stackoverflow.com/users/21960", "pm_score": 0, "selected": false, "text": "<p>There is/was an issue with the mail spooler and messages with attachments in CFMX 8 that was fixed with one of the Hotfixes. Version 8.0.1, at least, should have had that fixed.</p>\n" }, { "answer_id": 140645, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>We have not tried to run this without using the queue, due to the large amount of mail we send</p>\n</blockquote>\n\n<p>Regardless, have you <em>tried</em> turning off spooling? I've seen mail get sent at a rate of 500-600 messages in a half second, and that's on kind of a crappy server. With the standard page timeout at 60 seconds, that would be ~72,000 emails you could send before the page would time out. Are you sending more than 72,000 at a time?</p>\n\n<p>An alternative I used before CFMail was this fast was to build a custom spooler. Instead of sending the emails on the fly, save them to a database table. Then setup a scheduled job to send a few hundred of the messages and reschedule itself for a few minutes later, until the table is empty.</p>\n\n<p>We scheduled the job to run once a day; and it can re-schedule itself to run again in a couple of minutes if the table isn't empty. Never had a problem with it.</p>\n" }, { "answer_id": 528530, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 5, "selected": true, "text": "<p>What we ended up doing:</p>\n\n<p>I wrote two scheduled tasks. The first checked to see if there were any messages in the queue folder older than <em>n</em> minues (currently set to 30). The second reset the queue every night during low usage.</p>\n\n<p>Unfortunately, we never really discovered why the queue would come off the rails, but it only seems to happen when we use Exchange -- other mail servers we've tried do not have this issue.</p>\n\n<p><strong>Edit:</strong> I was asked to post my code, so here's the one to restart when old mail is found:</p>\n\n<pre><code>&lt;cfdirectory action=\"list\" directory=\"c:\\coldfusion8\\mail\\spool\\\" name=\"spool\" sort=\"datelastmodified\"&gt;\n&lt;cfset restart = 0&gt;\n&lt;cfif datediff('n', spool.datelastmodified, now()) gt 30&gt;\n &lt;cfset restart = 1&gt;\n&lt;/cfif&gt;\n&lt;cfif restart&gt;\n &lt;cfset sFactory = CreateObject(\"java\",\"coldfusion.server.ServiceFactory\")&gt;\n &lt;cfset MailSpoolService = sFactory.mailSpoolService&gt;\n &lt;cfset MailSpoolService.stop()&gt;\n &lt;cfset MailSpoolService.start()&gt;\n&lt;/cfif&gt;\n</code></pre>\n" }, { "answer_id": 10542516, "author": "Tariq Ahmed", "author_id": 175861, "author_profile": "https://Stackoverflow.com/users/175861", "pm_score": 2, "selected": false, "text": "<p>We have actually an identical setup, 32bit CF8 on Win2K3.</p>\n\n<p>We employed Ben's solution about a year ago, and that certain has helped auto re-queue emails that get stuck.</p>\n\n<p>However recently for no particular reason one of our 7 web servers decided to get into this state with every email attempt.</p>\n\n<blockquote>\n <p>An exception occurred when setting up mail server parameters.\n This exception was caused by: \n coldfusion.mail.MailSessionException: \n An exception occurred when setting up mail server \n parameters..</p>\n</blockquote>\n\n<p>Each of our web servers are identical clones of each other, so why it was only happening to that one is bizarre. </p>\n\n<p>Another item to note is that we had a script which reboot the machine in the middle of the night due to JRUN's memory management issues. The act of rebooting seemed to initiate the problem. A subsequent restarting of the CF service would then clear it, and the machine would be fine until it rebooted again.</p>\n\n<p>We found that the problem is related to the McAfee virus scanner, after updating it to exclude the c:\\ColdFusion8 directory, the problem went away.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 23314430, "author": "user3576573", "author_id": 3576573, "author_profile": "https://Stackoverflow.com/users/3576573", "pm_score": 1, "selected": false, "text": "<p>There is a bug in Ben Doom's code. Thank you anyway ben, the code is great, and we use it now on one of our servers with CF8 installed, but:\nif directory (\\spool) is empty, the code fails (error: Date value passed to date function DateDiff is unspecified or invalid.) That's because if the query object spool is empty (spool.recordcount EQ 0), the datediff function produces an error.</p>\n\n<p>we used this now:</p>\n\n<pre><code>&lt;!--- check if request for this page is local to prevent \"webusers\" to request this page over and over, only localhost (server) can get it e.g. by cf scheduled tasks---&gt;\n&lt;cfsetting requesttimeout=\"30000\"&gt;\n&lt;cfset who = CGI.SERVER_NAME&gt;\n&lt;cfif find(\"localhost\",who) LT 1&gt;\n security restriction, access denied.\n &lt;cfabort&gt;\n&lt;/cfif&gt; \n\n&lt;!--- get spool directory info ---&gt;\n&lt;cfdirectory action=\"list\" directory=\"C:\\JRun4\\servers\\cfusion\\cfusion-ear\\cfusion-war\\WEB-INF\\cfusion\\Mail\\Spool\\\" name=\"spool\" sort=\"datelastmodified\"&gt;\n&lt;cfset restart = 0&gt;\n&lt;cfif spool.recordcount GT 0&gt;&lt;!--- content there? ---&gt;\n &lt;cfif datediff('n', spool.datelastmodified, now()) gt 120&gt;\n &lt;cfset restart = 1&gt;\n &lt;/cfif&gt;\n&lt;/cfif&gt;\n&lt;cfif restart&gt;&lt;!--- restart ---&gt;\n &lt;cfsavecontent variable=\"liste\"&gt;\n &lt;cfdump var=\"#list#\"&gt;\n &lt;/cfsavecontent&gt; \n &lt;!--- info ---&gt;\n &lt;cfmail to=\"[email protected]\" subject=\"cfmailqueue restarted by daemon\" server=\"xxx\" port=\"25\" from=\"xxxx\" username=\"xxxx\" password=\"xxx\" replyto=\"xxxx\"&gt;\n 1/2 action: ...try to restart. Send another mail if succeeded!\n #now()#\n\n Mails:\n #liste#\n &lt;/cfmail&gt;\n\n &lt;cfset sFactory = CreateObject(\"java\",\"coldfusion.server.ServiceFactory\")&gt;\n &lt;cfset MailSpoolService = sFactory.mailSpoolService&gt;\n &lt;cfset MailSpoolService.stop()&gt;\n &lt;cfset MailSpoolService.start()&gt;\n\n &lt;!--- info ---&gt;\n &lt;cfmail to=\"[email protected]\" subject=\"cfmailqueue restarted by daemon\" server=\"xxx\" port=\"25\" from=\"xxxx\" username=\"xxxx\" password=\"xxx\" replyto=\"xxxx\"&gt;\n 2/2 action: ...succeeded!\n #now()#\n &lt;/cfmail&gt;\n\n&lt;/cfif&gt;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12267/" ]
Our CF server occasionally stops processing mail. This is problematic, as many of our clients depend on it. We found suggestions online that mention zero-byte files in the undeliverable folder, so I created a task that removes them every three minutes. However, the stoppage has occurred again. I am looking for suggestions for diagnosing and fixing this issue. * CF 8 standard * Win2k3 Added: * There are no errors in the mail log at the time the queue fails * We have not tried to run this without using the queue, due to the large amount of mail we send Added 2: * It does not seem to be a problem with any of the files in the spool folder. When we restart the mail queue, they all seem to process correctly. Added 3: * We are not using attachments.
What we ended up doing: I wrote two scheduled tasks. The first checked to see if there were any messages in the queue folder older than *n* minues (currently set to 30). The second reset the queue every night during low usage. Unfortunately, we never really discovered why the queue would come off the rails, but it only seems to happen when we use Exchange -- other mail servers we've tried do not have this issue. **Edit:** I was asked to post my code, so here's the one to restart when old mail is found: ``` <cfdirectory action="list" directory="c:\coldfusion8\mail\spool\" name="spool" sort="datelastmodified"> <cfset restart = 0> <cfif datediff('n', spool.datelastmodified, now()) gt 30> <cfset restart = 1> </cfif> <cfif restart> <cfset sFactory = CreateObject("java","coldfusion.server.ServiceFactory")> <cfset MailSpoolService = sFactory.mailSpoolService> <cfset MailSpoolService.stop()> <cfset MailSpoolService.start()> </cfif> ```
94,934
<p>I'd like to create a &quot;universal&quot; debug logging function that inspects the JS namespace for well-known logging libraries.</p> <p>For example, currently, it supports Firebug's console.log:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var console = window['console']; if (console &amp;&amp; console.log) { console.log(message); }</code></pre> </div> </div> </p> <p>Obviously, this only works in Firefox if Firebug is installed/enabled (it'll also work on other browsers with <a href="http://getfirebug.com/lite.html" rel="nofollow noreferrer">Firebug Lite</a>). Basically, I will be providing a JS library which I don't know what environment it will be pulled into, and I'd like to be able to figure out if there is a way to report debug output to the user.</p> <p>So, perhaps jQuery provides something - I'd check that jQuery is present and use it. Or maybe there are well-known IE plugins that work that I can sniff for. But it has to be fairly well-established and used machinery. I can't check for every obscure log function that people create.</p> <p>Please, only one library/technology per answer, so they can get voted ranked. Also, using alert() is a good short-term solution but breaks down if you want robust debug logging or if blocking the execution is a problem.</p>
[ { "answer_id": 94944, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": -1, "selected": false, "text": "<p>Myself, I am a firm believer in the following:</p>\n\n<pre><code>alert('Some message/variables');\n</code></pre>\n" }, { "answer_id": 94968, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">Firebug lite</a> is a cross browser, lite version of Firefbug that'll at least give you console.log capabilities on most browsers.</p>\n" }, { "answer_id": 94974, "author": "jpbarto", "author_id": 8511, "author_profile": "https://Stackoverflow.com/users/8511", "pm_score": 0, "selected": false, "text": "<p>What about <a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">Firebug Lite</a> (for those non-Firefox browsers)? I haven't used it much except when debugging Dojo code in IE. But it tries as best it can to put a Firebug console in IE, Safari, and Opera.</p>\n\n<p>Of course there is always the ever reliable 'alert (err_msg);' :D</p>\n" }, { "answer_id": 94976, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 0, "selected": false, "text": "<p>There is <a href=\"http://ajaxian.com/archives/jquery-logging\" rel=\"nofollow noreferrer\">JQuery Logging</a>, which looks promising.</p>\n" }, { "answer_id": 94996, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 1, "selected": false, "text": "<p>If you are already using jQuery, I can heartily recommend the jQuery Debug plugin (a.k.a., jquery.debug.js). See <a href=\"http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/\" rel=\"nofollow noreferrer\"><a href=\"http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/\" rel=\"nofollow noreferrer\">http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/</a></a>.</p>\n\n<p>This plugin allows you to switch debug logging off or on via a global switch. Logging looks like this:</p>\n\n<pre><code>$.log('My value is: ' + val);\n</code></pre>\n\n<p>Output is sent to console.log under Firefox and is written to a div block inserted at the bottom of the page on other browsers.</p>\n" }, { "answer_id": 95092, "author": "Cory R. King", "author_id": 16742, "author_profile": "https://Stackoverflow.com/users/16742", "pm_score": 3, "selected": false, "text": "<p>I personally use Firebug/Firebug Lite and on IE let Visual Studio do the debugging. None of these do any good when a visitor is using some insane browser though. You really need to get your client side javascript to log its errors to your server. Take a look at the power point presentation I've linked to below. It has some pretty neat ideas on how to get your javascript to log stuff on your server.</p>\n\n<p>Basically, you hook window.onerror and your try {} catch(){} blocks with a function that makes a request back to your server with useful debug info.</p>\n\n<p>I've just implemented such a process on my own web application. I've got every catch(){} block calling a function that sends a JSON encoded message back to the server, which in turn uses my existing logging infrastructure (in my case log4perl). The presentation I'm linking to also suggests loading an image in your javascript in including the errors as part of the GET request. The only problem is if you want to include stack traces (which IE doesn't generate for you at all), the request will be too large.</p>\n\n<p><a href=\"http://www.pascarello.com/presentation/CMAP_ERRORS/\" rel=\"noreferrer\">Tracking ClientSide Errors, by Eric Pascarello</a></p>\n\n<p>PS: I wanted to add that I dont think it is a good idea to use any kind of library like jQuery for \"hardcore\" logging because maybe the reason for the error you are logging <em>is</em> jQuery or Firebug Lite! Maybe the error is that the browser (<em>cough</em> IE6) did some crazy loading order and is throwing some kind of Null Reference error because it was too stupid to load the library correctly.</p>\n\n<p>In my instance, I made sure all my javascript log code is in the &lt;head&gt; and not pulled in as a .js file. This way, I can be reasonably sure that no matter what kinds of curve balls the browser throws, odds are good I am able to log it.</p>\n" }, { "answer_id": 95574, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.mochikit.com\" rel=\"nofollow noreferrer\">MochiKit</a> has the following functions (included here with full namespace resolution):</p>\n\n<pre><code>MochiKit.Logging.logDebug() // prefaces value with \"DEBUG: \"\nMochiKit.Logging.log() // prefaces value with \"INFO: \"\nMochiKit.Logging.logError() // prefaces value with \"ERROR: \"\nMochiKit.Logging.logFatal() // prefaces value with \"FATAL: \"\nMochiKit.Logging.logWarning() // prefaces value with \"WARNING: \"\n</code></pre>\n\n<p>There is a lot more to the <a href=\"http://mochikit.com/doc/html/MochiKit/Logging.html\" rel=\"nofollow noreferrer\"><strong>MochiKit.Logging</strong></a> namespace than this, but these are the basics.</p>\n" }, { "answer_id": 935477, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 3, "selected": false, "text": "<p>You could try <a href=\"http://log4javascript.org\" rel=\"noreferrer\">log4javascript</a>.</p>\n\n<p>Disclosure: I wrote it.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4465/" ]
I'd like to create a "universal" debug logging function that inspects the JS namespace for well-known logging libraries. For example, currently, it supports Firebug's console.log: ```js var console = window['console']; if (console && console.log) { console.log(message); } ``` Obviously, this only works in Firefox if Firebug is installed/enabled (it'll also work on other browsers with [Firebug Lite](http://getfirebug.com/lite.html)). Basically, I will be providing a JS library which I don't know what environment it will be pulled into, and I'd like to be able to figure out if there is a way to report debug output to the user. So, perhaps jQuery provides something - I'd check that jQuery is present and use it. Or maybe there are well-known IE plugins that work that I can sniff for. But it has to be fairly well-established and used machinery. I can't check for every obscure log function that people create. Please, only one library/technology per answer, so they can get voted ranked. Also, using alert() is a good short-term solution but breaks down if you want robust debug logging or if blocking the execution is a problem.
I personally use Firebug/Firebug Lite and on IE let Visual Studio do the debugging. None of these do any good when a visitor is using some insane browser though. You really need to get your client side javascript to log its errors to your server. Take a look at the power point presentation I've linked to below. It has some pretty neat ideas on how to get your javascript to log stuff on your server. Basically, you hook window.onerror and your try {} catch(){} blocks with a function that makes a request back to your server with useful debug info. I've just implemented such a process on my own web application. I've got every catch(){} block calling a function that sends a JSON encoded message back to the server, which in turn uses my existing logging infrastructure (in my case log4perl). The presentation I'm linking to also suggests loading an image in your javascript in including the errors as part of the GET request. The only problem is if you want to include stack traces (which IE doesn't generate for you at all), the request will be too large. [Tracking ClientSide Errors, by Eric Pascarello](http://www.pascarello.com/presentation/CMAP_ERRORS/) PS: I wanted to add that I dont think it is a good idea to use any kind of library like jQuery for "hardcore" logging because maybe the reason for the error you are logging *is* jQuery or Firebug Lite! Maybe the error is that the browser (*cough* IE6) did some crazy loading order and is throwing some kind of Null Reference error because it was too stupid to load the library correctly. In my instance, I made sure all my javascript log code is in the <head> and not pulled in as a .js file. This way, I can be reasonably sure that no matter what kinds of curve balls the browser throws, odds are good I am able to log it.
94,935
<p>Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about</p> <pre><code>for i in range(0, 20): for i in xrange(0, 20): </code></pre>
[ { "answer_id": 94953, "author": "Oko", "author_id": 9402, "author_profile": "https://Stackoverflow.com/users/9402", "pm_score": -1, "selected": false, "text": "<p>See this <a href=\"http://avinashv.net/2008/05/pythons-range-and-xrange/\" rel=\"nofollow noreferrer\">post</a> to find difference between range and xrange:</p>\n\n<p>To quote:</p>\n\n<blockquote>\n <p><code>range</code> returns exactly what you think: a list of consecutive\n integers, of a defined length beginning with 0. <code>xrange</code>, however,\n returns an <em>\"xrange object\"</em>, which acts a great deal like an iterator</p>\n</blockquote>\n" }, { "answer_id": 94957, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": false, "text": "<p>xrange returns an iterator and only keeps one number in memory at a time. range keeps the entire list of numbers in memory.</p>\n" }, { "answer_id": 94962, "author": "Charles", "author_id": 18031, "author_profile": "https://Stackoverflow.com/users/18031", "pm_score": 11, "selected": true, "text": "<p><strong>In Python 2.x:</strong></p>\n<ul>\n<li><p><code>range</code> creates a list, so if you do <code>range(1, 10000000)</code> it creates a list in memory with <code>9999999</code> elements.</p>\n</li>\n<li><p><code>xrange</code> is a sequence object that evaluates lazily.</p>\n</li>\n</ul>\n<p><strong>In Python 3:</strong></p>\n<ul>\n<li><code>range</code> does the equivalent of Python 2's <code>xrange</code>. To get the list, you have to explicitly use <code>list(range(...))</code>.</li>\n<li><code>xrange</code> no longer exists.</li>\n</ul>\n" }, { "answer_id": 94965, "author": "Eddie Deyo", "author_id": 9323, "author_profile": "https://Stackoverflow.com/users/9323", "pm_score": 2, "selected": false, "text": "<p>range generates the entire list and returns it. xrange does not -- it generates the numbers in the list on demand.</p>\n" }, { "answer_id": 94966, "author": "hacama", "author_id": 17457, "author_profile": "https://Stackoverflow.com/users/17457", "pm_score": 2, "selected": false, "text": "<p>xrange uses an iterator (generates values on the fly), range returns a list.</p>\n" }, { "answer_id": 94971, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 5, "selected": false, "text": "<p>Do spend some time with the <a href=\"https://docs.python.org/2/library/stdtypes.html#typesseq-xrange\" rel=\"nofollow noreferrer\">Library Reference</a>. The more familiar you are with it, the faster you can find answers to questions like this. Especially important are the first few chapters about builtin objects and types.</p>\n\n<blockquote>\n <p>The advantage of the xrange type is that an xrange object will always \n take the same amount of memory, no matter the size of the range it represents. \n There are no consistent performance advantages.</p>\n</blockquote>\n\n<p>Another way to find quick information about a Python construct is the docstring and the help-function:</p>\n\n<pre><code>print xrange.__doc__ # def doc(x): print x.__doc__ is super useful\nhelp(xrange)\n</code></pre>\n" }, { "answer_id": 95010, "author": "QAZ", "author_id": 14260, "author_profile": "https://Stackoverflow.com/users/14260", "pm_score": 4, "selected": false, "text": "<p>It is for optimization reasons.</p>\n\n<p>range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.</p>\n\n<p>xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.</p>\n" }, { "answer_id": 95100, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 8, "selected": false, "text": "<blockquote>\n<p>range creates a list, so if you do <code>range(1, 10000000)</code> it creates a list in memory with <code>9999999</code> elements.</p>\n<p><code>xrange</code> <s>is a generator, so it</s> is a sequence object <s>is a</s> that evaluates lazily.</p>\n</blockquote>\n<p>This is true, but in Python 3, <code>range()</code> will be implemented by the Python 2 <code>xrange()</code>. If you need to actually generate the list, you will need to do:</p>\n<pre><code>list(range(1,100))\n</code></pre>\n" }, { "answer_id": 95168, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 6, "selected": false, "text": "<p><code>xrange</code> only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:</p>\n\n<pre><code>xrange(2**32-1, 2**32+1) # When long is 32 bits, OverflowError: Python int too large to convert to C long\nrange(2**32-1, 2**32+1) # OK --&gt; [4294967295L, 4294967296L]\n</code></pre>\n\n<p>Note that in Python 3.0 there is only <code>range</code> and it behaves like the 2.x <code>xrange</code> but without the limitations on minimum and maximum end points.</p>\n" }, { "answer_id": 95549, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>range creates a list, so if you do range(1, 10000000) it creates a list in memory with 10000000 elements.\n xrange is a generator, so it evaluates lazily.</p>\n</blockquote>\n\n<p>This brings you two advantages:</p>\n\n<ol>\n<li>You can iterate longer lists without getting a <code>MemoryError</code>.</li>\n<li>As it resolves each number lazily, if you stop iteration early, you won't waste time creating the whole list.</li>\n</ol>\n" }, { "answer_id": 97530, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 7, "selected": false, "text": "<p>Remember, use the <code>timeit</code> module to test which of small snippets of code is faster!</p>\n<pre><code>$ python -m timeit 'for i in range(1000000):' ' pass'\n10 loops, best of 3: 90.5 msec per loop\n$ python -m timeit 'for i in xrange(1000000):' ' pass'\n10 loops, best of 3: 51.1 msec per loop\n</code></pre>\n<p>Personally, I always use <code>range()</code>, unless I were dealing with <em>really</em> huge lists -- as you can see, time-wise, for a list of a million entries, the extra overhead is only 0.04 seconds. And as Corey points out, in Python 3.0 <code>xrange()</code> will go away and <code>range()</code> will give you nice iterator behavior anyway.</p>\n" }, { "answer_id": 5351725, "author": "Dave Everitt", "author_id": 123033, "author_profile": "https://Stackoverflow.com/users/123033", "pm_score": 3, "selected": false, "text": "<p>When testing range against xrange in a loop (I know I should use <a href=\"http://docs.python.org/library/timeit.html\" rel=\"noreferrer\">timeit</a>, but this was swiftly hacked up from memory using a simple list comprehension example) I found the following:</p>\n\n<pre><code>import time\n\nfor x in range(1, 10):\n\n t = time.time()\n [v*10 for v in range(1, 10000)]\n print \"range: %.4f\" % ((time.time()-t)*100)\n\n t = time.time()\n [v*10 for v in xrange(1, 10000)]\n print \"xrange: %.4f\" % ((time.time()-t)*100)\n</code></pre>\n\n<p>which gives:</p>\n\n<pre><code>$python range_tests.py\nrange: 0.4273\nxrange: 0.3733\nrange: 0.3881\nxrange: 0.3507\nrange: 0.3712\nxrange: 0.3565\nrange: 0.4031\nxrange: 0.3558\nrange: 0.3714\nxrange: 0.3520\nrange: 0.3834\nxrange: 0.3546\nrange: 0.3717\nxrange: 0.3511\nrange: 0.3745\nxrange: 0.3523\nrange: 0.3858\nxrange: 0.3997 &lt;- garbage collection?\n</code></pre>\n\n<p>Or, using xrange in the for loop:</p>\n\n<pre><code>range: 0.4172\nxrange: 0.3701\nrange: 0.3840\nxrange: 0.3547\nrange: 0.3830\nxrange: 0.3862 &lt;- garbage collection?\nrange: 0.4019\nxrange: 0.3532\nrange: 0.3738\nxrange: 0.3726\nrange: 0.3762\nxrange: 0.3533\nrange: 0.3710\nxrange: 0.3509\nrange: 0.3738\nxrange: 0.3512\nrange: 0.3703\nxrange: 0.3509\n</code></pre>\n\n<p>Is my snippet testing properly? Any comments on the slower instance of xrange? Or a better example :-)</p>\n" }, { "answer_id": 21137807, "author": "SomeDoubts", "author_id": 3198177, "author_profile": "https://Stackoverflow.com/users/3198177", "pm_score": 1, "selected": false, "text": "<p>On a requirement for scanning/printing of 0-N items , range and xrange works as follows.</p>\n\n<p>range() - creates a new list in the memory and takes the whole 0 to N items(totally N+1) and prints them.\nxrange() - creates a iterator instance that scans through the items and keeps only the current encountered item into the memory , hence utilising same amount of memory all the time.</p>\n\n<p>In case the required element is somewhat at the beginning of the list only then it saves a good amount of time and memory.</p>\n" }, { "answer_id": 22905006, "author": "Kishor Pawar", "author_id": 1936024, "author_profile": "https://Stackoverflow.com/users/1936024", "pm_score": 4, "selected": false, "text": "<p>The <a href=\"https://docs.python.org/2/library/functions.html#xrange\" rel=\"nofollow noreferrer\">doc</a> clearly reads :</p>\n<blockquote>\n<p>This function is very similar to <code>range()</code>, but returns an <code>xrange</code> object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of <code>xrange()</code> over <code>range()</code> is minimal (since <code>xrange()</code> still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with <code>break</code>).</p>\n</blockquote>\n" }, { "answer_id": 27144195, "author": "kmario23", "author_id": 2956066, "author_profile": "https://Stackoverflow.com/users/2956066", "pm_score": 2, "selected": false, "text": "<p>What?<br>\n<code>range</code> returns a static list at runtime.<br>\n<code>xrange</code> returns an <code>object</code> (which acts like a generator, although it's certainly not one) from which values are generated as and when required.</p>\n\n<p>When to use which? </p>\n\n<ul>\n<li>Use <code>xrange</code> if you want to generate a list for a gigantic range, say 1 billion, especially when you have a \"memory sensitive system\" like a cell phone.</li>\n<li>Use <code>range</code> if you want to iterate over the list several times.</li>\n</ul>\n\n<p>PS: Python 3.x's <code>range</code> function == Python 2.x's <code>xrange</code> function.</p>\n" }, { "answer_id": 27752378, "author": "user299567", "author_id": 3935256, "author_profile": "https://Stackoverflow.com/users/3935256", "pm_score": 1, "selected": false, "text": "<p><strong>Range</strong> returns a <strong>list</strong> while <strong>xrange</strong> returns an <strong>xrange</strong> object which takes the same memory irrespective of the range size,as in this case,only one element is generated and available per iteration whereas in case of using range, all the elements are generated at once and are available in the memory.</p>\n" }, { "answer_id": 30088340, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 3, "selected": false, "text": "<p>Some of the other answers mention that Python 3 eliminated 2.x's <code>range</code> and renamed 2.x's <code>xrange</code> to <code>range</code>. However, unless you're using 3.0 or 3.1 (which nobody should be), it's actually a somewhat different type.</p>\n\n<p>As <a href=\"https://docs.python.org/3.1/library/stdtypes.html#range-type\" rel=\"noreferrer\">the 3.1 docs</a> say:</p>\n\n<blockquote>\n <p>Range objects have very little behavior: they only support indexing, iteration, and the <code>len</code> function.</p>\n</blockquote>\n\n<p>However, in 3.2+, <code>range</code> is a full sequence—it supports extended slices, and all of the methods of <a href=\"https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes\" rel=\"noreferrer\"><code>collections.abc.Sequence</code></a> with the same semantics as a <code>list</code>.<sup>*</sup></p>\n\n<p>And, at least in CPython and PyPy (the only two 3.2+ implementations that currently exist), it also has constant-time implementations of the <code>index</code> and <code>count</code> methods and the <code>in</code> operator (as long as you only pass it integers). This means writing <code>123456 in r</code> is reasonable in 3.2+, while in 2.7 or 3.1 it would be a horrible idea.</p>\n\n<hr>\n\n<p><sub>* The fact that <code>issubclass(xrange, collections.Sequence)</code> returns <code>True</code> in 2.6-2.7 and 3.0-3.1 is <a href=\"http://bugs.python.org/issue9213\" rel=\"noreferrer\">a bug</a> that was fixed in 3.2 and not backported.</sub></p>\n" }, { "answer_id": 30545536, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 1, "selected": false, "text": "<p>The difference decreases for smaller arguments to <code>range(..)</code> / <code>xrange(..)</code>:</p>\n\n<pre><code>$ python -m timeit \"for i in xrange(10111):\" \" for k in range(100):\" \" pass\"\n10 loops, best of 3: 59.4 msec per loop\n\n$ python -m timeit \"for i in xrange(10111):\" \" for k in xrange(100):\" \" pass\"\n10 loops, best of 3: 46.9 msec per loop\n</code></pre>\n\n<p>In this case <code>xrange(100)</code> is only about 20% more efficient.</p>\n" }, { "answer_id": 30997385, "author": "Tushar Patil", "author_id": 2013238, "author_profile": "https://Stackoverflow.com/users/2013238", "pm_score": 3, "selected": false, "text": "<p><strong>range():</strong> range(1, 10) returns a list from 1 to 10 numbers &amp; hold whole list in memory.</p>\n\n<p><strong>xrange():</strong> Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is lightly faster than range() and more memory efficient.\n xrange() object like an iterator and generates the numbers on demand.(Lazy Evaluation)</p>\n\n<pre><code>In [1]: range(1,10)\n\nOut[1]: [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nIn [2]: xrange(10)\n\nOut[2]: xrange(10)\n\nIn [3]: print xrange.__doc__\n\nxrange([start,] stop[, step]) -&gt; xrange object\n</code></pre>\n" }, { "answer_id": 34877258, "author": "Lakshaya Maheshwari", "author_id": 5808816, "author_profile": "https://Stackoverflow.com/users/5808816", "pm_score": 2, "selected": false, "text": "<p>xrange() and range() in python works similarly as for the user , but the difference comes when we are talking about how the memory is allocated in using both the function.</p>\n\n<p>When we are using range() we allocate memory for all the variables it is generating, so it is not recommended to use with larger no. of variables to be generated.</p>\n\n<p>xrange() on the other hand generate only a particular value at a time and can only be used with the for loop to print all the values required.</p>\n" }, { "answer_id": 35680931, "author": "Siyaram Malav", "author_id": 5326634, "author_profile": "https://Stackoverflow.com/users/5326634", "pm_score": 3, "selected": false, "text": "<p>In python 2.x</p>\n\n<p><strong>range(x)</strong> returns a list, that is created in memory with x elements.</p>\n\n<pre><code>&gt;&gt;&gt; a = range(5)\n&gt;&gt;&gt; a\n[0, 1, 2, 3, 4]\n</code></pre>\n\n<p><strong>xrange(x)</strong> returns an xrange object which is a generator obj which generates the numbers on demand. they are computed during for-loop(Lazy Evaluation).</p>\n\n<p>For looping, this is slightly faster than range() and more memory efficient.</p>\n\n<pre><code>&gt;&gt;&gt; b = xrange(5)\n&gt;&gt;&gt; b\nxrange(5)\n</code></pre>\n" }, { "answer_id": 38318039, "author": "Supercolbat", "author_id": 6491545, "author_profile": "https://Stackoverflow.com/users/6491545", "pm_score": 3, "selected": false, "text": "<p><code>range(x,y)</code> returns a list of each number in between x and y if you use a <code>for</code> loop, then <code>range</code> is slower. In fact, <code>range</code> has a bigger Index range. <code>range(x.y)</code> will print out a list of all the numbers in between x and y</p>\n\n<p><code>xrange(x,y)</code> returns <code>xrange(x,y)</code> but if you used a <code>for</code> loop, then <code>xrange</code> is faster. <code>xrange</code> has a smaller Index range. <code>xrange</code> will not only print out <code>xrange(x,y)</code> but it will still keep all the numbers that are in it.</p>\n\n<pre><code>[In] range(1,10)\n[Out] [1, 2, 3, 4, 5, 6, 7, 8, 9]\n[In] xrange(1,10)\n[Out] xrange(1,10)\n</code></pre>\n\n<p>If you use a <code>for</code> loop, then it would work</p>\n\n<pre><code>[In] for i in range(1,10):\n print i\n[Out] 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n[In] for i in xrange(1,10):\n print i\n[Out] 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n</code></pre>\n\n<p>There isn't much difference when using loops, though there is a difference when just printing it!</p>\n" }, { "answer_id": 40191633, "author": "User_Targaryen", "author_id": 6354622, "author_profile": "https://Stackoverflow.com/users/6354622", "pm_score": 4, "selected": false, "text": "<p>You will find the advantage of <code>xrange</code> over <code>range</code> in this simple example:</p>\n\n<pre><code>import timeit\n\nt1 = timeit.default_timer()\na = 0\nfor i in xrange(1, 100000000):\n pass\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 4.49153590202 seconds\n\nt1 = timeit.default_timer()\na = 0\nfor i in range(1, 100000000):\n pass\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 7.04547905922 seconds\n</code></pre>\n\n<p>The above example doesn't reflect anything substantially better in case of <code>xrange</code>.</p>\n\n<p>Now look at the following case where <code>range</code> is really really slow, compared to <code>xrange</code>.</p>\n\n<pre><code>import timeit\n\nt1 = timeit.default_timer()\na = 0\nfor i in xrange(1, 100000000):\n if i == 10000:\n break\nt2 = timeit.default_timer()\n\nprint \"time taken: \", (t2-t1) # 0.000764846801758 seconds\n\nt1 = timeit.default_timer()\na = 0\nfor i in range(1, 100000000):\n if i == 10000:\n break\nt2 = timeit.default_timer() \n\nprint \"time taken: \", (t2-t1) # 2.78506207466 seconds\n</code></pre>\n\n<p>With <code>range</code>, it already creates a list from 0 to 100000000(time consuming), but <code>xrange</code> is a generator and it only generates numbers based on the need, that is, if the iteration continues.</p>\n\n<p>In Python-3, the implementation of the <code>range</code> functionality is same as that of <code>xrange</code> in Python-2, while they have done away with <code>xrange</code> in Python-3</p>\n\n<p>Happy Coding!! </p>\n" }, { "answer_id": 41562087, "author": "tejaswini teju", "author_id": 6497476, "author_profile": "https://Stackoverflow.com/users/6497476", "pm_score": 1, "selected": false, "text": "<p>range :-range will populate everything at once.which means every number of the range will occupy the memory.</p>\n\n<p>xrange :-xrange is something like generator ,it will comes into picture when you want the range of numbers but you dont want them to be stored,like when you want to use in for loop.so memory efficient.</p>\n" }, { "answer_id": 45278377, "author": "ANKUR SATYA", "author_id": 8154961, "author_profile": "https://Stackoverflow.com/users/8154961", "pm_score": 2, "selected": false, "text": "<p>Everyone has explained it greatly. But I wanted it to see it for myself. I use python3. So, I opened the resource monitor (in Windows!), and first, executed the following command first:</p>\n\n<pre><code>a=0\nfor i in range(1,100000):\n a=a+i\n</code></pre>\n\n<p>and then checked the change in 'In Use' memory. It was insignificant.\nThen, I ran the following code:</p>\n\n<pre><code>for i in list(range(1,100000)):\n a=a+i\n</code></pre>\n\n<p>And it took a big chunk of the memory for use, instantly. And, I was convinced.\nYou can try it for yourself.</p>\n\n<p>If you are using Python 2X, then replace 'range()' with 'xrange()' in the first code and 'list(range())' with 'range()'.</p>\n" }, { "answer_id": 45768014, "author": "Rajendra Uppal", "author_id": 277734, "author_profile": "https://Stackoverflow.com/users/277734", "pm_score": 2, "selected": false, "text": "<p>From the help docs.</p>\n\n<p>Python 2.7.12</p>\n\n<pre><code>&gt;&gt;&gt; print range.__doc__\nrange(stop) -&gt; list of integers\nrange(start, stop[, step]) -&gt; list of integers\n\nReturn a list containing an arithmetic progression of integers.\nrange(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\nWhen step is given, it specifies the increment (or decrement).\nFor example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\nThese are exactly the valid indices for a list of 4 elements.\n\n&gt;&gt;&gt; print xrange.__doc__\nxrange(stop) -&gt; xrange object\nxrange(start, stop[, step]) -&gt; xrange object\n\nLike range(), but instead of returning a list, returns an object that\ngenerates the numbers in the range on demand. For looping, this is \nslightly faster than range() and more memory efficient.\n</code></pre>\n\n<p>Python 3.5.2</p>\n\n<pre><code>&gt;&gt;&gt; print(range.__doc__)\nrange(stop) -&gt; range object\nrange(start, stop[, step]) -&gt; range object\n\nReturn an object that produces a sequence of integers from start (inclusive)\nto stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\nstart defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\nThese are exactly the valid indices for a list of 4 elements.\nWhen step is given, it specifies the increment (or decrement).\n\n&gt;&gt;&gt; print(xrange.__doc__)\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\nNameError: name 'xrange' is not defined\n</code></pre>\n\n<p>Difference is apparent. In Python 2.x, <code>range</code> returns a list, <code>xrange</code> returns an xrange object which is iterable.</p>\n\n<p>In Python 3.x, <code>range</code> becomes <code>xrange</code> of Python 2.x, and <code>xrange</code> is removed.</p>\n" }, { "answer_id": 52696055, "author": "U12-Forward", "author_id": 8708364, "author_profile": "https://Stackoverflow.com/users/8708364", "pm_score": 1, "selected": false, "text": "<p>Additionally, if do <code>list(xrange(...))</code> will be equivalent to <code>range(...)</code>.</p>\n\n<p>So <code>list</code> is slow.</p>\n\n<p>Also <code>xrange</code> really doesn't fully finish the sequence</p>\n\n<p>So that's why its not a list, it's a <code>xrange</code> object</p>\n" }, { "answer_id": 60917801, "author": "Giorgos Myrianthous", "author_id": 7131757, "author_profile": "https://Stackoverflow.com/users/7131757", "pm_score": 2, "selected": false, "text": "<p><strong><a href=\"https://docs.python.org/2/library/functions.html#range\" rel=\"nofollow noreferrer\"><code>range()</code></a> in Python <code>2.x</code></strong></p>\n\n<p>This function is essentially the old <code>range()</code> function that was available in Python <code>2.x</code> and returns an instance of a <code>list</code> object that contains the elements in the specified range. </p>\n\n<p>However, this implementation is too inefficient when it comes to initialise a list with a range of numbers. For example, <code>for i in range(1000000)</code> would be a very expensive command to execute, both in terms of memory and time usage as it requires the storage of this list into the memory. </p>\n\n<hr>\n\n<p><strong><a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\"><code>range()</code></a> in Python <code>3.x</code> and <a href=\"https://docs.python.org/2/library/functions.html#xrange\" rel=\"nofollow noreferrer\"><code>xrange()</code></a> in Python <code>2.x</code></strong></p>\n\n<p>Python <code>3.x</code> introduced a newer implementation of <code>range()</code> (while the newer implementation was already available in Python <code>2.x</code> through the <code>xrange()</code> function). </p>\n\n<p>The <code>range()</code> exploits a strategy known as <strong>lazy evaluation.</strong> Instead of creating a huge list of elements in range, the newer implementation introduces the class <code>range</code>, a lightweight object that represents the required elements in the given range, <strong>without storing them explicitly in memory</strong> (this might sound like generators but the concept of lazy evaluation is different). </p>\n\n<hr>\n\n<p>As an example, consider the following: </p>\n\n<pre><code># Python 2.x\n&gt;&gt;&gt; a = range(10)\n&gt;&gt;&gt; type(a)\n&lt;type 'list'&gt;\n&gt;&gt;&gt; b = xrange(10)\n&gt;&gt;&gt; type(b)\n&lt;type 'xrange'&gt;\n</code></pre>\n\n<p>and </p>\n\n<pre><code># Python 3.x\n&gt;&gt;&gt; a = range(10)\n&gt;&gt;&gt; type(a)\n&lt;class 'range'&gt;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about ``` for i in range(0, 20): for i in xrange(0, 20): ```
**In Python 2.x:** * `range` creates a list, so if you do `range(1, 10000000)` it creates a list in memory with `9999999` elements. * `xrange` is a sequence object that evaluates lazily. **In Python 3:** * `range` does the equivalent of Python 2's `xrange`. To get the list, you have to explicitly use `list(range(...))`. * `xrange` no longer exists.
94,959
<p>I have a couple of triggers on a table that I want to keep <strong><em>separate</em></strong> and would like to priortize them.</p> <p>I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ?</p>
[ { "answer_id": 94973, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 4, "selected": true, "text": "<p>Use sp_settriggerorder. You can specify the first and last trigger to fire depending on the operation.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186762.aspx\" rel=\"noreferrer\">sp_settriggerorder on MSDN</a></p>\n\n<p>From the above link:<br>\n<b>A. Setting the firing order for a DML trigger</b><br>\nThe following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE operation occurs on the Sales.SalesOrderHeader table.</p>\n\n<pre>\nUSE AdventureWorks;\nGO\nsp_settriggerorder \n @triggername= 'Sales.uSalesOrderHeader', \n @order='First', \n @stmttype = 'UPDATE';\n</pre>\n\n<p><b>B. Setting the firing order for a DDL trigger</b><br>\nThe following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER_TABLE event occurs in the AdventureWorks database.</p>\n\n<pre>\nUSE AdventureWorks;\nGO\nsp_settriggerorder \n @triggername= 'ddlDatabaseTriggerLog', \n @order='First', \n @stmttype = 'ALTER_TABLE', \n @namespace = 'DATABASE';\n</pre>\n" }, { "answer_id": 94978, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"https://stackoverflow.com/questions/94103/sql-server-triggers-order-of-execution#94162\">here</a>.</p>\n" }, { "answer_id": 95050, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/ms186762.aspx\" rel=\"nofollow noreferrer\">sp_settriggerorder</a> to define the order of each trigger on a table.</p>\n\n<p>However, I would argue that you'd be much better off having a single trigger that does multiple things. This is <em>particularly</em> so if the order is important, since that importance will not be very obvious if you have multiple triggers. Imagine someone trying to support the database months/years down the track. Of course there are likely to be cases where you need to have multiple triggers or it really is better design, but I'd start assuming you should have one and work from there.</p>\n" }, { "answer_id": 95125, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>Rememebr if you change the trigger order, someone else could come by later and rearrange it again. And where would you document what the trigger order should be so a maintenance developer knows not to mess with the order or things will break? If two trigger tasks definitely must be performed in a specific order, the only safe route is to put them in the same trigger.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5853/" ]
I have a couple of triggers on a table that I want to keep ***separate*** and would like to priortize them. I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ?
Use sp\_settriggerorder. You can specify the first and last trigger to fire depending on the operation. [sp\_settriggerorder on MSDN](http://msdn.microsoft.com/en-us/library/ms186762.aspx) From the above link: **A. Setting the firing order for a DML trigger** The following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE operation occurs on the Sales.SalesOrderHeader table. ``` USE AdventureWorks; GO sp_settriggerorder @triggername= 'Sales.uSalesOrderHeader', @order='First', @stmttype = 'UPDATE'; ``` **B. Setting the firing order for a DDL trigger** The following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER\_TABLE event occurs in the AdventureWorks database. ``` USE AdventureWorks; GO sp_settriggerorder @triggername= 'ddlDatabaseTriggerLog', @order='First', @stmttype = 'ALTER_TABLE', @namespace = 'DATABASE'; ```
94,977
<p>In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks. For example, the following code does not compile:</p> <pre><code>try { String s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } </code></pre> <p>In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block. (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".)</p> <p>The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block:</p> <pre><code>String s; try { s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } </code></pre> <p>However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally).</p> <p>My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)? </p>
[ { "answer_id": 94998, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 6, "selected": false, "text": "<p>How could you be sure, that you reached the declaration part in your catch block? What if the instantiation throws the exception?</p>\n" }, { "answer_id": 95000, "author": "jpbarto", "author_id": 8511, "author_profile": "https://Stackoverflow.com/users/8511", "pm_score": 0, "selected": false, "text": "<p>My thought would be that because something in the try block triggered the exception its namespace contents cannot be trusted - ie referencing the String 's' in the catch block could cause the throw of yet another exception.</p>\n" }, { "answer_id": 95003, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 0, "selected": false, "text": "<p>Well if it doesn't throw a compile error, and you could declare it for the rest of the method, then there would be no way to only declare it only within try scope. It's forcing you to be explicit as to where the variable is supposed to exists and doesn't make assumptions. </p>\n" }, { "answer_id": 95006, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 3, "selected": false, "text": "<p>In C++ at any rate, the scope of an automatic variable is limited by the curly braces that surround it. Why would anyone expect this to be different by plunking down a try keyword outside the curly braces?</p>\n" }, { "answer_id": 95015, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "<p>You solution is exactly what you should do. You can't be sure that your declaration was even reached in the try block, which would result in another exception in the catch block.</p>\n\n<p>It simply must work as separate scopes.</p>\n\n<pre><code>try\n dim i as integer = 10 / 0 ''// Throw an exception\n dim s as string = \"hi\"\ncatch (e)\n console.writeln(s) ''// Would throw another exception, if this was allowed to compile\nend try\n</code></pre>\n" }, { "answer_id": 95024, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": -1, "selected": false, "text": "<p>If the assignment operation fails your catch statement will have a null reference back to the unassigned variable.</p>\n" }, { "answer_id": 95030, "author": "John Christensen", "author_id": 1194, "author_profile": "https://Stackoverflow.com/users/1194", "pm_score": 9, "selected": true, "text": "<p>Two things:</p>\n\n<ol>\n<li><p>Generally, Java has just 2 levels of scope: global and function. But, try/catch is an exception (no pun intended). When an exception is thrown and the exception object gets a variable assigned to it, that object variable is only available within the \"catch\" section and is destroyed as soon as the catch completes.</p></li>\n<li><p>(and more importantly). You can't know where in the try block the exception was thrown. It may have been before your variable was declared. Therefore it is impossible to say what variables will be available for the catch/finally clause. Consider the following case, where scoping is as you suggested:</p>\n\n<pre><code>\ntry\n{\n throw new ArgumentException(\"some operation that throws an exception\");\n string s = \"blah\";\n}\ncatch (e as ArgumentException)\n{ \n Console.Out.WriteLine(s);\n}\n</code></pre></li>\n</ol>\n\n<p>This clearly is a problem - when you reach the exception handler, s will not have been declared. Given that catches are meant to handle exceptional circumstances and finallys <em>must</em> execute, being safe and declaring this a problem at compile time is far better than at runtime.</p>\n" }, { "answer_id": 95034, "author": "jW.", "author_id": 8880, "author_profile": "https://Stackoverflow.com/users/8880", "pm_score": 2, "selected": false, "text": "<p>The variables are block level and restricted to that Try or Catch block. Similar to defining a variable in an if statement. Think of this situation.</p>\n\n<pre><code>try { \n fileOpen(\"no real file Name\"); \n String s = \"GO TROJANS\"; \n} catch (Exception) { \n print(s); \n}\n</code></pre>\n\n<p>The String would never be declared, so it can't be depended upon. </p>\n" }, { "answer_id": 95040, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "<p>In the specific example you've given, initialising s can't throw an exception. So you'd think that maybe its scope could be extended.</p>\n\n<p>But in general, initialiser expressions can throw exceptions. It wouldn't make sense for a variable whose initialiser threw an exception (or which was declared after another variable where that happened) to be in scope for catch/finally.</p>\n\n<p>Also, code readability would suffer. The rule in C (and languages which follow it, including C++, Java and C#) is simple: variable scopes follow blocks.</p>\n\n<p>If you want a variable to be in scope for try/catch/finally but nowhere else, then wrap the whole thing in another set of braces (a bare block) and declare the variable before the try.</p>\n" }, { "answer_id": 95047, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "<p>Traditionally, in C-style languages, what happens inside the curly braces stays inside the curly braces. I think that having the lifetime of a variable stretch across scopes like that would be unintuitive to most programmers. You can achieve what you want by enclosing the try/catch/finally blocks inside another level of braces. e.g.</p>\n\n<pre><code>... code ...\n{\n string s = \"test\";\n try\n {\n // more code\n }\n catch(...)\n {\n Console.Out.WriteLine(s);\n }\n}\n</code></pre>\n\n<p>EDIT: I guess every rule <em>does</em> have an exception. The following is valid C++:</p>\n\n<pre><code>int f() { return 0; }\n\nvoid main() \n{\n int y = 0;\n\n if (int x = f())\n {\n cout &lt;&lt; x;\n }\n else\n {\n cout &lt;&lt; x;\n }\n}\n</code></pre>\n\n<p>The scope of x is the conditional, the then clause and the else clause.</p>\n" }, { "answer_id": 95054, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 3, "selected": false, "text": "<p>Like ravenspoint pointed out, everyone expects variables to be local to the block they are defined in. <code>try</code> introduces a block and so does <code>catch</code>.</p>\n\n<p>If you want variables local to both <code>try</code> and <code>catch</code>, try enclosing both in a block:</p>\n\n<pre><code>// here is some code\n{\n string s;\n try\n {\n\n throw new Exception(\":(\")\n }\n catch (Exception e)\n {\n Debug.WriteLine(s);\n }\n}\n</code></pre>\n" }, { "answer_id": 95057, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 1, "selected": false, "text": "<p>Part of the reason they are not in the same scope is because at any point of the try block, you can have thrown the exception. If they were in the same scope, its a disaster in waiting, because depending on where the exception was thrown, it could be even more ambiguous.</p>\n\n<p>At least when its declared outside of the try block, you know for sure what the variable at minimum could be when an exception is thrown; The value of the variable before the try block.</p>\n" }, { "answer_id": 95068, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 2, "selected": false, "text": "<p>Because the try block and the catch block are 2 different blocks. </p>\n\n<p>In the following code, would you expect s defined in block A be visible in block B? </p>\n\n<pre><code>{ // block A\n string s = \"dude\";\n}\n\n{ // block B\n Console.Out.WriteLine(s); // or printf or whatever\n}\n</code></pre>\n" }, { "answer_id": 95078, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 3, "selected": false, "text": "<p>The simple answer is that C and most of the languages that have inherited its syntax are block scoped. That means that if a variable is defined in one block, i.e., inside { }, that is its scope.</p>\n\n<p>The exception, by the way, is JavaScript, which has a similar syntax, but is function scoped. In JavaScript, a variable declared in a try block is in scope in the catch block, and everywhere else in its containing function.</p>\n" }, { "answer_id": 95133, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 2, "selected": false, "text": "<p>While in your example it is weird that it does not work, take this similar one:</p>\n\n<pre><code> try\n {\n //Code 1\n String s = \"1|2\";\n //Code 2\n }\n catch\n {\n Console.WriteLine(s.Split('|')[1]);\n }\n</code></pre>\n\n<p>This would cause the catch to throw a null reference exception if Code 1 broke. Now while the semantics of try/catch are pretty well understood, this would be an annoying corner case, since s is defined with an initial value, so it should in theory never be null, but under shared semantics, it would be.</p>\n\n<p>Again this could in theory be fixed by only allowing separated definitions (<code>String s; s = \"1|2\";</code>), or some other set of conditions, but it is generally easier to just say no.</p>\n\n<p>Additionally, it allows the semantics of scope to be defined globally without exception, specifically, locals last as long as the <code>{}</code> they are defined in, in all cases. Minor point, but a point.</p>\n\n<p>Finally, in order to do what you want, you can add a set of brackets around the try catch. Gives you the scope you want, although it does come at the cost of a little readability, but not too much.</p>\n\n<pre><code>{\n String s;\n try\n {\n s = \"test\";\n //More code\n }\n catch\n {\n Console.WriteLine(s);\n }\n}\n</code></pre>\n" }, { "answer_id": 95136, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 2, "selected": false, "text": "<p>@burkhard has the question as to why answered properly, but as a note I wanted to add, while your recommended solution example is good 99.9999+% of time, it is not good practice, it is far safer to either check for null before using something instantiate within the try block, or initialize the variable to something instead of just declaring it before the try block. For example:</p>\n\n<pre><code>string s = String.Empty;\ntry\n{\n //do work\n}\ncatch\n{\n //safely access s\n Console.WriteLine(s);\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>string s;\ntry\n{\n //do work\n}\ncatch\n{\n if (!String.IsNullOrEmpty(s))\n {\n //safely access s\n Console.WriteLine(s);\n }\n}\n</code></pre>\n\n<p>This should provide scalability in the workaround, so that even when what you're doing in the try block is more complex than assigning a string, you should be able to safely access the data from your catch block.</p>\n" }, { "answer_id": 95144, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 1, "selected": false, "text": "<p>When you declare a local variable it is placed on the stack (for some types the entire value of the object will be on the stack, for other types only a reference will be on the stack). When there is an exception inside a try block, the local variables within the block are freed, which means the stack is \"unwound\" back to the state it was at at the beginning of the try block. This is by design. It's how the try / catch is able to back out of all of the function calls within the block and puts your system back into a functional state. Without this mechanism you could never be sure of the state of anything when an exception occurs.</p>\n\n<p>Having your error handling code rely on externally declared variables which have their values changed inside the try block seems like bad design to me. What you are doing is essentially leaking resources intentionally in order to gain information (in this particular case it's not so bad because you are only leaking information, but imagine if it were some other resource? you're just making life harder on yourself in the future). I would suggest breaking up your try blocks into smaller chunks if you require more granularity in error handling.</p>\n" }, { "answer_id": 95180, "author": "tamberg", "author_id": 3588, "author_profile": "https://Stackoverflow.com/users/3588", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://www.ecma-international.org/publications/standards/Ecma-334.htm\" rel=\"nofollow noreferrer\">C# Spec</a> (15.2) states \"The scope of a local variable or constant declared in a block ist the block.\"</p>\n\n<p>(in your first example the try block is the block where \"s\" is declared)</p>\n" }, { "answer_id": 95230, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 1, "selected": false, "text": "<p>When you have a try catch, you should at the most part know that errors that it might throw. Theese Exception classes normaly tell everything you need about the exception. If not, you should make you're own exception classes and pass that information along. That way, you will never need to get the variables from inside the try block, because the Exception is self explainatory. So if you need to do this alot, think about you're design, and try to think if there is some other way, that you can either predict exceptions comming, or use the information comming from the exceptions, and then maybe rethrow your own exception with more information.</p>\n" }, { "answer_id": 95270, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>As has been pointed out by other users, the curly braces define scope in pretty much every C style language that I know of.</p>\n\n<p>If it's a simple variable, then why do you care how long it will be in scope? It's not that big a deal.</p>\n\n<p>in C#, if it is a complex variable, you will want to implement IDisposable. You can then either use try/catch/finally and call obj.Dispose() in the finally block. Or you can use the using keyword, which will automatically call the Dispose at the end of the code section.</p>\n" }, { "answer_id": 95451, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 2, "selected": false, "text": "<p>The answer, as everyone has pointed out, is pretty much \"that's how blocks are defined\".</p>\n\n<p>There are some proposals to make the code prettier. See <a href=\"http://docs.google.com/View?docid=dffxznxr_1nmsqkz&amp;pli=1\" rel=\"nofollow noreferrer\">ARM</a></p>\n\n<pre><code> try (FileReader in = makeReader(), FileWriter out = makeWriter()) {\n // code using in and out\n } catch(IOException e) {\n // ...\n }\n</code></pre>\n\n<p><a href=\"http://www.javac.info/\" rel=\"nofollow noreferrer\">Closures</a> are supposed to address this as well.</p>\n\n<pre><code>with(FileReader in : makeReader()) with(FileWriter out : makeWriter()) {\n // code using in and out\n}\n</code></pre>\n\n<p><strong>UPDATE:</strong> ARM is implemented in Java 7. <a href=\"http://download.java.net/jdk7/docs/technotes/guides/language/try-with-resources.html\" rel=\"nofollow noreferrer\">http://download.java.net/jdk7/docs/technotes/guides/language/try-with-resources.html</a></p>\n" }, { "answer_id": 97346, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 4, "selected": false, "text": "<p>Everyone else has brought up the basics -- what happens in a block stays in a block. But in the case of .NET, it may be helpful to examine what the compiler thinks is happening. Take, for example, the following try/catch code (note that the StreamReader is declared, correctly, outside the blocks):</p>\n\n<pre><code>static void TryCatchFinally()\n{\n StreamReader sr = null;\n try\n {\n sr = new StreamReader(path);\n Console.WriteLine(sr.ReadToEnd());\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.ToString());\n }\n finally\n {\n if (sr != null)\n {\n sr.Close();\n }\n }\n}\n</code></pre>\n\n<p>This will compile out to something similar to the following in MSIL:</p>\n\n<pre><code>.method private hidebysig static void TryCatchFinallyDispose() cil managed\n{\n // Code size 53 (0x35) \n .maxstack 2 \n .locals init ([0] class [mscorlib]System.IO.StreamReader sr, \n [1] class [mscorlib]System.Exception ex) \n IL_0000: ldnull \n IL_0001: stloc.0 \n .try \n { \n .try \n { \n IL_0002: ldsfld string UsingTest.Class1::path \n IL_0007: newobj instance void [mscorlib]System.IO.StreamReader::.ctor(string) \n IL_000c: stloc.0 \n IL_000d: ldloc.0 \n IL_000e: callvirt instance string [mscorlib]System.IO.TextReader::ReadToEnd()\n IL_0013: call void [mscorlib]System.Console::WriteLine(string) \n IL_0018: leave.s IL_0028\n } // end .try\n catch [mscorlib]System.Exception \n {\n IL_001a: stloc.1\n IL_001b: ldloc.1 \n IL_001c: callvirt instance string [mscorlib]System.Exception::ToString() \n IL_0021: call void [mscorlib]System.Console::WriteLine(string) \n IL_0026: leave.s IL_0028 \n } // end handler \n IL_0028: leave.s IL_0034 \n } // end .try \n finally \n { \n IL_002a: ldloc.0 \n IL_002b: brfalse.s IL_0033 \n IL_002d: ldloc.0 \n IL_002e: callvirt instance void [mscorlib]System.IDisposable::Dispose() \n IL_0033: endfinally \n } // end handler \n IL_0034: ret \n} // end of method Class1::TryCatchFinallyDispose\n</code></pre>\n\n<p>What do we see? MSIL respects the blocks -- they're intrinsically part of the underlying code generated when you compile your C#. The scope isn't just hard-set in the C# spec, it's in the CLR and CLS spec as well. </p>\n\n<p>The scope protects you, but you do occasionally have to work around it. Over time, you get used to it, and it begins to feel natural. Like everyone else said, what happens in a block stays in that block. You want to share something? You have to go outside the blocks ... </p>\n" }, { "answer_id": 98148, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "<p>If we ignore the scoping-block issue for a moment, the complier would have to work a lot harder in a situation that's not well defined. While this is not impossible, the scoping error also forces you, the author of the code, to realise the implication of the code you write (that the string s may be null in the catch block). If your code was legal, in the case of an OutOfMemory exception, s isn't even guaranteed to be allocated a memory slot: </p>\n\n<pre><code>// won't compile!\ntry\n{\n VeryLargeArray v = new VeryLargeArray(TOO_BIG_CONSTANT); // throws OutOfMemoryException\n string s = \"Help\";\n}\ncatch\n{\n Console.WriteLine(s); // whoops!\n}\n</code></pre>\n\n<p>The CLR (and therefore compiler) also force you to initialize variables before they are used. In the catch block presented it can't guarantee this. </p>\n\n<p>So we end up with the compiler having to do a lot of work, which in practice doesn't provide much benefit and would probably confuse people and lead them to ask why try/catch works differently. </p>\n\n<p>In addition to consistency, by not allowing anything fancy and adhering to the already established scoping semantics used throughout the language, the compiler and CLR are able to provide a greater guarantee of the state of a variable inside a catch block. That it exists and has been initialized.</p>\n\n<p>Note that the language designers have done a good job with other constructs like <em>using</em> and <em>lock</em> where the problem and scope is well defined, which allows you to write clearer code.</p>\n\n<p>e.g. the <em>using</em> keyword with <em>IDisposable</em> objects in:</p>\n\n<pre><code>using(Writer writer = new Writer())\n{\n writer.Write(\"Hello\");\n}\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>Writer writer = new Writer();\ntry\n{ \n writer.Write(\"Hello\");\n}\nfinally\n{\n if( writer != null)\n {\n ((IDisposable)writer).Dispose();\n }\n}\n</code></pre>\n\n<p>If your try/catch/finally is hard to understand, try refactoring or introducing another layer of indirection with an intermediate class that encapsulates the semantics of what you are trying to accomplish. Without seeing real code, it's hard to be more specific.</p>\n" }, { "answer_id": 98160, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": -1, "selected": false, "text": "<p>C# 3.0:</p>\n\n<pre><code>string html = new Func&lt;string&gt;(() =&gt;\n{\n string webpage;\n\n try\n {\n using(WebClient downloader = new WebClient())\n {\n webpage = downloader.DownloadString(url);\n }\n }\n catch(WebException)\n {\n Console.WriteLine(\"Download failed.\"); \n }\n\n return webpage;\n})();\n</code></pre>\n" }, { "answer_id": 99978, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In Python they are visible in the catch/finally blocks if the line declaring them didn't throw.</p>\n" }, { "answer_id": 100257, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 3, "selected": false, "text": "<p>According to the section titled \"How to Throw and Catch Exceptions\" in Lesson 2 of <strong>MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation</strong>, the reason is that the exception may have occurred before variable declarations in the try block (as others have noted already).</p>\n\n<p>Quote from page 25:</p>\n\n<p>\"Notice that the StreamReader declaration was moved outside the Try block in the preceding example. This is necessary because the Finally block cannot access variables that are declared within the Try block. <strong><em>This makes sense because depending on where an exception occurred, variable declarations within the Try block might not yet have been executed</em></strong>.\"</p>\n" }, { "answer_id": 4553265, "author": "Ravi", "author_id": 556970, "author_profile": "https://Stackoverflow.com/users/556970", "pm_score": 1, "selected": false, "text": "<p>What if the exception is thrown in some code which is above the declaration of the variable. Which means, the declaration itself was not happend in this case.</p>\n\n<pre><code>try {\n\n //doSomeWork // Exception is thrown in this line. \n String s;\n //doRestOfTheWork\n\n} catch (Exception) {\n //Use s;//Problem here\n} finally {\n //Use s;//Problem here\n}\n</code></pre>\n" }, { "answer_id": 17817256, "author": "usefulBee", "author_id": 2093880, "author_profile": "https://Stackoverflow.com/users/2093880", "pm_score": 0, "selected": false, "text": "<p>Instead of a local variable, a public property could be declared; this also should avoid another potential error of an unassigned variable.\npublic string S { get; set; }</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12484/" ]
In C# and in Java (and possibly other languages as well), variables declared in a "try" block are not in scope in the corresponding "catch" or "finally" blocks. For example, the following code does not compile: ``` try { String s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } ``` In this code, a compile-time error occurs on the reference to s in the catch block, because s is only in scope in the try block. (In Java, the compile error is "s cannot be resolved"; in C#, it's "The name 's' does not exist in the current context".) The general solution to this issue seems to be to instead declare variables just before the try block, instead of within the try block: ``` String s; try { s = "test"; // (more code...) } catch { Console.Out.WriteLine(s); //Java fans: think "System.out.println" here instead } ``` However, at least to me, (1) this feels like a clunky solution, and (2) it results in the variables having a larger scope than the programmer intended (the entire remainder of the method, instead of only in the context of the try-catch-finally). My question is, what were/are the rationale(s) behind this language design decision (in Java, in C#, and/or in any other applicable languages)?
Two things: 1. Generally, Java has just 2 levels of scope: global and function. But, try/catch is an exception (no pun intended). When an exception is thrown and the exception object gets a variable assigned to it, that object variable is only available within the "catch" section and is destroyed as soon as the catch completes. 2. (and more importantly). You can't know where in the try block the exception was thrown. It may have been before your variable was declared. Therefore it is impossible to say what variables will be available for the catch/finally clause. Consider the following case, where scoping is as you suggested: ``` try { throw new ArgumentException("some operation that throws an exception"); string s = "blah"; } catch (e as ArgumentException) { Console.Out.WriteLine(s); } ``` This clearly is a problem - when you reach the exception handler, s will not have been declared. Given that catches are meant to handle exceptional circumstances and finallys *must* execute, being safe and declaring this a problem at compile time is far better than at runtime.
94,999
<p>I am looking for a command in Unix that returns the status of a process(active, dead, sleeping, waiting for another process, etc.)</p> <p>is there any available?<br> A shell script maybe?</p>
[ { "answer_id": 95063, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 0, "selected": false, "text": "<p>Playing with ps options doesn't give you what you need?</p>\n" }, { "answer_id": 96154, "author": "Brian Mitchell", "author_id": 13716, "author_profile": "https://Stackoverflow.com/users/13716", "pm_score": 2, "selected": false, "text": "<p>in linux, something like ps -p somepid --no-headers -o state should work, alternately you can look for the info in proc with grep ^State: /proc/somepid/status</p>\n" }, { "answer_id": 107300, "author": "TLS", "author_id": 19417, "author_profile": "https://Stackoverflow.com/users/19417", "pm_score": 3, "selected": true, "text": "<p>Try <em>pflags &lt;pid&gt;</em>, which will give you per-thread status information. Example:</p>\n\n<pre>\nroot@weetbix # pflags $$\n3384: bash\n data model = _ILP32 flags = ORPHAN|MSACCT|MSFORK\n /1: flags = ASLEEP waitid(0x7,0x0,0xffbfefc0,0xf)\n sigmask = 0x00020000,0x00000000\n</pre>\n\n<p>Also check out the manpage for <em>pflags</em> to see other useful tools like <em>pstack</em>, <em>pfiles</em>, <em>pargs</em> etc.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/94999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15884/" ]
I am looking for a command in Unix that returns the status of a process(active, dead, sleeping, waiting for another process, etc.) is there any available? A shell script maybe?
Try *pflags <pid>*, which will give you per-thread status information. Example: ``` root@weetbix # pflags $$ 3384: bash data model = _ILP32 flags = ORPHAN|MSACCT|MSFORK /1: flags = ASLEEP waitid(0x7,0x0,0xffbfefc0,0xf) sigmask = 0x00020000,0x00000000 ``` Also check out the manpage for *pflags* to see other useful tools like *pstack*, *pfiles*, *pargs* etc.
95,005
<p>If I want to inject a globally scoped array variable into a page's client-side javascript during a full page postback, I can use:</p> <pre><code>this.Page.ClientScript.RegisterArrayDeclaration("WorkCalendar", "\"" + date.ToShortDateString() + "\""); </code></pre> <p>to declare and populate a client-side javascript array on the page. Nice and simple. </p> <p>But I want to do the same from a async postback from an UpdatePanel. </p> <p>The closest I can figure so far is to create a .js file that just contains the var declaration, update the file during the async postback, and then use a <code>ScriptManagerProxy.Scripts.Add</code> to add the .js file to the page's global scope. </p> <p>Is there anything simpler? r iz doin it wrong?</p>
[ { "answer_id": 95081, "author": "typemismatch", "author_id": 13714, "author_profile": "https://Stackoverflow.com/users/13714", "pm_score": 1, "selected": true, "text": "<p>You could also update a hidden label inside the update panel which allows you to write out any javascript you like. I would suggest though using web services or even page methods to fetch the data you need instead of using update panels.</p>\n\n<p>Example: myLabel.Text = \"....\"; ... put your logic in this or you can add [WebMethod] to any public static page method and return data directly.</p>\n" }, { "answer_id": 98326, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Use the static method System.Web.UI.ScriptManager.AddStartupScript()</p>\n\n<p>The script will run on all full and partial postbacks.</p>\n" }, { "answer_id": 2713219, "author": "Sangeet", "author_id": 207514, "author_profile": "https://Stackoverflow.com/users/207514", "pm_score": 2, "selected": false, "text": "<p>Sam is correct.\nScriptManager.RegisterStartupScript is the correct name of the function .\nIt will run on all full and partial page updates.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637/" ]
If I want to inject a globally scoped array variable into a page's client-side javascript during a full page postback, I can use: ``` this.Page.ClientScript.RegisterArrayDeclaration("WorkCalendar", "\"" + date.ToShortDateString() + "\""); ``` to declare and populate a client-side javascript array on the page. Nice and simple. But I want to do the same from a async postback from an UpdatePanel. The closest I can figure so far is to create a .js file that just contains the var declaration, update the file during the async postback, and then use a `ScriptManagerProxy.Scripts.Add` to add the .js file to the page's global scope. Is there anything simpler? r iz doin it wrong?
You could also update a hidden label inside the update panel which allows you to write out any javascript you like. I would suggest though using web services or even page methods to fetch the data you need instead of using update panels. Example: myLabel.Text = "...."; ... put your logic in this or you can add [WebMethod] to any public static page method and return data directly.
95,061
<p>How can I tell Activerecord to not load blob columns unless explicitly asked for? There are some pretty large blobs in my legacy DB that must be excluded for 'normal' Objects.</p>
[ { "answer_id": 95413, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "<p>I believe you can ask AR to load specific columns in your invocation to find:</p>\n\n<pre><code>MyModel.find(id, :select =&gt; 'every, attribute, except, the, blobs')\n</code></pre>\n\n<p>However, this would need to be updated as you add columns, so it's not ideal. I don't think there is any way to specifically exclude one column in rails (nor in a single SQL select).</p>\n\n<p>I guess you could write it like this:</p>\n\n<pre><code>MyModel.find(id, :select =&gt; (MyModel.column_names - ['column_to_exclude']).join(', '))\n</code></pre>\n\n<p>Test these out before you take my word for it though. :)</p>\n" }, { "answer_id": 1354650, "author": "Zeke", "author_id": 95670, "author_profile": "https://Stackoverflow.com/users/95670", "pm_score": 2, "selected": false, "text": "<p>fd's answer is mostly right, but ActiveRecord <a href=\"http://dev.rubyonrails.org/ticket/5863\" rel=\"nofollow noreferrer\">doesn't currently accept an array</a> as a :select argument, so you'll need to join the desired columns into a comma-delimited string, like so:</p>\n\n<pre><code>desired_columns = (MyModel.column_names - ['column_to_exclude']).join(', ')\nMyModel.find(id, :select =&gt; desired_columns)\n</code></pre>\n" }, { "answer_id": 1604529, "author": "choonkeat", "author_id": 136558, "author_profile": "https://Stackoverflow.com/users/136558", "pm_score": 1, "selected": false, "text": "<p>A clean approach requiring NO CHANGES to the way you code else where in your app, i.e. no messing with <code>:select</code> options</p>\n\n<blockquote>\n <p>For whatever reason you need or choose to store blobs in databases.\n Yet, you do not wish to mix blob columns in the same table as your\n regular attributes. BinaryColumnTable helps you store ALL blobs in\n a separate table, managed transparently by an ActiveRecord model. \n Optionally, it helps you record the content-type of the blob. </p>\n \n <p><a href=\"http://github.com/choonkeat/binary_column_table\" rel=\"nofollow noreferrer\">http://github.com/choonkeat/binary_column_table</a></p>\n</blockquote>\n\n<p>Usage is simple</p>\n\n<pre><code>Member.create(:name =&gt; \"Michael\", :photo =&gt; IO.read(\"avatar.png\"))\n#=&gt; creates a record in \"members\" table, saving \"Michael\" into the \"name\" column\n#=&gt; creates a record in \"binary_columns\" table, saving \"avatar.png\" binary into \"content\" column\n\nm = Member.last #=&gt; only columns in \"members\" table is fetched (no blobs)\nm.name #=&gt; \"Michael\"\nm.photo #=&gt; binary content of the \"avatar.png\" file\n</code></pre>\n" }, { "answer_id": 3274347, "author": "Chris Hoffman", "author_id": 394985, "author_profile": "https://Stackoverflow.com/users/394985", "pm_score": 4, "selected": false, "text": "<p>I just ran into this using rail 3.</p>\n\n<p>Fortunately it wasn't that difficult to solve. I set a <code>default_scope</code> that removed the particular columns I didn't want from the result. For example, in the model I had there was an xml text field that could be quite long that wasn't used in most views.</p>\n\n<pre><code>default_scope select((column_names - ['data']).map { |column_name| \"`#{table_name}`.`#{column_name}`\"})\n</code></pre>\n\n<p>You'll see from the solution that I had to map the columns to fully qualified versions so I could continue to use the model through relationships without ambiguities in attributes. Later where you do want to have the field just tack on another <code>.select(:data)</code> to have it included.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I tell Activerecord to not load blob columns unless explicitly asked for? There are some pretty large blobs in my legacy DB that must be excluded for 'normal' Objects.
I just ran into this using rail 3. Fortunately it wasn't that difficult to solve. I set a `default_scope` that removed the particular columns I didn't want from the result. For example, in the model I had there was an xml text field that could be quite long that wasn't used in most views. ``` default_scope select((column_names - ['data']).map { |column_name| "`#{table_name}`.`#{column_name}`"}) ``` You'll see from the solution that I had to map the columns to fully qualified versions so I could continue to use the model through relationships without ambiguities in attributes. Later where you do want to have the field just tack on another `.select(:data)` to have it included.
95,074
<p>I have noticed that setting row height in DataGridView control is slow. Is there a way to make it faster?</p>
[ { "answer_id": 95291, "author": "Chris", "author_id": 15578, "author_profile": "https://Stackoverflow.com/users/15578", "pm_score": 1, "selected": false, "text": "<p>If you can, try setting the height before you bind the control.</p>\n\n<p>If you can't do that, try making the control hidden before setting the height.</p>\n" }, { "answer_id": 95362, "author": "ImJustPondering", "author_id": 17940, "author_profile": "https://Stackoverflow.com/users/17940", "pm_score": 0, "selected": false, "text": "<p>This works in most cases but I'm not sure if this is what you are looking for...</p>\n\n<p>Try setting up the RowTemplate and use that to set the rows height. </p>\n\n<pre><code> // my test to specify a size for a datagridview row\n dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { Name = \"ColumnNameGoesHere\" });\n dataGridView1.RowTemplate.Height = 50;\n for (var x = 0; x &lt;= 10000; x++)\n {\n dataGridView1.Rows.Add(x.ToString());\n }\n</code></pre>\n\n<p>Here is also a nice page on Windows Forms Programming\nBest Practices for Scaling the Windows Forms DataGridView Control which you may find to be handy: <a href=\"http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx</a></p>\n" }, { "answer_id": 95437, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 2, "selected": false, "text": "<p>What's caused similar layout delays for myself was related to\nthe <strong>AutoSizeRowsMode</strong> and <strong>AutoSizeColumnsMode</strong></p>\n\n<pre><code>DataGridView1.AutoSizeRowsMode = None\n</code></pre>\n\n<p>will likely fix it.</p>\n\n<p>Also try <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadersheightsizemode.aspx\" rel=\"nofollow noreferrer\">ColumnHeadersHeightSizeMode</a></strong> to None and <strong><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.allowusertoresizerows.aspx\" rel=\"nofollow noreferrer\">AllowUserToResizeRows</a></strong> to False.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18046/" ]
I have noticed that setting row height in DataGridView control is slow. Is there a way to make it faster?
What's caused similar layout delays for myself was related to the **AutoSizeRowsMode** and **AutoSizeColumnsMode** ``` DataGridView1.AutoSizeRowsMode = None ``` will likely fix it. Also try **[ColumnHeadersHeightSizeMode](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadersheightsizemode.aspx)** to None and **[AllowUserToResizeRows](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.allowusertoresizerows.aspx)** to False.
95,089
<p>Trying the easy approach:</p> <blockquote> <p>sqlite2 mydb.db .dump | sqlite3 mydb-new.db</p> </blockquote> <p>I got this error:</p> <blockquote> <p>SQL error near line 84802: no such column: Ð</p> </blockquote> <p>In that line the script is this:</p> <blockquote> <p>INSERT INTO vehiculo VALUES(127548,'21K0065217',<strong>Ñ</strong>,'PA007808',65217,279,1989,3,468,'1998-07-30 00:00:00.000000','14/697/98-07',2,'',1);</p> </blockquote> <p>My guess is that <strong>the 'Ñ' without quotes is the problem</strong>.</p> <p>any idea?</p> <p>PD: I'm under Windows right now and I would like to use the command-line so it can be automatized (this process will be done on daily basis by a server).</p>
[ { "answer_id": 95292, "author": "levhita", "author_id": 7946, "author_profile": "https://Stackoverflow.com/users/7946", "pm_score": 0, "selected": false, "text": "<p>I tried to do it without windows intervention:</p>\n<blockquote>\n<p>*by calling sqlite2 on old.db, and send the dump directly to a file</p>\n<p>*and then call sqlite3 on new.db and loading the dump directly from the file.</p>\n</blockquote>\n<p>Just in case windows was messing with the characters on the command-line.</p>\n<p>Same Result.</p>\n" }, { "answer_id": 99043, "author": "levhita", "author_id": 7946, "author_profile": "https://Stackoverflow.com/users/7946", "pm_score": 1, "selected": false, "text": "<p>Well nobody answer... at the end I end up modifying my original script(the one that created the sqlite2 database in the first place) to create the database directly in sqlite3.</p>\n\n<p>I think that a big string processing script(big because mi databases are 800mb and 200mb each) can do the job, but generating the database directly was easier for me. </p>\n" }, { "answer_id": 548310, "author": "Kyle Brantley", "author_id": 66329, "author_profile": "https://Stackoverflow.com/users/66329", "pm_score": 2, "selected": false, "text": "<p>Simply open the v2 database with the sqlite3 binary CLI, and then save it. The database file will be transparently migrated to v3.</p>\n\n<pre><code>$ sqlite3 v2database.db\nsqlite&gt; .quit\n$\n</code></pre>\n\n<p>Note: you may need to insert/delete a row before quitting to force an update.</p>\n" }, { "answer_id": 1193101, "author": "ygrek", "author_id": 118799, "author_profile": "https://Stackoverflow.com/users/118799", "pm_score": 2, "selected": true, "text": "<blockquote>\n <p>Simply open the v2 database with the sqlite3 binary CLI, and then save it. The database file will be transparently migrated to v3.</p>\n</blockquote>\n\n<p>It doesn't work.</p>\n\n<pre><code>$sqlite3 db2\nSQLite version 3.6.16\nEnter \".help\" for instructions\nEnter SQL statements terminated with a \";\"\nsqlite&gt; .tables\nError: file is encrypted or is not a database\nsqlite&gt; .q\n</code></pre>\n\n<p>And the file is not changed (apparently sqlite3 couldn't read it). I think the original problem is a bug in sqlite2.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
Trying the easy approach: > > sqlite2 mydb.db .dump | sqlite3 mydb-new.db > > > I got this error: > > SQL error near line 84802: no such column: Ð > > > In that line the script is this: > > INSERT INTO vehiculo VALUES(127548,'21K0065217',**Ñ**,'PA007808',65217,279,1989,3,468,'1998-07-30 00:00:00.000000','14/697/98-07',2,'',1); > > > My guess is that **the 'Ñ' without quotes is the problem**. any idea? PD: I'm under Windows right now and I would like to use the command-line so it can be automatized (this process will be done on daily basis by a server).
> > Simply open the v2 database with the sqlite3 binary CLI, and then save it. The database file will be transparently migrated to v3. > > > It doesn't work. ``` $sqlite3 db2 SQLite version 3.6.16 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .tables Error: file is encrypted or is not a database sqlite> .q ``` And the file is not changed (apparently sqlite3 couldn't read it). I think the original problem is a bug in sqlite2.
95,105
<p>Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?</p>
[ { "answer_id": 95116, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<pre><code>string foo = Convert.ToString(myint,base);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/14kwkz77.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/14kwkz77.aspx</a></p>\n\n<p><strong>EDIT</strong>: My bad, this will throw an argument exception unless you pass in the specified bases (2, 8, 10, and 16)</p>\n\n<p>Your probably SOL if you want to use a different base (but why???).</p>\n" }, { "answer_id": 95331, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 3, "selected": false, "text": "<p>Probably to eliminate someone typing a 7 instead of an 8, since the uses for arbitrary bases are few (But not non-existent).</p>\n\n<p>Here is an example method that can do arbitrary base conversions. You can use it if you like, no restrictions.</p>\n\n<pre><code>string ConvertToBase(int value, int toBase)\n{\n if (toBase &lt; 2 || toBase &gt; 36) throw new ArgumentException(\"toBase\");\n if (value &lt; 0) throw new ArgumentException(\"value\");\n\n if (value == 0) return \"0\"; //0 would skip while loop\n\n string AlphaCodes = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n string retVal = \"\";\n\n while (value &gt; 0)\n {\n retVal = AlphaCodes[value % toBase] + retVal;\n value /= toBase;\n }\n\n return retVal;\n}\n</code></pre>\n\n<p>Untested, but you should be able to figure it out from here.</p>\n" }, { "answer_id": 95411, "author": "Brian", "author_id": 8959, "author_profile": "https://Stackoverflow.com/users/8959", "pm_score": 0, "selected": false, "text": "<pre><code>//untested -- public domain\n// if you do a lot of conversions, using StringBuilder will be \n// much, much more efficient with memory and time than using string\n// alone.\n\nstring toStringWithBase(int number, int base)\n { \n if(0==number) //handle corner case\n return \"0\";\n if(base &lt; 2)\n return \"ERROR: Base less than 2\";\n\n StringBuilder buffer = new StringBuilder(); \n\n bool negative = (number &lt; 0) ? true : false;\n if(negative)\n {\n number=-number;\n buffer.Append('-');\n }\n\n int digits=0;\n int factor=1;\n\n int runningTotal=number;\n while(number &gt; 0)\n {\n number = number/base;\n digits++;\n factor*=base;\n }\n factor = factor/base;\n\n while(factor &gt;= 1)\n {\n int remainder = (number/factor) % base;\n\n Char out = '0'+remainder;\n if(remainder &gt; 9)\n out = 'A' + remainder - 10;\n buffer.Append(out);\n factor = factor/base;\n }\n\n return buffer.ToString\n }\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9913/" ]
Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?
Probably to eliminate someone typing a 7 instead of an 8, since the uses for arbitrary bases are few (But not non-existent). Here is an example method that can do arbitrary base conversions. You can use it if you like, no restrictions. ``` string ConvertToBase(int value, int toBase) { if (toBase < 2 || toBase > 36) throw new ArgumentException("toBase"); if (value < 0) throw new ArgumentException("value"); if (value == 0) return "0"; //0 would skip while loop string AlphaCodes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string retVal = ""; while (value > 0) { retVal = AlphaCodes[value % toBase] + retVal; value /= toBase; } return retVal; } ``` Untested, but you should be able to figure it out from here.
95,112
<p>I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?</p> <p>Trivial example:</p> <pre><code>Call ExternalLongRunningProcess Call DoOtherStuff </code></pre> <p>How do I delay 'DoOtherStuff'?</p>
[ { "answer_id": 95128, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>Break your code up into 2 processes. Run the first, then run your \"long running process\", then run the second process.</p>\n" }, { "answer_id": 95135, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>Run your long-running process in the middle of your current process and wait for it to complete. </p>\n" }, { "answer_id": 95142, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 5, "selected": true, "text": "<p>VB.Net: I would use a <a href=\"http://msdn.microsoft.com/en-us/library/kzy257t0.aspx\" rel=\"noreferrer\">WaitOne</a> event handle.</p>\n\n<p>VB 6.0: I've seen a DoEvents Loop.</p>\n\n<pre><code>Do\n If isSomeCheckCondition() Then Exit Do\n DoEvents\nLoop\n</code></pre>\n\n<p>Finally, You could just sleep:</p>\n\n<pre><code>Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n\nSleep 10000\n</code></pre>\n" }, { "answer_id": 95161, "author": "Sean Gough", "author_id": 12842, "author_profile": "https://Stackoverflow.com/users/12842", "pm_score": 2, "selected": false, "text": "<p>How To Determine When a Shelled Process Has Terminated:</p>\n\n<ul>\n<li><p><a href=\"https://web.archive.org/web/20130706022352/http://support.microsoft.com/kb/96844\" rel=\"nofollow noreferrer\">Archive 1</a></p></li>\n<li><p><a href=\"https://jeffpar.github.io/kbarchive/kb/129/Q129796/\" rel=\"nofollow noreferrer\">Archive 2</a></p></li>\n</ul>\n\n<p>If you're calling an external process then you are, in effect, calling it asynchronously. Refer to the above MS Support document for how to wait until your external process is complete.</p>\n" }, { "answer_id": 102685, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 4, "selected": false, "text": "<p>While Nescio's <a href=\"https://stackoverflow.com/questions/95112/how-do-i-delay-code-execution-in-visual-basic-vb6#95142\">answer</a> (DoEvents) will work, it will cause your application to use 100% of one CPU. Sleep will make the UI unresponsive. What you need is a combination of the two, and the magic combination that seems to work best is:</p>\n\n<pre><code>Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n\nWhile IsStillWaitingForSomething()\n DoEvents\n DoEvents\n Sleep(55)\nWend\n</code></pre>\n\n<p>Why two DoEvents, and one sleep for 55 milliseconds? The sleep of 55 milliseconds is the smallest slice that VB6 can handle, and using two DoEvents is sometimes required in instances when super-responsiveness is needed (not by the API, but if you application is responding to outside events, SendMessage, Interupts, etc). </p>\n" }, { "answer_id": 19862277, "author": "twynham", "author_id": 2969458, "author_profile": "https://Stackoverflow.com/users/2969458", "pm_score": -1, "selected": false, "text": "<p><code>System.Threading.Thread.Sleep(500)</code></p>\n" }, { "answer_id": 44914645, "author": "RetroDev", "author_id": 8256081, "author_profile": "https://Stackoverflow.com/users/8256081", "pm_score": 0, "selected": false, "text": "<p>I wish you could just add the .net framework system.dll or whatever to your project references so that you could just do this:</p>\n\n<pre><code>Dim ALongTime As Integer = 2000\nSystem.Threading.Thread.Sleep(ALongTime)\n</code></pre>\n\n<p>...every time. I have VB6, and VB.net 2008 on my machine, and its always difficult for me to switch between the very different IDE's.</p>\n" }, { "answer_id": 67009079, "author": "RkdL", "author_id": 6277654, "author_profile": "https://Stackoverflow.com/users/6277654", "pm_score": 1, "selected": false, "text": "<p>If you want to write a <code>sleep</code> or <code>wait</code> without declaring <code>sleep</code> you can write up a loop that uses the systemtimer. This is what i use for testing/debugging when running the interpreter. This can be added while the interpreter is paused, if you'd need such a thing:</p>\n<pre><code>Dim TimeStart as currency\nDim TimeStop as currency\nDim TimePassed as currency\nDim TimeWait as currency\n\n'use this block where you need a pause\nTimeWait = 0.5 'seconds\nTimeStart = Timer()\nTimePassed = 0\nDo while TimePassed &lt; TimeWait 'seconds\n TimeStop = timer()\n TimePassed = TimeStop - TimeStart \n doevents\nloop\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait? Trivial example: ``` Call ExternalLongRunningProcess Call DoOtherStuff ``` How do I delay 'DoOtherStuff'?
VB.Net: I would use a [WaitOne](http://msdn.microsoft.com/en-us/library/kzy257t0.aspx) event handle. VB 6.0: I've seen a DoEvents Loop. ``` Do If isSomeCheckCondition() Then Exit Do DoEvents Loop ``` Finally, You could just sleep: ``` Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Sleep 10000 ```
95,134
<p>I'm using the following code to query a database from my jsp, but I'd like to know more about what's happening behind the scenes.</p> <p>These are my two primary questions.</p> <p>Does the tag access the ResultSet directly, or is the query result being stored in a datastructure in memory?</p> <p>When is the connection closed?</p> <pre><code>&lt;%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %&gt; &lt;sql:query var="query" dataSource="${ds}" sql="${listQuery}"&gt;&lt;/sql:query&gt; &lt;c:forEach var="row" items="${query.rows}" begin="0"&gt; ${row.data } ${row.more_data } &lt;/c:forEach&gt; </code></pre> <p>Note: I've always been against running queries in the jsp, but my result set is too large to store in memory between my action and my jsp. Using this tag library looks like the easiest solution.</p>
[ { "answer_id": 95813, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>The key thing here is this: javax.servlet.jsp.jstl.sql.Result</p>\n\n<p>That's what JSTL uses as the result of a SQL Query. If you look at the interface, it has this method: </p>\n\n<p>public java.util.SortedMap[] getRows()</p>\n\n<p>c:forEach \"knows\" about javax.servlet.jsp.jstl.sql.Result, since Result isn't anything else that forEach knows about (Collections, arrays, iterators, etc).</p>\n\n<p>So, all of that implies that the SQL query will suck the entire result set in to RAM.</p>\n\n<p>If you moved your query in to the JSP because you didn't want to load the entire result set in to a collection, then it doesn't look like the SQL tag will solve that problem for you.</p>\n\n<p>In truth you should look up Value List Pattern.</p>\n\n<p>But a \"simple\" solution to your problem would be to create a custom Iterator that \"knows\" about your ResultSet. This one wraps a result set and closes everything if it encounters an exception or if the result runs its course (like it would in a forEach). Kind of a special purpose thing.</p>\n\n<p><code>\npublic class ResultSetIterator implements Iterator {</p>\n\n<pre><code>Connection con;\nStatement s;\nResultSet rs;\nObject curObject;\nboolean closed;\n\npublic ResultSetIterator(Connection con, Statement s, ResultSet rs) {\n this.con = con;\n this.s = s;\n this.rs = rs;\n closed = false;\n}\n\npublic boolean hasNext() {\n advance();\n return curObject != null;\n}\n\npublic Object next() {\n advance();\n if (curObject == null) {\n throw new NoSuchElementException();\n } else {\n Object result = curObject;\n curObject = null;\n return result;\n }\n}\n\npublic void remove() {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n}\n\nprivate void advance() {\n if (closed) {\n curObject = null;\n return;\n }\n if (curObject == null) {\n try {\n if (rs.next()) {\n curObject = bindObject(rs);\n }\n } catch (SQLException ex) {\n shutDown();\n throw new RuntimeException(ex);\n }\n }\n if (curObject == null) {\n // Still no object, must be at the end of the result set\n shutDown();\n }\n}\n\nprotected Object bindObject(ResultSet rs) throws SQLException {\n // Bind result set row to an object, replace or override this method\n String name = rs.getString(1);\n return name;\n}\n\npublic void shutDown() {\n closed = true;\n try {\n rs.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n s.close();\n } catch (SQLException ex) {\n // Ignored\n }\n try {\n con.close();\n } catch (SQLException ex) {\n // Ignored\n }\n}\n</code></pre>\n\n<p>}\n</code></p>\n\n<p>This is, naturally, untested. But since JSTLs forEach can work with an Iterator, it's the simplest object you could really pass to it. This will prevent you from loading the entire result set in to memory. (As an interesting aside, it's notable how almost, but not quite, completely unlike Iterator a ResultSets behavior is.)</p>\n" }, { "answer_id": 95984, "author": "jt.", "author_id": 4362, "author_profile": "https://Stackoverflow.com/users/4362", "pm_score": 4, "selected": true, "text": "<p>Observations based on the source for org.apache.taglibs.standard.tag.common.sql.QueryTagSupport</p>\n\n<p>The taglib traverses through the ResultSet and puts all of the data in arrays, Maps, and Lists. So, everything is loaded into memory before you even start looping.</p>\n\n<p>The connection is opened when the query start tag is encountered (doStartTag method). The results are retrieved when the query end tag is encountered (doEndTag method). The connection is closed in the doFinally method.</p>\n\n<p>It a nutshell, it is absolutely awful.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
I'm using the following code to query a database from my jsp, but I'd like to know more about what's happening behind the scenes. These are my two primary questions. Does the tag access the ResultSet directly, or is the query result being stored in a datastructure in memory? When is the connection closed? ``` <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <sql:query var="query" dataSource="${ds}" sql="${listQuery}"></sql:query> <c:forEach var="row" items="${query.rows}" begin="0"> ${row.data } ${row.more_data } </c:forEach> ``` Note: I've always been against running queries in the jsp, but my result set is too large to store in memory between my action and my jsp. Using this tag library looks like the easiest solution.
Observations based on the source for org.apache.taglibs.standard.tag.common.sql.QueryTagSupport The taglib traverses through the ResultSet and puts all of the data in arrays, Maps, and Lists. So, everything is loaded into memory before you even start looping. The connection is opened when the query start tag is encountered (doStartTag method). The results are retrieved when the query end tag is encountered (doEndTag method). The connection is closed in the doFinally method. It a nutshell, it is absolutely awful.
95,181
<p>I have:</p> <pre><code>class MyClass extends MyClass2 implements Serializable { //... } </code></pre> <p>In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object?</p> <p>Correction: MyClass2 is, of course, not an interface but a class.</p>
[ { "answer_id": 95208, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 5, "selected": false, "text": "<p>MyClass2 is just an interface so techinicaly it has no properties, only methods. That being said if you have instance variables that are themselves not serializeable the only way I know of to get around it is to declare those fields transient.</p>\n\n<p>ex:</p>\n\n<pre><code>private transient Foo foo;\n</code></pre>\n\n<p>When you declare a field transient it will be ignored during the serialization and deserialization process. Keep in mind that when you deserialize an object with a transient field that field's value will always be it's default (usually null.)</p>\n\n<p>Note you can also override the readResolve() method of your class in order to initialize transient fields based on other system state.</p>\n" }, { "answer_id": 95224, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 3, "selected": false, "text": "<p>You will need to implement <code>writeObject()</code> and <code>readObject()</code> and do manual serialization/deserialization of those fields. See the javadoc page for <code>java.io.Serializable</code> for details. Josh Bloch's <em>Effective Java</em> also has some good chapters on implementing robust and secure serialization.</p>\n" }, { "answer_id": 95242, "author": "Hank", "author_id": 7610, "author_profile": "https://Stackoverflow.com/users/7610", "pm_score": 2, "selected": false, "text": "<p>You can start by looking into the <em>transient</em> keyword, which marks fields as not part of the persistent state of an object.</p>\n" }, { "answer_id": 95272, "author": "ykaganovich", "author_id": 10026, "author_profile": "https://Stackoverflow.com/users/10026", "pm_score": 4, "selected": false, "text": "<p>If you can modify MyClass2, the easiest way to address this is declare the property transient.</p>\n" }, { "answer_id": 95273, "author": "Boris Terzic", "author_id": 1996, "author_profile": "https://Stackoverflow.com/users/1996", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://x-stream.github.io\" rel=\"nofollow noreferrer\">XStream</a> is a great library for doing fast Java to XML serialization for any object no matter if it is Serializable or not. Even if the XML target format doesn't suit you, you can use the source code to learn how to do it.</p>\n" }, { "answer_id": 95323, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "<p>Depends why that member of MyClass2 isn't serializable.</p>\n\n<p>If there's some good reason why MyClass2 can't be represented in a serialized form, then chances are good the same reason applies to MyClass, since it's a subclass.</p>\n\n<p>It may be possible to write a custom serialized form for MyClass by implementing readObject and writeObject, in such a way that the state of the MyClass2 instance data in MyClass can be suitably recreated from the serialized data. This would be the way to go if MyClass2's API is fixed and you can't add Serializable.</p>\n\n<p>But first you should figure out why MyClass2 isn't serializable, and maybe change it.</p>\n" }, { "answer_id": 97630, "author": "Scott Bale", "author_id": 2495576, "author_profile": "https://Stackoverflow.com/users/2495576", "pm_score": 7, "selected": true, "text": "<p>As someone else noted, chapter 11 of Josh Bloch's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java</a> is an indispensible resource on Java Serialization.</p>\n\n<p>A couple points from that chapter pertinent to your question:</p>\n\n<ul>\n<li>assuming you want to serialize the state of the non-serializable field in MyClass2, that field must be accessible to MyClass, either directly or through getters and setters. MyClass will have to implement custom serialization by providing readObject and writeObject methods.</li>\n<li>the non-serializable field's Class must have an API to allow getting it's state (for writing to the object stream) and then instantiating a new instance with that state (when later reading from the object stream.)</li>\n<li>per Item 74 of Effective Java, MyClass2 <em>must</em> have a no-arg constructor accessible to MyClass, otherwise it is impossible for MyClass to extend MyClass2 and implement Serializable.</li>\n</ul>\n\n<p>I've written a quick example below illustrating this.</p>\n\n<pre><code>\nclass MyClass extends MyClass2 implements Serializable{\n\n public MyClass(int quantity) {\n setNonSerializableProperty(new NonSerializableClass(quantity));\n }\n\n private void writeObject(java.io.ObjectOutputStream out)\n throws IOException{\n // note, here we don't need out.defaultWriteObject(); because\n // MyClass has no other state to serialize\n out.writeInt(super.getNonSerializableProperty().getQuantity());\n }\n\n private void readObject(java.io.ObjectInputStream in)\n throws IOException {\n // note, here we don't need in.defaultReadObject();\n // because MyClass has no other state to deserialize\n super.setNonSerializableProperty(new NonSerializableClass(in.readInt()));\n }\n}\n\n/* this class must have no-arg constructor accessible to MyClass */\nclass MyClass2 {\n\n /* this property must be gettable/settable by MyClass. It cannot be final, therefore. */\n private NonSerializableClass nonSerializableProperty;\n\n public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) {\n this.nonSerializableProperty = nonSerializableProperty;\n }\n\n public NonSerializableClass getNonSerializableProperty() {\n return nonSerializableProperty;\n }\n}\n\nclass NonSerializableClass{\n\n private final int quantity;\n\n public NonSerializableClass(int quantity){\n this.quantity = quantity;\n }\n\n public int getQuantity() {\n return quantity;\n }\n}\n</code></pre>\n" }, { "answer_id": 100949, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>A useful approach for serialising instances of non-serializable classes (or at least subclasses of) is known a Serial Proxy. Essentially you implement writeReplace to return an instance of a completely different serializable class which implements readResolve to return a copy of the original object. I wrote an example of serialising java.awt.BasicStroke on <a href=\"http://groups.google.com/group/comp.lang.java.programmer/msg/820a7343ae7713a6\" rel=\"nofollow noreferrer\">Usenet</a></p>\n" }, { "answer_id": 115950, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "<p>Several possibilities poped out and i resume them here:</p>\n\n<ul>\n<li>Implement writeObject() and readObject() as <a href=\"https://stackoverflow.com/users/16399/sk\">sk</a> suggested</li>\n<li>declare the property transient and it won't be serialized as first stated by <a href=\"https://stackoverflow.com/users/7610/hank\">hank</a></li>\n<li>use XStream as stated by <a href=\"https://stackoverflow.com/users/1996/boris-terzic\">boris-terzic</a></li>\n<li>use a Serial Proxy as stated by <a href=\"https://stackoverflow.com/users/4725/tom-hawtin-tackline\">tom-hawtin-tackline</a></li>\n</ul>\n" }, { "answer_id": 13347836, "author": "Radim Burget", "author_id": 1168635, "author_profile": "https://Stackoverflow.com/users/1168635", "pm_score": 4, "selected": false, "text": "<p>If possible, the non-serialiable parts can be set as transient</p>\n\n<pre><code>private transient SomeClass myClz;\n</code></pre>\n\n<p>Otherwise you can use <a href=\"https://github.com/EsotericSoftware/kryo\" rel=\"nofollow\">Kryo</a>. Kryo is a fast and efficient object graph serialization framework for Java (e.g. JAVA serialization of java.awt.Color requires 170 bytes, Kryo only 4 bytes), which can serialize also non serializable objects. Kryo can also perform automatic deep and shallow copying/cloning. This is direct copying from object to object, not <code>object-&gt;bytes-&gt;object</code>.</p>\n\n<p>Here is an example how to use kryo</p>\n\n<pre><code>Kryo kryo = new Kryo();\n// #### Store to disk...\nOutput output = new Output(new FileOutputStream(\"file.bin\"));\nSomeClass someObject = ...\nkryo.writeObject(output, someObject);\noutput.close();\n// ### Restore from disk...\nInput input = new Input(new FileInputStream(\"file.bin\"));\nSomeClass someObject = kryo.readObject(input, SomeClass.class);\ninput.close();\n</code></pre>\n\n<p>Serialized objects can be also compressed by registering exact serializer:</p>\n\n<pre><code>kryo.register(SomeObject.class, new DeflateCompressor(new FieldSerializer(kryo, SomeObject.class)));\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
I have: ``` class MyClass extends MyClass2 implements Serializable { //... } ``` In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object? Correction: MyClass2 is, of course, not an interface but a class.
As someone else noted, chapter 11 of Josh Bloch's [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) is an indispensible resource on Java Serialization. A couple points from that chapter pertinent to your question: * assuming you want to serialize the state of the non-serializable field in MyClass2, that field must be accessible to MyClass, either directly or through getters and setters. MyClass will have to implement custom serialization by providing readObject and writeObject methods. * the non-serializable field's Class must have an API to allow getting it's state (for writing to the object stream) and then instantiating a new instance with that state (when later reading from the object stream.) * per Item 74 of Effective Java, MyClass2 *must* have a no-arg constructor accessible to MyClass, otherwise it is impossible for MyClass to extend MyClass2 and implement Serializable. I've written a quick example below illustrating this. ``` class MyClass extends MyClass2 implements Serializable{ public MyClass(int quantity) { setNonSerializableProperty(new NonSerializableClass(quantity)); } private void writeObject(java.io.ObjectOutputStream out) throws IOException{ // note, here we don't need out.defaultWriteObject(); because // MyClass has no other state to serialize out.writeInt(super.getNonSerializableProperty().getQuantity()); } private void readObject(java.io.ObjectInputStream in) throws IOException { // note, here we don't need in.defaultReadObject(); // because MyClass has no other state to deserialize super.setNonSerializableProperty(new NonSerializableClass(in.readInt())); } } /* this class must have no-arg constructor accessible to MyClass */ class MyClass2 { /* this property must be gettable/settable by MyClass. It cannot be final, therefore. */ private NonSerializableClass nonSerializableProperty; public void setNonSerializableProperty(NonSerializableClass nonSerializableProperty) { this.nonSerializableProperty = nonSerializableProperty; } public NonSerializableClass getNonSerializableProperty() { return nonSerializableProperty; } } class NonSerializableClass{ private final int quantity; public NonSerializableClass(int quantity){ this.quantity = quantity; } public int getQuantity() { return quantity; } } ```
95,183
<p>How do I create an index on the date part of DATETIME field?</p> <pre><code>mysql&gt; SHOW COLUMNS FROM transactionlist; +-------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+----------------+ | TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment | | WagerId | int(11) | YES | MUL | 0 | | | TranNum | int(11) | YES | MUL | 0 | | | TranDateTime | datetime | NO | | NULL | | | Amount | double | YES | | 0 | | | Action | smallint(6) | YES | | 0 | | | Uid | int(11) | YES | | 1 | | | AuthId | int(11) | YES | | 1 | | +-------------------+------------------+------+-----+---------+----------------+ 8 rows in set (0.00 sec) </code></pre> <p>TranDateTime is used to save the date and time of a transaction as it happens</p> <p>My Table has over 1,000,000 records in it and the statement </p> <pre><code>SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17' </code></pre> <p>takes a long time.</p> <p>EDIT: </p> <p>Have a look at this blog post on "<a href="http://billauer.co.il/blog/2009/03/mysql-datetime-epoch-unix-time/" rel="noreferrer">Why MySQL’s DATETIME can and should be avoided</a>"</p>
[ { "answer_id": 95248, "author": "nathan", "author_id": 16430, "author_profile": "https://Stackoverflow.com/users/16430", "pm_score": 0, "selected": false, "text": "<p>What does 'explain' say? (run EXPLAIN SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17')</p>\n\n<p>If it's not using your index because of the date() function, a range query should run fast:</p>\n\n<p>SELECT * FROM transactionlist where TranDateTime >= '2008-08-17' AND TranDateTime &lt; '2008-08-18'</p>\n" }, { "answer_id": 95252, "author": "Clinton Pierce", "author_id": 8173, "author_profile": "https://Stackoverflow.com/users/8173", "pm_score": 3, "selected": false, "text": "<p>I don't know about the specifics of mySql, but what's the harm in just indexing the date field in its entirety?</p>\n\n<p>Then just search:</p>\n\n<pre><code> select * from translist \n where TranDateTime &gt; '2008-08-16 23:59:59'\n and TranDateTime &lt; '2008-08-18 00:00:00'\n</code></pre>\n\n<p>If the indexes are b-trees or something else that's reasonable, these should get found quickly.</p>\n" }, { "answer_id": 95256, "author": "Michael Johnson", "author_id": 17688, "author_profile": "https://Stackoverflow.com/users/17688", "pm_score": 7, "selected": true, "text": "<p>If I remember correctly, that will run a whole table scan because you're passing the column through a function. MySQL will obediently run the function for each and every column, bypassing the index since the query optimizer can't really know the results of the function.</p>\n\n<p>What I would do is something like:</p>\n\n<pre><code>SELECT * FROM transactionlist \nWHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-17 23:59:59.999999';\n</code></pre>\n\n<p>That should give you everything that happened on 2008-08-17.</p>\n" }, { "answer_id": 95265, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 4, "selected": false, "text": "<p>I don't mean to sound cute, but a simple way would be to add a new column that only contained the date part and index on that.</p>\n" }, { "answer_id": 95290, "author": "Justsalt", "author_id": 13693, "author_profile": "https://Stackoverflow.com/users/13693", "pm_score": 0, "selected": false, "text": "<p>Rather than making an index based on a function (if that is even possible in mysql) make your where clause do a range comparison. Something like:</p>\n\n<blockquote>\n <p>Where TranDateTime > '2008-08-17\n 00:00:00' and TranDateTime &lt;\n '2008-08-17 11:59:59')</p>\n</blockquote>\n\n<p>This lets the DB use the index on TranDateTime (there is one, right?) to do the select.</p>\n" }, { "answer_id": 95295, "author": "Ray Jenkins", "author_id": 12425, "author_profile": "https://Stackoverflow.com/users/12425", "pm_score": 2, "selected": false, "text": "<p>Valeriy Kravchuk on a feature request for this very issue on the MySQL site said to use this method.</p>\n\n<p>\"In the meantime you can use character columns for storing DATETIME values as strings, with only first N characters being indexed. With some careful usage of triggers in MySQL 5 you can create a reasonably robust solution based on this idea.\"</p>\n\n<p>You could write a routine pretty easy to add this column, and then with triggers keep this column synced up. The index on this string column should be pretty quick.</p>\n" }, { "answer_id": 95759, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 3, "selected": false, "text": "<p>You can't create an index on just the date part. Is there a reason you have to?</p>\n\n<p>Even if you could create an index on just the date part, the optimiser would probably still not use it for the above query.</p>\n\n<p>I think you'll find that </p>\n\n<pre><code>SELECT * FROM transactionlist WHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-18'\n</code></pre>\n\n<p>Is efficient and does what you want.</p>\n" }, { "answer_id": 2424539, "author": "antonia007", "author_id": 291421, "author_profile": "https://Stackoverflow.com/users/291421", "pm_score": 1, "selected": false, "text": "<p>I don't know about the specifics of mySQL, but what's the harm in just indexing the date field in its entirety?</p>\n\n<p>If you use functional magic for * trees, hashes, ... is gone, because for obtaining values you must call the function. But, because you do not know the results ahead, you have to do a full scan of the table.</p>\n\n<p>There is nothing to add.</p>\n\n<p>Maybe you mean something like computed (calculated?) indexes... but to date, I have only seen this in Intersystems Caché. I don't think there's a case in relational databases (AFAIK).</p>\n\n<p>A good solution, in my opinion, is the following (updated clintp example):</p>\n\n<pre><code>SELECT * FROM translist \nWHERE TranDateTime &gt;= '2008-08-17 00:00:00.0000'\n AND TranDateTime &lt; '2008-08-18 00:00:00.0000'\n</code></pre>\n\n<p>Whether you use <code>00:00:00.0000</code> or <code>00:00</code> in my opinion makes no difference (I've generally used it in this format).</p>\n" }, { "answer_id": 6979909, "author": "Mari", "author_id": 883727, "author_profile": "https://Stackoverflow.com/users/883727", "pm_score": -1, "selected": false, "text": "<p>Create a new fields with just the dates <code>convert(datetime, left(date_field,10))</code> and then index that.</p>\n" }, { "answer_id": 9468308, "author": "Valentin Rusk", "author_id": 1116177, "author_profile": "https://Stackoverflow.com/users/1116177", "pm_score": 2, "selected": false, "text": "<p>The one and good solution that is pretty good working is to use timestamp as time, rather than datetime.\nIt is stored as INT and being indexed good enough.\nPersonally i encountered such problem on transactions table, that has about million records and slowed down hard, finally i pointed out that this caused by bad indexed field (datetime).\nNow it runs very quick.</p>\n" }, { "answer_id": 26417792, "author": "Dr. Tyrell", "author_id": 1102778, "author_profile": "https://Stackoverflow.com/users/1102778", "pm_score": 1, "selected": false, "text": "<p>datetime LIKE something% will not catch the index either.</p>\n\n<p>Use this: <strong>WHERE datetime_field >= curdate();</strong><br>\nThat will catch the index, <br>\nand cover <strong>today:00:00:00 up to today:23:59:59</strong><br>\nDone.</p>\n" }, { "answer_id": 44548610, "author": "Liran Brimer", "author_id": 1924716, "author_profile": "https://Stackoverflow.com/users/1924716", "pm_score": 4, "selected": false, "text": "<p>Another option (<a href=\"https://dev.mysql.com/doc/refman/5.7/en/alter-table-generated-columns.html\" rel=\"nofollow noreferrer\">relevant for version <em>5.7.3</em> and above</a>) is to create a generated/virtual column based on the datetime column, then index it.</p>\n<pre><code>CREATE TABLE `table` (\n`my_datetime` datetime NOT NULL,\n`my_date` varchar(12) GENERATED ALWAYS AS (DATE(`my_datetime`)) STORED,\nKEY `my_idx` (`my_date`)\n) ENGINE=InnoDB;\n</code></pre>\n" }, { "answer_id": 53773972, "author": "Walf", "author_id": 315024, "author_profile": "https://Stackoverflow.com/users/315024", "pm_score": 0, "selected": false, "text": "<p>If modifying the table is an option, or you're writing a new one, consider storing date and time in separate columns with respective types. You get performance by having a much smaller key space, and reduced storage (compared to a date-only column derived from a datetime). This also makes it feasible to use in compound keys, even before other columns.</p>\n\n<p>In OP's case:</p>\n\n<pre><code>+-------------------+------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------------+------------------+------+-----+---------+----------------+\n| TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment |\n| WagerId | int(11) | YES | MUL | 0 | |\n| TranNum | int(11) | YES | MUL | 0 | |\n| TranDate | date | NO | | NULL | |\n| TranTime | time | NO | | NULL | |\n| Amount | double | YES | | 0 | |\n| Action | smallint(6) | YES | | 0 | |\n| Uid | int(11) | YES | | 1 | |\n| AuthId | int(11) | YES | | 1 | |\n+-------------------+------------------+------+-----+---------+----------------+\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ]
How do I create an index on the date part of DATETIME field? ``` mysql> SHOW COLUMNS FROM transactionlist; +-------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+------------------+------+-----+---------+----------------+ | TransactionNumber | int(10) unsigned | NO | PRI | NULL | auto_increment | | WagerId | int(11) | YES | MUL | 0 | | | TranNum | int(11) | YES | MUL | 0 | | | TranDateTime | datetime | NO | | NULL | | | Amount | double | YES | | 0 | | | Action | smallint(6) | YES | | 0 | | | Uid | int(11) | YES | | 1 | | | AuthId | int(11) | YES | | 1 | | +-------------------+------------------+------+-----+---------+----------------+ 8 rows in set (0.00 sec) ``` TranDateTime is used to save the date and time of a transaction as it happens My Table has over 1,000,000 records in it and the statement ``` SELECT * FROM transactionlist where date(TranDateTime) = '2008-08-17' ``` takes a long time. EDIT: Have a look at this blog post on "[Why MySQL’s DATETIME can and should be avoided](http://billauer.co.il/blog/2009/03/mysql-datetime-epoch-unix-time/)"
If I remember correctly, that will run a whole table scan because you're passing the column through a function. MySQL will obediently run the function for each and every column, bypassing the index since the query optimizer can't really know the results of the function. What I would do is something like: ``` SELECT * FROM transactionlist WHERE TranDateTime BETWEEN '2008-08-17' AND '2008-08-17 23:59:59.999999'; ``` That should give you everything that happened on 2008-08-17.
95,192
<p>Our CruiseControl system checks out from starteam. I've noticed that it is sometimes not checking out new versions of files, only added files.</p> <p>Does anyone know why this is?</p>
[ { "answer_id": 95353, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 1, "selected": false, "text": "<p>I cannot say <em>why</em> this happens, but for what it's worth, we avoid the problem entirely by having StarTeam delete all of the local files before checking-out. We get <em>all</em> of the files that way. We use the following StarTeam arguments in our NAnt script:</p>\n\n<pre><code>delete-local -q -p &amp;quot;${starteam_project_root}&amp;quot; -is -filter &amp;quot;N&amp;quot; -cfgd &amp;quot;${exec_time}&amp;quot;\n</code></pre>\n\n<p>Which translates to something like:</p>\n\n<pre><code>delete-local -q -p \"user:passwd@SERVER:49201/ProjectName/\" -is -filter \"N\"-cfgd \"09/18/2008 14:33:22\"\n</code></pre>\n" }, { "answer_id": 95452, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>This is a CI build, so I want to see the diffs on each build, cleaning out the build gives me a fresh build each time, and I don't know what is new.</p>\n\n<p>So its a known issue?</p>\n" }, { "answer_id": 243753, "author": "Doug Porter", "author_id": 4311, "author_profile": "https://Stackoverflow.com/users/4311", "pm_score": 0, "selected": false, "text": "<p>If you are using the StarTeam Ant task, check to see what you have set for the <strong>includes</strong> and <strong>excludes</strong> parameters to make sure you are not unintentionally restricting what gets checked out. </p>\n\n<p>Also the <strong>forced</strong> and <strong>recursive</strong> parameters may be something to look at as well.</p>\n\n<p>You can see a full explanation of the checkout task here:</p>\n\n<p><a href=\"http://nantcontrib.sourceforge.net/help/tasks/stcheckout.html\" rel=\"nofollow noreferrer\">http://nantcontrib.sourceforge.net/help/tasks/stcheckout.html</a></p>\n" }, { "answer_id": 10252893, "author": "Eddddddddddd1", "author_id": 1325181, "author_profile": "https://Stackoverflow.com/users/1325181", "pm_score": 1, "selected": false, "text": "<p>I recently ran into this same issue. The reason this happens is the same reason you don't see out of date files in the GUI or you have a file with unknown status, the status is not updated. So if you update the status on your files it will then be able to pick up those files that have changed from the source control. We accomplish this by adding a step to our configuration file.</p>\n\n<pre><code> &lt;prebuild&gt;\n &lt;exec&gt;\n &lt;executable&gt;C:\\Program Files\\Borland\\StarTeam Cross-Platform Client 2006 R2\\stcmd.exe&lt;/executable &gt;\n &lt;buildArgs&gt;update-status -nologo -is -q -p \"username:[email protected]:49201/Code Project/Code Path\" -fp \"C:\\projects\\My Code Directory\"&lt;/buildArgs&gt;\n &lt;buildTimeoutSeconds&gt;0&lt;/buildTimeoutSeconds&gt;\n &lt;/exec&gt;\n &lt;/prebuild&gt;\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Our CruiseControl system checks out from starteam. I've noticed that it is sometimes not checking out new versions of files, only added files. Does anyone know why this is?
I cannot say *why* this happens, but for what it's worth, we avoid the problem entirely by having StarTeam delete all of the local files before checking-out. We get *all* of the files that way. We use the following StarTeam arguments in our NAnt script: ``` delete-local -q -p &quot;${starteam_project_root}&quot; -is -filter &quot;N&quot; -cfgd &quot;${exec_time}&quot; ``` Which translates to something like: ``` delete-local -q -p "user:passwd@SERVER:49201/ProjectName/" -is -filter "N"-cfgd "09/18/2008 14:33:22" ```
95,213
<p>Simple example: I want to have some items on a page (like divs or table rows), and I want to let the user click on them to select them. That seems easy enough in jQuery. To save which items a user clicks on with no server-side post backs, I was thinking a cookie would be a simple way to get this done.</p> <ol> <li>Is this assumption that a cookie is OK in this case, correct?</li> <li>If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?</li> </ol>
[ { "answer_id": 95241, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 3, "selected": false, "text": "<p>Take a look at the <a href=\"http://plugins.jquery.com/cookie/\" rel=\"nofollow noreferrer\">Cookie Plugin</a> for jQuery.</p>\n" }, { "answer_id": 95348, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 3, "selected": false, "text": "<p>To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.</p>\n\n<p>It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult. </p>\n\n<p>You may want to consider posting your second question in another topic.</p>\n" }, { "answer_id": 95351, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 4, "selected": false, "text": "<p>You'll need the cookie plugin, which provides several additional signatures to the cookie function.</p>\n\n<p><code>$.cookie('cookie_name', 'cookie_value')</code> stores a transient cookie (only exists within this session's scope, while <code>$.cookie('cookie_name', 'cookie_value', 'cookie_expiration\")</code> creates a cookie that will last across sessions - see <a href=\"http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/\" rel=\"noreferrer\">http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/</a> for more information on the JQuery cookie plugin.</p>\n\n<p>If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:</p>\n\n<pre><code>document.cookie = \"name=value; expires=date; domain=domain; path=path; secure\"\n</code></pre>\n" }, { "answer_id": 292755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>A new jQuery plugin for cookie retrieval and manipulation with binding for forms, etc: <a href=\"http://plugins.jquery.com/project/cookies\" rel=\"noreferrer\">http://plugins.jquery.com/project/cookies</a></p>\n" }, { "answer_id": 2210411, "author": "adam", "author_id": 116718, "author_profile": "https://Stackoverflow.com/users/116718", "pm_score": 6, "selected": false, "text": "<p>The default JavaScript \"API\" for setting a cookie is as easy as:</p>\n\n<pre><code>document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'\n</code></pre>\n\n<p>Use the jQuery cookie plugin like:</p>\n\n<pre><code>$.cookie('mycookie', 'valueOfCookie')\n</code></pre>\n" }, { "answer_id": 3764876, "author": "jQuery Lover", "author_id": 49200, "author_profile": "https://Stackoverflow.com/users/49200", "pm_score": 2, "selected": false, "text": "<p>It seems the jQuery cookie plugin is not available for download. However, you can download the same jQuery cookie plugin with some improvements described in <em><a href=\"http://jquery-howto.blogspot.com/2010/09/jquery-cookies-getsetdelete-plugin.html\" rel=\"nofollow noreferrer\">jQuery &amp; Cookies (get/set/delete &amp; a plugin)</a></em>.</p>\n" }, { "answer_id": 4702786, "author": "Marshall Æon", "author_id": 553791, "author_profile": "https://Stackoverflow.com/users/553791", "pm_score": 2, "selected": false, "text": "<p>You can browse all the jQuery plugins tagged with \"cookie\" here:</p>\n\n<p><a href=\"http://plugins.jquery.com/plugin-tags/cookies\" rel=\"nofollow\">http://plugins.jquery.com/plugin-tags/cookies</a></p>\n\n<p>Plenty of options there.</p>\n\n<p>Check out the one called jQuery Storage, which takes advantage of HTML5's localStorage. If localStorage isn't available, it defaults to cookies. However, it doesn't allow you to set expiration.</p>\n" }, { "answer_id": 24208846, "author": "Porta Shqipe", "author_id": 2542393, "author_profile": "https://Stackoverflow.com/users/2542393", "pm_score": 2, "selected": false, "text": "<p>I have managed to write a script allowing the user to choose his/her language, using the cookie script from <a href=\"https://github.com/carhartl/jquery-cookie\" rel=\"nofollow\">Klaus Hartl</a>. It took me a few hours work, and I hope I can help others.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
Simple example: I want to have some items on a page (like divs or table rows), and I want to let the user click on them to select them. That seems easy enough in jQuery. To save which items a user clicks on with no server-side post backs, I was thinking a cookie would be a simple way to get this done. 1. Is this assumption that a cookie is OK in this case, correct? 2. If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?
The default JavaScript "API" for setting a cookie is as easy as: ``` document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/' ``` Use the jQuery cookie plugin like: ``` $.cookie('mycookie', 'valueOfCookie') ```
95,218
<p>Here's something I haven't been able to fix, and I've looked <strong>everywhere</strong>. Perhaps someone here will know!</p> <p>I have a table called dandb_raw, with three columns in particular: dunsId (PK), name, and searchName. I also have a trigger that acts on this table:</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dandb_raw_searchNames] ON [dandb_raw] FOR INSERT, UPDATE AS SET NOCOUNT ON select dunsId, name into #magic from inserted UPDATE dandb SET dandb.searchName = company_generateSearchName(dandb.name) FROM (select dunsId, name from #magic) i INNER JOIN dandb_raw dandb on i.dunsId = dandb.dunsId --Add new search matches SELECT c.companyId, dandb.dunsId INTO #newMatches FROM dandb_raw dandb INNER JOIN (select dunsId, name from #magic) a on a.dunsId = dandb.dunsId INNER JOIN companies c ON dandb.searchName = c.searchBrand --avoid url matches that are potentially wrong AND (lower(dandb.url) = lower(c.url) OR dandb.url = '' OR c.url = '' OR c.url is null) INSERT INTO #newMatches (companyId, dunsId) SELECT c.companyId, max(dandb.dunsId) dunsId FROM dandb_raw dandb INNER JOIN ( select case when charindex('/',url) &lt;&gt; 0 then left(url, charindex('/',url)-1) else url end urlMatch, * from companies ) c ON dandb.url = c.urlMatch where subsidiaryOf = 1 and isReported = 1 and dandb.url &lt;&gt; '' and c.companyId not in (select companyId from #newMatches) group by companyId having count(dandb.dunsId) = 1 UPDATE cd SET cd.dunsId = nm.dunsId FROM companies_dandb cd INNER JOIN #newMatches nm ON cd.companyId = nm.companyId GO </code></pre> <p>The trigger causes inserts to fail:</p> <pre><code>insert into [dandb_raw](dunsId, name) select 3442355, 'harper' union all select 34425355, 'har 466per' update [dandb_raw] set name ='grap6767e' </code></pre> <p>With this error:</p> <pre><code>Msg 213, Level 16, State 1, Procedure companies_contactInfo_updateTerritories, Line 20 Insert Error: Column name or number of supplied values does not match table definition. </code></pre> <p>The most curious thing about this is that each of the individual statements in the trigger works on its own. It's almost as though inserted is a one-off table that infects temporary tables if you try to move inserted into one of them.</p> <p>So what causes the trigger to fail? How can it be stopped?</p>
[ { "answer_id": 95610, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 1, "selected": false, "text": "<p>What is companies_contactInfo_updateTerritories? The actual reference mentions procedure \"companies_contactInfo_updateTerritories\" but I do not see it in the code given. Also I do not see where it is being called. Unless it is from your application that is calling the SQL and hence irrelevant....</p>\n\n<p>If you tested everything and it worked but now it doesn't work, then something must be different. One thing to consider is security. I noticed that you just call the table [dandb_raw] and not [dbo].[dandb_raw]. So if the user had a table of the same name [user].[dandb_raw], that table would be used to check the definitions instead of your table. Also, the trigger creates temp tables. But if some of the temp tables already existed for whatever reason but with different definitions, this may also be a problem.</p>\n" }, { "answer_id": 95768, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>I don't see any obvious problem in the code.</p>\n\n<p>\"SELECT .. INTO\" is weak kung-fu. Try explicitly creating the temp table definition:</p>\n\n<pre><code>CREATE TABLE #newMatches\n(\n CompanyID int PRIMARY KEY,\n DunsID int\n)\n</code></pre>\n\n<p>When you're done with #newMatches, you should get rid of it so you can create it again later (temp tables are connection scoped!!)</p>\n\n<pre><code>DROP TABLE #newMatches\n</code></pre>\n" }, { "answer_id": 95809, "author": "Chris", "author_id": 40352, "author_profile": "https://Stackoverflow.com/users/40352", "pm_score": 3, "selected": true, "text": "<p>I think David and Cervo combined have hit on the problem here.</p>\n\n<p>I'm pretty sure part of what was happening was that we were using #newMatches in multiple triggers. When one trigger changed some rows, it would fire another trigger, which would attempt to use the connection scoped #newMatches.</p>\n\n<p>As a result, it would try to, find the table already existed with a different schema, die, and produce the message above. One piece of evidence that would be in favor: Does inserted use a stack style scope (nested triggers have their own inserteds?)</p>\n\n<p>Still speculating though - at least things seem to be working now!</p>\n" }, { "answer_id": 105930, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>Trigger code (because it must run everytime the data is updated) must be efficient and must account for multiple record inserts. You've succeeded at the second but not the first. You have made this overly complicated and have used things such as Not in statements that are usually less efficeint than using a left join. Temp tables are unnecessary here (I would never consider using one in a trigger) as they add to the inefficiency of the trigger. There is not reason not to write \nFrom inserted i \ninstead of \n FROM (select dunsId, name from #magic) i</p>\n\n<p>The first is likely to be faster and is simpler to read and maintain.</p>\n\n<p>Here:\nJOIN ( select case when charindex('/',url) &lt;> 0 then left(url, charindex('/',url)-1) else url end urlMatch, * from companies ) c ON dandb.url = c.urlMatch</p>\n\n<p>You are selecting all the fields in the table even though you only appear to be using one. Why? You are also running that case stament on all the records in company even though after you join you may not need all of them.</p>\n\n<p>Also in general I would avoid using select * but especially in a trigger. Suppose you are inserting into another table and you used select * from some table joined to inserted or deleted. Adding a column to that table would cause the trigger to fail and stop all data changes until it was fixed.</p>\n\n<p>You've also used a function in the trigger. This coudl be painfully slow if you havea large insert. I suggest you test this by updating a large group of records and see what happens. All data changes do not happen just from the user interface, one record at a time. There will be times when one field is updated from an ad-hoc query in management studio (when all prices need to be adjusted by 10% as the simplest example that comes to mind.) Your trigger needs to be able to handle those types if updates as well as the ones you are expecting. I would run a test case updating 100000 rows and see how much this trigger slows things down.</p>\n\n<p>Maybe this isn't really answering your problem, but the trigger just is so far from optimal, I had to say it.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40352/" ]
Here's something I haven't been able to fix, and I've looked **everywhere**. Perhaps someone here will know! I have a table called dandb\_raw, with three columns in particular: dunsId (PK), name, and searchName. I also have a trigger that acts on this table: ``` SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER TRIGGER [dandb_raw_searchNames] ON [dandb_raw] FOR INSERT, UPDATE AS SET NOCOUNT ON select dunsId, name into #magic from inserted UPDATE dandb SET dandb.searchName = company_generateSearchName(dandb.name) FROM (select dunsId, name from #magic) i INNER JOIN dandb_raw dandb on i.dunsId = dandb.dunsId --Add new search matches SELECT c.companyId, dandb.dunsId INTO #newMatches FROM dandb_raw dandb INNER JOIN (select dunsId, name from #magic) a on a.dunsId = dandb.dunsId INNER JOIN companies c ON dandb.searchName = c.searchBrand --avoid url matches that are potentially wrong AND (lower(dandb.url) = lower(c.url) OR dandb.url = '' OR c.url = '' OR c.url is null) INSERT INTO #newMatches (companyId, dunsId) SELECT c.companyId, max(dandb.dunsId) dunsId FROM dandb_raw dandb INNER JOIN ( select case when charindex('/',url) <> 0 then left(url, charindex('/',url)-1) else url end urlMatch, * from companies ) c ON dandb.url = c.urlMatch where subsidiaryOf = 1 and isReported = 1 and dandb.url <> '' and c.companyId not in (select companyId from #newMatches) group by companyId having count(dandb.dunsId) = 1 UPDATE cd SET cd.dunsId = nm.dunsId FROM companies_dandb cd INNER JOIN #newMatches nm ON cd.companyId = nm.companyId GO ``` The trigger causes inserts to fail: ``` insert into [dandb_raw](dunsId, name) select 3442355, 'harper' union all select 34425355, 'har 466per' update [dandb_raw] set name ='grap6767e' ``` With this error: ``` Msg 213, Level 16, State 1, Procedure companies_contactInfo_updateTerritories, Line 20 Insert Error: Column name or number of supplied values does not match table definition. ``` The most curious thing about this is that each of the individual statements in the trigger works on its own. It's almost as though inserted is a one-off table that infects temporary tables if you try to move inserted into one of them. So what causes the trigger to fail? How can it be stopped?
I think David and Cervo combined have hit on the problem here. I'm pretty sure part of what was happening was that we were using #newMatches in multiple triggers. When one trigger changed some rows, it would fire another trigger, which would attempt to use the connection scoped #newMatches. As a result, it would try to, find the table already existed with a different schema, die, and produce the message above. One piece of evidence that would be in favor: Does inserted use a stack style scope (nested triggers have their own inserteds?) Still speculating though - at least things seem to be working now!
95,222
<p>I found this link <a href="http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/" rel="noreferrer">http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/</a>, but there isn't a lot of description around it, aside that it's "simple".</p> <p>Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode.</p> <p>If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated.</p> <p>EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.</p>
[ { "answer_id": 95494, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 5, "selected": true, "text": "<p>Add the following code to your ~/.emacs file.</p>\n\n<pre><code>(autoload 'glsl-mode \"glsl-mode\" nil t)\n(add-to-list 'auto-mode-alist '(\"\\\\.vert\\\\'\" . glsl-mode))\n(add-to-list 'auto-mode-alist '(\"\\\\.frag\\\\'\" . glsl-mode))\n</code></pre>\n\n<p>Put the file <a href=\"http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el\" rel=\"noreferrer\">http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el</a> somewhere on your emacs path. You can eval (print load-path) in your <em>scratch</em> buffer to get the list of possible locations. If you don't have write access to any of those, you can append another location to load-paths by adding </p>\n\n<pre><code>(setq load-path (cons \"~/.emacs.d\" load-path))\n</code></pre>\n\n<p>to your ~/.emacs file.</p>\n" }, { "answer_id": 9059945, "author": "Buzz", "author_id": 200788, "author_profile": "https://Stackoverflow.com/users/200788", "pm_score": 2, "selected": false, "text": "<p>Based on GLSL mode, I wrote a similar one for HLSL which is used in Direct3D effect.\nHere it is. <a href=\"http://sourceforge.net/projects/hlslmode/files/hlsl-mode.el\" rel=\"nofollow\">http://sourceforge.net/projects/hlslmode/files/hlsl-mode.el</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13894/" ]
I found this link <http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/>, but there isn't a lot of description around it, aside that it's "simple". Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode. If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated. EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.
Add the following code to your ~/.emacs file. ``` (autoload 'glsl-mode "glsl-mode" nil t) (add-to-list 'auto-mode-alist '("\\.vert\\'" . glsl-mode)) (add-to-list 'auto-mode-alist '("\\.frag\\'" . glsl-mode)) ``` Put the file <http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el> somewhere on your emacs path. You can eval (print load-path) in your *scratch* buffer to get the list of possible locations. If you don't have write access to any of those, you can append another location to load-paths by adding ``` (setq load-path (cons "~/.emacs.d" load-path)) ``` to your ~/.emacs file.
95,257
<p>I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0</p>
[ { "answer_id": 95271, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": -1, "selected": false, "text": "<p>Just: WHERE col > start-date AND col &lt; end-date</p>\n" }, { "answer_id": 95300, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>I think that you might as well just do it in a while loop. I know it's ugly, but it's easy and it works.</p>\n" }, { "answer_id": 95322, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 0, "selected": false, "text": "<p>I was actually doing something similar a little while back, but I couldn't come up with a way that didn't use a loop.</p>\n\n<p>The best I got was a temp table, and then selecting the dates I wanted to join on into that.</p>\n\n<p>The blog bduke linked to is cute, although I think the temp table solution is perhaps a cleaner solution.</p>\n" }, { "answer_id": 95517, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 0, "selected": false, "text": "<p>I've found another table that stores every date (it's visitors to the website), so how about this...</p>\n\n<pre><code>Declare @FromDate datetime, \n @ToDate datetime \nDeclare @tmpDates table \n (StatsDate datetime)\nSet @FromDate = DateAdd(day,-30,GetDate())\nSet @ToDate = GetDate()\n\nInsert Into @tmpDates (StatsDate)\nSelect \n distinct CAST(FLOOR(CAST(visitDate AS DECIMAL(12, 5))) AS DATETIME)\nFROM tbl_visitorstats \nWhere visitDate between @FromDate And @ToDate \nOrder By CAST(FLOOR(CAST(visitDate AS DECIMAL(12, 5))) AS DATETIME) \n\n\nSelect * FROM @tmpDates\n</code></pre>\n\n<p>It does rely on the other table having an entry for every date I want, but it's 98% likely there'll be data for every day.</p>\n" }, { "answer_id": 95728, "author": "BigJump", "author_id": 8542, "author_profile": "https://Stackoverflow.com/users/8542", "pm_score": 5, "selected": true, "text": "<p>Strictly speaking this doesn't exactly answer your question, but its pretty neat.</p>\n\n<p>Assuming you can live with specifying the number of days after the start date, then using a Common Table Expression gives you:</p>\n\n<pre><code>WITH numbers ( n ) AS (\n SELECT 1 UNION ALL\n SELECT 1 + n FROM numbers WHERE n &lt; 500 )\n SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers\n OPTION ( MAXRECURSION 500 )\n</code></pre>\n" }, { "answer_id": 95963, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": -1, "selected": false, "text": "<p>Just write the loop. Someone has to write a loop for this, be it you - or SQL Server.</p>\n\n<pre><code>DECLARE @Dates TABLE\n(\n TheDate datetime PRIMARY KEY\n)\nDECLARE @StartDate datetime, @EndDate datetime\nSELECT @StartDate = '2000-01-01', @EndDate = '2010-01-01'\n\n\nDECLARE @LoopVar int, @LoopEnd int \nSELECT @LoopEnd = DateDiff(dd, @StartDate, @EndDate), @LoopVar = 0\n\n\nWHILE @LoopVar &lt;= @LoopEnd\nBEGIN\n INSERT INTO @Dates (TheDate)\n SELECT DateAdd(dd,@LoopVar,@StartDate)\n\n SET @LoopVar = @LoopVar + 1\nEND\n\n\nSELECT *\nFROM @Dates\n</code></pre>\n" }, { "answer_id": 96053, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 1, "selected": false, "text": "<p>I would create a Calendar table that just contained every date from a suitable start date until a suitable end date. This wouldn't take up much space in your database and would make these types of query child's play.</p>\n\n<pre><code>select ...\nfrom Calendar\n left outer join\n ...\nwhere Calendar.Date &gt;= @x\nand Calendar.Date &lt;= @y\n</code></pre>\n" }, { "answer_id": 36001142, "author": "Adrian Russell", "author_id": 395440, "author_profile": "https://Stackoverflow.com/users/395440", "pm_score": 0, "selected": false, "text": "<p>A slight twist on the answer given as <a href=\"https://stackoverflow.com/a/95728/395440\">https://stackoverflow.com/a/95728/395440</a>. Allows days to be specified and also calculates range up to the current date.</p>\n\n<pre><code>DECLARE @startDate datetime\nSET @startDate = '2015/5/29';\n\nWITH number ( n ) AS (\n SELECT 1 UNION ALL\n SELECT 1 + n FROM dates WHERE n &lt; DATEDIFF(Day, @startDate, GETDATE()) )\n SELECT DATEADD(day,n-1,@startDate) FROM number where\n datename(dw, DATEADD(day,n-1,@startDate)) in ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')\n OPTION ( MAXRECURSION 500 )\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0
Strictly speaking this doesn't exactly answer your question, but its pretty neat. Assuming you can live with specifying the number of days after the start date, then using a Common Table Expression gives you: ``` WITH numbers ( n ) AS ( SELECT 1 UNION ALL SELECT 1 + n FROM numbers WHERE n < 500 ) SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers OPTION ( MAXRECURSION 500 ) ```
95,277
<p>I'd like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset back and do some basic calculations with them. I'm coming up short in figuring out how to get the parameters of the query to be populated by the form elements. If I have to use VBA, that's fine.</p>
[ { "answer_id": 96047, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "<p>Here is a snippet of code. It updates a table using the parameter txtHospital:</p>\n\n<pre><code>Set db = CurrentDb\n\nSet qdf = db.QueryDefs(\"AddHospital\")\nqdf.Parameters!txtHospital = Trim(Me.HospName)\nqdf.ReturnsRecords = False\n\nqdf.Execute dbFailOnError\n\nintResult = qdf.RecordsAffected\n</code></pre>\n\n<p>Here is a sample of the SQL:</p>\n\n<pre><code>PARAMETERS txtHospital Text(255); \n\nINSERT INTO tblHospitals ( \n[Hospital] )\n\nVALUES ( \n[txtHospital] )\n</code></pre>\n" }, { "answer_id": 96128, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "<p>Let's take an example. the parameterized query looks like that:</p>\n\n<pre><code>Select Tbl_Country.* From Tbl_Country WHERE id_Country = _\n [?enter ISO code of the country]\n</code></pre>\n\n<p>and you'd like to be able to get this value (the [?enter ... country] one) from a form, where you have your controls and some data in it. Well... this might be possible, but it requires some code normalisation. </p>\n\n<p>One solution would be to have your form controls named after a certain logic, such as <code>fid_Country</code> for the control that will hold an <code>id_Country</code> value. Your can then have your query as a string:</p>\n\n<pre><code>qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = [fid_country]\"\n</code></pre>\n\n<p>Once you have entered all requested data in your form, press your \"query\" button. The logic will browse all controls and check if they are in the query, eventually replacing the parameter by the control's value:</p>\n\n<pre><code>Dim ctl as Control\nFor each ctl in Me.controls\n If instr(qr,\"[\" &amp; ctl.name &amp; \"]\") &gt; 0 Then\n qr = replace(qr,\"[\" &amp; ctl.name &amp; \"]\",ctl.value)\n End if\nNext i\n</code></pre>\n\n<p>Doing so, you will have a fully updated query, where parameters have been replaced by real data. Depending on the type of fid_country (string, GUID, date, etc), you could have to add some extra double quotes or not, to get a final query such as:</p>\n\n<pre><code>qr = \"Select Tbl_Country.* From Tbl_Country WHERE id_Country = \"\"GB\"\"\"\n</code></pre>\n\n<p>Which is a fully Access compatible query you can use to open a recordset:</p>\n\n<pre><code>Set rsQuery = currentDb.openRecordset(qr)\n</code></pre>\n\n<p>I think you are done here.</p>\n\n<p>This subject is critical when your objective is to developp Access applications. You have to offer users a standard way to query data from their GUI, not only to launch queries, but also to filter continuous forms (just in the way Excel do it with its \"autofilter\" option) and manage reports parameters. Good luck!</p>\n" }, { "answer_id": 96134, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "<p>There are three traditional ways to get around this issue:</p>\n\n<ol>\n<li>Name the parameter something cleaver so that the user will be prompted to enter the value when the query is run. </li>\n<li>Reference field on a form (possibly hidden)</li>\n<li>Build the query on the fly, and don't use parameters.</li>\n</ol>\n\n<p>I think it's just wrong to me that you would ave to inject something like <code>[?enter ISO code of the country]</code> or references to fields on your form like : <code>[Forms]![MyForm]![LastName]</code>.</p>\n\n<p>It means we can't re-use the same query in more than one place, with different fields supplying the data or have to rely on the user not to foul up the data entry when the query is run. As I recall, it may be hard to use the same value more than once with the user entered parameter.</p>\n\n<p>Typically I've chosen the last option an built the query on the fly, and updated the query object as needed. However, that's rife for an SQL injection attack (accidental or on purpose knowing my users), and it's just icky.</p>\n\n<p>So I did some digging and I found the following here (<a href=\"http://forums.devarticles.com/microsoft-access-development-49/pass-parameters-from-vba-to-query-62367.html\" rel=\"nofollow noreferrer\">http://forums.devarticles.com/microsoft-access-development-49/pass-parameters-from-vba-to-query-62367.html</a>):</p>\n\n<pre><code>'Ed. Start - for completion of the example\ndim qryStartDate as date\ndim qryEndDate as date\nqryStartDate = #2001-01-01# \nqryEndDate = #2010-01-01# \n'Ed. End\n\n'QUOTEING \"stallyon\": To pass parameters to a query in VBA \n' is really quite simple:\n\n'First we'll set some variables:\nDim qdf As Querydef\nDim rst As Recordset\n\n'then we'll open up the query:\nSet qdf = CurrentDB.QueryDefs(qryname)\n\n'Now we'll assign values to the query using the parameters option:\nqdf.Parameters(0) = qryStartDate\nqdf.Parameters(1) = qryEndDate\n\n'Now we'll convert the querydef to a recordset and run it\nSet rst = qdf.OpenRecordset\n\n'Run some code on the recordset\n'Close all objects\nrst.Close\nqdf.Close\nSet rst = Nothing\nSet qdf = Nothing\n</code></pre>\n\n<p>(I haven't tested it myself, just something I collected in my travels, because every once in a while I've wanted to do this to, but ended up using one of my previously mentioned kludges)</p>\n\n<p><strong>Edit</strong>\nI finally had cause to use this. Here's the actual code.</p>\n\n<pre><code>'...\nDim qdf As DAO.QueryDef\nDim prmOne As DAO.Parameter\nDim prmTwo As DAO.Parameter\nDim rst as recordset\n '...\n 'open up the query:\n Set qdf = db.QueryDefs(\"my_two_param_query\") 'params called param_one and \n 'param_two\n\n 'link your DAP.Parameters to the query\n Set prmOne = qdf.Parameters!param_one\n Set prmTwo = qdf.Parameters!param_two\n\n 'set the values of the parameters\n prmOne = 1 \n prmTwo = 2\n\n Set rst = qdf.OpenRecordset(dbOpenDynaset, _\n dbSeeChanges)\n '... treat the recordset as normal\n\n 'make sure you clean up after your self\n Set rst = Nothing\n Set prmOne = Nothing\n Set prmTwo = Nothing\n Set qdf = Nothing\n</code></pre>\n" }, { "answer_id": 97350, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": false, "text": "<p>References to the controls on the form can be used directly in Access queries, though it's important to define them as parameters (otherwise, results in recent versions of Access can be unpredictable where they were once reliable).</p>\n\n<p>For instance, if you want to filter a query by the LastName control on MyForm, you'd use this as your criteria:</p>\n\n<pre><code>LastName = Forms!MyForm!LastName\n</code></pre>\n\n<p>Then you'd define the form reference as a parameter. The resulting SQL might look something like this:</p>\n\n<pre><code>PARAMETERS [[Forms]!MyForm![LastName]] Text ( 255 );\nSELECT tblCustomers.*\nFROM tblCustomers\nWHERE tblCustomers.LastName=[Forms]![MyForm]![LastName];\n</code></pre>\n\n<p>I would, however, ask why you need to have a saved query for this purpose. What are you doing with the results? Displaying them in a form or report? If so, you can do this in the Recordsource of the form/report and leave your saved query untouched by the parameters, so it can be used in other contexts without popping up the prompts to fill out the parameters.</p>\n\n<p>On the other hand, if you're doing something in code, just write the SQL on the fly and use the literal value of the form control for constructing your WHERE clause.</p>\n" }, { "answer_id": 48668448, "author": "Mart", "author_id": 5179566, "author_profile": "https://Stackoverflow.com/users/5179566", "pm_score": 0, "selected": false, "text": "<p>the easy method is here <a href=\"https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-setparameter-method-access\" rel=\"nofollow noreferrer\">Microsoft 'setparameter' info page</a></p>\n\n<pre><code>DoCmd.SetParameter \"frontMthOffset\", -3\nDoCmd.SetParameter \"endMthOffset\", -2\nDoCmd.OpenQuery \"QryShowDifference_ValuesChangedBetweenSELECTEDMonths\"\n</code></pre>\n\n<p>where the SQL of the Access query includes [frontMthOffset] actually in the SQL.\ne.g.</p>\n\n<pre><code>\"select blah from mytable where dateoffset=[frontMthOffset]\"\n</code></pre>\n\n<p>It all just works!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16562/" ]
I'd like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset back and do some basic calculations with them. I'm coming up short in figuring out how to get the parameters of the query to be populated by the form elements. If I have to use VBA, that's fine.
References to the controls on the form can be used directly in Access queries, though it's important to define them as parameters (otherwise, results in recent versions of Access can be unpredictable where they were once reliable). For instance, if you want to filter a query by the LastName control on MyForm, you'd use this as your criteria: ``` LastName = Forms!MyForm!LastName ``` Then you'd define the form reference as a parameter. The resulting SQL might look something like this: ``` PARAMETERS [[Forms]!MyForm![LastName]] Text ( 255 ); SELECT tblCustomers.* FROM tblCustomers WHERE tblCustomers.LastName=[Forms]![MyForm]![LastName]; ``` I would, however, ask why you need to have a saved query for this purpose. What are you doing with the results? Displaying them in a form or report? If so, you can do this in the Recordsource of the form/report and leave your saved query untouched by the parameters, so it can be used in other contexts without popping up the prompts to fill out the parameters. On the other hand, if you're doing something in code, just write the SQL on the fly and use the literal value of the form control for constructing your WHERE clause.
95,286
<p>I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style. I know that you can do this with size rolling style by using the maxSizeRollBackups.</p> <pre><code>&lt;appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="mylog.log" /&gt; &lt;appendToFile value="true" /&gt; &lt;lockingModel type="log4net.Appender.FileAppender+MinimalLock" /&gt; &lt;rollingStyle value="Date" /&gt; &lt;datePattern value=".yyMMdd.'log'" /&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%d %-5p %c - %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; </code></pre>
[ { "answer_id": 95390, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 2, "selected": false, "text": "<p>Not sure exactly what you need. Below is an extract from one of my lo4net.config files:</p>\n\n<pre><code> &lt;appender name=\"RollingFile\" type=\"log4net.Appender.RollingFileAppender\"&gt;\n &lt;param name=\"File\" value=\"App_Data\\log\"/&gt;\n &lt;param name=\"DatePattern\" value=\".yyyy-MM-dd-tt&amp;quot;.log&amp;quot;\"/&gt;\n &lt;param name=\"AppendToFile\" value=\"true\"/&gt;\n &lt;param name=\"RollingStyle\" value=\"Date\"/&gt;\n &lt;param name=\"StaticLogFileName\" value=\"false\"/&gt;\n &lt;param name=\"maxSizeRollBackups\" value=\"60\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%r %d [%t] %-5p %c - %m%n\"/&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n</code></pre>\n" }, { "answer_id": 97641, "author": "Charley Rathkopf", "author_id": 10119, "author_profile": "https://Stackoverflow.com/users/10119", "pm_score": 6, "selected": false, "text": "<p>You can't.</p>\n<p>from\n<a href=\"https://logging.apache.org/log4net/release/sdk/html/T_log4net_Appender_RollingFileAppender.htm\" rel=\"noreferrer\">log4net SDK Reference<br />\nRollingFileAppender Class\n</a></p>\n<blockquote>\n<p><strong>CAUTION</strong></p>\n<p>A maximum number of backup files when rolling on date/time boundaries is not supported.</p>\n</blockquote>\n" }, { "answer_id": 2434646, "author": "Mafu Josh", "author_id": 119418, "author_profile": "https://Stackoverflow.com/users/119418", "pm_score": 4, "selected": false, "text": "<p>I spent some time looking into this a few months ago. v1.2.10 doesn't support deleting older log files based on rolling by date. It is on the task list for the next release. I took the source code and added the functionality myself, and posted it for others if they are interested. The issue and the patch can be found at <a href=\"https://issues.apache.org/jira/browse/LOG4NET-27\" rel=\"noreferrer\">https://issues.apache.org/jira/browse/LOG4NET-27</a> .</p>\n" }, { "answer_id": 2916628, "author": "Jeff", "author_id": 303284, "author_profile": "https://Stackoverflow.com/users/303284", "pm_score": 5, "selected": false, "text": "<p>Even though its not supported, here is how I handled this situation:</p>\n\n<p>This is my configuration:</p>\n\n<pre><code> &lt;appender name=\"RollingLogFileAppender\" type=\"log4net.Appender.RollingFileAppender\"&gt;\n &lt;file value=\"C:\\logs\\LoggingTest\\logfile.txt\" /&gt;\n &lt;appendToFile value=\"true\" /&gt;\n &lt;rollingStyle value=\"Composite\" /&gt;\n &lt;datePattern value=\"yyyyMMdd\" /&gt;\n &lt;maxSizeRollBackups value=\"10\" /&gt;\n &lt;maximumFileSize value=\"1MB\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date - %message%newline\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n</code></pre>\n\n<p>On application start up I do:</p>\n\n<pre><code> XmlConfigurator.Configure();\n var date = DateTime.Now.AddDays(-10);\n var task = new LogFileCleanupTask();\n task.CleanUp(date);\n</code></pre>\n\n<hr>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\n\nusing log4net;\nusing log4net.Appender;\nusing log4net.Config;\n\n public class LogFileCleanupTask\n {\n #region - Constructor -\n public LogFileCleanupTask()\n {\n }\n #endregion\n\n #region - Methods -\n /// &lt;summary&gt;\n /// Cleans up. Auto configures the cleanup based on the log4net configuration\n /// &lt;/summary&gt;\n /// &lt;param name=\"date\"&gt;Anything prior will not be kept.&lt;/param&gt;\n public void CleanUp(DateTime date)\n {\n string directory = string.Empty;\n string filePrefix = string.Empty;\n\n var repo = LogManager.GetAllRepositories().FirstOrDefault(); ;\n if (repo == null)\n throw new NotSupportedException(\"Log4Net has not been configured yet.\");\n\n var app = repo.GetAppenders().Where(x =&gt; x.GetType() == typeof(RollingFileAppender)).FirstOrDefault();\n if (app != null)\n {\n var appender = app as RollingFileAppender;\n\n directory = Path.GetDirectoryName(appender.File);\n filePrefix = Path.GetFileName(appender.File);\n\n CleanUp(directory, filePrefix, date);\n }\n }\n\n /// &lt;summary&gt;\n /// Cleans up.\n /// &lt;/summary&gt;\n /// &lt;param name=\"logDirectory\"&gt;The log directory.&lt;/param&gt;\n /// &lt;param name=\"logPrefix\"&gt;The log prefix. Example: logfile dont include the file extension.&lt;/param&gt;\n /// &lt;param name=\"date\"&gt;Anything prior will not be kept.&lt;/param&gt;\n public void CleanUp(string logDirectory, string logPrefix, DateTime date)\n {\n if (string.IsNullOrEmpty(logDirectory))\n throw new ArgumentException(\"logDirectory is missing\");\n\n if (string.IsNullOrEmpty(logPrefix))\n throw new ArgumentException(\"logPrefix is missing\");\n\n var dirInfo = new DirectoryInfo(logDirectory);\n if (!dirInfo.Exists)\n return;\n\n var fileInfos = dirInfo.GetFiles(\"{0}*.*\".Sub(logPrefix));\n if (fileInfos.Length == 0)\n return;\n\n foreach (var info in fileInfos)\n {\n if (info.CreationTime &lt; date)\n {\n info.Delete();\n }\n }\n\n }\n #endregion\n }\n</code></pre>\n\n<p>The Sub Method is an Extension Method, it basically wraps string.format like so:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Extension helper methods for strings\n/// &lt;/summary&gt;\n[DebuggerStepThrough, DebuggerNonUserCode]\npublic static class StringExtensions\n{\n /// &lt;summary&gt;\n /// Formats a string using the &lt;paramref name=\"format\"/&gt; and &lt;paramref name=\"args\"/&gt;.\n /// &lt;/summary&gt;\n /// &lt;param name=\"format\"&gt;The format.&lt;/param&gt;\n /// &lt;param name=\"args\"&gt;The args.&lt;/param&gt;\n /// &lt;returns&gt;A string with the format placeholders replaced by the args.&lt;/returns&gt;\n public static string Sub(this string format, params object[] args)\n {\n return string.Format(format, args);\n }\n}\n</code></pre>\n" }, { "answer_id": 12613278, "author": "Matthew Lock", "author_id": 74585, "author_profile": "https://Stackoverflow.com/users/74585", "pm_score": 0, "selected": false, "text": "<p>It's fairly easy to inherit from a log4net appender and add say your own override method which performs the clean up of files. I overrode OpenFile to do this. Here's an example of a custom log4net appender to get you started: <a href=\"https://stackoverflow.com/a/2385874/74585\">https://stackoverflow.com/a/2385874/74585</a></p>\n" }, { "answer_id": 15364915, "author": "mattezell", "author_id": 159720, "author_profile": "https://Stackoverflow.com/users/159720", "pm_score": 2, "selected": false, "text": "<p>I recently came across this need when attempting to clean up log logs based on a maxAgeInDays configuration value passed into my service... As many have before me, I became exposed to the NTFS 'feature' Tunneling, which makes using FileInfo.CreationDate problematic (though I have since worked around this as well)... </p>\n\n<p>Since I had a pattern to go off of, I decided to just roll my own clean up method... My logger is configured programmatically, so I merely call the following after my logger setup has completed...</p>\n\n<pre><code> //.........................\n //Log Config Stuff Above...\n\n log4net.Config.BasicConfigurator.Configure(fileAppender);\n if(logConfig.DaysToKeep &gt; 0)\n CleanupLogs(logConfig.LogFilePath, logConfig.DaysToKeep);\n}\n\nstatic void CleanupLogs(string logPath, int maxAgeInDays)\n{\n if (File.Exists(logPath))\n {\n var datePattern = \"yyyy.MM.dd\";\n List&lt;string&gt; logPatternsToKeep = new List&lt;string&gt;();\n for (var i = 0; i &lt;= maxAgeInDays; i++)\n {\n logPatternsToKeep.Add(DateTime.Now.AddDays(-i).ToString(datePattern));\n }\n\n FileInfo fi = new FileInfo(logPath);\n\n var logFiles = fi.Directory.GetFiles(fi.Name + \"*\")\n .Where(x =&gt; logPatternsToKeep.All(y =&gt; !x.Name.Contains(y) &amp;&amp; x.Name != fi.Name));\n\n foreach (var log in logFiles)\n {\n if (File.Exists(log.FullName)) File.Delete(log.FullName);\n }\n }\n}\n</code></pre>\n\n<p>Probably not the prettiest approach, but working pretty well for our purposes...</p>\n" }, { "answer_id": 37679221, "author": "Phil", "author_id": 6435209, "author_profile": "https://Stackoverflow.com/users/6435209", "pm_score": 4, "selected": false, "text": "<p>To limit the number of logs, do not include the year or month in the datepattern,e.g. datePattern value=\"_dd'.log'\"</p>\n\n<p>This will create a new log each day, and it will get overwritten next month.</p>\n" }, { "answer_id": 41557184, "author": "Coruscate5", "author_id": 6237912, "author_profile": "https://Stackoverflow.com/users/6237912", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://nlog-project.org/\" rel=\"nofollow noreferrer\">NLog</a>, which is set up nearly the same way as Log4Net (&amp; is actively maintained - even has support for .NET Core), supports rolling logs based on date.</p>\n" }, { "answer_id": 70396398, "author": "HouseCat", "author_id": 3072640, "author_profile": "https://Stackoverflow.com/users/3072640", "pm_score": 0, "selected": false, "text": "<p>Stopped worrying about a more complex x per date and just specified and arbitrary file count and just sort of threw this one together. Be careful with the <a href=\"https://stackoverflow.com/questions/2914819/what-is-the-purpose-of-the-permissionset-attribute-in-the-msdn-filesystemwatcher\"> [SecurityAction.Demand]</a>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public string LogPath { get; set; }\npublic int MaxFileCount { get; set; } = 10;\n\nprivate FileSystemWatcher _fileSystemWatcher;\n\n[PermissionSet(SecurityAction.Demand, Name = &quot;FullTrust&quot;)]\npublic async Task StartAsync()\n{\n await Task.Yield();\n\n if (!Directory.Exists(LogPath))\n { Directory.CreateDirectory(LogPath); }\n\n _fileSystemWatcher = new FileSystemWatcher\n {\n Filter = &quot;*.*&quot;,\n Path = LogPath,\n EnableRaisingEvents = true,\n NotifyFilter = NotifyFilters.FileName\n | NotifyFilters.LastAccess\n | NotifyFilters.LastWrite\n | NotifyFilters.Security\n | NotifyFilters.Size\n };\n\n _fileSystemWatcher.Created += OnCreated;\n}\n\npublic async Task StopAsync()\n{\n await Task.Yield();\n\n _fileSystemWatcher.Created -= OnCreated; // prevents a resource / memory leak.\n _fileSystemWatcher = null; // not using dispose allows us to re-start if necessary.\n}\n\nprivate void OnCreated(object sender, FileSystemEventArgs e)\n{\n var fileInfos = Directory\n .GetFiles(LogPath)\n .Select(filePath =&gt; new FileInfo(filePath))\n .OrderBy(fileInfo =&gt; fileInfo.LastWriteTime)\n .ToArray();\n\n if (fileInfos.Length &lt;= MaxFileCount)\n { return; }\n\n // For every file (over MaxFileCount) delete, starting with the oldest file.\n for (var i = 0; i &lt; fileInfos.Length - MaxFileCount; i++)\n {\n try\n {\n fileInfos[i].Delete();\n }\n catch (Exception ex)\n {\n /* Handle */\n }\n }\n}\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4191/" ]
I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style. I know that you can do this with size rolling style by using the maxSizeRollBackups. ``` <appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="mylog.log" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Date" /> <datePattern value=".yyMMdd.'log'" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d %-5p %c - %m%n" /> </layout> </appender> ```
You can't. from [log4net SDK Reference RollingFileAppender Class](https://logging.apache.org/log4net/release/sdk/html/T_log4net_Appender_RollingFileAppender.htm) > > **CAUTION** > > > A maximum number of backup files when rolling on date/time boundaries is not supported. > > >
95,305
<p>Most of my users have email addresses associated with their profile in <code>/etc/passwd</code>. They are always in the 5th field, which I can grab, but they appear at different places within a comma-separated list in the 5th field.</p> <p>Can somebody give me a <strong>regex to grab just the email address</strong> (delimeted by commas) from a line in this file? (I will be using grep and sed from a bash script)</p> <p>Sample lines from file:</p> <pre><code>user1:x:1147:5005:User One,Department,,,[email protected]:/home/directory:/bin/bash user2:x:1148:5002:User Two,Department2,[email protected],:/home/directory:/bin/bash </code></pre>
[ { "answer_id": 95338, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 4, "selected": true, "text": "<p>What about:</p>\n\n<blockquote>\n <p>,([^@]+@[^,:]+)</p>\n</blockquote>\n\n<p>Where the group contains the email address.</p>\n\n<p><strong>[Updated based upon comment that address doesn't always get terminated by a comma]</strong></p>\n" }, { "answer_id": 95342, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 1, "selected": false, "text": "<p>Search for all email-valid-characters before and after the @ sign. Like:</p>\n\n<blockquote>\n <p>[-A-z0-9.<em>]+@[-A-z0-9.</em>]+</p>\n</blockquote>\n\n<p>Greedy matching should pull in everything it can, and it'll stop at the commas or colons.</p>\n\n<p>Check which characters are valid in email addresses, though. I've left some out (like +)</p>\n" }, { "answer_id": 95344, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<pre><code>[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\n</code></pre>\n\n<p>should catch most emials</p>\n" }, { "answer_id": 95474, "author": "reefnet_alex", "author_id": 2745, "author_profile": "https://Stackoverflow.com/users/2745", "pm_score": 3, "selected": false, "text": "<p>Actually, this looks like a perfect job for Awk. Now, like most people I will say \"I'm no expert in Awk\" before proceeding...</p>\n\n<pre><code>awk -F : '{print $5}' /etc/passwd\n</code></pre>\n\n<p>would get the 5th field where ':' is the field separator from /etc/passwd - it's probably the 5th field you are wanting. </p>\n\n<pre><code>awk -F , '{print $1}'\n</code></pre>\n\n<p>would get the 1st field from standard input where ',' was he delimimter so</p>\n\n<pre><code>awk -F : '{print $5}' /etc/passwd | awk -F , '{print $1}'\n</code></pre>\n\n<p>would get the first comma separated field (the Name field) from the fifth colon separated field (the field with all that kind of cruft in it!) in your /etc/passwd file.</p>\n\n<p>Adjust the print $1 to get the field with your emails in it. </p>\n\n<p>Doubtless there is away to do this without the pipe in Awk. I use Awk for splitting out fields in things and not much else. I find it confusing, and that's from somebody that loves regular expressions...</p>\n" }, { "answer_id": 95860, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 2, "selected": false, "text": "<pre><code>sed -r -e \"s/^.*[,:]([^,:]+@[^,:]+).*$/\\1/g\" /etc/passwd\n</code></pre>\n\n<p>Will do the trick</p>\n" }, { "answer_id": 97803, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": -1, "selected": false, "text": "<p>How about the standard <a href=\"https://www.rfc-editor.org/rfc/rfc2822\" rel=\"nofollow noreferrer\">RFC 2822</a>:</p>\n<pre><code>(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|&quot;(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*&quot;)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n</code></pre>\n<p>Yep. That's it. :)</p>\n" }, { "answer_id": 2474985, "author": "ghostdog74", "author_id": 131527, "author_profile": "https://Stackoverflow.com/users/131527", "pm_score": 0, "selected": false, "text": "<pre><code>sed 's/,*:\\/.*//;s/^.*://;s/.*,//' /etc/passwd\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
Most of my users have email addresses associated with their profile in `/etc/passwd`. They are always in the 5th field, which I can grab, but they appear at different places within a comma-separated list in the 5th field. Can somebody give me a **regex to grab just the email address** (delimeted by commas) from a line in this file? (I will be using grep and sed from a bash script) Sample lines from file: ``` user1:x:1147:5005:User One,Department,,,[email protected]:/home/directory:/bin/bash user2:x:1148:5002:User Two,Department2,[email protected],:/home/directory:/bin/bash ```
What about: > > ,([^@]+@[^,:]+) > > > Where the group contains the email address. **[Updated based upon comment that address doesn't always get terminated by a comma]**
95,361
<p>I'm programming in C++ on Visual Studio 2005. My question deals with .rc files. You can manually place include directives like (#include "blah.h"), at the top of an .rc file. But that's bad news since the first time someone opens the .rc file in the resource editor, it gets overwritten. I know there is a place to make these defines so that they don't get trashed but I can't find it and googling hasn't helped. Anyone know?</p>
[ { "answer_id": 95618, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>I'm not completely sure why you're trying to do, but modifying the resource files manually probably isn't a good idea.</p>\n\n<p>I believe general practice for VC++ for globally-accessible values is to define them in stdafx.h (at least that's how I've seen it done), or to create something like a \"globals.h\" header file and include that wherever you need it. It really depends on what you're trying to accomplish though.</p>\n" }, { "answer_id": 95669, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 2, "selected": false, "text": "<p>You want to <a href=\"http://msdn.microsoft.com/en-us/library/6e7446zd(VS.80).aspx\" rel=\"nofollow noreferrer\">Include Resources at Compile Time</a> (MSDN).</p>\n" }, { "answer_id": 95718, "author": "dgvid", "author_id": 9897, "author_profile": "https://Stackoverflow.com/users/9897", "pm_score": 4, "selected": true, "text": "<p>Add your #include to the file in the normal way, but also add it to one the three \"TEXTINCLUDE\" sections in the file, like so:</p>\n\n<pre><code>2 TEXTINCLUDE\nBEGIN\n \"#include \"\"windows.h\"\"\\r\\n\"\n \"#include \"\"blah.h\\r\\n\"\n \"\\0\"\n END\n</code></pre>\n\n<p>Note the following details:</p>\n\n<ul>\n<li>Each line is contained in quotes</li>\n<li>Use pairs of quotes, <em>e.g.</em>, \"\" to place a quote character inline</li>\n<li>End each line with \\r\\n</li>\n<li>End the TEXTINCLUDE block with \"\\0\"</li>\n</ul>\n\n<p>Statements placed in the \"1 TEXTINCLUDE\" block will be written to the beginning of the .rc file when the file is re-written by the resource editor. Statements placed in the 2 and 3 blocks follow, so you can guarantee relative include file order by using the appropriately numbered block.</p>\n\n<p>If your existing rc file does not already include TEXTINCLUDE blocks, use the new file wizard from the Solution Explorer pane to add a new rc file, then use that as a template.</p>\n" }, { "answer_id": 96257, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 2, "selected": false, "text": "<p>Within Visual Studio IDE, right-click on the .rc file (in the Resource View panel), and select \"Resource includes\" from the shortcut menu. When the dialog opens, use its \"Compile-time directives\" area to enter whatever you want to include in the .rc file. For example, if you want your 64-bit and 32-bit builds to use different icons, you could include the appropriate resource file for each build as follows:</p>\n\n<pre><code>#ifdef WIN64\n#include \"Icons64.rc\"\n#else\n#include \"Icons32.rc\"\n#endif\n</code></pre>\n\n<p>It's worth noting that these defines are not set in the resource compiler by default, so for your 64 bit build make sure you add /DWIN64 to the rc build.</p>\n" }, { "answer_id": 1476145, "author": "Ron Pihlgren", "author_id": 178195, "author_profile": "https://Stackoverflow.com/users/178195", "pm_score": 2, "selected": false, "text": "<p>All the gory details can be found in <a href=\"http://msdn.microsoft.com/en-us/library/6t3612sk.aspx\" rel=\"nofollow noreferrer\">MFC Technote #35</a>.</p>\n\n<p>-Ron</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm programming in C++ on Visual Studio 2005. My question deals with .rc files. You can manually place include directives like (#include "blah.h"), at the top of an .rc file. But that's bad news since the first time someone opens the .rc file in the resource editor, it gets overwritten. I know there is a place to make these defines so that they don't get trashed but I can't find it and googling hasn't helped. Anyone know?
Add your #include to the file in the normal way, but also add it to one the three "TEXTINCLUDE" sections in the file, like so: ``` 2 TEXTINCLUDE BEGIN "#include ""windows.h""\r\n" "#include ""blah.h\r\n" "\0" END ``` Note the following details: * Each line is contained in quotes * Use pairs of quotes, *e.g.*, "" to place a quote character inline * End each line with \r\n * End the TEXTINCLUDE block with "\0" Statements placed in the "1 TEXTINCLUDE" block will be written to the beginning of the .rc file when the file is re-written by the resource editor. Statements placed in the 2 and 3 blocks follow, so you can guarantee relative include file order by using the appropriately numbered block. If your existing rc file does not already include TEXTINCLUDE blocks, use the new file wizard from the Solution Explorer pane to add a new rc file, then use that as a template.
95,364
<p>I have a LINQ to SQL generated class with a readonly property:</p> <pre><code>&lt;Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)&gt; _ Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer) Get Return Me._TotalLogins End Get End Property </code></pre> <p>This prevents it from being changed externally, but I would like to update the property from within my class like below:</p> <pre><code>Partial Public Class User ... Public Shared Sub Login(Username, Password) ValidateCredentials(UserName, Password) Dim dc As New MyDataContext() Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault() user._TotalLogins += 1 dc.SubmitChanges() End Sub ... End Class </code></pre> <p>But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?</p>
[ { "answer_id": 96076, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "<pre><code>Make a second property that is protected or internal(?) \n\n&lt;Column(Name:=\"totalLogins\", Storage:=\"_TotalLogins\", DbType:=\"Int\", UpdateCheck:=UpdateCheck.Never)&gt; _\nprotected Property TotalLogins2() As System.Nullable(Of Integer)\n Get\n Return Me._TotalLogins\n End Get\n Set(byval value as System.Nullable(Of Integer))\n Return Me._TotalLogins\n End Get\nEnd Property\n</code></pre>\n\n<p>and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.</p>\n" }, { "answer_id": 96157, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": true, "text": "<p>Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins.</p>\n\n<p>Then create a new property by hand in the partial class that exposes it publically as a read-only property:</p>\n\n<pre><code>Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)\n Get\n Return Me.InternalTotalLogins\n End Get\nEnd Property\n</code></pre>\n" }, { "answer_id": 961653, "author": "Andrew Davey", "author_id": 7011, "author_profile": "https://Stackoverflow.com/users/7011", "pm_score": 0, "selected": false, "text": "<p>Before you change the field call SendPropertyChanging() and then after call SendPropertyChanged(\"\").\nThis will make the Table entity tracking know something changed.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11991/" ]
I have a LINQ to SQL generated class with a readonly property: ``` <Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)> _ Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer) Get Return Me._TotalLogins End Get End Property ``` This prevents it from being changed externally, but I would like to update the property from within my class like below: ``` Partial Public Class User ... Public Shared Sub Login(Username, Password) ValidateCredentials(UserName, Password) Dim dc As New MyDataContext() Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault() user._TotalLogins += 1 dc.SubmitChanges() End Sub ... End Class ``` But the call to user.\_TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?
Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins. Then create a new property by hand in the partial class that exposes it publically as a read-only property: ``` Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer) Get Return Me.InternalTotalLogins End Get End Property ```
95,378
<p>What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?</p> <p>The spell check should be <em>source code aware</em> meaning that it would stick to checking string literals in the code and not the code itself. Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values). Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.</p> <p>Many IDEs can do this for the file you are currently working with. The difference in what I am looking for is something that can operate upon a whole source code base at once.</p> <p>Something like a Findbugs or PMD type tool for mis-spellings would be ideal.</p>
[ { "answer_id": 96076, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "<pre><code>Make a second property that is protected or internal(?) \n\n&lt;Column(Name:=\"totalLogins\", Storage:=\"_TotalLogins\", DbType:=\"Int\", UpdateCheck:=UpdateCheck.Never)&gt; _\nprotected Property TotalLogins2() As System.Nullable(Of Integer)\n Get\n Return Me._TotalLogins\n End Get\n Set(byval value as System.Nullable(Of Integer))\n Return Me._TotalLogins\n End Get\nEnd Property\n</code></pre>\n\n<p>and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.</p>\n" }, { "answer_id": 96157, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 3, "selected": true, "text": "<p>Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins.</p>\n\n<p>Then create a new property by hand in the partial class that exposes it publically as a read-only property:</p>\n\n<pre><code>Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)\n Get\n Return Me.InternalTotalLogins\n End Get\nEnd Property\n</code></pre>\n" }, { "answer_id": 961653, "author": "Andrew Davey", "author_id": 7011, "author_profile": "https://Stackoverflow.com/users/7011", "pm_score": 0, "selected": false, "text": "<p>Before you change the field call SendPropertyChanging() and then after call SendPropertyChanged(\"\").\nThis will make the Table entity tracking know something changed.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9925/" ]
What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files? The spell check should be *source code aware* meaning that it would stick to checking string literals in the code and not the code itself. Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values). Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored. Many IDEs can do this for the file you are currently working with. The difference in what I am looking for is something that can operate upon a whole source code base at once. Something like a Findbugs or PMD type tool for mis-spellings would be ideal.
Set the existing TotalLogins property as either private or protected and remove the readonly attribute. You may also want to rename it e.g. InternalTotalLogins. Then create a new property by hand in the partial class that exposes it publically as a read-only property: ``` Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer) Get Return Me.InternalTotalLogins End Get End Property ```
95,389
<p>If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation?</p> <p>For instance, we have a simple class/subclass pair that share the <code>@Author @interface.</code> What I'd like to do is force each further subclass to define the same <code>@Author</code> annotation, preventing a <code>RuntimeException</code> somewhere down the road. </p> <p>TestClass.java:</p> <pre><code>import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @interface Author { String name(); } @Author( name = "foo" ) public abstract class TestClass { public static String getInfo( Class&lt;? extends TestClass&gt; c ) { return c.getAnnotation( Author.class ).name(); } public static void main( String[] args ) { System.out.println( "The test class was written by " + getInfo( TestClass.class ) ); System.out.println( "The test subclass was written by " + getInfo( TestSubClass.class ) ); } } </code></pre> <p>TestSubClass.java:</p> <pre><code>@Author( name = "bar" ) public abstract class TestSubClass extends TestClass {} </code></pre> <p>I know I can enumerate all annotations at runtime and check for the missing <code>@Author</code>, but I'd really like to do this at compile time, if possible.</p>
[ { "answer_id": 95467, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 2, "selected": false, "text": "<p>I am quite sure that this is impossible to do at compile time.</p>\n\n<p>However, this is an obvious task for a \"unit\"-test. If you have conventions like this that you would like enforced, but which can be difficult or impossible to check with the compiler, \"unit\"-tests are a simple way to check them.</p>\n\n<p>Another possibility is to implement a custom rule in a static analyzer. There are many options here, too.</p>\n\n<p>(I put unit in scare-quotes, since this is really a test of conventions, rather than of a specific unit. But it should run together with your unit-tests).</p>\n" }, { "answer_id": 95522, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 2, "selected": false, "text": "<p>You could make an Annotation (e.g. @EnforceAuthor) with @Inherited on the superclass and use compiler annotations (since Java 1.6) to catch up at compile time. Then you have a reference to the subclass and can check if another Annotation (e.g. @Author)) is missing. This would allow to cancel compiling with an error message.</p>\n" }, { "answer_id": 213866, "author": "Bouil", "author_id": 29106, "author_profile": "https://Stackoverflow.com/users/29106", "pm_score": 3, "selected": true, "text": "<p>You can do that with JSR 269, at compile time.\nSee : <a href=\"http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api\" rel=\"nofollow noreferrer\">http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api</a></p>\n<p>Edit 2020-09-20: Link is dead, archived version here : <a href=\"https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18058/" ]
If a class defined an annotation, is it somehow possible to force its subclass to define the same annotation? For instance, we have a simple class/subclass pair that share the `@Author @interface.` What I'd like to do is force each further subclass to define the same `@Author` annotation, preventing a `RuntimeException` somewhere down the road. TestClass.java: ``` import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @interface Author { String name(); } @Author( name = "foo" ) public abstract class TestClass { public static String getInfo( Class<? extends TestClass> c ) { return c.getAnnotation( Author.class ).name(); } public static void main( String[] args ) { System.out.println( "The test class was written by " + getInfo( TestClass.class ) ); System.out.println( "The test subclass was written by " + getInfo( TestSubClass.class ) ); } } ``` TestSubClass.java: ``` @Author( name = "bar" ) public abstract class TestSubClass extends TestClass {} ``` I know I can enumerate all annotations at runtime and check for the missing `@Author`, but I'd really like to do this at compile time, if possible.
You can do that with JSR 269, at compile time. See : <http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html#pluggable-annotation-processing-api> Edit 2020-09-20: Link is dead, archived version here : <https://web.archive.org/web/20150516080739/http://today.java.net/pub/a/today/2006/06/29/validate-java-ee-annotations-with-annotation-processors.html>
95,419
<p>Had a conversation with a coworker the other day about this.</p> <p>There's the obvious using a constructor, but what are the other ways there?</p>
[ { "answer_id": 95428, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Clone_(Java_method)\" rel=\"noreferrer\">Cloning</a> and <a href=\"http://exampledepot.com/egs/java.io/DeserializeObj.html\" rel=\"noreferrer\">deserialization</a>.</p>\n" }, { "answer_id": 95448, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 2, "selected": false, "text": "<p>Reflection:</p>\n\n<pre><code>someClass.newInstance();\n</code></pre>\n" }, { "answer_id": 95496, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": -1, "selected": false, "text": "<p>Depends exactly what you mean by create but some other ones are:</p>\n\n<ul>\n<li>Clone method</li>\n<li>Deserialization</li>\n<li>Reflection (Class.newInstance())</li>\n<li>Reflection (Constructor object)</li>\n</ul>\n" }, { "answer_id": 95743, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 5, "selected": false, "text": "<p>Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.</p>\n" }, { "answer_id": 96395, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 0, "selected": false, "text": "<p>From an API user perspective, another alternative to constructors are static factory methods (like BigInteger.valueOf()), though for the API author (and technically \"for real\") the objects are still created using a constructor.</p>\n" }, { "answer_id": 96473, "author": "Randy L", "author_id": 13800, "author_profile": "https://Stackoverflow.com/users/13800", "pm_score": -1, "selected": false, "text": "<p>there is also ClassLoader.loadClass(string) but this is not often used.</p>\n\n<p>and if you want to be a total lawyer about it, arrays are <em>technically</em> objects because of an array's .length property. so initializing an array creates an object.</p>\n" }, { "answer_id": 2103107, "author": "Thomas Lötzer", "author_id": 3587, "author_profile": "https://Stackoverflow.com/users/3587", "pm_score": 4, "selected": false, "text": "<p>Yes, you can create objects using reflection. For example, <code>String.class.newInstance()</code> will give you a new empty String object.</p>\n" }, { "answer_id": 2103118, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": "<p>Also you can use </p>\n\n<pre><code> Object myObj = Class.forName(\"your.cClass\").newInstance();\n</code></pre>\n" }, { "answer_id": 2103142, "author": "ryanprayogo", "author_id": 93979, "author_profile": "https://Stackoverflow.com/users/93979", "pm_score": 2, "selected": false, "text": "<p>Reflection will also do the job for you.</p>\n\n<pre><code>SomeClass anObj = SomeClass.class.newInstance();\n</code></pre>\n\n<p>is another way to create a new instance of a class. In this case, you will also need to handle the exceptions that might get thrown.</p>\n" }, { "answer_id": 2103146, "author": "stacker", "author_id": 241590, "author_profile": "https://Stackoverflow.com/users/241590", "pm_score": 3, "selected": false, "text": "<p>This should be noticed if you are new to java, every object has inherited from Object </p>\n\n<p>protected native Object clone() throws CloneNotSupportedException;</p>\n" }, { "answer_id": 2103287, "author": "KLE", "author_id": 146347, "author_profile": "https://Stackoverflow.com/users/146347", "pm_score": 3, "selected": false, "text": "<p>Also, you can <strong>de-serialize</strong> data into an object. This doesn't go through the class Constructor !</p>\n\n<hr>\n\n<p><strong>UPDATED</strong> : Thanks Tom for pointing that out in your comment ! And Michael also experimented.</p>\n\n<blockquote>\n <p>It goes through the constructor of the most derived non-serializable superclass.<br>\n And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.</p>\n</blockquote>\n\n<p>Please see Tom's answer for a complete treatment of all cases ;-)<br>\n<a href=\"https://stackoverflow.com/questions/2103089/is-there-any-other-way-of-creating-an-object-without-using-new-keyword-in-java/2103578#2103578\">is there any other way of creating an object without using &quot;new&quot; keyword in java</a></p>\n" }, { "answer_id": 2103314, "author": "Roman", "author_id": 100516, "author_profile": "https://Stackoverflow.com/users/100516", "pm_score": 2, "selected": false, "text": "<p>You can also clone existing object (if it implements Cloneable).</p>\n\n<pre><code>Foo fooClone = fooOriginal.clone (); \n</code></pre>\n" }, { "answer_id": 2103578, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "<p>There are various ways:</p>\n\n<ul>\n<li>Through <code>Class.newInstance</code>.</li>\n<li>Through <code>Constructor.newInstance</code>.</li>\n<li>Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).</li>\n<li>Through <code>Object.clone</code> (<strong>does not call a constructor</strong>).</li>\n<li>Through JNI (should call a constructor).</li>\n<li>Through any other method that calls a <code>new</code> for you.</li>\n<li>I guess you could describe class loading as creating new objects (such as interned <code>String</code>s).</li>\n<li>A literal array as part of the initialisation in a declaration (no constructor for arrays).</li>\n<li>The array in a \"varargs\" (<code>...</code>) method call (no constructor for arrays).</li>\n<li>Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).</li>\n<li>Causing an exception to be created and thrown by the runtime. For instance <code>throw null;</code> or <code>\"\".toCharArray()[0]</code>.</li>\n<li>Oh, and boxing of primitives (unless cached), of course.</li>\n<li>JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.</li>\n<li>For completeness (and Paŭlo Ebermann), there's some syntax with the <code>new</code> keyword as well.</li>\n</ul>\n" }, { "answer_id": 5104598, "author": "Bozho", "author_id": 203907, "author_profile": "https://Stackoverflow.com/users/203907", "pm_score": 2, "selected": false, "text": "<ul>\n<li>using the <code>new</code> operator (thus invoking a constructor)</li>\n<li>using reflection <code>clazz.newInstance()</code> (which again invokes the constructor). Or by <code>clazz.getConstructor(..).newInstance(..)</code> (again using a constructor, but you can thus choose which one)</li>\n</ul>\n\n<p>To summarize the answer - one main way - by invoking the constructor of the object's class.</p>\n\n<p>Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning. </p>\n" }, { "answer_id": 5104630, "author": "kamaci", "author_id": 453596, "author_profile": "https://Stackoverflow.com/users/453596", "pm_score": 9, "selected": true, "text": "<p>There are four different ways to create objects in java:</p>\n\n<p><strong>A</strong>. Using <code>new</code> keyword<br>\nThis is the most common way to create an object in java. Almost 99% of objects are created in this way.</p>\n\n<pre><code> MyObject object = new MyObject();\n</code></pre>\n\n<p><strong>B</strong>. Using <code>Class.forName()</code><br>\nIf we know the name of the class &amp; if it has a public default constructor we can create an object in this way.</p>\n\n<pre><code>MyObject object = (MyObject) Class.forName(\"subin.rnd.MyObject\").newInstance();\n</code></pre>\n\n<p><strong>C</strong>. Using <code>clone()</code><br>\nThe clone() can be used to create a copy of an existing object.</p>\n\n<pre><code>MyObject anotherObject = new MyObject();\nMyObject object = (MyObject) anotherObject.clone();\n</code></pre>\n\n<p><strong>D</strong>. Using <code>object deserialization</code><br>\nObject deserialization is nothing but creating an object from its serialized form.</p>\n\n<pre><code>ObjectInputStream inStream = new ObjectInputStream(anInputStream );\nMyObject object = (MyObject) inStream.readObject();\n</code></pre>\n\n<p>You can read them from <a href=\"http://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 5104913, "author": "Paŭlo Ebermann", "author_id": 600500, "author_profile": "https://Stackoverflow.com/users/600500", "pm_score": 3, "selected": false, "text": "<p>There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): <strong>Arrays</strong>. Arrays are created with</p>\n\n<pre><code> A[] array = new A[len];\n</code></pre>\n\n<p>or</p>\n\n<pre><code> A[] array = new A[] { value0, value1, value2 };\n</code></pre>\n\n<p>As Sean said in a comment, this is syntactically similar to a constructor call and internally it is not much more than allocation and zero-initializing (or initializing with explicit content, in the second case) a memory block, with some header to indicate the type and the length.</p>\n\n<p>When passing arguments to a varargs-method, an array is there created (and filled) implicitly, too.</p>\n\n<p>A fourth way would be</p>\n\n<pre><code> A[] array = (A[]) Array.newInstance(A.class, len);\n</code></pre>\n\n<p>Of course, cloning and deserializing works here, too.</p>\n\n<p>There are many methods in the Standard API which create arrays, but they all in fact are using one (or more) of these ways.</p>\n" }, { "answer_id": 5105730, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 3, "selected": false, "text": "<p>Other ways if we are being exhaustive.</p>\n\n<ul>\n<li>On the Oracle JVM is Unsafe.allocateInstance() which creates an instance without calling a constructor.</li>\n<li>Using byte code manipulation you can add code to <code>anewarray</code>, <code>multianewarray</code>, <code>newarray</code> or <code>new</code>. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.</li>\n</ul>\n" }, { "answer_id": 6000453, "author": "K.V.Subrahmanya Reddy", "author_id": 753398, "author_profile": "https://Stackoverflow.com/users/753398", "pm_score": 2, "selected": false, "text": "<p>There are FIVE different ways to create objects in Java:</p>\n\n<h3>1. Using `new` keyword:</h3>\n\n<p>This is the most common way to create an object in Java. Almost 99% of objects are created in this way.</p>\n\n<pre><code>MyObject object = new MyObject();//normal way\n</code></pre>\n\n<h3>2. By Using Factory Method:</h3>\n\n<pre><code>ClassName ObgRef=ClassName.FactoryMethod();\n</code></pre>\n\n<p><em>Example:</em></p>\n\n<pre><code>RunTime rt=Runtime.getRunTime();//Static Factory Method\n</code></pre>\n\n<h3>3. By Using Cloning Concept:</h3>\n\n<p>By using <code>clone()</code>, the <code>clone()</code> can be used to create a copy of an existing object.</p>\n\n<pre><code>MyObjectName anotherObject = new MyObjectName();\nMyObjectName object = anotherObjectName.clone();//cloning Object\n</code></pre>\n\n<h3>4. Using `Class.forName()`:</h3>\n\n<p>If we know the name of the class &amp; if it has a public default constructor we can create an object in this way.</p>\n\n<pre><code>MyObjectName object = (MyObjectNmae) Class.forName(\"PackageName.ClassName\").newInstance();\n</code></pre>\n\n<p><em>Example:</em></p>\n\n<pre><code>String st=(String)Class.forName(\"java.lang.String\").newInstance();\n</code></pre>\n\n<h3>5. Using object deserialization:</h3>\n\n<p>Object deserialization is nothing but creating an object from its serialized form.</p>\n\n<pre><code>ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );\nMyObjectName object = (MyObjectNmae) inStream.readObject();\n</code></pre>\n" }, { "answer_id": 7205343, "author": "tanushree roy", "author_id": 914163, "author_profile": "https://Stackoverflow.com/users/914163", "pm_score": -1, "selected": false, "text": "<p>We can create an objects in 5 ways:</p>\n\n<ol>\n<li>by new operator</li>\n<li>by reflection (e.g. Class.forName() followed by Class.newInstance())</li>\n<li>by factory method</li>\n<li>by cloning</li>\n<li>by reflection api</li>\n</ol>\n" }, { "answer_id": 24379913, "author": "Deepak Sharma", "author_id": 1047565, "author_profile": "https://Stackoverflow.com/users/1047565", "pm_score": -1, "selected": false, "text": "<p>We can also create the object in this way:-</p>\n\n<pre><code>String s =\"Hello\";\n</code></pre>\n\n<p>Nobody has discuss it.</p>\n" }, { "answer_id": 31313449, "author": "Andriya", "author_id": 4939075, "author_profile": "https://Stackoverflow.com/users/4939075", "pm_score": 2, "selected": false, "text": "<p>Method 1</p>\n\n<p>Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.</p>\n\n<pre><code>Employee object = new Employee();\n</code></pre>\n\n<p>Method 2</p>\n\n<p>Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName(\"ExampleClass\").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.</p>\n\n<pre><code>Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();\n</code></pre>\n\n<p>Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).</p>\n\n<p>Another must read:</p>\n\n<p>Java: Thread State Introduction with Example\nSimple Java Enum Example</p>\n\n<p>Method 3</p>\n\n<p>Using clone(). The clone() can be used to create a copy of an existing object.</p>\n\n<pre><code>Employee secondObject = new Employee();\nEmployee object3 = (Employee) secondObject.clone();\n</code></pre>\n\n<p>Method 4</p>\n\n<p>Using newInstance() method</p>\n\n<pre><code>Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();\n</code></pre>\n\n<p>Method 5</p>\n\n<p>Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.</p>\n\n<pre><code>// Create Object5\n// create a new file with an ObjectOutputStream\nFileOutputStream out = new FileOutputStream(\"\");\nObjectOutputStream oout = new ObjectOutputStream(out);\n\n// write something in the file\noout.writeObject(object3);\noout.flush();\n\n// create an ObjectInputStream for the file we created before\nObjectInputStream ois = new ObjectInputStream(new FileInputStream(\"crunchify.txt\"));\nEmployee object5 = (Employee) ois.readObject();\n</code></pre>\n" }, { "answer_id": 40689708, "author": "Naresh Joshi", "author_id": 2078093, "author_profile": "https://Stackoverflow.com/users/2078093", "pm_score": 4, "selected": false, "text": "<p>There are five different ways to create an object in Java,</p>\n<p><strong>1. Using <code>new</code> keyword</strong> → constructor get called</p>\n<pre><code>Employee emp1 = new Employee();\n</code></pre>\n<p><strong>2. Using <code>newInstance()</code> method of <code>Class</code></strong> → constructor get called</p>\n<pre><code>Employee emp2 = (Employee) Class.forName(&quot;org.programming.mitra.exercises.Employee&quot;)\n .newInstance();\n</code></pre>\n<p>It can also be written as</p>\n<pre><code>Employee emp2 = Employee.class.newInstance();\n</code></pre>\n<p><strong>3. Using <code>newInstance()</code> method of <code>Constructor</code></strong> → constructor get called</p>\n<pre><code>Constructor&lt;Employee&gt; constructor = Employee.class.getConstructor();\nEmployee emp3 = constructor.newInstance();\n</code></pre>\n<p><strong>4. Using <code>clone()</code> method</strong> → no constructor call</p>\n<pre><code>Employee emp4 = (Employee) emp3.clone();\n</code></pre>\n<p><strong>5. Using deserialization</strong> → no constructor call</p>\n<pre><code>ObjectInputStream in = new ObjectInputStream(new FileInputStream(&quot;data.obj&quot;));\nEmployee emp5 = (Employee) in.readObject();\n</code></pre>\n<p>First three methods <code>new</code> keyword and both <code>newInstance()</code> include a constructor call but later two clone and deserialization methods create objects without calling the constructor.</p>\n<p>All above methods have different bytecode associated with them, Read <a href=\"https://programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html\" rel=\"noreferrer\">Different ways to create objects in Java with Example</a> for examples and more detailed description e.g. bytecode conversion of all these methods.</p>\n<p>However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
Had a conversation with a coworker the other day about this. There's the obvious using a constructor, but what are the other ways there?
There are four different ways to create objects in java: **A**. Using `new` keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way. ``` MyObject object = new MyObject(); ``` **B**. Using `Class.forName()` If we know the name of the class & if it has a public default constructor we can create an object in this way. ``` MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); ``` **C**. Using `clone()` The clone() can be used to create a copy of an existing object. ``` MyObject anotherObject = new MyObject(); MyObject object = (MyObject) anotherObject.clone(); ``` **D**. Using `object deserialization` Object deserialization is nothing but creating an object from its serialized form. ``` ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); ``` You can read them from [here](http://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/).
95,432
<p>I'd like to create a hotkey to search for files <strong>under a specific folder</strong> in Windows XP; I'm using AutoHotkey to create this shortcut.</p> <p>Problem is that I need to know a command-line statement to run in order to open the standard Windows "Find Files/Folders" dialog. I've googled for a while and haven't found any page indicating how to do this.</p> <p>I'm assuming that if I know the command-line statement for bringing up this prompt, it will allow me to pass in a parameter for what folder I want to be searching under. I know you can do this by right-clicking on a folder in XP, so I assume there's some way I could do it on the command line...?</p>
[ { "answer_id": 95450, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": -1, "selected": false, "text": "<p>Why don't you try bashing F3? :)</p>\n" }, { "answer_id": 95497, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 0, "selected": false, "text": "<p>Try \"Launchy\". For windows and linux. Awesome util.</p>\n" }, { "answer_id": 95502, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 0, "selected": false, "text": "<p>If you need just a hotkey then use <code>Win+f</code>.</p>\n" }, { "answer_id": 95580, "author": "Charles Roper", "author_id": 1944, "author_profile": "https://Stackoverflow.com/users/1944", "pm_score": 3, "selected": false, "text": "<h2>Use <a href=\"http://www.locate32.net/\" rel=\"noreferrer\">Locate32</a></h2>\n\n<p>This isn't the exact answer to your question, but you could use <a href=\"http://www.locate32.net/\" rel=\"noreferrer\"><strong>Locate32</strong></a> instead of the Windows search facility. It has a whole suite of command-line options plus has the huge benefit of being an indexed search, which means the results will display instantaneously. It's a tool I can't be without on Windows.</p>\n\n<p>This is the command you would issue to search for all <code>index.php</code> files in <code>D:\\home</code>:</p>\n\n<pre><code>locate32.exe -r -p D:\\home index.php\n</code></pre>\n\n<p>where the <code>-r</code> switch makes Locate32 search immediately without user intervention (without it, the interface would launch and the fields would be populated, but you'd have to hit Enter to proceed with the search) and <code>-p D:\\home</code> is the path to search.</p>\n\n<p>Using AutoHotKey, it's simple to assign the above command to a keyboard shortcut.</p>\n\n<p>There is also a fully command-line based version of Locate32 in the same package called <code>locate.exe</code>. This uses the same indexes as Locate32, but because it is completely CLI-based, can be used by scripting languages and other tools to take advantage of the blistering search performance it offers.</p>\n" }, { "answer_id": 95638, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 2, "selected": false, "text": "<p>There is no way from command line to get Explorer to show the Search Files pane. But you can get over it with some VBScript.</p>\n\n<p>Try this</p>\n\n<pre><code>'ExplorerFind.vbs\nDim objShell\nSet objShell = WScript.CreateObject(\"Shell.Application\")\nobjShell.FindFiles\n</code></pre>\n\n<p>And compile it with cscript /nologo ExplorerFind.vbs</p>\n" }, { "answer_id": 95640, "author": "Brian", "author_id": 2831, "author_profile": "https://Stackoverflow.com/users/2831", "pm_score": 3, "selected": true, "text": "<p>from <a href=\"http://www.pcreview.co.uk/forums/thread-1468270.php\" rel=\"nofollow noreferrer\">http://www.pcreview.co.uk/forums/thread-1468270.php</a></p>\n\n<pre><code>@echo off\necho CreateObject(\"Shell.Application\").FindFiles &gt;%temp%\\myff.vbs\ncscript.exe //Nologo %temp%\\myff.vbs\ndel %temp%\\myff.vbs\n</code></pre>\n" }, { "answer_id": 95662, "author": "Ben Dunlap", "author_id": 8722, "author_profile": "https://Stackoverflow.com/users/8722", "pm_score": 0, "selected": false, "text": "<p>It's a little unclear whether the end-result you want is the open \"find\" dialog, or if you're just looking for a command-line way to search an arbitrary directory. If the latter there's FINDSTR (assuming you want to search the content of files and not their names):</p>\n\n<p><a href=\"https://stackoverflow.com/questions/87350/what-are-good-grep-tool-for-windows#87394\">What are good grep tools for Windows?</a></p>\n" }, { "answer_id": 96302, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 2, "selected": false, "text": "<p>F3 or Win+F is a hotkey that will launch Find Files. If you then do a search using the criteria you want, you can save the search using the File menu. This creates a .FND file. The FND file can be launched from the command line or from a hot key created with autohotkey.</p>\n\n<p>It is possible to edit the .FND file (binary) and change what it is searching for, but I would avoid doing that unless it's the only way you can accomplish what you want. I tried it and it worked fine.</p>\n" }, { "answer_id": 7509943, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 2, "selected": false, "text": "<p>just execute this line! (WinKey+R, CmdPrompt, Shortcut, ShellExecute, WinExec, etc)</p>\n\n<pre><code>search-ms:query=New%20Folder&amp;\n</code></pre>\n\n<p>Find all shortcuts in your desktop</p>\n\n<pre><code>search-ms:query=*.lnk&amp;crumb=folder:%userprofile%\\Desktop&amp;\n</code></pre>\n\n<p>Find the text \"exe\" in the folder \"C:\\Program Files\"</p>\n\n<pre><code>search-ms:query=exe&amp;crumb=location:C:\\Program Files&amp;\n</code></pre>\n\n<p>Other exemples</p>\n\n<pre><code>search-ms:query=microsoft&amp;\nsearch-ms:query=vacation&amp;subquery=mydepartment.search-ms&amp;\nsearch-ms:query=seattle&amp;crumb=kind:pics&amp; \nsearch-ms:query=seattle&amp;crumb=folder:C:\\MyFolder&amp;\n</code></pre>\n\n<p>reference here <a href=\"http://msdn.microsoft.com/en-us/library/ff684385.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ff684385.aspx</a></p>\n" }, { "answer_id": 26204590, "author": "Tom", "author_id": 4110905, "author_profile": "https://Stackoverflow.com/users/4110905", "pm_score": 0, "selected": false, "text": "<p>Addition to Ben Dunlap's answer: You could also use FINDSTR on the output of the DIR command (for instance in a FOR loop)\nThis would search for filenames, not in files.</p>\n" }, { "answer_id": 45701457, "author": "Trevor", "author_id": 2697942, "author_profile": "https://Stackoverflow.com/users/2697942", "pm_score": 0, "selected": false, "text": "<p>Based on the answer by Vitim.us from cmd all you need is\n<code>explorer.exe \"search-ms:query=*.exe&amp;crumb=location:C:\\Program Files&amp;\"</code>\nChange the location and query as needed</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766670/" ]
I'd like to create a hotkey to search for files **under a specific folder** in Windows XP; I'm using AutoHotkey to create this shortcut. Problem is that I need to know a command-line statement to run in order to open the standard Windows "Find Files/Folders" dialog. I've googled for a while and haven't found any page indicating how to do this. I'm assuming that if I know the command-line statement for bringing up this prompt, it will allow me to pass in a parameter for what folder I want to be searching under. I know you can do this by right-clicking on a folder in XP, so I assume there's some way I could do it on the command line...?
from <http://www.pcreview.co.uk/forums/thread-1468270.php> ``` @echo off echo CreateObject("Shell.Application").FindFiles >%temp%\myff.vbs cscript.exe //Nologo %temp%\myff.vbs del %temp%\myff.vbs ```
95,492
<p>Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT?</p> <p>Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array?</p>
[ { "answer_id": 95539, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 6, "selected": true, "text": "<p>This is the simplest way to get unix time:</p>\n\n<pre><code>use Time::Local;\ntimelocal($second,$minute,$hour,$day,$month-1,$year);\n</code></pre>\n\n<p>Note the reverse order of the arguments and that January is month 0.\nFor many more options, see the <a href=\"https://metacpan.org/pod/DateTime\" rel=\"noreferrer\">DateTime</a> module from CPAN. </p>\n\n<p>As for parsing, see the <a href=\"https://metacpan.org/pod/Date::Parse\" rel=\"noreferrer\">Date::Parse</a> module from CPAN. If you really need to get fancy with date parsing, the <a href=\"https://metacpan.org/pod/Date::Manip\" rel=\"noreferrer\">Date::Manip</a> may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster.</p>\n\n<p>If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module <a href=\"https://metacpan.org/pod/DateTime::Format::ISO8601\" rel=\"noreferrer\">DateTime::Format::ISO8601</a>.</p>\n\n<hr>\n\n<p>For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the \"HMS\" part optional. It accepts any delimiters (eg, \"2009-02-15\" or \"2009.02.15\"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to \"69\" refer to \"20XX\", otherwise \"19XX\" (eg, \"50-02-15\" means 2050-02-15 but \"75-02-15\" means 1975-02-15).</p>\n\n<pre><code>use Time::Local;\n\nsub parsedate { \n my($s) = @_;\n my($year, $month, $day, $hour, $minute, $second);\n\n if($s =~ m{^\\s*(\\d{1,4})\\W*0*(\\d{1,2})\\W*0*(\\d{1,2})\\W*0*\n (\\d{0,2})\\W*0*(\\d{0,2})\\W*0*(\\d{0,2})}x) {\n $year = $1; $month = $2; $day = $3;\n $hour = $4; $minute = $5; $second = $6;\n $hour |= 0; $minute |= 0; $second |= 0; # defaults.\n $year = ($year&lt;100 ? ($year&lt;70 ? 2000+$year : 1900+$year) : $year);\n return timelocal($second,$minute,$hour,$day,$month-1,$year); \n }\n return -1;\n}\n</code></pre>\n" }, { "answer_id": 95604, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 5, "selected": false, "text": "<p>If you're using the <a href=\"https://metacpan.org/pod/DateTime\" rel=\"noreferrer\">DateTime</a> module, you can call the <a href=\"https://metacpan.org/pod/DateTime#METHODS\" rel=\"noreferrer\">epoch()</a> method on a DateTime object, since that's what you think of as unix time.</p>\n\n<p>Using DateTimes allows you to convert fairly easily from epoch, to date objects.</p>\n\n<p>Alternativly, <a href=\"http://perldoc.perl.org/functions/localtime.html\" rel=\"noreferrer\">localtime</a> and gmtime will convert an epoch into an array containing day month and year, and timelocal and timegm from the <a href=\"https://metacpan.org/pod/Time::Local\" rel=\"noreferrer\">Time::Local module</a> will do the opposite, converting an array of time elements (seconds, minutes, ..., days, months etc.) into an epoch.</p>\n" }, { "answer_id": 95629, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": -1, "selected": false, "text": "<p>If you're just looking for a command-line utility (i.e., not something that will get called from other functions), try out this script. It assumes the existence of GNU date (present on pretty much any Linux system):</p>\n\n<pre><code>#! /usr/bin/perl -w\n\nuse strict;\n\n$_ = (join ' ', @ARGV);\n$_ ||= &lt;STDIN&gt;;\n\nchomp;\n\nif (/^[\\d.]+$/) {\n print scalar localtime $_;\n print \"\\n\";\n}\nelse {\n exec \"date -d '$_' +%s\";\n}\n</code></pre>\n\n<p>Here's how it works:</p>\n\n<pre><code>$ Time now\n1221763842\n\n$ Time yesterday\n1221677444\n\n$ Time 1221677444\nWed Sep 17 11:50:44 2008\n\n$ Time '12:30pm jan 4 1987'\n536790600\n\n$ Time '9am 8 weeks ago'\n1216915200\n</code></pre>\n" }, { "answer_id": 95654, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 4, "selected": false, "text": "<p>To parse a date, look at <a href=\"https://metacpan.org/pod/Date::Parse\" rel=\"noreferrer\">Date::Parse</a> in CPAN.</p>\n" }, { "answer_id": 95741, "author": "Martin Dorey", "author_id": 18096, "author_profile": "https://Stackoverflow.com/users/18096", "pm_score": -1, "selected": false, "text": "<p>A filter converting any dates in various ISO-related formats (and who'd use anything else after reading <a href=\"http://www.cl.cam.ac.uk/~mgk25/iso-time.html\" rel=\"nofollow noreferrer\">the writings</a> of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:</p>\n\n<pre><code>martind@whitewater:~$ cat `which isoToEpoch`\n#!/usr/bin/perl -w\nuse strict;\nuse Time::Piece;\n# sudo apt-get install libtime-piece-perl\nwhile (&lt;&gt;) {\n # date --iso=s:\n # 2007-02-15T18:25:42-0800\n # Other matched formats:\n # 2007-02-15 13:50:29 (UTC-0800)\n # 2007-02-15 13:50:29 (UTC-08:00)\n s/(\\d{4}-\\d{2}-\\d{2}([T ])\\d{2}:\\d{2}:\\d{2})(?:\\.\\d+)? ?(?:\\(UTC)?([+\\-]\\d{2})?:?00\\)?/Time::Piece-&gt;strptime ($1, \"%Y-%m-%d$2%H:%M:%S\")-&gt;epoch - (defined ($3) ? $3 * 3600 : 0)/eg;\n print;\n}\nmartind@whitewater:~$ \n</code></pre>\n" }, { "answer_id": 95806, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 2, "selected": false, "text": "<p>My favorite datetime parser is <a href=\"http://search.cpan.org/perldoc?DateTime::Format::ISO8601\" rel=\"nofollow noreferrer\">DateTime::Format::ISO8601</a> Once you've got that working, you'll have a DateTime object, easily convertable to epoch seconds with epoch()</p>\n" }, { "answer_id": 95838, "author": "scottc", "author_id": 7408, "author_profile": "https://Stackoverflow.com/users/7408", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://metacpan.org/pod/Date::Manip\" rel=\"nofollow noreferrer\">Get Date::Manip from CPAN</a>, then:</p>\n\n<pre><code>use Date::Manip;\n$string = '18-Sep-2008 20:09'; # or a wide range of other date formats\n$unix_time = UnixDate( ParseDate($string), \"%s\" );\n</code></pre>\n\n<p>edit:</p>\n\n<p>Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.</p>\n\n<p>e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.</p>\n\n<p>See <a href=\"https://metacpan.org/pod/Date::Manip::Misc#SHOULD-I-USE-DATE::MANIP\" rel=\"nofollow noreferrer\">the authors comments</a>.</p>\n\n<p>(Thanks to the author of the first comment below)</p>\n" }, { "answer_id": 96515, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 2, "selected": false, "text": "<p>Possibly one of the better examples of 'There's More Than One Way To Do It\", with or without the help of CPAN.</p>\n\n<p>If you have control over what you get passed as a 'date/time', I'd suggest going the <a href=\"https://metacpan.org/pod/DateTime\" rel=\"nofollow noreferrer\">DateTime</a> route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the <a href=\"http://datetime.perl.org/index.cgi?FAQBasicUsage\" rel=\"nofollow noreferrer\">datetime FAQ</a> for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.</p>\n\n<p>If you're expecting weird freeform stuff, throw it at <a href=\"http://search.cpan.org/dist/TimeDate/\" rel=\"nofollow noreferrer\">Date::Parse</a>'s str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of <a href=\"https://metacpan.org/pod/Date::Manip\" rel=\"nofollow noreferrer\">Date::Manip</a>.</p>\n" }, { "answer_id": 96591, "author": "Shlomi Fish", "author_id": 7709, "author_profile": "https://Stackoverflow.com/users/7709", "pm_score": 2, "selected": false, "text": "<p>There are many Date manipulation modules on CPAN. My particular favourite is <a href=\"http://search.cpan.org/dist/DateTime/\" rel=\"nofollow noreferrer\">DateTime</a> and you can use the <a href=\"http://search.cpan.org/search?query=strptime&amp;mode=all\" rel=\"nofollow noreferrer\">strptime modules</a> to parse dates in arbitrary formats. There are also many DateTime::Format modules on CPAN for handling specialised date formats, but strptime is the most generic.</p>\n" }, { "answer_id": 125869, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "<pre><code>$ENV{TZ}=\"GMT\";\nPOSIX::tzset();\n$time = POSIX::mktime($s,$m,$h,$d,$mo-1,$y-1900);\n</code></pre>\n" }, { "answer_id": 2499485, "author": "Anders", "author_id": 127751, "author_profile": "https://Stackoverflow.com/users/127751", "pm_score": 2, "selected": false, "text": "<p>For further reference, a one liner that can be applied in, for example, <code>!#/bin/sh</code> scripts.</p>\n\n<pre><code>EPOCH=\"`perl -e 'use Time::Local; print timelocal('${SEC}','${MIN}','${HOUR}','${DAY}','${MONTH}','${YEAR}'),\\\"\\n\\\";'`\"\n</code></pre>\n\n<p>Just remember to avoid octal values!</p>\n" }, { "answer_id": 28484217, "author": "Sobrique", "author_id": 2566198, "author_profile": "https://Stackoverflow.com/users/2566198", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question, but thought I would offer another answer. </p>\n\n<p><a href=\"https://metacpan.org/pod/Time::Piece\" rel=\"noreferrer\"><code>Time::Piece</code></a> is core as of Perl 5.9.5 </p>\n\n<p>This allows parsing of time in arbitrary formats via the <code>strptime</code> method. </p>\n\n<p>e.g.:</p>\n\n<pre><code>my $t = Time::Piece-&gt;strptime(\"Sunday 3rd Nov, 1943\",\n \"%A %drd %b, %Y\");\n</code></pre>\n\n<p>The useful part is - because it's an overloaded object, you can use it for numeric comparisons.</p>\n\n<p>e.g. </p>\n\n<pre><code>if ( $t &lt; time() ) { #do something }\n</code></pre>\n\n<p>Or if you access it in a string context:</p>\n\n<pre><code>print $t,\"\\n\"; \n</code></pre>\n\n<p>You get:</p>\n\n<pre><code>Wed Nov 3 00:00:00 1943\n</code></pre>\n\n<p>There's a bunch of accessor methods that allow for some assorted other useful time based transforms. <a href=\"https://metacpan.org/pod/Time::Piece\" rel=\"noreferrer\">https://metacpan.org/pod/Time::Piece</a></p>\n" }, { "answer_id": 60908148, "author": "NotThat JohnSmith", "author_id": 13144150, "author_profile": "https://Stackoverflow.com/users/13144150", "pm_score": 0, "selected": false, "text": "<p>I'm using a very old O/S that I don't dare install libraries onto, so here's what I use;</p>\n\n<pre><code>%MonthMatrix=(\"Jan\",0,\"Feb\",31,\"Mar\",59,\"Apr\",90,\"May\",120,\"Jun\",151,\"Jul\",181,\"Aug\",212,\"Sep\",243,\"Oct\",273,\"Nov\",304,\"Dec\",334);\n$LeapYearCount=int($YearFourDigits/4);\n$EpochDayNumber=$MonthMatrix{$MonthThreeLetters};\nif ($LeapYearCount==($YearFourDigits/4)) { if ($EpochDayNumber&lt;32) { $EpochDayNumber--; }}\n$EpochDayNumber=($YearFourDigits-1970)*365+$LeapYearCount+$EpochDayNumber+$DayAsNumber-493;\n$TimeOfDaySeconds=($HourAsNumber*3600)+($MinutesAsNumber*60)+$SecondsAsNumber;\n$ActualEpochTime=($EpochDayNumber*86400)+$TimeOfDaySeconds;\n</code></pre>\n\n<p>The input variables are;</p>\n\n<pre><code>$MonthThreeLetters\n$DayAsNumber\n$YearFourDigits\n$HourAsNumber\n$MinutesAsNumber\n$SecondsAsNumber\n</code></pre>\n\n<p>...which should be self-explanatory.</p>\n\n<p>The input variables, of course, assume GMT (UTC). The output variable is \"$ActualEpochTime\". (Often, I only need $EpochDayNumber, so that's why that otherwise superfluous variable sits on its own.)</p>\n\n<p>I've used this formula for years with nary an error.</p>\n" }, { "answer_id": 74570979, "author": "gpwr", "author_id": 2870624, "author_profile": "https://Stackoverflow.com/users/2870624", "pm_score": 0, "selected": false, "text": "<p>Here is a quick example that uses the Perl module Time::Local</p>\n<pre><code>use Time::Local;\n$number_of_seconds = timelocal(0,24,2, 26,3,2022); \n</code></pre>\n<p>The arguments timelocal needs are: second, minute, hour, day, month, year</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT? Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array?
This is the simplest way to get unix time: ``` use Time::Local; timelocal($second,$minute,$hour,$day,$month-1,$year); ``` Note the reverse order of the arguments and that January is month 0. For many more options, see the [DateTime](https://metacpan.org/pod/DateTime) module from CPAN. As for parsing, see the [Date::Parse](https://metacpan.org/pod/Date::Parse) module from CPAN. If you really need to get fancy with date parsing, the [Date::Manip](https://metacpan.org/pod/Date::Manip) may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster. If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module [DateTime::Format::ISO8601](https://metacpan.org/pod/DateTime::Format::ISO8601). --- For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the "HMS" part optional. It accepts any delimiters (eg, "2009-02-15" or "2009.02.15"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to "69" refer to "20XX", otherwise "19XX" (eg, "50-02-15" means 2050-02-15 but "75-02-15" means 1975-02-15). ``` use Time::Local; sub parsedate { my($s) = @_; my($year, $month, $day, $hour, $minute, $second); if($s =~ m{^\s*(\d{1,4})\W*0*(\d{1,2})\W*0*(\d{1,2})\W*0* (\d{0,2})\W*0*(\d{0,2})\W*0*(\d{0,2})}x) { $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; $hour |= 0; $minute |= 0; $second |= 0; # defaults. $year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year); return timelocal($second,$minute,$hour,$day,$month-1,$year); } return -1; } ```
95,500
<p>While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure:</p> <pre><code>#define STRUCTSIZE(s) (sizeof(s) / sizeof(*s)) </code></pre> <p>Very useful as it is but can it be converted into an inline function or template?</p> <p>OK, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.</p>
[ { "answer_id": 95518, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 1, "selected": false, "text": "<ul>\n<li>function, no template function, yes</li>\n<li>template, I think so (but C++</li>\n<li>templates are not my thing)</li>\n</ul>\n\n<p><strong>Edit:</strong> From Doug's code</p>\n\n<pre><code>template &lt;typename T&gt;\nuint32_t StructSize() // This might get inlined to a constant at compile time\n{\n return sizeof(T)/sizeof(*T);\n}\n\n// or to get it at compile time for shure\n\nclass StructSize&lt;typename T&gt;\n{\n enum { result = sizeof(T)/sizeof(*T) };\n}\n</code></pre>\n\n<p>I've been told that the 2nd one doesn't work. OTOH something like it should be workable, I just don't use C++ enough to fix it.</p>\n\n<p><a href=\"http://www.digitalmars.com/d/2.0/templates-revisited.html\" rel=\"nofollow noreferrer\">A page on C++ (and D) templates for compile time stuff</a></p>\n" }, { "answer_id": 95521, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>Yes it can be made a template in C++</p>\n\n<pre><code>template &lt;typename T&gt;\nsize_t getTypeSize()\n{\n return sizeof(T)/sizeof(*T);\n}\n</code></pre>\n\n<p>to use:</p>\n\n<pre><code>struct JibbaJabba\n{\n int int1;\n float f;\n};\n\nint main()\n{\n cout &lt;&lt; \"sizeof JibbaJabba is \" &lt;&lt; getTypeSize&lt;JibbaJabba&gt;() &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n\n<p>See BCS's post above or below about a cool way to do this with a class at compile time using some light template metaprogramming.</p>\n" }, { "answer_id": 95550, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 0, "selected": false, "text": "<p>I don't think that that really does work out the number of elements in a structure. If the structure is packed and you used things smaller than the pointer size (such as char on a 32-bit system) then your results are wrong. Also, if the struct contains a struct you are wrong too!</p>\n" }, { "answer_id": 95633, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 1, "selected": false, "text": "<p>Your macro is misnamed, it should be called ARRAYSIZE. It is used to determine the number of elements in an array whos size is fixed at compile time. Here's a way it can work:</p>\n\n<blockquote>\n <p>char foo[ 128 ]; // In reality, you'd\n have some constant or constant\n expression as the array size. </p>\n \n <p>for( unsigned i = 0; i &lt; STRUCTSIZE(\n foo ); ++i ) { }</p>\n</blockquote>\n\n<p>It's kind of brittle to use, because you can make this mistake:</p>\n\n<blockquote>\n <p>char* foo = new char[128];</p>\n \n <p>for( unsigned i = 0; i &lt; STRUCTSIZE(\n foo ); ++i ) { }</p>\n</blockquote>\n\n<p>You will now iterate for i = 0 to &lt; 1 and tear your hair out.</p>\n" }, { "answer_id": 95664, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "<p>The type of a template function is inferred automatically, in contrast with that of a template class. You can use it even simpler:</p>\n\n<pre><code>template&lt; typename T &gt; size_t structsize( const T&amp; t ) { \n return sizeof( t ) / sizeof( *t ); \n}\n\n\nint ints[] = { 1,2,3 };\nassert( structsize( ints ) == 3 );\n</code></pre>\n\n<p>But I do agree it doesn't work for structs: it works for arrays. So I would rather call it Arraysize :)</p>\n" }, { "answer_id": 95714, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>The macro has a very misleading name - the expression in the macro will return the number of elements in an array if an array's name is passed in as the macro parameter.</p>\n\n<p>For other types you'll get something more or less meaningless if the type is a pointer or you'll get a syntax error.</p>\n\n<p>Usually that macro is named something like NUM_ELEMENTS() or something to indicate its true usefulness. It's not possible to replace the macro with a function in C, but in C++ a template can be used.</p>\n\n<p>The version I use is based on code in Microsoft's winnt.h header (please let me know if posting this snippet goes beyond fair use):</p>\n\n<pre><code>//\n// Return the number of elements in a statically sized array.\n// DWORD Buffer[100];\n// RTL_NUMBER_OF(Buffer) == 100\n// This is also popularly known as: NUMBER_OF, ARRSIZE, _countof, NELEM, etc.\n//\n#define RTL_NUMBER_OF_V1(A) (sizeof(A)/sizeof((A)[0]))\n\n#if defined(__cplusplus) &amp;&amp; \\\n !defined(MIDL_PASS) &amp;&amp; \\\n !defined(RC_INVOKED) &amp;&amp; \\\n !defined(_PREFAST_) &amp;&amp; \\\n (_MSC_FULL_VER &gt;= 13009466) &amp;&amp; \\\n !defined(SORTPP_PASS)\n//\n// RtlpNumberOf is a function that takes a reference to an array of N Ts.\n//\n// typedef T array_of_T[N];\n// typedef array_of_T &amp;reference_to_array_of_T;\n//\n// RtlpNumberOf returns a pointer to an array of N chars.\n// We could return a reference instead of a pointer but older compilers do not accept that.\n//\n// typedef char array_of_char[N];\n// typedef array_of_char *pointer_to_array_of_char;\n//\n// sizeof(array_of_char) == N\n// sizeof(*pointer_to_array_of_char) == N\n//\n// pointer_to_array_of_char RtlpNumberOf(reference_to_array_of_T);\n//\n// We never even call RtlpNumberOf, we just take the size of dereferencing its return type.\n// We do not even implement RtlpNumberOf, we just decare it.\n//\n// Attempts to pass pointers instead of arrays to this macro result in compile time errors.\n// That is the point.\n//\nextern \"C++\" // templates cannot be declared to have 'C' linkage\ntemplate &lt;typename T, size_t N&gt;\nchar (*RtlpNumberOf( UNALIGNED T (&amp;)[N] ))[N];\n\n#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))\n\n//\n// This does not work with:\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// RTL_NUMBER_OF_V2(y); // illegal use of anonymous local type in template instantiation\n// }\n//\n// You must instead do:\n//\n// struct Foo1 { int x; };\n//\n// void Foo()\n// {\n// Foo1 y[2];\n// RTL_NUMBER_OF_V2(y); // ok\n// }\n//\n// OR\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// RTL_NUMBER_OF_V1(y); // ok\n// }\n//\n// OR\n//\n// void Foo()\n// {\n// struct { int x; } y[2];\n// _ARRAYSIZE(y); // ok\n// }\n//\n\n#else\n#define RTL_NUMBER_OF_V2(A) RTL_NUMBER_OF_V1(A)\n#endif\n\n#ifdef ENABLE_RTL_NUMBER_OF_V2\n#define RTL_NUMBER_OF(A) RTL_NUMBER_OF_V2(A)\n#else\n#define RTL_NUMBER_OF(A) RTL_NUMBER_OF_V1(A)\n#endif\n\n//\n// ARRAYSIZE is more readable version of RTL_NUMBER_OF_V2, and uses\n// it regardless of ENABLE_RTL_NUMBER_OF_V2\n//\n// _ARRAYSIZE is a version useful for anonymous types\n//\n#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A)\n#define _ARRAYSIZE(A) RTL_NUMBER_OF_V1(A)\n</code></pre>\n\n<p>Also, Matthew Wilson's book \"Imperfect C++\" has a nice treatment of what's going on here (Section 14.3 - page 211-213 - Arrays and Pointers - dimensionof()).</p>\n" }, { "answer_id": 95896, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 5, "selected": true, "text": "<p>As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array.</p>\n\n<pre><code>template&lt;typename T,int SIZE&gt;\ninline size_t array_size(const T (&amp;array)[SIZE])\n{\n return SIZE;\n}\n</code></pre>\n\n<p>The above is similar to <a href=\"https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#95664\">xtofl's</a>, except it guards against passing a pointer to it (that says point to a dynamically allocated array) and getting the wrong answer by mistake.</p>\n\n<p><strong>EDIT</strong>: Simplified as per <a href=\"https://stackoverflow.com/users/1674/johnmcg\">JohnMcG</a>.\n<strong>EDIT</strong>: inline.</p>\n\n<p>Unfortunately, the above does not provide a compile time answer (even if the compiler does inline &amp; optimize it to be a constant under the hood), so cannot be used as a compile time constant expression. i.e. It cannot be used as size to declare a static array. Under C++0x, this problem go away if one replaces the keyword <em>inline</em> by <em>constexpr</em> (constexpr is inline implicitly).</p>\n\n<pre><code>constexpr size_t array_size(const T (&amp;array)[SIZE])\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#97523\">jwfearn's</a> solution work for compile time, but involve having a typedef which effectively \"saved\" the array size in the declaration of a new name. The array size is then worked out by initialising a constant via that new name. In such case, one may as well simply save the array size into a constant from the start.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#98059\">Martin York's</a> posted solution also work under compile time, but involve using the non-standard <em>typeof()</em> operator. The work around to that is either wait for C++0x and use <em>decltype</em> (by which time one wouldn't actually need it for this problem as we'll have <em>constexpr</em>). Another alternative is to use Boost.Typeof, in which case we'll end up with</p>\n\n<pre><code>#include &lt;boost/typeof/typeof.hpp&gt;\n\ntemplate&lt;typename T&gt;\nstruct ArraySize\n{\n private: static T x;\n public: enum { size = sizeof(T)/sizeof(*x)};\n};\ntemplate&lt;typename T&gt;\nstruct ArraySize&lt;T*&gt; {};\n</code></pre>\n\n<p>and is used by writing</p>\n\n<pre><code>ArraySize&lt;BOOST_TYPEOF(foo)&gt;::size\n</code></pre>\n\n<p>where <em>foo</em> is the name of an array.</p>\n" }, { "answer_id": 96038, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 0, "selected": false, "text": "<p>xtofl has the right answer for finding an array size. No macro or template should be necessary for finding the size of a struct, since sizeof() should do nicely.</p>\n\n<p>I agree the <a href=\"http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.8\" rel=\"nofollow noreferrer\">preprocessor is evil</a>, but there are occasions where it is the <a href=\"http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.16\" rel=\"nofollow noreferrer\">least evil of the alternatives</a>.</p>\n" }, { "answer_id": 96085, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 1, "selected": false, "text": "<p>Simplfying @KTC's, since we have the size of the array in the template argument:</p>\n\n<pre><code>template&lt;typename T, int SIZE&gt;\nint arraySize(const T(&amp;arr)[SIZE])\n{\n return SIZE;\n}\n</code></pre>\n\n<p>Disadvantage is you will have a copy of this in your binary for every Typename, Size combination.</p>\n" }, { "answer_id": 96227, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 0, "selected": false, "text": "<p>As JohnMcG's answer, but </p>\n\n<p><em>Disadvantage is you will have a copy of this in your binary for every Typename, Size combination.</em></p>\n\n<p>That's why you'd make it an <strong>inline</strong> template function.</p>\n" }, { "answer_id": 96291, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Answered in detail here:\n<a href=\"http://heifner.blogspot.com/2008/04/c-array-size-determination.html\" rel=\"nofollow noreferrer\">Array Size determination Part 1</a>\nand here:\n<a href=\"http://heifner.blogspot.com/2008/04/c-array-size-determination-part-2.html\" rel=\"nofollow noreferrer\">Array Size determination Part 2</a>.</p>\n" }, { "answer_id": 97523, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/12868/ktc\">KTC</a>'s solution is clean but it can't be used at compile-time and it is dependent on compiler optimization to prevent code-bloat and function call overhead.</p>\n\n<p>One can calculate array size with a compile-time-only metafunction with zero runtime cost. <a href=\"https://stackoverflow.com/users/1343/bcs\">BCS</a> was on the right track but that solution is incorrect.</p>\n\n<p>Here's my solution:</p>\n\n<pre><code>// asize.hpp\ntemplate &lt; typename T &gt;\nstruct asize; // no implementation for all types...\n\ntemplate &lt; typename T, size_t N &gt;\nstruct asize&lt; T[N] &gt; { // ...except arrays\n static const size_t val = N;\n};\n\ntemplate&lt; size_t N &gt;\nstruct count_type { char val[N]; };\n\ntemplate&lt; typename T, size_t N &gt;\ncount_type&lt; N &gt; count( const T (&amp;)[N] ) {}\n\n#define ASIZE( a ) ( sizeof( count( a ).val ) ) \n#define ASIZET( A ) ( asize&lt; A &gt;::val ) \n</code></pre>\n\n<p>with test code (using <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_staticassert.html\" rel=\"nofollow noreferrer\">Boost.StaticAssert</a> to demonstrate compile-time-only usage):</p>\n\n<pre><code>// asize_test.cpp\n#include &lt;boost/static_assert.hpp&gt;\n#include \"asize.hpp\"\n\n#define OLD_ASIZE( a ) ( sizeof( a ) / sizeof( *a ) )\n\ntypedef char C;\ntypedef struct { int i; double d; } S;\ntypedef C A[42];\ntypedef S B[42];\ntypedef C * PA;\ntypedef S * PB;\n\nint main() {\n A a; B b; PA pa; PB pb;\n BOOST_STATIC_ASSERT( ASIZET( A ) == 42 );\n BOOST_STATIC_ASSERT( ASIZET( B ) == 42 );\n BOOST_STATIC_ASSERT( ASIZET( A ) == OLD_ASIZE( a ) );\n BOOST_STATIC_ASSERT( ASIZET( B ) == OLD_ASIZE( b ) );\n BOOST_STATIC_ASSERT( ASIZE( a ) == OLD_ASIZE( a ) );\n BOOST_STATIC_ASSERT( ASIZE( b ) == OLD_ASIZE( b ) );\n BOOST_STATIC_ASSERT( OLD_ASIZE( pa ) != 42 ); // logic error: pointer accepted\n BOOST_STATIC_ASSERT( OLD_ASIZE( pb ) != 42 ); // logic error: pointer accepted\n // BOOST_STATIC_ASSERT( ASIZE( pa ) != 42 ); // compile error: pointer rejected\n // BOOST_STATIC_ASSERT( ASIZE( pb ) != 42 ); // compile error: pointer rejected\n return 0;\n}\n</code></pre>\n\n<p>This solution rejects non-array types at compile time so it will not get confused by pointers as the macro version does.</p>\n" }, { "answer_id": 98059, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "<p>I prefer the enum method suggested by [BCS](in <a href=\"https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#95518\">Can this macro be converted to a function?</a>)</p>\n\n<p>This is because you can use it where the compiler is expecting a compile time constant. The current version of the language does not let you use functions results for compile time consts but I believe this coming in the next version of the compiler:</p>\n\n<p>The problem with this method is that it does not generate a compile time error when used with a class that has overloaded the '*' operator (see code below for details).</p>\n\n<p>Unfortunately the version supplied by 'BCS' does not quite compile as expected so here is my version:</p>\n\n<pre><code>#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\n\ntemplate&lt;typename T&gt;\nstruct StructSize\n{\n private: static T x;\n public: enum { size = sizeof(T)/sizeof(*x)};\n};\n\ntemplate&lt;typename T&gt;\nstruct StructSize&lt;T*&gt;\n{\n /* Can only guarantee 1 item (maybe we should even disallow this situation) */\n //public: enum { size = 1};\n};\n\nstruct X\n{\n int operator *();\n};\n\n\nint main(int argc,char* argv[])\n{\n int data[] = {1,2,3,4,5,6,7,8};\n int copy[ StructSize&lt;typeof(data)&gt;::size];\n\n std::copy(&amp;data[0],&amp;data[StructSize&lt;typeof(data)&gt;::size],&amp;copy[0]);\n std::copy(&amp;copy[0],&amp;copy[StructSize&lt;typeof(copy)&gt;::size],std::ostream_iterator&lt;int&gt;(std::cout,\",\"));\n\n /*\n * For extra points we should make the following cause the compiler to generate an error message */\n X bad1;\n X bad2[StructSize&lt;typeof(bad1)&gt;::size];\n}\n</code></pre>\n" }, { "answer_id": 100495, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 0, "selected": false, "text": "<p>Windows specific:</p>\n\n<p>There is the macro <code>_countof()</code> supplied by the CRT exactly for this purpose.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms175773(VS.80).aspx\" rel=\"nofollow noreferrer\">A link to the doc at MSDN</a></p>\n" }, { "answer_id": 100872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>None has so far proposed a portable way to get the size of an array when you only have an instance of an array and not its type. (typeof and _countof is not portable so can't be used.)</p>\n\n<p>I'd do it the following way:</p>\n\n<pre><code>template&lt;int n&gt;\nstruct char_array_wrapper{\n char result[n];\n};\n\ntemplate&lt;typename T, int s&gt;\nchar_array_wrapper&lt;s&gt; the_type_of_the_variable_is_not_an_array(const T (&amp;array)[s]){\n}\n\n\n#define ARRAYSIZE_OF_VAR(v) sizeof(the_type_of_the_variable_is_not_an_array(v).result)\n\n#include &lt;iostream&gt;\nusing namespace std;\n\nint main(){\n int foo[42];\n int*bar;\n cout&lt;&lt;ARRAYSIZE_OF_VAR(foo)&lt;&lt;endl;\n // cout&lt;&lt;ARRAYSIZE_OF_VAR(bar)&lt;&lt;endl; fails\n}\n</code></pre>\n\n<ul>\n<li>It works when only the value is around.</li>\n<li>It is portable and only uses std-C++.</li>\n<li>It fails with a descriptiv error message.</li>\n<li>It does not evaluate the value. (I can't think up of a situation where this would be a problem because array type can't be returned by a function, but better be safe than sorry.)</li>\n<li>It returns the size as compiletime constant.</li>\n</ul>\n\n<p>I wrapped the construct into a macro to have some decent syntax. If you want to get rid of it your only option is to do the substitution manually.</p>\n" }, { "answer_id": 175209, "author": "Josh Kelley", "author_id": 25507, "author_profile": "https://Stackoverflow.com/users/25507", "pm_score": 0, "selected": false, "text": "<p>For C99-style variable-length arrays, it appears that the pure macro approach (sizeof(arr) / sizeof(arr[0])) is the only one that will work.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure: ``` #define STRUCTSIZE(s) (sizeof(s) / sizeof(*s)) ``` Very useful as it is but can it be converted into an inline function or template? OK, ARRAYSIZE would be a better name but this is legacy code (no idea where it came from, it's at least 15 years old) so I pasted it 'as is'.
As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array. ``` template<typename T,int SIZE> inline size_t array_size(const T (&array)[SIZE]) { return SIZE; } ``` The above is similar to [xtofl's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#95664), except it guards against passing a pointer to it (that says point to a dynamically allocated array) and getting the wrong answer by mistake. **EDIT**: Simplified as per [JohnMcG](https://stackoverflow.com/users/1674/johnmcg). **EDIT**: inline. Unfortunately, the above does not provide a compile time answer (even if the compiler does inline & optimize it to be a constant under the hood), so cannot be used as a compile time constant expression. i.e. It cannot be used as size to declare a static array. Under C++0x, this problem go away if one replaces the keyword *inline* by *constexpr* (constexpr is inline implicitly). ``` constexpr size_t array_size(const T (&array)[SIZE]) ``` [jwfearn's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#97523) solution work for compile time, but involve having a typedef which effectively "saved" the array size in the declaration of a new name. The array size is then worked out by initialising a constant via that new name. In such case, one may as well simply save the array size into a constant from the start. [Martin York's](https://stackoverflow.com/questions/95500/can-this-macro-be-converted-to-a-function#98059) posted solution also work under compile time, but involve using the non-standard *typeof()* operator. The work around to that is either wait for C++0x and use *decltype* (by which time one wouldn't actually need it for this problem as we'll have *constexpr*). Another alternative is to use Boost.Typeof, in which case we'll end up with ``` #include <boost/typeof/typeof.hpp> template<typename T> struct ArraySize { private: static T x; public: enum { size = sizeof(T)/sizeof(*x)}; }; template<typename T> struct ArraySize<T*> {}; ``` and is used by writing ``` ArraySize<BOOST_TYPEOF(foo)>::size ``` where *foo* is the name of an array.
95,510
<p>I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?</p>
[ { "answer_id": 95533, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 2, "selected": false, "text": "<p>Check for the registry value at HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System</p>\n\n<p>The EnableLUA value determines if UAC is active.</p>\n" }, { "answer_id": 95538, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html\" rel=\"nofollow noreferrer\">This post</a> has sample code in C# to test if UAC is on and if the current app has been given elevated rights. You can download the code and interpret as needed. Also linked there is a sample that shows the same in C++ </p>\n\n<p><a href=\"http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html\" rel=\"nofollow noreferrer\">http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html</a> </p>\n\n<p>The code in that post does not just read from the registry. If UAC is enabled, chances are you may not have rights to read that from the registry. </p>\n" }, { "answer_id": 95540, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": -1, "selected": false, "text": "<p>AFAIK, UAC is apolicy setting on the local user or group. So you can read this property from within .Net. Sorry for not having more details but I hope this helps</p>\n" }, { "answer_id": 95605, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 5, "selected": true, "text": "<p>This registry key should tell you:</p>\n\n<pre><code>HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\n</code></pre>\n\n<p>Value <code>EnableLUA (DWORD)</code></p>\n\n<p><code>1</code> enabled / <code>0</code> or missing disabled</p>\n\n<p>But that assumes you have the rights to read it. </p>\n\n<p>Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see <a href=\"http://blogs.msdn.com/cjacks/archive/2006/10/09/How-to-Determine-if-a-User-is-a-Member-of-the-Administrators-Group-with-UAC-Enabled-on-Windows-Vista.aspx\" rel=\"nofollow noreferrer\">here</a>). Not foolproof, but it may work.</p>\n\n<p>The issue here is more of a \"why do you need to know\" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem. </p>\n" }, { "answer_id": 95646, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 2, "selected": false, "text": "<p>You can do it be examining the DWORD value <strong>EnableLUA</strong> in the following registry key:</p>\n\n<p>HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System</p>\n\n<p>If the value is 0 (or does not exist) then the UAC is OFF. If it's present and non-zero, then UAC is ON:</p>\n\n<pre><code>BOOL IsUacEnabled( )\n{\n LPCTSTR pszSubKey = _T(\"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\");\n LPCTSTR pszValue = _T(\"EnableLUA\");\n DWORD dwType = 0;\n DWORD dwValue = 0;\n DWORD dwValueSize = sizeof( DWORD );\n\n if ( ERROR_SUCCESS != SHGetValue( HKEY_LOCAL_MACHINE, pszSubKey, pszValueOn, \n &amp;dwType, &amp;dwValue, &amp;dwValueSize) )\n {\n return FALSE;\n }\n\n return dwValue != 0;\n} \n</code></pre>\n\n<p>Note that if the user has changed the state of UAC but has not restarted the computer yet, this function will return an inconsistent result. </p>\n" }, { "answer_id": 6114816, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "<p>You don't want to check if UAC is enabled; that doesn't tell you anything.</p>\n\n<p>I can be a standard user with UAC disabled.</p>\n\n<p>You want to check <a href=\"http://msdn.microsoft.com/en-us/library/aa376389.aspx\" rel=\"nofollow\">if the user is running with administrative privileges using <code>CheckTokenMembership</code></a>:</p>\n\n<pre><code>///This function tells us if we're running with administrative permissions.\nfunction IsUserAdmin: Boolean;\nvar\n b: BOOL;\n AdministratorsGroup: PSID;\nbegin\n {\n This function returns true if you are currently running with \n admin privileges.\n In Vista and later, if you are non-elevated, this function will \n return false (you are not running with administrative privileges).\n If you *are* running elevated, then IsUserAdmin will return \n true, as you are running with admin privileges.\n\n Windows provides this similar function in Shell32.IsUserAnAdmin.\n But the function is depricated, and this code is lifted from the \n docs for CheckTokenMembership: \n http://msdn.microsoft.com/en-us/library/aa376389.aspx\n }\n\n {\n Routine Description: This routine returns TRUE if the caller's\n process is a member of the Administrators local group. Caller is NOT\n expected to be impersonating anyone and is expected to be able to\n open its own process and process token.\n Arguments: None.\n Return Value:\n TRUE - Caller has Administrators local group.\n FALSE - Caller does not have Administrators local group.\n }\n b := AllocateAndInitializeSid(\n SECURITY_NT_AUTHORITY,\n 2, //2 sub-authorities\n SECURITY_BUILTIN_DOMAIN_RID, //sub-authority 0\n DOMAIN_ALIAS_RID_ADMINS, //sub-authority 1\n 0, 0, 0, 0, 0, 0, //sub-authorities 2-7 not passed\n AdministratorsGroup);\n if (b) then\n begin\n if not CheckTokenMembership(0, AdministratorsGroup, b) then\n b := False;\n FreeSid(AdministratorsGroup);\n end;\n\n Result := b;\nend;\n</code></pre>\n" }, { "answer_id": 12700735, "author": "Nik Bougalis", "author_id": 970543, "author_profile": "https://Stackoverflow.com/users/970543", "pm_score": 2, "selected": false, "text": "<p>This post is rather ancient, but I wanted to comment on the \"why do you need to know\" and \"check token membership\" bits.</p>\n\n<p>The fact is that Microsoft's very own documentation says that \"If User Account Control has been turned off and a Standard user attempts to perform a task that requires elevation\" we should provide an error instead of showing buttons and/or links with the UAC shield that attempt elevation. See <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa511445.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/aa511445.aspx</a> towards the bottom for the details.</p>\n\n<p>How are we do to this without a way of checking whether UAC is enabled?</p>\n\n<p>Perhaps checking whether the user is running with admin privileges is the right thing to do in this instance, but who knows? The guidance that Microsoft gives is, <em>at best</em>, iffy, if not just downright confusing.</p>\n" }, { "answer_id": 14899279, "author": "Mark D. MacLachlan", "author_id": 2076290, "author_profile": "https://Stackoverflow.com/users/2076290", "pm_score": 1, "selected": false, "text": "<p>For anyone else that finds this and is looking for a VBScript solution. Here is what I came up with to detect if UAC is enabled and if so relaunch my script with elevated privileges. Just put your code in the Body() function. I found there were problems with transportability between XP and Windows 7 if I wrote code to always launch elevated. Using this method I bypass the elevation if there is no UAC. Should also take into account 2008 and above server versions that have UAC enabled.</p>\n\n<pre><code>On Error Resume Next\nUACPath = \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\EnableLUA\"\nDim WshShell\nSet WshShell = CreateObject(\"wscript.Shell\")\nUACValue = WshShell.RegRead(UACPath)\nIf UACValue = 1 Then\n'Run Elevated\n If WScript.Arguments.length =0 Then\n Set objShell = CreateObject(\"Shell.Application\")\n 'Pass a bogus argument with leading blank space, say [ uac]\n objShell.ShellExecute \"wscript.exe\", Chr(34) &amp; _\n WScript.ScriptFullName &amp; Chr(34) &amp; \" uac\", \"\", \"runas\", 1\n WScript.Quit\n Else \n Body()\n End If\nElse\nBody()\nEnd If\n\nFunction Body()\nMsgBox \"This is the body of the script\"\nEnd Function\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ]
I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?
This registry key should tell you: ``` HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System ``` Value `EnableLUA (DWORD)` `1` enabled / `0` or missing disabled But that assumes you have the rights to read it. Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see [here](http://blogs.msdn.com/cjacks/archive/2006/10/09/How-to-Determine-if-a-User-is-a-Member-of-the-Administrators-Group-with-UAC-Enabled-on-Windows-Vista.aspx)). Not foolproof, but it may work. The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem.
95,543
<p>I am trying to merge a directory in subversion, but I get the following error when I do so:</p> <pre><code>svn: Working copy '[directory name]' not locked' </code></pre> <p>I tried deleting the working directory and doing a fresh update, but that did not solve the issue. I also did a cleanup on the directory. </p> <p>Does anyone know how to fix this?</p> <p>In this instance, the parent directory has the same name as the sub directory. I don't know if this has anything to do with the error though.</p>
[ { "answer_id": 95560, "author": "EmmEff", "author_id": 9188, "author_profile": "https://Stackoverflow.com/users/9188", "pm_score": 2, "selected": false, "text": "<p>Check out this blog posting (<a href=\"http://news.e-scribe.com/145\" rel=\"nofollow noreferrer\">Obscure \"svn mv\" problem solved</a>)... I typically just remove the directory and grab fresh sources.</p>\n" }, { "answer_id": 95677, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": -1, "selected": false, "text": "<p>Try doing a clean-up and then an update. If that not work, please explain better your issue.</p>\n" }, { "answer_id": 95687, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 0, "selected": false, "text": "<p>Are you by chance using TortoiseSVN and some other client (Such as subversive or the commandline client?). Sometimes Tortoise can unintentionally gum up other clients. I don't remember what exactly causes this to happen.</p>\n" }, { "answer_id": 96026, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 0, "selected": false, "text": "<p>Without seeing your exact directory setup it's hard to say what is happening. One reason for this error message could be that one part of your merge command does refer to a directory that is not under version control.</p>\n\n<p>Can you post the exact merge command that triggers the error?</p>\n" }, { "answer_id": 635287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I got this error using IDEA. I got around this by doing a tortoise svn cleanup in windows explorer, the equivalent cleanup in IDEA did not work.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215086/" ]
I am trying to merge a directory in subversion, but I get the following error when I do so: ``` svn: Working copy '[directory name]' not locked' ``` I tried deleting the working directory and doing a fresh update, but that did not solve the issue. I also did a cleanup on the directory. Does anyone know how to fix this? In this instance, the parent directory has the same name as the sub directory. I don't know if this has anything to do with the error though.
Check out this blog posting ([Obscure "svn mv" problem solved](http://news.e-scribe.com/145))... I typically just remove the directory and grab fresh sources.
95,547
<p>Should I catch exceptions for logging purposes?</p> <pre> public foo(..) { try { ... } catch (Exception ex) { Logger.Error(ex); throw; } } </pre> <p>If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.</p> <p>Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them? Why? Why not? Is there a different approach I could use?</p>
[ { "answer_id": 95573, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 6, "selected": true, "text": "<p>Definitely not. You should find the correct place to <strong>handle</strong> the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.</p>\n" }, { "answer_id": 95591, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 4, "selected": false, "text": "<p>Unless you are going to change the exception, you should only log at the level where you are going to handle the error and not rethrow it. Otherwise your log just has a bunch of \"noise\", 3 or more of the same message logged, once at each layer.</p>\n\n<p>My best practice is:</p>\n\n<ol>\n<li>Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)</li>\n<li>Only log in the UI layer right before suppressing the error and redirecting to an error page/form.</li>\n</ol>\n" }, { "answer_id": 95602, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 1, "selected": false, "text": "<p>Use your own exceptions to wrap inbuild exception. This way you can distinct between known and unknown errors when catching exception. This is usefull if you have a method that calls other methods that are likely throwing excpetions to react upon expected and unexpected failures</p>\n" }, { "answer_id": 95608, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 0, "selected": false, "text": "<p>If you're required to log all exceptions, then it's a fantastic idea. That said, logging all exceptions without another reason isn't such a good idea.</p>\n" }, { "answer_id": 95611, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>You may want to log at the highest level, which is usually your UI or web service code. Logging multiple times is sort of a waste. Also, you want to know the whole story when you are looking at the log.</p>\n\n<p>In one of our applications, all of our pages are derived from a BasePage object, and this object handles the exception handling and error logging.</p>\n" }, { "answer_id": 95620, "author": "Lucas S.", "author_id": 7363, "author_profile": "https://Stackoverflow.com/users/7363", "pm_score": 0, "selected": false, "text": "<p>If that's the only thing it does, i think is better to remove the try/catch's from those classes and let the exception be raised to the class that is responsible on handling them. That way you get only one log per exception giving you more clear logs and even you can log the stacktrace so you wont miss from where the exception was originated.</p>\n" }, { "answer_id": 95645, "author": "SmartyP", "author_id": 18005, "author_profile": "https://Stackoverflow.com/users/18005", "pm_score": 1, "selected": false, "text": "<p>you may want to lookup standard exception handling styles, but my understanding is this: handle exceptions at the level where you can add extra detail to the exception, or at the level where you will present the exception to the user.</p>\n\n<p>in your example you are doing nothing but catching the exception, logging it, and throwing it again.. why not just catch it at the highest level with one try/catch instead of inside every method if all you are doing is logging it?</p>\n\n<p>i would only handle it at that tier if you were going to add some useful information to the exception before throwing it again - wrap the exception in a new exception you create that has useful information beyond the low level exception text which usually means little to anyone without some context..</p>\n" }, { "answer_id": 95648, "author": "Karl", "author_id": 17613, "author_profile": "https://Stackoverflow.com/users/17613", "pm_score": 0, "selected": false, "text": "<p>My method is to log the exceptions only in the handler. The 'real' handler so to speak. Otherwise the log will be very hard to read and the code less structured. </p>\n" }, { "answer_id": 95667, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 0, "selected": false, "text": "<p>It depends on the Exception: if this actually should not happen, I definitely would log it. On the other way: if you expect this Exception you should think about the design of the application.</p>\n\n<p>Either way: you should at least try to specify the Exception you want to rethrow, catch or log.</p>\n\n<pre><code>public foo(..)\n{\n try\n {\n ...\n }\n catch (NullReferenceException ex) {\n DoSmth(e);\n }\n catch (ArgumentExcetion ex) {\n DoSmth(e);\n }\n catch (Exception ex) {\n DoSmth(e);\n }\n}\n</code></pre>\n" }, { "answer_id": 95690, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 2, "selected": false, "text": "<p>It's good practice is to <strong>translate the exceptions</strong>. Don't just log them. If you want to know the specific reason an exception was thrown, throw specific exceptions:</p>\n\n<pre><code>public void connect() throws ConnectionException {\n try {\n File conf = new File(\"blabla\");\n ...\n } catch (FileNotFoundException ex) {\n LOGGER.error(\"log message\", ex);\n throw new ConnectionException(\"The configuration file was not found\", ex);\n }\n}\n</code></pre>\n" }, { "answer_id": 95722, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>You will want to log at a tier boundary. For example, if your business tier can be deployed on a physically separate machine in an n-tier application, then it makes sense to log and throw the error in this way. </p>\n\n<p>In this way you have a log of exceptions on the server and don't need to go poking around client machines to find out what happened.</p>\n\n<p>I use this pattern in business tiers of applications that use Remoting or ASMX web services. With WCF you can intercept and log an exception using an IErrorHandler attached to your ChannelDispatcher (another subject entirely) - so you don't need the try/catch/throw pattern.</p>\n" }, { "answer_id": 95773, "author": "Pat", "author_id": 14206, "author_profile": "https://Stackoverflow.com/users/14206", "pm_score": 3, "selected": false, "text": "<p>The general rule of thumb is that you only catch an exception if you can actually do something about it. So at the Business or Data layer, you would only catch the exception in situation's like this:</p>\n<pre><code>try\n{\n this.Persist(trans);\n}\ncatch(Exception ex)\n{\n trans.Rollback();\n throw ex;\n}\n</code></pre>\n<p>My Business/Data Layer attempts to save the data - if an exception is generated, any transactions are rolled back and the exception is sent to the UI layer.</p>\n<p>At the UI layer, you can implement a common exception handler:</p>\n<pre><code>Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);\n</code></pre>\n<p>Which then handles all exceptions. It might log the exception and then display a user friendly response:</p>\n<pre><code>static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)\n{\n LogException(e.Exception);\n}\n\nstatic void LogException(Exception ex)\n{\n YYYExceptionHandling.HandleException(ex,\n YYYExceptionHandling.ExceptionPolicyType.YYY_Policy,\n YYYExceptionHandling.ExceptionPriority.Medium,\n &quot;An error has occurred, please contact Administrator&quot;);\n} \n</code></pre>\n<p>In the actual UI code, you can catch individual exception's if you are going to do something different - such as display a different friendly message or modify the screen, etc.</p>\n<p>Also, just as a reminder, always try to handle errors - for example divide by 0 - rather than throw an exception.</p>\n" }, { "answer_id": 96217, "author": "Diastrophism", "author_id": 18093, "author_profile": "https://Stackoverflow.com/users/18093", "pm_score": 0, "selected": false, "text": "<p>You need to develop a strategy for handling exceptions. I don't recommend the catch and rethrow. In addition to the superfluous log entries it makes the code harder to read.\nConsider writing to the log in the constructor for the exception. This reserves the try/catch for exceptions that you want to recover from; making the code easier to read. To deal with unexpected or unrecoverable exceptions, you may want a try/catch near the outermost layer of the program to log diagnostic information.</p>\n\n<p>BTW, if this is C++ your catch block is creating a copy of the exception object which can be a potential source of additional problems. Try catching a reference to the exception type:<pre>\n catch (const Exception&amp; ex) { ... }\n</pre></p>\n" }, { "answer_id": 96655, "author": "Andrew Cowenhoven", "author_id": 12281, "author_profile": "https://Stackoverflow.com/users/12281", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.se-radio.net/podcast/2006-07/episode-21-error-handling-pt-2\" rel=\"nofollow noreferrer\">This</a> Software Engineering Radio podcast is a very good reference for best practices in error handling. There are actually 2 lectures.</p>\n" }, { "answer_id": 231732, "author": "David Leppik", "author_id": 18078, "author_profile": "https://Stackoverflow.com/users/18078", "pm_score": 1, "selected": false, "text": "<p>Sometimes you need to log data which is not available where the exception is handled. In that case, it is appropriate to log just to get that information out.</p>\n\n<p>For example (Java pseudocode):</p>\n\n<pre><code>public void methodWithDynamicallyGeneratedSQL() throws SQLException {\n String sql = ...; // Generate some SQL\n try {\n ... // Try running the query\n }\n catch (SQLException ex) {\n // Don't bother to log the stack trace, that will\n // be printed when the exception is handled for real\n logger.error(ex.toString()+\"For SQL: '\"+sql+\"'\");\n throw ex; // Handle the exception long after the SQL is gone\n }\n}\n</code></pre>\n\n<p>This is similar to retroactive logging (my terminology), where you buffer a log of events but don't write them unless there's a trigger event, such as an exception being thrown.</p>\n" }, { "answer_id": 66049440, "author": "Rezwan4029", "author_id": 3485546, "author_profile": "https://Stackoverflow.com/users/3485546", "pm_score": 0, "selected": false, "text": "<p>It's bad practice in general, unless you need to log for very specific reasons.</p>\n<p>With respect in general log exception, it should be handled in root exception handler.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
Should I catch exceptions for logging purposes? ``` public foo(..) { try { ... } catch (Exception ex) { Logger.Error(ex); throw; } } ``` If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times. Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them? Why? Why not? Is there a different approach I could use?
Definitely not. You should find the correct place to **handle** the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.
95,554
<p>I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json"). I tried to register the MIME type again in mime_types.rb but that didn't work. Any suggestions?</p> <p>Thanks.</p>
[ { "answer_id": 95863, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>render :json =&gt; var_containing_my_json, :content_type =&gt; 'text/x-json'\n</code></pre>\n" }, { "answer_id": 95968, "author": "Ben Scofield", "author_id": 6478, "author_profile": "https://Stackoverflow.com/users/6478", "pm_score": 5, "selected": true, "text": "<p>This should work (in an initializer, plugin, or some similar place):</p>\n\n<pre><code>Mime.send(:remove_const, :JSON)\nMime::Type.register \"text/x-json\", :json\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json"). I tried to register the MIME type again in mime\_types.rb but that didn't work. Any suggestions? Thanks.
This should work (in an initializer, plugin, or some similar place): ``` Mime.send(:remove_const, :JSON) Mime::Type.register "text/x-json", :json ```
95,578
<ul> <li>I have an Oracle database backup file (.dmp) that was created with <code>expdp</code>.</li> <li>The .dmp file was an export of an entire database.</li> <li>I need to restore 1 of the schemas from within this dump file.</li> <li>I don't know the names of the schemas inside this dump file.</li> <li>To use <code>impdp</code> to import the data I need the name of the schema to load.</li> </ul> <p>So, I need to inspect the .dmp file and list all of the schemas in it, how do I do that?</p> <hr /> <p><em>Update (2008-09-18 13:02) - More detailed information:</em></p> <p>The impdp command i'm current using is:</p> <pre><code>impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP logfile=IMPORT.LOG </code></pre> <p>And the DPUMP_DIR is correctly configured.</p> <pre><code>SQL&gt; SELECT directory_path 2 FROM dba_directories 3 WHERE directory_name = 'DPUMP_DIR'; DIRECTORY_PATH ------------------------- D:\directory_path\dpump_dir\ </code></pre> <p>And yes, the EXPORT.DMP file is in fact in that folder.</p> <p>The error message I get when I run the <code>impdp</code> command is:</p> <pre><code>Connected to: Oracle Database 10g Enterprise Edition ... ORA-31655: no data or metadata objects selected for the job ORA-39154: Objects from foreign schemas have been removed from import </code></pre> <p>This error message is mostly expected. I need the <code>impdp</code> command be:</p> <pre><code>impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP SCHEMAS=SOURCE_SCHEMA REMAP_SCHEMA=SOURCE_SCHEMA:MY_SCHEMA </code></pre> <p>But to do that, I need the source schema.</p>
[ { "answer_id": 100024, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 3, "selected": false, "text": "<p>Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the <a href=\"http://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_import.htm#sthref354\" rel=\"nofollow noreferrer\">SQLFILE parameter</a> to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.</p>\n" }, { "answer_id": 100032, "author": "Petros", "author_id": 2812, "author_profile": "https://Stackoverflow.com/users/2812", "pm_score": 5, "selected": true, "text": "<p>If you open the DMP file with an editor that can handle big files, you might be able to locate the areas where the schema names are mentioned. Just be sure not to change anything. It would be better if you opened a copy of the original dump.</p>\n" }, { "answer_id": 103454, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 4, "selected": false, "text": "<p><em>Update (2008-09-19 10:05) - Solution:</em></p>\n\n<p><strong>My Solution:</strong> Social engineering, I dug real hard and found someone who knew the schema name.<br>\n<strong>Technical Solution:</strong> Searching the .dmp file <strong>did</strong> yield the schema name.<br>\nOnce I knew the schema name, I searched the dump file and learned where to find it. </p>\n\n<p>Places the Schemas name were seen, in the .dmp file:</p>\n\n<ul>\n<li><p><strong><code>&lt;OWNER_NAME&gt;SOURCE_SCHEMA&lt;/OWNER_NAME&gt;</code></strong>\nThis was seen before each table name/definition.</p></li>\n<li><p><strong><code>SCHEMA_LIST 'SOURCE_SCHEMA'</code></strong>\nThis was seen near the end of the .dmp. </p></li>\n</ul>\n\n<p>Interestingly enough, around the <code>SCHEMA_LIST 'SOURCE_SCHEMA'</code> section, it also had the command line used to create the dump, directories used, par files used, windows version it was run on, and export session settings (language, date formats).</p>\n\n<p>So, problem solved :)</p>\n" }, { "answer_id": 6708618, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 7, "selected": false, "text": "<p><code>impdp</code> exports the DDL of a <code>dmp</code> backup to a file if you use the <a href=\"https://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_import.htm#sthref354\" rel=\"noreferrer\"><code>SQLFILE</code> parameter</a>. For example, put this into a text file </p>\n\n<pre><code>impdp '/ as sysdba' dumpfile=&lt;your .dmp file&gt; logfile=import_log.txt sqlfile=ddl_dump.txt\n</code></pre>\n\n<p>Then check <code>ddl_dump.txt</code> for the tablespaces, users, and schemas in the backup.</p>\n\n<p>According to the documentation, this does not actually modify the database:</p>\n\n<blockquote>\n <p>The SQL is not actually executed, and the target system remains unchanged.</p>\n</blockquote>\n" }, { "answer_id": 14450325, "author": "Peter Wiseman", "author_id": 1998792, "author_profile": "https://Stackoverflow.com/users/1998792", "pm_score": 2, "selected": false, "text": "<p>The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.</p>\n\n<p>Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g. </p>\n\n<pre><code>select value_t \nfrom SYS_IMPORT_TABLE_01 \nwhere name = 'CLIENT_COMMAND' \nand process_order = -59;\n\ncol object_name for a30\ncol processing_status head STATUS for a6\ncol processing_state head STATE for a5\nselect distinct\n object_schema,\n object_name,\n object_type,\n object_tablespace,\n process_order,\n duplicate,\n processing_status,\n processing_state\nfrom sys_import_table_01\nwhere process_order &gt; 0\nand object_name is not null\norder by object_schema, object_name\n/\n</code></pre>\n\n<p><a href=\"http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf\" rel=\"nofollow\">http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf</a></p>\n" }, { "answer_id": 16192910, "author": "slafs", "author_id": 407001, "author_profile": "https://Stackoverflow.com/users/407001", "pm_score": 2, "selected": false, "text": "<p>My solution (similar to KyleLanser's answer) (on a Unix box):</p>\n\n<pre><code>strings dumpfile.dmp | grep SCHEMA_LIST\n</code></pre>\n" }, { "answer_id": 16230116, "author": "DBA", "author_id": 2295045, "author_profile": "https://Stackoverflow.com/users/2295045", "pm_score": 2, "selected": false, "text": "<p>Step 1: Here is one simple example. You have to create a SQL file from the dump file using <code>SQLFILE</code> option.</p>\n\n<p>Step 2: Grep for <code>CREATE USER</code> in the generated SQL file (here tables.sql)</p>\n\n<p>Example here:</p>\n\n<pre><code>$ impdp directory=exp_dir dumpfile=exp_user1_all_tab.dmp logfile=imp_exp_user1_tab sqlfile=tables.sql\n</code></pre>\n\n<blockquote>\n <p>Import: Release 11.2.0.3.0 - Production on Fri Apr 26 08:29:06 2013</p>\n \n <p>Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved.</p>\n \n <p>Username: / as sysdba</p>\n \n <p>Processing object type SCHEMA_EXPORT/PRE_SCHEMA/PROCACT_SCHEMA Job \"SYS\".\"SYS_SQL_FILE_FULL_01\" successfully completed at 08:29:12</p>\n</blockquote>\n\n<pre><code>$ grep \"CREATE USER\" tables.sql\n</code></pre>\n\n<blockquote>\n <p>CREATE USER \"USER1\" IDENTIFIED BY VALUES 'S:270D559F9B97C05EA50F78507CD6EAC6AD63969E5E;BBE7786A5F9103'</p>\n</blockquote>\n\n<p>Lot of datapump options explained here <a href=\"http://www.acehints.com/p/site-map.html\" rel=\"nofollow\">http://www.acehints.com/p/site-map.html</a></p>\n" }, { "answer_id": 42374293, "author": "Aldur", "author_id": 12942, "author_profile": "https://Stackoverflow.com/users/12942", "pm_score": 2, "selected": false, "text": "<p>You need to search for OWNER_NAME. </p>\n\n<pre><code>cat -v dumpfile.dmp | grep -o '&lt;OWNER_NAME&gt;.*&lt;/OWNER_NAME&gt;' | uniq -u\n</code></pre>\n\n<p>cat -v turn the dumpfile into visible text. </p>\n\n<p>grep -o shows only the match so we don't see really long lines</p>\n\n<p>uniq -u removes duplicate lines so you see less output. </p>\n\n<p>This works pretty well, even on large dump files, and could be tweaked for usage in a script.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923/" ]
* I have an Oracle database backup file (.dmp) that was created with `expdp`. * The .dmp file was an export of an entire database. * I need to restore 1 of the schemas from within this dump file. * I don't know the names of the schemas inside this dump file. * To use `impdp` to import the data I need the name of the schema to load. So, I need to inspect the .dmp file and list all of the schemas in it, how do I do that? --- *Update (2008-09-18 13:02) - More detailed information:* The impdp command i'm current using is: ``` impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP logfile=IMPORT.LOG ``` And the DPUMP\_DIR is correctly configured. ``` SQL> SELECT directory_path 2 FROM dba_directories 3 WHERE directory_name = 'DPUMP_DIR'; DIRECTORY_PATH ------------------------- D:\directory_path\dpump_dir\ ``` And yes, the EXPORT.DMP file is in fact in that folder. The error message I get when I run the `impdp` command is: ``` Connected to: Oracle Database 10g Enterprise Edition ... ORA-31655: no data or metadata objects selected for the job ORA-39154: Objects from foreign schemas have been removed from import ``` This error message is mostly expected. I need the `impdp` command be: ``` impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP SCHEMAS=SOURCE_SCHEMA REMAP_SCHEMA=SOURCE_SCHEMA:MY_SCHEMA ``` But to do that, I need the source schema.
If you open the DMP file with an editor that can handle big files, you might be able to locate the areas where the schema names are mentioned. Just be sure not to change anything. It would be better if you opened a copy of the original dump.
95,600
<p>The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action)</p> <p>Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error</p> <pre><code>error: function(request, error){} </code></pre> <p>What are other things you evaluate in the error option? do you include the optional exception object?</p> <p><strong>EDIT:</strong> one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful</p> <p>This is a complete $.ajax call:</p> <pre><code>$.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , dataType: "text", data: { '_service' : 'myService', '_program' : 'myProgram', 'start' : start, 'end' : end }, beforeSend: function() { $("#loading").removeClass("hide"); }, timeout: 5000, error: function(request,error) { $("#loading").addClass("hide"); if (error == "timeout") { $("#error").append("The request timed out, please resubmit"); } else { $("#error").append("ERROR: " + error); } }, success: function(request) { $("#loading").addClass("hide"); var t = eval( "(" + request + ")" ) ; } // End success }); // End ajax method </code></pre> <p>Thanks for the input</p>
[ { "answer_id": 95947, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 0, "selected": false, "text": "<p>Are you sure that response is correct? Parse error mean that there is sth wrong with data being evaluted in line\n<code>var t = eval( \"(\" + request + \")\" ) ;</code></p>\n" }, { "answer_id": 96245, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 6, "selected": true, "text": "<p>Looking at the jQuery source code, there are four returned statuses, in additon to <strong>success</strong>:</p>\n\n<ul>\n<li><strong>timeout</strong> - when your specified\ntimeout is exceeded</li>\n<li><strong>error</strong> - http error, like 404</li>\n<li><strong>notmodified</strong> - when requested\nresource was not modified since last\nrequest</li>\n<li><strong>parsererror</strong> - when an xml/json response is\nbad</li>\n</ul>\n" }, { "answer_id": 96246, "author": "Jataro", "author_id": 9292, "author_profile": "https://Stackoverflow.com/users/9292", "pm_score": 1, "selected": false, "text": "<p>The second argument that is passed to your error function will either be the string \"timeout\" \"parserror\" \"error\" or \"notmodified\". The third will be the exception object. This object can be helpful for debugging.</p>\n" }, { "answer_id": 1682211, "author": "davegurnell", "author_id": 203842, "author_profile": "https://Stackoverflow.com/users/203842", "pm_score": 2, "selected": false, "text": "<p>This is an aside, but I think there's a bug in the code you submitted. The line:</p>\n\n<pre><code> if (error = \"timeout\") {\n</code></pre>\n\n<p>should have more equals signs in it:</p>\n\n<pre><code> if (error == \"timeout\") {\n</code></pre>\n" }, { "answer_id": 1956505, "author": "Matt", "author_id": 179310, "author_profile": "https://Stackoverflow.com/users/179310", "pm_score": 5, "selected": false, "text": "<p>I find the request more useful than the error.</p>\n\n<pre><code>error:function(xhr,err){\n alert(\"readyState: \"+xhr.readyState+\"\\nstatus: \"+xhr.status);\n alert(\"responseText: \"+xhr.responseText);\n}</code></pre>\n\n<p><strong>xhr</strong> is XmlHttpRequest.<br/>\n<strong>readyState</strong> values are 1:loading, 2:loaded, 3:interactive, <em>4:complete</em>.<br/>\n<strong>status</strong> is the HTTP status number, i.e. 404: not found, 500: server error, <em>200: ok</em>.<br/>\n<strong>responseText</strong> is the response from the server - this could be text or JSON from the web service, or HTML from the web server.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action) Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error ``` error: function(request, error){} ``` What are other things you evaluate in the error option? do you include the optional exception object? **EDIT:** one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful This is a complete $.ajax call: ``` $.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , dataType: "text", data: { '_service' : 'myService', '_program' : 'myProgram', 'start' : start, 'end' : end }, beforeSend: function() { $("#loading").removeClass("hide"); }, timeout: 5000, error: function(request,error) { $("#loading").addClass("hide"); if (error == "timeout") { $("#error").append("The request timed out, please resubmit"); } else { $("#error").append("ERROR: " + error); } }, success: function(request) { $("#loading").addClass("hide"); var t = eval( "(" + request + ")" ) ; } // End success }); // End ajax method ``` Thanks for the input
Looking at the jQuery source code, there are four returned statuses, in additon to **success**: * **timeout** - when your specified timeout is exceeded * **error** - http error, like 404 * **notmodified** - when requested resource was not modified since last request * **parsererror** - when an xml/json response is bad
95,625
<p>Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?</p>
[ { "answer_id": 95695, "author": "Matt", "author_id": 17849, "author_profile": "https://Stackoverflow.com/users/17849", "pm_score": 0, "selected": false, "text": "<p>Not tested:</p>\n\n<pre><code>mailItem.Subject = \"Dept - \" &amp; mailItem.Subject\nmailItem.Save \n</code></pre>\n" }, { "answer_id": 95746, "author": "Matt", "author_id": 17849, "author_profile": "https://Stackoverflow.com/users/17849", "pm_score": 2, "selected": false, "text": "<p>Or if you need an entire script:</p>\n\n<p>Do the Run a script with the MailItem as the parameter.</p>\n\n<pre><code>Sub RewriteSubject(MyMail As MailItem)\n\n Dim mailId As String\n Dim outlookNS As Outlook.NameSpace\n Dim myMailItem As Outlook.MailItem\n\n mailId = MyMail.EntryID\n Set outlookNS = Application.GetNamespace(\"MAPI\")\n Set myMailItem = outlookNS.GetItemFromID(mailId)\n\n ' Do any detection here\n\n With myMailItem \n .Subject = \"Dept - \" &amp; mailItem.Subject\n .Save\n End With\n\n Set myMailItem = Nothing\n Set outlookNS = Nothing\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 95837, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>Sub AppendSubject(MyMail As MailItem)\n Dim strID As String\n Dim mailNS As Outlook.NameSpace\n Dim mailItem As Outlook.MailItem\n\n strID = MyMail.EntryID\n Set mailNS = Application.GetNamespace(\"MAPI\")\n Set mailItem = mailNS.GetItemFromID(strID)\n mailItem.Subject = \"Dept - \" &amp; mailItem.Subject\n mailItem.Save\n\n Set mailItem = Nothing\n Set mailNS = Nothing\nEnd Sub\n</code></pre>\n\n<p>Are we missing anything? EDIT: Doh! You already answered our question with a full script... Thanks!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?
Or if you need an entire script: Do the Run a script with the MailItem as the parameter. ``` Sub RewriteSubject(MyMail As MailItem) Dim mailId As String Dim outlookNS As Outlook.NameSpace Dim myMailItem As Outlook.MailItem mailId = MyMail.EntryID Set outlookNS = Application.GetNamespace("MAPI") Set myMailItem = outlookNS.GetItemFromID(mailId) ' Do any detection here With myMailItem .Subject = "Dept - " & mailItem.Subject .Save End With Set myMailItem = Nothing Set outlookNS = Nothing End Sub ```
95,631
<p>Suppose I want to open a file in an existing Emacs session using <code>su</code> or <code>sudo</code>, without dropping down to a shell and doing <code>sudoedit</code> or <code>sudo emacs</code>. One way to do this is</p> <pre><code>C-x C-f /sudo::/path/to/file </code></pre> <p>but this requires an expensive <a href="http://www.gnu.org/software/tramp/" rel="noreferrer">round-trip through SSH</a>. Is there a more direct way?</p> <p>[EDIT] @JBB is right. I want to be able to invoke <code>su</code>/<code>sudo</code> to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of <code>find-file</code> and <code>save-buffer</code> that can be "piped" through <code>su</code>/<code>sudo</code>.</p>
[ { "answer_id": 95758, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 0, "selected": false, "text": "<p>Ugh. Perhaps you could open a shell in Emacs and exec sudo emacs. </p>\n\n<p>The problem is that you presumably don't just want to open the file. You want to be able to save it later. Thus you need your root privs to persist, not just exist for opening the file.</p>\n\n<p>Sounds like you want Emacs to become your window manager. It's bloated enough without that. :)</p>\n" }, { "answer_id": 98931, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 7, "selected": true, "text": "<p>The nice thing about Tramp is that you only pay for that round-trip to SSH when you open the first file. Sudo then caches your credentials, and Emacs saves a handle, so that subsequent sudo-opened files take much less time.</p>\n\n<p>I haven't found the extra time it takes to save burdening, either. It's fast enough, IMO.</p>\n" }, { "answer_id": 99223, "author": "jfm3", "author_id": 11138, "author_profile": "https://Stackoverflow.com/users/11138", "pm_score": 3, "selected": false, "text": "<p>Your example doesn't start ssh at all, at least not with my version of TRAMP (\"2.1.13-pre\"). Both find-file and save-buffer work great.</p>\n" }, { "answer_id": 2071375, "author": "Teddy", "author_id": 54435, "author_profile": "https://Stackoverflow.com/users/54435", "pm_score": 6, "selected": false, "text": "<p>Tramp does <strong>not</strong> round-trip sudo via SSH, it uses a <em>subshell</em>. See the manual: <a href=\"https://www.gnu.org/software/tramp/#Inline-methods\" rel=\"noreferrer\">https://www.gnu.org/software/tramp/#Inline-methods</a></p>\n\n<p>Therefore, I recommend that you stick with TRAMP.</p>\n" }, { "answer_id": 3061523, "author": "Francois G", "author_id": 47978, "author_profile": "https://Stackoverflow.com/users/47978", "pm_score": 3, "selected": false, "text": "<p>At least for saving, a <a href=\"http://www.emacswiki.org/emacs/SudoSave\" rel=\"noreferrer\">sudo-save package</a> was written exactly for that kind of problem.</p>\n" }, { "answer_id": 7043786, "author": "Burton Samograd", "author_id": 450756, "author_profile": "https://Stackoverflow.com/users/450756", "pm_score": 4, "selected": false, "text": "<p>Not really an answer to the original question, but here's a helper function to make doing the tramp/sudo route a bit easier:</p>\n\n<pre>\n(defun sudo-find-file (file-name)\n \"Like find file, but opens the file as root.\"\n (interactive \"FSudo Find File: \")\n (let ((tramp-file-name (concat \"/sudo::\" (expand-file-name file-name))))\n (find-file tramp-file-name)))\n</pre>\n" }, { "answer_id": 29255604, "author": "anquegi", "author_id": 1900722, "author_profile": "https://Stackoverflow.com/users/1900722", "pm_score": 2, "selected": false, "text": "<p>I recommend you to use advising commands. Put this function in your ~/.emacs</p>\n\n<pre><code>(defadvice ido-find-file (after find-file-sudo activate)\n \"Find file as root if necessary.\"\n (unless (and buffer-file-name\n (file-writable-p buffer-file-name))\n (find-alternate-file (concat \"/sudo:root@localhost:\" buffer-file-name))))\n</code></pre>\n" }, { "answer_id": 31092680, "author": "Qudit", "author_id": 3101625, "author_profile": "https://Stackoverflow.com/users/3101625", "pm_score": 4, "selected": false, "text": "<p>If you use <code>helm</code>, <code>helm-find-files</code> supports opening a file as root with <code>C-c r</code>.</p>\n" }, { "answer_id": 36569381, "author": "alex_1948511", "author_id": 1948511, "author_profile": "https://Stackoverflow.com/users/1948511", "pm_score": 1, "selected": false, "text": "<p>(works only locally. Need to be updated to work correctly via tramp)</p>\n\n<p>A little bit extended Burton's answer:</p>\n\n<pre><code>(defun sudo-find-file (file-name)\n\"Like find file, but opens the file as root.\"\n(interactive \"FSudo Find File: \")\n(let ((tramp-file-name (concat \"/sudo::\" (expand-file-name file-name))))\n(find-file tramp-file-name)))\n\n\n(add-hook 'dired-mode-hook\n (lambda ()\n ;; open current file as sudo \n (local-set-key (kbd \"C-x &lt;M-S-return&gt;\") (lambda()\n (interactive)\n (message \"!!! SUDO opening %s\" (dired-file-name-at-point))\n (sudo-find-file (dired-file-name-at-point))\n ))\n )\n)\n</code></pre>\n" }, { "answer_id": 68870716, "author": "Daoist Paul", "author_id": 12980261, "author_profile": "https://Stackoverflow.com/users/12980261", "pm_score": 0, "selected": false, "text": "<p>I find <code>sudo edit</code> function very useful for that. After opening a file, press <code>s-e</code> to have sudo access to edit/save the file.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
Suppose I want to open a file in an existing Emacs session using `su` or `sudo`, without dropping down to a shell and doing `sudoedit` or `sudo emacs`. One way to do this is ``` C-x C-f /sudo::/path/to/file ``` but this requires an expensive [round-trip through SSH](http://www.gnu.org/software/tramp/). Is there a more direct way? [EDIT] @JBB is right. I want to be able to invoke `su`/`sudo` to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of `find-file` and `save-buffer` that can be "piped" through `su`/`sudo`.
The nice thing about Tramp is that you only pay for that round-trip to SSH when you open the first file. Sudo then caches your credentials, and Emacs saves a handle, so that subsequent sudo-opened files take much less time. I haven't found the extra time it takes to save burdening, either. It's fast enough, IMO.
95,642
<p>Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete.</p> <p>If my application crashes, I want to ensure these system resources are properly released.</p> <p>Does it make sense to do something like the following?</p> <pre><code>def main(): # TODO: main application entry point pass def cleanup(): # TODO: release system resources here pass if __name__ == "__main__": try: main() except: cleanup() raise </code></pre> <p>Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?</p>
[ { "answer_id": 95659, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>Application wide handler is fine. They are great for logging. Just make sure that the application wide one is durable and is unlikely to crash itself.</p>\n" }, { "answer_id": 95676, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 5, "selected": true, "text": "<p>I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception.</p>\n\n<p>It's also a fantastic place to <strong>log</strong> those exceptions if you have such a framework in place. Top-level handlers will catch those bizarre exceptions you didn't plan on and let you correct them in the future, otherwise, you may never know about them at all.</p>\n\n<p>Just be careful that your top-level handler doesn't throw exceptions!</p>\n" }, { "answer_id": 95682, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 3, "selected": false, "text": "<p>A destructor (as in a __del__ method) is a bad idea, as these are not guaranteed to be called. The atexit module is a safer approach, although these will still not fire if the Python interpreter crashes (rather than the Python application), or if os._exit() is used, or the process is killed aggressively, or the machine reboots. (Of course, the last item isn't an issue in your case.) If your process is crash-prone (it uses fickle third-party extension modules, for instance) you may want to do the cleanup in a simple parent process for more isolation.</p>\n\n<p>If you aren't really worried, use the atexit module.</p>\n" }, { "answer_id": 95692, "author": "keturn", "author_id": 9585, "author_profile": "https://Stackoverflow.com/users/9585", "pm_score": 1, "selected": false, "text": "<p>That seems like a reasonable approach, and more straightforward and reliable than a destructor on a singleton class. You might also look at the \"<a href=\"http://docs.python.org/lib/module-atexit.html\" rel=\"nofollow noreferrer\">atexit</a>\" module. (Pronounced \"at exit\", not \"a tex it\" or something like that. I confused that for a long while.)</p>\n" }, { "answer_id": 98085, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 2, "selected": false, "text": "<p>if you use classes, you should free the resources they allocate in their destructors instead, of course. Use the try: on entire application just if you want to free resources that aren't already liberated by your classes' destructors.</p>\n\n<p>And instead of using a catch-all except:, you should use the following block:</p>\n\n<pre><code>try:\n main()\nfinally:\n cleanup()\n</code></pre>\n\n<p>That will ensure cleanup in a more pythonic way.</p>\n" }, { "answer_id": 120224, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 1, "selected": false, "text": "<p>Consider writing a context manager and using the with statement.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9188/" ]
Long story short, I have a substantial Python application that, among other things, does outcalls to "losetup", "mount", etc. on Linux. Essentially consuming system resources that must be released when complete. If my application crashes, I want to ensure these system resources are properly released. Does it make sense to do something like the following? ``` def main(): # TODO: main application entry point pass def cleanup(): # TODO: release system resources here pass if __name__ == "__main__": try: main() except: cleanup() raise ``` Is this something that is typically done? Is there a better way? Perhaps the destructor in a singleton class?
I like top-level exception handlers in general (regardless of language). They're a great place to cleanup resources that may not be immediately related to resources consumed inside the method that throws the exception. It's also a fantastic place to **log** those exceptions if you have such a framework in place. Top-level handlers will catch those bizarre exceptions you didn't plan on and let you correct them in the future, otherwise, you may never know about them at all. Just be careful that your top-level handler doesn't throw exceptions!
95,683
<p>I have a .NET 3.5 (target framework) web application. I have some code that looks like this:</p> <pre><code>public string LogPath { get; private set; } public string ErrorMsg { get; private set; } </code></pre> <p>It's giving me this compilation error for these lines:</p> <pre><code>"must declare a body because it is not marked abstract or extern." </code></pre> <p>Any ideas? My understanding was that this style of property was valid as of .NET 3.0.</p> <p>Thanks!</p> <hr> <p>The problem turned out to be in my .sln file itself. Although I was changing the target version in my build options, in the .sln file, I found this:</p> <pre><code>TargetFramework = "3.0" </code></pre> <p>Changing that to "3.5" solved it. Thanks, guys!</p>
[ { "answer_id": 95716, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": -1, "selected": false, "text": "<p>It is, as long as you put <strong>abstract</strong> in front, or implement the methods.</p>\n\n<pre><code>public abstract string LogPath { get; private set; }\npublic abstract string ErrorMsg { get; private set; }\n</code></pre>\n\n<p>See <a href=\"http://forums.asp.net/t/1031651.aspx\" rel=\"nofollow noreferrer\">http://forums.asp.net/t/1031651.aspx</a></p>\n" }, { "answer_id": 95720, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>You are correct; that style is allowed.</p>\n\n<p>I'd look into the standard assemblies referenced. I'm not sure which you'd need to get that to compile, but I figure somewhat you're pointing to the .Net v2.0 version of csc.exe.</p>\n" }, { "answer_id": 95748, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>The syntax is valid. And you can set different access modifiers. You aren't on an Interface are you? And the class these are in isn't abstract is it?</p>\n\n<p>Also, doesn't matter what v. of the framework you target because this is <strong>a compiler feature</strong>. VS2008 will implement the property w/ backing stores for you.</p>\n" }, { "answer_id": 95772, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 0, "selected": false, "text": "<p>Where do you define this Properties? Directly in the as*x file or in the codeBehind? (I don't think that can be a reason, but if the build-Target is .NET 3.5 I can't see anything else)</p>\n" }, { "answer_id": 95808, "author": "Mike Comstock", "author_id": 16872, "author_profile": "https://Stackoverflow.com/users/16872", "pm_score": 2, "selected": false, "text": "<p>Your code is valid - it should work fine. Go in to the property pages of your project and make sure that the \"Target Framework\" is .NET 3.0 or 3.5.</p>\n" }, { "answer_id": 95847, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 1, "selected": false, "text": "<p>That error should not be coming from the code you posted. According to MSDN, you've done this right: <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb384054.aspx</a></p>\n\n<p>Hence I would recommend you re-check the error message, and where the compiler says the error is coming from. The text of the message you posted did not include a reference to properties, and there is a similar message for functions... Anything that is missing an implementation and not on an interface or marked abstract or extern can generate this error.</p>\n\n<p>The auto-property is a feature of the C# 3.0 language/compiler. If you are using VS 2008, it should work even if you are targeting .NET 2.0. I JUST tested it to make sure.</p>\n" }, { "answer_id": 1140423, "author": "R.L.", "author_id": 104991, "author_profile": "https://Stackoverflow.com/users/104991", "pm_score": 5, "selected": true, "text": "<p>add to web.config</p>\n\n<pre><code>&lt;system.codedom&gt;\n &lt;compilers&gt;\n &lt;compiler language=\"c#;cs;csharp\" extension=\".cs\" type=\"Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" warningLevel=\"4\"&gt;\n &lt;providerOption name=\"CompilerVersion\" value=\"v3.5\" /&gt;\n &lt;providerOption name=\"WarnAsError\" value=\"false\" /&gt;\n &lt;/compiler&gt;\n &lt;/compilers&gt;\n&lt;/system.codedom&gt;\n</code></pre>\n" }, { "answer_id": 1330525, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This also happens on a raw web site project where there was no web.config generated.</p>\n\n<p>Although the solution file said 3.5, .Net needed the web.config to state it also to recognize. I ran debug allowing it to create a webconfig, and all was working.</p>\n\n<p>So it is like the answer provided, but just make sure you have one.</p>\n" }, { "answer_id": 1566587, "author": "Maurice Lenz", "author_id": 189876, "author_profile": "https://Stackoverflow.com/users/189876", "pm_score": 1, "selected": false, "text": "<p>This error can also happen if you are using <strong>CodeFile</strong>=\"MyControl.ascx.cs\" in your MyControl.ascx instead of <strong>CodeBehind</strong>=\"MyControl.ascx.cs\". </p>\n\n<p>In case of <strong>CodeFile</strong>, the 2.0 compiler tries to recompile the page, even if you have a WebProject instead of a WebSite and of course - does fail. </p>\n\n<p>Changing the attribute name to <strong>CodeBehind</strong> fixed the problem in my case.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ]
I have a .NET 3.5 (target framework) web application. I have some code that looks like this: ``` public string LogPath { get; private set; } public string ErrorMsg { get; private set; } ``` It's giving me this compilation error for these lines: ``` "must declare a body because it is not marked abstract or extern." ``` Any ideas? My understanding was that this style of property was valid as of .NET 3.0. Thanks! --- The problem turned out to be in my .sln file itself. Although I was changing the target version in my build options, in the .sln file, I found this: ``` TargetFramework = "3.0" ``` Changing that to "3.5" solved it. Thanks, guys!
add to web.config ``` <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4"> <providerOption name="CompilerVersion" value="v3.5" /> <providerOption name="WarnAsError" value="false" /> </compiler> </compilers> </system.codedom> ```
95,700
<p>I am looking to build a multi-threaded text import facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#. I have VS 2008 trial and just dont know where to begin. Can anyone point me in the direction of where I can look at and play with the source of a <em>VERY</em> simple multi-threaded application for VS 2008?</p> <p>Thanks!</p>
[ { "answer_id": 95721, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 2, "selected": false, "text": "<p>This is a great article:</p>\n\n<p><a href=\"http://www.devx.com/DevX/10MinuteSolution/20365\" rel=\"nofollow noreferrer\">http://www.devx.com/DevX/10MinuteSolution/20365</a></p>\n\n<p>In particular:</p>\n\n<pre><code>Dim t As Thread\nt = New Thread(AddressOf Me.BackgroundProcess)\nt.Start()\n\nPrivate Sub BackgroundProcess()\n Dim i As Integer = 1\n Do While True\n ListBox1.Items.Add(\"Iterations: \" + i)\n i += 1\n Thread.CurrentThread.Sleep(2000)\n Loop\nEnd Sub\n</code></pre>\n" }, { "answer_id": 509999, "author": "Tom A", "author_id": 10226, "author_profile": "https://Stackoverflow.com/users/10226", "pm_score": 3, "selected": true, "text": "<p>The referenced <em>DevX</em> article is from 2001 and .Net Framework 1.1, but today .Net Framework 2.0 provides the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.95).aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a> class. This is the recommended threading class if your application includes a foreground UI component.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/6kac2kdh.aspx\" rel=\"nofollow noreferrer\">MSDN Threads and Threading</a>:</p>\n\n<blockquote>\n <p>If you need to run background threads\n that interact with the user interface,\n the .NET Framework version 2.0\n provides a BackgroundWorker component\n that communicates using events, with\n cross-thread marshaling to the\n user-interface thread.</p>\n</blockquote>\n\n<p>This example from <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">MSDN BackgroundWorker Class</a> shows a background task, progress %, and cancel option. (The example is longer than the DevX sample, but has a lot more functionality.)</p>\n\n<pre><code>Imports System.ComponentModel\n\nPartial Public Class Page\n Inherits UserControl\n Private bw As BackgroundWorker = New BackgroundWorker\n\n Public Sub New()\n InitializeComponent()\n\n bw.WorkerReportsProgress = True\n bw.WorkerSupportsCancellation = True\n AddHandler bw.DoWork, AddressOf bw_DoWork\n AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged\n AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted\n\n End Sub\n Private Sub buttonStart_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n If Not bw.IsBusy = True Then\n bw.RunWorkerAsync()\n End If\n End Sub\n Private Sub buttonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n If bw.WorkerSupportsCancellation = True Then\n bw.CancelAsync()\n End If\n End Sub\n Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)\n Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)\n\n For i = 1 To 10\n If bw.CancellationPending = True Then\n e.Cancel = True\n Exit For\n Else\n ' Perform a time consuming operation and report progress.\n System.Threading.Thread.Sleep(500)\n bw.ReportProgress(i * 10)\n End If\n Next\n End Sub\n Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)\n If e.Cancelled = True Then\n Me.tbProgress.Text = \"Canceled!\"\n ElseIf e.Error IsNot Nothing Then\n Me.tbProgress.Text = \"Error: \" &amp; e.Error.Message\n Else\n Me.tbProgress.Text = \"Done!\"\n End If\n End Sub\n Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs)\n Me.tbProgress.Text = e.ProgressPercentage.ToString() &amp; \"%\"\n End Sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 1277670, "author": "Simon", "author_id": 154962, "author_profile": "https://Stackoverflow.com/users/154962", "pm_score": 1, "selected": false, "text": "<p>About the best threading document I ever found was this <a href=\"http://www.albahari.com/threading/\" rel=\"nofollow noreferrer\">http://www.albahari.com/threading/</a></p>\n\n<p>If I may, the problem with simple examples is that that they're often too simple. Once you get past the counting or sort in background demos you generally need to update the UI or similar and there are some gotchas. Similarly you rarely have to deal with resource contention in simple examples and having threads degrade gracefully when a resource isn't available (such as a Db connection) requires thought.</p>\n\n<p>Conceptually you need to decide how you're going to distribute your work across the threads and how many do you want. There's overhead associated with managing threads and some mechanisms use a shared thread pool that could be subject to resource contention itself (for example, any time you run a program that simply displays an empty form, how many threads do you see under task manager).</p>\n\n<p>So for your case, you threads doing the actual uploading need to signal back if they've completed, if they've failed (and what the failure was). The controller needs to be able to deal with those and manage the start/stop processes and so on.</p>\n\n<p>Finally (almost), assuming that making something multithread will increase performance doesn't always hold true. If for example, you chop a file up into segments but it has to travel across a low speed link (ADSL say), you're constrained by external forces and no amount of threading trickery is going to get around that. The same can apply for database updates, web requests, anything invloving large amounts of disk i/o and so on.</p>\n\n<p>Despite all this, I'm not the prophet of doom. The references here are more than adequate to help you achieve what you want but be aware that one of the reasons threading seems complicated is because it can be :)</p>\n\n<p>If you want more control than the BackgroundWorker/Threadpool but don't want to do everything yourself there are at least two very good freebie threading libraries knocking around the place (Wintellect &amp; PowerThreading)</p>\n\n<p>Cheers</p>\n\n<p>Simon</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14728/" ]
I am looking to build a multi-threaded text import facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#. I have VS 2008 trial and just dont know where to begin. Can anyone point me in the direction of where I can look at and play with the source of a *VERY* simple multi-threaded application for VS 2008? Thanks!
The referenced *DevX* article is from 2001 and .Net Framework 1.1, but today .Net Framework 2.0 provides the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(VS.95).aspx) class. This is the recommended threading class if your application includes a foreground UI component. From [MSDN Threads and Threading](http://msdn.microsoft.com/en-us/library/6kac2kdh.aspx): > > If you need to run background threads > that interact with the user interface, > the .NET Framework version 2.0 > provides a BackgroundWorker component > that communicates using events, with > cross-thread marshaling to the > user-interface thread. > > > This example from [MSDN BackgroundWorker Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) shows a background task, progress %, and cancel option. (The example is longer than the DevX sample, but has a lot more functionality.) ``` Imports System.ComponentModel Partial Public Class Page Inherits UserControl Private bw As BackgroundWorker = New BackgroundWorker Public Sub New() InitializeComponent() bw.WorkerReportsProgress = True bw.WorkerSupportsCancellation = True AddHandler bw.DoWork, AddressOf bw_DoWork AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted End Sub Private Sub buttonStart_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) If Not bw.IsBusy = True Then bw.RunWorkerAsync() End If End Sub Private Sub buttonCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) If bw.WorkerSupportsCancellation = True Then bw.CancelAsync() End If End Sub Private Sub bw_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Dim worker As BackgroundWorker = CType(sender, BackgroundWorker) For i = 1 To 10 If bw.CancellationPending = True Then e.Cancel = True Exit For Else ' Perform a time consuming operation and report progress. System.Threading.Thread.Sleep(500) bw.ReportProgress(i * 10) End If Next End Sub Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) If e.Cancelled = True Then Me.tbProgress.Text = "Canceled!" ElseIf e.Error IsNot Nothing Then Me.tbProgress.Text = "Error: " & e.Error.Message Else Me.tbProgress.Text = "Done!" End If End Sub Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Me.tbProgress.Text = e.ProgressPercentage.ToString() & "%" End Sub End Class ```
95,727
<p>Let's say we have <code>0.33</code>, we need to output <code>1/3</code>. <br /> If we have <code>0.4</code>, we need to output <code>2/5</code>.</p> <p>The idea is to make it human-readable to make the user understand "<strong>x parts out of y</strong>" as a better way of understanding data.</p> <p>I know that percentages is a good substitute but I was wondering if there was a simple way to do this?</p>
[ { "answer_id": 95778, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 4, "selected": false, "text": "<p>You might want to read <a href=\"https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"nofollow noreferrer\">What Every Computer Scientist Should Know about Floating Point Arithmetic</a>.</p>\n<p>You'll have to specify some precision by multiplying by a large number:</p>\n<pre><code>3.141592 * 1000000 = 3141592\n</code></pre>\n<p>then you can make a fraction:</p>\n<pre><code>3 + (141592 / 1000000)\n</code></pre>\n<p>and reduce via GCD...</p>\n<pre><code>3 + (17699 / 125000)\n</code></pre>\n<p>but there is no way to get the <em>intended</em> fraction out. You might want to <em>always</em> use fractions throughout your code instead --just remember to reduce fractions when you can to avoid overflow!</p>\n" }, { "answer_id": 95785, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 4, "selected": false, "text": "<p>Here's a link explaining the math behind converting a decimal to a fraction:</p>\n<p><a href=\"http://www.webmath.com/dec2fract.html\" rel=\"nofollow noreferrer\">http://www.webmath.com/dec2fract.html</a></p>\n<p>And here's an example function for how to actually do it using VB (from <a href=\"http://www.freevbcode.com/ShowCode.asp?ID=582\" rel=\"nofollow noreferrer\">www.freevbcode.com/ShowCode.asp?ID=582</a>):</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Function Dec2Frac(ByVal f As Double) As String\n\n Dim df As Double\n Dim lUpperPart As Long\n Dim lLowerPart As Long\n \n lUpperPart = 1\n lLowerPart = 1\n \n df = lUpperPart / lLowerPart\n While (df &lt;&gt; f)\n If (df &lt; f) Then\n lUpperPart = lUpperPart + 1\n Else\n lLowerPart = lLowerPart + 1\n lUpperPart = f * lLowerPart\n End If\n df = lUpperPart / lLowerPart\n Wend\nDec2Frac = CStr(lUpperPart) &amp; &quot;/&quot; &amp; CStr(lLowerPart)\nEnd Function\n</code></pre>\n<p>(From google searches: convert decimal to fraction, convert decimal to fraction code)</p>\n" }, { "answer_id": 95789, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 1, "selected": false, "text": "<p>You are going to have two basic problems that will make this hard:</p>\n\n<p>1) Floating point isn't an exact representation which means that if you have a fraction of \"x/y\" which results in a value of \"z\", your fraction algorithm may return a result other than \"x/y\".</p>\n\n<p>2) There are infinity many more irrational numbers than rational. A rational number is one that can be represented as a fraction. Irrational being ones that can not.</p>\n\n<p>However, in a cheap sort of way, since floating point has limit accuracy, then you can always represent it as some form of faction. (I think...)</p>\n" }, { "answer_id": 95790, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 3, "selected": false, "text": "<p>Part of the problem is that so many fractions aren't actually easily construed as fractions. E.g. 0.33 isn't 1/3, it's 33/100. But if you remember your elementary school training, then there is a process of converting decimal values into fractions, however it's unlikely to give you what you want since most of the time decimal numbers aren't stored at 0.33, but 0.329999999999998 or some such.</p>\n\n<p>Do yourself a favor and don't bother with this, but if you need to then you can do the following:</p>\n\n<p>Multiply the original value by 10 until you remove the fractional part. Keep that number, and use it as the divisor. Then do a series of simplifications by looking for common denominators.</p>\n\n<p>So 0.4 would be 4/10. You would then look for common divisors starting with low values, probably prime numbers. Starting with 2, you would see if 2 divides both the numerator and denominator evenly by checking if the floor of division is the same as the division itself.</p>\n\n<pre><code>floor(5/2) = 2\n5/2 = 2.5\n</code></pre>\n\n<p>So 5 does not divide 2 evenly. So then you check the next number, say 3. You do this until you hit at or above the square root of the smaller number.</p>\n\n<p>After you do that then you need</p>\n" }, { "answer_id": 95811, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 2, "selected": false, "text": "<p>You'll have to figure out what level of error you're willing to accept. Not all decimal fractions will reduce to a simple fraction. I'd probably pick an easily-divisible number, like 60, and figure out how many 60ths is closest to the value, then simplify the fraction.</p>\n" }, { "answer_id": 95851, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 2, "selected": false, "text": "<p>\"Let's say we have 0.33, we need to output \"1/3\". \"</p>\n\n<p>What precision do you expect the \"solution\" to have? 0.33 is not equal to 1/3. How do you recognize a \"good\" (easy to read) answer?</p>\n\n<p>No matter what, a possible algorithm could be:</p>\n\n<p>If you expect to find a nearest fraction in a form X/Y where Y is less then 10, then you can loop though all 9 possible Ys, for each Y compute X, and then select the most accurate one.</p>\n" }, { "answer_id": 95873, "author": "Pascal", "author_id": 1311, "author_profile": "https://Stackoverflow.com/users/1311", "pm_score": 2, "selected": false, "text": "<p>You can do this in any programming language using the following steps:</p>\n\n<ol>\n<li>Multiply and Divide by 10^x where x is the power of 10 required to make sure that the number has no decimal places remaining. \nExample: Multiply 0.33 by 10^2 = 100 to make it 33 and divide it by the same to get 33/100</li>\n<li>Reduce the numerator and the denominator of the resulting fraction by factorization, till you can no longer obtain integers from the result.</li>\n<li>The resulting reduced fraction should be your answer.</li>\n</ol>\n\n<p>Example:\n0.2\n=0.2 x 10^1/10^1\n=2/10\n=1/5</p>\n\n<p>So, that can be read as '1 part out of 5'</p>\n" }, { "answer_id": 95917, "author": "Tim", "author_id": 387361, "author_profile": "https://Stackoverflow.com/users/387361", "pm_score": 0, "selected": false, "text": "<p>As many people have stated you really can't convert a floating point back to a fraction (unless its extremely exact like .25). Of course you could create some type of look up for a large array of fractions and use some sort of fuzzy logic to produce the result you are looking for. Again this wouldn't be exact though and you would need to define a lower bounds of how large your want the denominator to go.</p>\n\n<p>.32 &lt; x &lt; .34 = 1/3 or something like that.</p>\n" }, { "answer_id": 96035, "author": "Epsilon", "author_id": 18143, "author_profile": "https://Stackoverflow.com/users/18143", "pm_score": 7, "selected": true, "text": "<p>I have found David Eppstein's <a href=\"http://www.ics.uci.edu/%7Eeppstein/numth/frap.c\" rel=\"nofollow noreferrer\">find rational approximation to given real number</a> C code to be exactly what you are asking for. Its based on the theory of continued fractions and very fast and fairly compact.</p>\n<p>I have used versions of this customized for specific numerator and denominator limits.</p>\n<pre class=\"lang-c prettyprint-override\"><code>/*\n** find rational approximation to given real number\n** David Eppstein / UC Irvine / 8 Aug 1993\n**\n** With corrections from Arno Formella, May 2008\n**\n** usage: a.out r d\n** r is real number to approx\n** d is the maximum denominator allowed\n**\n** based on the theory of continued fractions\n** if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...)))\n** then best approximation is found by truncating this series\n** (with some adjustments in the last term).\n**\n** Note the fraction can be recovered as the first column of the matrix\n** ( a1 1 ) ( a2 1 ) ( a3 1 ) ...\n** ( 1 0 ) ( 1 0 ) ( 1 0 )\n** Instead of keeping the sequence of continued fraction terms,\n** we just keep the last partial product of these matrices.\n*/\n\n#include &lt;stdio.h&gt;\n\nmain(ac, av)\nint ac;\nchar ** av;\n{\n double atof();\n int atoi();\n void exit();\n\n long m[2][2];\n double x, startx;\n long maxden;\n long ai;\n\n /* read command line arguments */\n if (ac != 3) {\n fprintf(stderr, &quot;usage: %s r d\\n&quot;,av[0]); // AF: argument missing\n exit(1);\n }\n startx = x = atof(av[1]);\n maxden = atoi(av[2]);\n\n /* initialize matrix */\n m[0][0] = m[1][1] = 1;\n m[0][1] = m[1][0] = 0;\n\n /* loop finding terms until denom gets too big */\n while (m[1][0] * ( ai = (long)x ) + m[1][1] &lt;= maxden) {\n long t;\n t = m[0][0] * ai + m[0][1];\n m[0][1] = m[0][0];\n m[0][0] = t;\n t = m[1][0] * ai + m[1][1];\n m[1][1] = m[1][0];\n m[1][0] = t;\n if(x==(double)ai) break; // AF: division by zero\n x = 1/(x - (double) ai);\n if(x&gt;(double)0x7FFFFFFF) break; // AF: representation failure\n } \n\n /* now remaining x is between 0 and 1/ai */\n /* approx as either 0 or 1/m where m is max that will fit in maxden */\n /* first try zero */\n printf(&quot;%ld/%ld, error = %e\\n&quot;, m[0][0], m[1][0],\n startx - ((double) m[0][0] / (double) m[1][0]));\n\n /* now try other possibility */\n ai = (maxden - m[1][1]) / m[1][0];\n m[0][0] = m[0][0] * ai + m[0][1];\n m[1][0] = m[1][0] * ai + m[1][1];\n printf(&quot;%ld/%ld, error = %e\\n&quot;, m[0][0], m[1][0],\n startx - ((double) m[0][0] / (double) m[1][0]));\n}\n</code></pre>\n" }, { "answer_id": 97337, "author": "jpsecher", "author_id": 13372, "author_profile": "https://Stackoverflow.com/users/13372", "pm_score": 5, "selected": false, "text": "<p>If the the output is to give a human reader a fast impression of the order of the result, it makes no sense return something like &quot;113/211&quot;, so the output should limit itself to using one-digit numbers (and maybe 1/10 and 9/10). If so, you can observe that there are only 27 <em>different</em> fractions.</p>\n<p>Since the underlying math for generating the output will never change, a solution could be to simply hard-code a binary search tree, so that the function would perform at most log(27) ~= 4 3/4 comparisons. Here is a tested C version of the code</p>\n<pre class=\"lang-c prettyprint-override\"><code>char *userTextForDouble(double d, char *rval)\n{\n if (d == 0.0)\n return &quot;0&quot;;\n \n // TODO: negative numbers:if (d &lt; 0.0)...\n if (d &gt;= 1.0)\n sprintf(rval, &quot;%.0f &quot;, floor(d));\n d = d-floor(d); // now only the fractional part is left\n \n if (d == 0.0)\n return rval;\n \n if( d &lt; 0.47 )\n {\n if( d &lt; 0.25 )\n {\n if( d &lt; 0.16 )\n {\n if( d &lt; 0.12 ) // Note: fixed from .13\n {\n if( d &lt; 0.11 )\n strcat(rval, &quot;1/10&quot;); // .1\n else\n strcat(rval, &quot;1/9&quot;); // .1111....\n }\n else // d &gt;= .12\n {\n if( d &lt; 0.14 )\n strcat(rval, &quot;1/8&quot;); // .125\n else\n strcat(rval, &quot;1/7&quot;); // .1428...\n }\n }\n else // d &gt;= .16\n {\n if( d &lt; 0.19 )\n {\n strcat(rval, &quot;1/6&quot;); // .1666...\n }\n else // d &gt; .19\n {\n if( d &lt; 0.22 )\n strcat(rval, &quot;1/5&quot;); // .2\n else\n strcat(rval, &quot;2/9&quot;); // .2222...\n }\n }\n }\n else // d &gt;= .25\n {\n if( d &lt; 0.37 ) // Note: fixed from .38\n {\n if( d &lt; 0.28 ) // Note: fixed from .29\n {\n strcat(rval, &quot;1/4&quot;); // .25\n }\n else // d &gt;=.28\n {\n if( d &lt; 0.31 )\n strcat(rval, &quot;2/7&quot;); // .2857...\n else\n strcat(rval, &quot;1/3&quot;); // .3333...\n }\n }\n else // d &gt;= .37\n {\n if( d &lt; 0.42 ) // Note: fixed from .43\n {\n if( d &lt; 0.40 )\n strcat(rval, &quot;3/8&quot;); // .375\n else\n strcat(rval, &quot;2/5&quot;); // .4\n }\n else // d &gt;= .42\n {\n if( d &lt; 0.44 )\n strcat(rval, &quot;3/7&quot;); // .4285...\n else\n strcat(rval, &quot;4/9&quot;); // .4444...\n }\n }\n }\n }\n else\n {\n if( d &lt; 0.71 )\n {\n if( d &lt; 0.60 )\n {\n if( d &lt; 0.55 ) // Note: fixed from .56\n {\n strcat(rval, &quot;1/2&quot;); // .5\n }\n else // d &gt;= .55\n {\n if( d &lt; 0.57 )\n strcat(rval, &quot;5/9&quot;); // .5555...\n else\n strcat(rval, &quot;4/7&quot;); // .5714\n }\n }\n else // d &gt;= .6\n {\n if( d &lt; 0.62 ) // Note: Fixed from .63\n {\n strcat(rval, &quot;3/5&quot;); // .6\n }\n else // d &gt;= .62\n {\n if( d &lt; 0.66 )\n strcat(rval, &quot;5/8&quot;); // .625\n else\n strcat(rval, &quot;2/3&quot;); // .6666...\n }\n }\n }\n else\n {\n if( d &lt; 0.80 )\n {\n if( d &lt; 0.74 )\n {\n strcat(rval, &quot;5/7&quot;); // .7142...\n }\n else // d &gt;= .74\n {\n if(d &lt; 0.77 ) // Note: fixed from .78\n strcat(rval, &quot;3/4&quot;); // .75\n else\n strcat(rval, &quot;7/9&quot;); // .7777...\n }\n }\n else // d &gt;= .8\n {\n if( d &lt; 0.85 ) // Note: fixed from .86\n {\n if( d &lt; 0.83 )\n strcat(rval, &quot;4/5&quot;); // .8\n else\n strcat(rval, &quot;5/6&quot;); // .8333...\n }\n else // d &gt;= .85\n {\n if( d &lt; 0.87 ) // Note: fixed from .88\n {\n strcat(rval, &quot;6/7&quot;); // .8571\n }\n else // d &gt;= .87\n {\n if( d &lt; 0.88 ) // Note: fixed from .89\n {\n strcat(rval, &quot;7/8&quot;); // .875\n }\n else // d &gt;= .88\n {\n if( d &lt; 0.90 )\n strcat(rval, &quot;8/9&quot;); // .8888...\n else\n strcat(rval, &quot;9/10&quot;); // .9\n }\n }\n }\n }\n }\n }\n \n return rval;\n}\n</code></pre>\n" }, { "answer_id": 97574, "author": "robottobor", "author_id": 10184, "author_profile": "https://Stackoverflow.com/users/10184", "pm_score": 2, "selected": false, "text": "<p>One solution is to just store all numbers as rational numbers in the first place. There are libraries for rational number arithmetic (eg <a href=\"http://gmplib.org/\" rel=\"nofollow noreferrer\">GMP</a>). If using an OO language you may be able to just use a rational number class library to replace your number class.</p>\n\n<p>Finance programs, among others, would use such a solution to be able to make exact calculations and preserve precision that may be lost using a plain float.</p>\n\n<p>Of course it will be a lot slower so it may not be practical for you. Depends on how much calculations you need to do, and how important the precision is for you.</p>\n\n<pre><code>a = rational(1);\nb = rational(3);\nc = a / b;\n\nprint (c.asFraction) ---&gt; \"1/3\"\nprint (c.asFloat) ----&gt; \"0.333333\"\n</code></pre>\n" }, { "answer_id": 98983, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Stern-Brocot_tree\" rel=\"noreferrer\">Stern-Brocot Tree</a> induces a fairly natural way to approximate real numbers by fractions with simple denominators.</p>\n" }, { "answer_id": 681534, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "<p>Here are Perl and Javascript versions of the VB code suggested by devinmoore:</p>\n<p>Perl:</p>\n<pre class=\"lang-perl prettyprint-override\"><code>sub dec2frac {\n my $d = shift;\n\n my $df = 1;\n my $top = 1;\n my $bot = 1;\n\n while ($df != $d) {\n if ($df &lt; $d) {\n $top += 1;\n }\n else {\n $bot += 1;\n $top = int($d * $bot);\n }\n $df = $top / $bot;\n }\n return &quot;$top/$bot&quot;;\n}\n</code></pre>\n<p>And the almost identical javascript:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function dec2frac(d) {\n\n var df = 1;\n var top = 1;\n var bot = 1;\n\n while (df != d) {\n if (df &lt; d) {\n top += 1;\n }\n else {\n bot += 1;\n top = parseInt(d * bot);\n }\n df = top / bot;\n }\n return top + '/' + bot;\n}\n\n//Put in your test number here:\nvar floatNumber = 2.56;\nalert(floatNumber + \" = \" + dec2frac(floatNumber));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 1331433, "author": "eldad", "author_id": 163131, "author_profile": "https://Stackoverflow.com/users/163131", "pm_score": 3, "selected": false, "text": "<p>This is not an &quot;algorithm&quot;, just a Python solution:\n<a href=\"http://docs.python.org/library/fractions.html\" rel=\"nofollow noreferrer\">http://docs.python.org/library/fractions.html</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; from fractions import Fraction\n&gt;&gt;&gt; Fraction('3.1415926535897932').limit_denominator(1000)\nFraction(355, 113)\n</code></pre>\n" }, { "answer_id": 1992465, "author": "João Lopes", "author_id": 242395, "author_profile": "https://Stackoverflow.com/users/242395", "pm_score": 1, "selected": false, "text": "<p>Completed the above code and converted it to as3</p>\n<pre class=\"lang-swift prettyprint-override\"><code>public static function toFrac(f:Number) : String\n {\n if (f&gt;1)\n {\n var parte1:int;\n var parte2:Number;\n var resultado:String;\n var loc:int = String(f).indexOf(&quot;.&quot;);\n parte2 = Number(String(f).slice(loc, String(f).length));\n parte1 = int(String(f).slice(0,loc));\n resultado = toFrac(parte2);\n parte1 *= int(resultado.slice(resultado.indexOf(&quot;/&quot;) + 1, resultado.length)) + int(resultado.slice(0, resultado.indexOf(&quot;/&quot;)));\n resultado = String(parte1) + resultado.slice(resultado.indexOf(&quot;/&quot;), resultado.length)\n return resultado;\n }\n if( f &lt; 0.47 )\n if( f &lt; 0.25 )\n if( f &lt; 0.16 )\n if( f &lt; 0.13 )\n if( f &lt; 0.11 )\n return &quot;1/10&quot;;\n else\n return &quot;1/9&quot;;\n else\n if( f &lt; 0.14 )\n return &quot;1/8&quot;;\n else\n return &quot;1/7&quot;;\n else\n if( f &lt; 0.19 )\n return &quot;1/6&quot;;\n else\n if( f &lt; 0.22 )\n return &quot;1/5&quot;;\n else\n return &quot;2/9&quot;;\n else\n if( f &lt; 0.38 )\n if( f &lt; 0.29 )\n return &quot;1/4&quot;;\n else\n if( f &lt; 0.31 )\n return &quot;2/7&quot;;\n else\n return &quot;1/3&quot;;\n else\n if( f &lt; 0.43 )\n if( f &lt; 0.40 )\n return &quot;3/8&quot;;\n else\n return &quot;2/5&quot;;\n else\n if( f &lt; 0.44 )\n return &quot;3/7&quot;;\n else\n return &quot;4/9&quot;;\n else\n if( f &lt; 0.71 )\n if( f &lt; 0.60 )\n if( f &lt; 0.56 )\n return &quot;1/2&quot;;\n else\n if( f &lt; 0.57 )\n return &quot;5/9&quot;;\n else\n return &quot;4/7&quot;;\n else\n if( f &lt; 0.63 )\n return &quot;3/5&quot;;\n else\n if( f &lt; 0.66 )\n return &quot;5/8&quot;;\n else\n return &quot;2/3&quot;;\n else\n if( f &lt; 0.80 )\n if( f &lt; 0.74 )\n return &quot;5/7&quot;;\n else\n if(f &lt; 0.78 )\n return &quot;3/4&quot;;\n else\n return &quot;7/9&quot;;\n else\n if( f &lt; 0.86 )\n if( f &lt; 0.83 )\n return &quot;4/5&quot;;\n else\n return &quot;5/6&quot;;\n else\n if( f &lt; 0.88 )\n return &quot;6/7&quot;;\n else\n if( f &lt; 0.89 )\n return &quot;7/8&quot;;\n else\n if( f &lt; 0.90 )\n return &quot;8/9&quot;;\n else\n return &quot;9/10&quot;;\n }\n</code></pre>\n" }, { "answer_id": 1992522, "author": "Debilski", "author_id": 200266, "author_profile": "https://Stackoverflow.com/users/200266", "pm_score": 5, "selected": false, "text": "<p>From Python 2.6 on there is the <a href=\"http://docs.python.org/library/fractions.html\" rel=\"nofollow noreferrer\"><code>fractions</code></a> module.</p>\n<p>(Quoting from the docs.)</p>\n<pre class=\"lang-python prettyprint-override\"><code>&gt;&gt;&gt; from fractions import Fraction\n&gt;&gt;&gt; Fraction('3.1415926535897932').limit_denominator(1000)\nFraction(355, 113)\n\n&gt;&gt;&gt; from math import pi, cos\n&gt;&gt;&gt; Fraction.from_float(cos(pi/3))\nFraction(4503599627370497, 9007199254740992)\n&gt;&gt;&gt; Fraction.from_float(cos(pi/3)).limit_denominator()\nFraction(1, 2)\n</code></pre>\n" }, { "answer_id": 2912737, "author": "valodzka", "author_id": 159550, "author_profile": "https://Stackoverflow.com/users/159550", "pm_score": 0, "selected": false, "text": "<p>Here is implementation for ruby <a href=\"http://github.com/valodzka/frac\" rel=\"nofollow noreferrer\">http://github.com/valodzka/frac</a></p>\n<pre class=\"lang-ruby prettyprint-override\"><code>Math.frac(0.2, 100) # =&gt; (1/5)\nMath.frac(0.33, 10) # =&gt; (1/3)\nMath.frac(0.33, 100) # =&gt; (33/100)\n</code></pre>\n" }, { "answer_id": 7457287, "author": "bpm", "author_id": 950575, "author_profile": "https://Stackoverflow.com/users/950575", "pm_score": 2, "selected": false, "text": "<p>I think the best way to do this is to first convert your float value to an ascii representation. In C++ you could use <code>ostringstream</code> or in C, you could use <code>sprintf</code>. Here's how it would look in C++:</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>ostringstream oss;\nfloat num;\ncin &gt;&gt; num;\noss &lt;&lt; num;\nstring numStr = oss.str();\nint i = numStr.length(), pow_ten = 0;\nwhile (i &gt; 0) {\n if (numStr[i] == '.')\n break;\n pow_ten++;\n i--;\n}\nfor (int j = 1; j &lt; pow_ten; j++) {\n num *= 10.0;\n}\ncout &lt;&lt; static_cast&lt;int&gt;(num) &lt;&lt; &quot;/&quot; &lt;&lt; pow(10, pow_ten - 1) &lt;&lt; endl;\n</code></pre>\n<p>A similar approach could be taken in straight C.</p>\n<p>Afterwards you would need to check that the fraction is in lowest terms. This algorithm will give a precise answer, i.e. 0.33 would output &quot;33/100&quot;, not &quot;1/3.&quot; However, 0.4 would give &quot;4/10,&quot; which when reduced to lowest terms would be &quot;2/5.&quot; This may not be as powerful as EppStein's solution, but I believe this is more straightforward.</p>\n" }, { "answer_id": 8584303, "author": "Tom", "author_id": 882436, "author_profile": "https://Stackoverflow.com/users/882436", "pm_score": 3, "selected": false, "text": "<p>A C# implementation</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// Represents a rational number\n/// &lt;/summary&gt;\npublic struct Fraction\n{\n public int Numerator;\n public int Denominator;\n\n /// &lt;summary&gt;\n /// Constructor\n /// &lt;/summary&gt;\n public Fraction(int numerator, int denominator)\n {\n this.Numerator = numerator;\n this.Denominator = denominator;\n }\n\n /// &lt;summary&gt;\n /// Approximates a fraction from the provided double\n /// &lt;/summary&gt;\n public static Fraction Parse(double d)\n {\n return ApproximateFraction(d);\n }\n\n /// &lt;summary&gt;\n /// Returns this fraction expressed as a double, rounded to the specified number of decimal places.\n /// Returns double.NaN if denominator is zero\n /// &lt;/summary&gt;\n public double ToDouble(int decimalPlaces)\n {\n if (this.Denominator == 0)\n return double.NaN;\n\n return System.Math.Round(\n Numerator / (double)Denominator,\n decimalPlaces\n );\n }\n\n\n /// &lt;summary&gt;\n /// Approximates the provided value to a fraction.\n /// http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions\n /// &lt;/summary&gt;\n private static Fraction ApproximateFraction(double value)\n {\n const double EPSILON = .000001d;\n\n int n = 1; // numerator\n int d = 1; // denominator\n double fraction = n / d;\n\n while (System.Math.Abs(fraction - value) &gt; EPSILON)\n {\n if (fraction &lt; value)\n {\n n++;\n }\n else\n {\n d++;\n n = (int)System.Math.Round(value * d);\n }\n\n fraction = n / (double)d;\n }\n\n return new Fraction(n, d);\n }\n}\n</code></pre>\n" }, { "answer_id": 12564894, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Let's say we have 0.33, we need to output \"1/3\". If we have \"0.4\", we\n need to output \"2/5\".</p>\n</blockquote>\n\n<p>It's wrong in common case, because of 1/3 = 0.3333333 = 0.(3)\nMoreover, it's impossible to find out from suggested above solutions is decimal can be converted to fraction with defined precision, because output is always fraction.</p>\n\n<p>BUT, i suggest my comprehensive function with many options based on idea of <a href=\"http://en.wikipedia.org/wiki/Geometric_progression#Infinite_geometric_series\" rel=\"nofollow noreferrer\">Infinite geometric series</a>, specifically on formula:</p>\n\n<p><img src=\"https://i.stack.imgur.com/S6jaC.png\" alt=\"enter image description here\"></p>\n\n<p>At first this function is trying to find period of fraction in string representation. After that described above formula is applied.</p>\n\n<p>Rational numbers code is borrowed from <a href=\"http://exif-utils.googlecode.com/svn/trunk/ExifUtils/ExifUtils/Rational.cs\" rel=\"nofollow noreferrer\">Stephen M. McKamey</a> rational numbers implementation in C#. I hope there is not very hard to port my code on other languages.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// &lt;summary&gt;\n/// Convert decimal to fraction\n/// &lt;/summary&gt;\n/// &lt;param name=\"value\"&gt;decimal value to convert&lt;/param&gt;\n/// &lt;param name=\"result\"&gt;result fraction if conversation is succsess&lt;/param&gt;\n/// &lt;param name=\"decimalPlaces\"&gt;precision of considereation frac part of value&lt;/param&gt;\n/// &lt;param name=\"trimZeroes\"&gt;trim zeroes on the right part of the value or not&lt;/param&gt;\n/// &lt;param name=\"minPeriodRepeat\"&gt;minimum period repeating&lt;/param&gt;\n/// &lt;param name=\"digitsForReal\"&gt;precision for determination value to real if period has not been founded&lt;/param&gt;\n/// &lt;returns&gt;&lt;/returns&gt;\npublic static bool FromDecimal(decimal value, out Rational&lt;T&gt; result, \n int decimalPlaces = 28, bool trimZeroes = false, decimal minPeriodRepeat = 2, int digitsForReal = 9)\n{\n var valueStr = value.ToString(\"0.0000000000000000000000000000\", CultureInfo.InvariantCulture);\n var strs = valueStr.Split('.');\n\n long intPart = long.Parse(strs[0]);\n string fracPartTrimEnd = strs[1].TrimEnd(new char[] { '0' });\n string fracPart;\n\n if (trimZeroes)\n {\n fracPart = fracPartTrimEnd;\n decimalPlaces = Math.Min(decimalPlaces, fracPart.Length);\n }\n else\n fracPart = strs[1];\n\n result = new Rational&lt;T&gt;();\n try\n {\n string periodPart;\n bool periodFound = false;\n\n int i;\n for (i = 0; i &lt; fracPart.Length; i++)\n {\n if (fracPart[i] == '0' &amp;&amp; i != 0)\n continue;\n\n for (int j = i + 1; j &lt; fracPart.Length; j++)\n {\n periodPart = fracPart.Substring(i, j - i);\n periodFound = true;\n decimal periodRepeat = 1;\n decimal periodStep = 1.0m / periodPart.Length;\n var upperBound = Math.Min(fracPart.Length, decimalPlaces);\n int k;\n for (k = i + periodPart.Length; k &lt; upperBound; k += 1)\n {\n if (periodPart[(k - i) % periodPart.Length] != fracPart[k])\n {\n periodFound = false;\n break;\n }\n periodRepeat += periodStep;\n }\n\n if (!periodFound &amp;&amp; upperBound - k &lt;= periodPart.Length &amp;&amp; periodPart[(upperBound - i) % periodPart.Length] &gt; '5')\n {\n var ind = (k - i) % periodPart.Length;\n var regroupedPeriod = (periodPart.Substring(ind) + periodPart.Remove(ind)).Substring(0, upperBound - k);\n ulong periodTailPlusOne = ulong.Parse(regroupedPeriod) + 1;\n ulong fracTail = ulong.Parse(fracPart.Substring(k, regroupedPeriod.Length));\n if (periodTailPlusOne == fracTail)\n periodFound = true;\n }\n\n if (periodFound &amp;&amp; periodRepeat &gt;= minPeriodRepeat)\n {\n result = FromDecimal(strs[0], fracPart.Substring(0, i), periodPart);\n break;\n }\n else\n periodFound = false;\n }\n\n if (periodFound)\n break;\n }\n\n if (!periodFound)\n {\n if (fracPartTrimEnd.Length &gt;= digitsForReal)\n return false;\n else\n {\n result = new Rational&lt;T&gt;(long.Parse(strs[0]), 1, false);\n if (fracPartTrimEnd.Length != 0)\n result = new Rational&lt;T&gt;(ulong.Parse(fracPartTrimEnd), TenInPower(fracPartTrimEnd.Length));\n return true;\n }\n }\n\n return true;\n }\n catch\n {\n return false;\n }\n}\n\npublic static Rational&lt;T&gt; FromDecimal(string intPart, string fracPart, string periodPart)\n{\n Rational&lt;T&gt; firstFracPart;\n if (fracPart != null &amp;&amp; fracPart.Length != 0)\n {\n ulong denominator = TenInPower(fracPart.Length);\n firstFracPart = new Rational&lt;T&gt;(ulong.Parse(fracPart), denominator);\n }\n else\n firstFracPart = new Rational&lt;T&gt;(0, 1, false);\n\n Rational&lt;T&gt; secondFracPart;\n if (periodPart != null &amp;&amp; periodPart.Length != 0)\n secondFracPart =\n new Rational&lt;T&gt;(ulong.Parse(periodPart), TenInPower(fracPart.Length)) *\n new Rational&lt;T&gt;(1, Nines((ulong)periodPart.Length), false);\n else\n secondFracPart = new Rational&lt;T&gt;(0, 1, false);\n\n var result = firstFracPart + secondFracPart;\n if (intPart != null &amp;&amp; intPart.Length != 0)\n {\n long intPartLong = long.Parse(intPart);\n result = new Rational&lt;T&gt;(intPartLong, 1, false) + (intPartLong == 0 ? 1 : Math.Sign(intPartLong)) * result;\n }\n\n return result;\n}\n\nprivate static ulong TenInPower(int power)\n{\n ulong result = 1;\n for (int l = 0; l &lt; power; l++)\n result *= 10;\n return result;\n}\n\nprivate static decimal TenInNegPower(int power)\n{\n decimal result = 1;\n for (int l = 0; l &gt; power; l--)\n result /= 10.0m;\n return result;\n}\n\nprivate static ulong Nines(ulong power)\n{\n ulong result = 9;\n if (power &gt;= 0)\n for (ulong l = 0; l &lt; power - 1; l++)\n result = result * 10 + 9;\n return result;\n}\n</code></pre>\n\n<p>There are some examples of usings:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Rational&lt;long&gt;.FromDecimal(0.33333333m, out r, 8, false);\n// then r == 1 / 3;\n\nRational&lt;long&gt;.FromDecimal(0.33333333m, out r, 9, false);\n// then r == 33333333 / 100000000;\n</code></pre>\n\n<p>Your case with right part zero part trimming:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Rational&lt;long&gt;.FromDecimal(0.33m, out r, 28, true);\n// then r == 1 / 3;\n\nRational&lt;long&gt;.FromDecimal(0.33m, out r, 28, true);\n// then r == 33 / 100;\n</code></pre>\n\n<p>Min period demostration:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Rational&lt;long&gt;.FromDecimal(0.123412m, out r, 28, true, 1.5m));\n// then r == 1234 / 9999;\nRational&lt;long&gt;.FromDecimal(0.123412m, out r, 28, true, 1.6m));\n// then r == 123412 / 1000000; because of minimu repeating of period is 0.1234123 in this case.\n</code></pre>\n\n<p>Rounding at the end:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Rational&lt;long&gt;.FromDecimal(0.8888888888888888888888888889m, out r));\n// then r == 8 == 9;\n</code></pre>\n\n<p>The most interesting case:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Rational&lt;long&gt;.FromDecimal(0.12345678m, out r, 28, true, 2, 9);\n// then r == 12345678 / 100000000;\n\nRational&lt;long&gt;.FromDecimal(0.12345678m, out r, 28, true, 2, 8);\n// Conversation failed, because of period has not been founded and there are too many digits in fraction part of input value.\n\nRational&lt;long&gt;.FromDecimal(0.12121212121212121m, out r, 28, true, 2, 9));\n// then r == 4 / 33; Despite of too many digits in input value, period has been founded. Thus it's possible to convert value to fraction.\n</code></pre>\n\n<p>Other tests and code everyone can find in <a href=\"https://github.com/KvanTTT/Math-Functions/blob/master/MathFunctions/Rational.cs\" rel=\"nofollow noreferrer\">my MathFunctions library on github</a>.</p>\n" }, { "answer_id": 13774496, "author": "Josh W Lewis", "author_id": 1406964, "author_profile": "https://Stackoverflow.com/users/1406964", "pm_score": 2, "selected": false, "text": "<p>Ruby already has a built in solution:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>0.33.rationalize.to_s # =&gt; &quot;33/100&quot;\n0.4.rationalize.to_s # =&gt; &quot;2/5&quot;\n</code></pre>\n<p>In Rails, ActiveRecord numerical attributes can be converted too:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>product.size = 0.33\nproduct.size.to_r.to_s # =&gt; &quot;33/100&quot;\n</code></pre>\n" }, { "answer_id": 14085473, "author": "Ben Bolker", "author_id": 190277, "author_profile": "https://Stackoverflow.com/users/190277", "pm_score": 2, "selected": false, "text": "<p>A built-in solution in R:</p>\n<pre class=\"lang-r prettyprint-override\"><code>library(MASS)\nfractions(0.666666666)\n## [1] 2/3\n</code></pre>\n<p>This uses a continued fraction method and has optional <code>cycles</code> and <code>max.denominator</code> arguments for adjusting the precision.</p>\n" }, { "answer_id": 20468509, "author": "Deepak Joy Cheenath", "author_id": 446215, "author_profile": "https://Stackoverflow.com/users/446215", "pm_score": 1, "selected": false, "text": "<p>Here is a quick and dirty implementation in javascript that uses a brute force approach.\nNot at all optimized, it works within a predefined range of fractions: <a href=\"http://jsfiddle.net/PdL23/1/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/PdL23/1/</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* This should convert any decimals to a simplified fraction within the range specified by the two for loops. Haven't done any thorough testing, but it seems to work fine.\n\nI have set the bounds for numerator and denominator to 20, 20... but you can increase this if you want in the two for loops.\n\nDisclaimer: Its not at all optimized. (Feel free to create an improved version.)\n*/\n\ndecimalToSimplifiedFraction = function(n) {\n \nfor(num = 1; num &lt; 20; num++) { // \"num\" is the potential numerator\n for(den = 1; den &lt; 20; den++) { // \"den\" is the potential denominator\n var multiplyByInverse = (n * den ) / num;\n \n var roundingError = Math.round(multiplyByInverse) - multiplyByInverse;\n \n // Checking if we have found the inverse of the number, \n if((Math.round(multiplyByInverse) == 1) &amp;&amp; (Math.abs(roundingError) &lt; 0.01)) {\n return num + \"/\" + den;\n }\n }\n}\n};\n\n//Put in your test number here.\nvar floatNumber = 2.56;\n\nalert(floatNumber + \" = \" + decimalToSimplifiedFraction(floatNumber));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This is inspired by the approach used by JPS.</p>\n" }, { "answer_id": 20834613, "author": "barak manos", "author_id": 1382251, "author_profile": "https://Stackoverflow.com/users/1382251", "pm_score": 2, "selected": false, "text": "<p>Answer in C++, assuming that you have a <code>BigInt</code> class, which can store unlimited-size integers.</p>\n<p>You can use <code>unsigned long long</code> instead, but it will only work for certain values.</p>\n<pre class=\"lang-c++ prettyprint-override\"><code>void GetRational(double val)\n{\n if (val == val+1) // Inf\n throw &quot;Infinite Value&quot;;\n if (val != val) // NaN\n throw &quot;Undefined Value&quot;;\n\n bool sign = false;\n BigInt enumerator = 0;\n BigInt denominator = 1;\n\n if (val &lt; 0)\n {\n val = -val;\n sign = true;\n }\n\n while (val &gt; 0)\n {\n unsigned int intVal = (unsigned int)val;\n val -= intVal;\n enumerator += intVal;\n val *= 2;\n enumerator *= 2;\n denominator *= 2;\n }\n\n BigInt gcd = GCD(enumerator,denominator);\n enumerator /= gcd;\n denominator /= gcd;\n\n Print(sign? &quot;-&quot;:&quot;+&quot;);\n Print(enumerator);\n Print(&quot;/&quot;);\n Print(denominator);\n\n // Or simply return {sign,enumerator,denominator} as you wish\n}\n</code></pre>\n<p>BTW, GetRational(0.0) will return &quot;+0/1&quot;, so you might wanna handle this case separately.</p>\n<p>P.S.: I've been using this code in my own 'RationalNum' class for several years, and it's been tested thoroughly.</p>\n" }, { "answer_id": 42197629, "author": "Kay Zed", "author_id": 344541, "author_profile": "https://Stackoverflow.com/users/344541", "pm_score": 2, "selected": false, "text": "<p>This algorithm by <a href=\"https://www.maa.org/sites/default/files/pdf/upload_library/22/Allendoerfer/1982/0025570x.di021121.02p0002y.pdf\" rel=\"nofollow noreferrer\">Ian Richards</a> / <a href=\"https://sites.google.com/site/johnkennedyshome/home/downloadable-papers/dec2frac.pdf\" rel=\"nofollow noreferrer\">John Kennedy</a> not only returns nice fractions, it also performs very well in terms of speed. This is C# code as taken from <a href=\"https://stackoverflow.com/a/42085412/344541\">this answer</a> by me.</p>\n<p>It can handle all <code>double</code> values except special values like NaN and +/- infinity, which you'll have to add if needed.</p>\n<p>It returns a <code>new Fraction(numerator, denominator)</code>. Replace by your own type.</p>\n<p><strong>For more example values and a comparison with other algorithms, <a href=\"https://stackoverflow.com/a/32903747\">go here</a></strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Fraction RealToFraction(double value, double accuracy)\n{\n if (accuracy &lt;= 0.0 || accuracy &gt;= 1.0)\n {\n throw new ArgumentOutOfRangeException(&quot;accuracy&quot;, &quot;Must be &gt; 0 and &lt; 1.&quot;);\n }\n\n int sign = Math.Sign(value);\n\n if (sign == -1)\n {\n value = Math.Abs(value);\n }\n\n // Accuracy is the maximum relative error; convert to absolute maxError\n double maxError = sign == 0 ? accuracy : value * accuracy;\n\n int n = (int) Math.Floor(value);\n value -= n;\n\n if (value &lt; maxError)\n {\n return new Fraction(sign * n, 1);\n }\n\n if (1 - maxError &lt; value)\n {\n return new Fraction(sign * (n + 1), 1);\n }\n\n double z = value;\n int previousDenominator = 0;\n int denominator = 1;\n int numerator;\n\n do\n {\n z = 1.0 / (z - (int) z);\n int temp = denominator;\n denominator = denominator * (int) z + previousDenominator;\n previousDenominator = temp;\n numerator = Convert.ToInt32(value * denominator);\n }\n while (Math.Abs(value - (double) numerator / denominator) &gt; maxError &amp;&amp; z != (int) z);\n\n return new Fraction((n * denominator + numerator) * sign, denominator);\n}\n</code></pre>\n<p>Example values returned by this algorithm:</p>\n<pre><code>Accuracy: 1.0E-3 | Richards \nInput | Result Error \n======================| =============================\n 3 | 3/1 0 \n 0.999999 | 1/1 1.0E-6 \n 1.000001 | 1/1 -1.0E-6 \n 0.50 (1/2) | 1/2 0 \n 0.33... (1/3) | 1/3 0 \n 0.67... (2/3) | 2/3 0 \n 0.25 (1/4) | 1/4 0 \n 0.11... (1/9) | 1/9 0 \n 0.09... (1/11) | 1/11 0 \n 0.62... (307/499) | 8/13 2.5E-4 \n 0.14... (33/229) | 16/111 2.7E-4 \n 0.05... (33/683) | 10/207 -1.5E-4 \n 0.18... (100/541) | 17/92 -3.3E-4 \n 0.06... (33/541) | 5/82 -3.7E-4 \n 0.1 | 1/10 0 \n 0.2 | 1/5 0 \n 0.3 | 3/10 0 \n 0.4 | 2/5 0 \n 0.5 | 1/2 0 \n 0.6 | 3/5 0 \n 0.7 | 7/10 0 \n 0.8 | 4/5 0 \n 0.9 | 9/10 0 \n 0.01 | 1/100 0 \n 0.001 | 1/1000 0 \n 0.0001 | 1/10000 0 \n 0.33333333333 | 1/3 1.0E-11 \n 0.333 | 333/1000 0 \n 0.7777 | 7/9 1.0E-4 \n 0.11 | 10/91 -1.0E-3 \n 0.1111 | 1/9 1.0E-4 \n 3.14 | 22/7 9.1E-4 \n 3.14... (pi) | 22/7 4.0E-4 \n 2.72... (e) | 87/32 1.7E-4 \n 0.7454545454545 | 38/51 -4.8E-4 \n 0.01024801004 | 2/195 8.2E-4 \n 0.99011 | 100/101 -1.1E-5 \n 0.26... (5/19) | 5/19 0 \n 0.61... (37/61) | 17/28 9.7E-4 \n | \nAccuracy: 1.0E-4 | Richards \nInput | Result Error \n======================| =============================\n 0.62... (307/499) | 299/486 -6.7E-6 \n 0.05... (33/683) | 23/476 6.4E-5 \n 0.06... (33/541) | 33/541 0 \n 1E-05 | 1/99999 1.0E-5 \n 0.7777 | 1109/1426 -1.8E-7 \n 3.14... (pi) | 333/106 -2.6E-5 \n 2.72... (e) | 193/71 1.0E-5 \n 0.61... (37/61) | 37/61 0 \n</code></pre>\n" }, { "answer_id": 46127671, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I came across an especially elegant Haskell solution making use of an anamorphism. It depends on the <a href=\"https://hackage.haskell.org/package/recursion-schemes\" rel=\"nofollow noreferrer\">recursion-schemes</a> package.</p>\n<pre class=\"lang-haskell prettyprint-override\"><code>{-# LANGUAGE AllowAmbiguousTypes #-}\n{-# LANGUAGE FlexibleContexts #-}\n\nimport Control.Applicative (liftA2)\nimport Control.Monad (ap)\nimport Data.Functor.Foldable\nimport Data.Ratio (Ratio, (%))\n\nisInteger :: (RealFrac a) =&gt; a -&gt; Bool\nisInteger = ((==) &lt;*&gt;) (realToFrac . floor)\n\ncontinuedFraction :: (RealFrac a) =&gt; a -&gt; [Int]\ncontinuedFraction = liftA2 (:) floor (ana coalgebra)\n where coalgebra x\n | isInteger x = Nil\n | otherwise = Cons (floor alpha) alpha\n where alpha = 1 / (x - realToFrac (floor x))\n\ncollapseFraction :: (Integral a) =&gt; [Int] -&gt; Ratio a\ncollapseFraction [x] = fromIntegral x % 1\ncollapseFraction (x:xs) = (fromIntegral x % 1) + 1 / collapseFraction xs\n\n-- | Use the nth convergent to approximate x\napproximate :: (RealFrac a, Integral b) =&gt; a -&gt; Int -&gt; Ratio b\napproximate x n = collapseFraction $ take n (continuedFraction x)\n</code></pre>\n<p>If you try this out in ghci, it really does work!</p>\n<pre><code>λ:&gt; approximate pi 2\n22 % 7\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4869/" ]
Let's say we have `0.33`, we need to output `1/3`. If we have `0.4`, we need to output `2/5`. The idea is to make it human-readable to make the user understand "**x parts out of y**" as a better way of understanding data. I know that percentages is a good substitute but I was wondering if there was a simple way to do this?
I have found David Eppstein's [find rational approximation to given real number](http://www.ics.uci.edu/%7Eeppstein/numth/frap.c) C code to be exactly what you are asking for. Its based on the theory of continued fractions and very fast and fairly compact. I have used versions of this customized for specific numerator and denominator limits. ```c /* ** find rational approximation to given real number ** David Eppstein / UC Irvine / 8 Aug 1993 ** ** With corrections from Arno Formella, May 2008 ** ** usage: a.out r d ** r is real number to approx ** d is the maximum denominator allowed ** ** based on the theory of continued fractions ** if x = a1 + 1/(a2 + 1/(a3 + 1/(a4 + ...))) ** then best approximation is found by truncating this series ** (with some adjustments in the last term). ** ** Note the fraction can be recovered as the first column of the matrix ** ( a1 1 ) ( a2 1 ) ( a3 1 ) ... ** ( 1 0 ) ( 1 0 ) ( 1 0 ) ** Instead of keeping the sequence of continued fraction terms, ** we just keep the last partial product of these matrices. */ #include <stdio.h> main(ac, av) int ac; char ** av; { double atof(); int atoi(); void exit(); long m[2][2]; double x, startx; long maxden; long ai; /* read command line arguments */ if (ac != 3) { fprintf(stderr, "usage: %s r d\n",av[0]); // AF: argument missing exit(1); } startx = x = atof(av[1]); maxden = atoi(av[2]); /* initialize matrix */ m[0][0] = m[1][1] = 1; m[0][1] = m[1][0] = 0; /* loop finding terms until denom gets too big */ while (m[1][0] * ( ai = (long)x ) + m[1][1] <= maxden) { long t; t = m[0][0] * ai + m[0][1]; m[0][1] = m[0][0]; m[0][0] = t; t = m[1][0] * ai + m[1][1]; m[1][1] = m[1][0]; m[1][0] = t; if(x==(double)ai) break; // AF: division by zero x = 1/(x - (double) ai); if(x>(double)0x7FFFFFFF) break; // AF: representation failure } /* now remaining x is between 0 and 1/ai */ /* approx as either 0 or 1/m where m is max that will fit in maxden */ /* first try zero */ printf("%ld/%ld, error = %e\n", m[0][0], m[1][0], startx - ((double) m[0][0] / (double) m[1][0])); /* now try other possibility */ ai = (maxden - m[1][1]) / m[1][0]; m[0][0] = m[0][0] * ai + m[0][1]; m[1][0] = m[1][0] * ai + m[1][1]; printf("%ld/%ld, error = %e\n", m[0][0], m[1][0], startx - ((double) m[0][0] / (double) m[1][0])); } ```
95,731
<p>Ran into this problem today, posting in case someone else has the same issue.</p> <pre><code>var execBtn = document.createElement('input'); execBtn.setAttribute("type", "button"); execBtn.setAttribute("id", "execBtn"); execBtn.setAttribute("value", "Execute"); execBtn.setAttribute("onclick", "runCommand();"); </code></pre> <p>Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run.</p> <pre><code>execBtn.onclick = function() { runCommand() }; </code></pre> <p><strong>BAD IDEAS:</strong></p> <p>You can do </p> <pre><code>execBtn.setAttribute("onclick", function() { runCommand() }); </code></pre> <p>but it will break in IE in non-standards mode according to @scunliffe.</p> <p>You can't do this at all </p> <pre><code>execBtn.setAttribute("onclick", runCommand() ); </code></pre> <p>because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do</p> <pre><code>execBtn.setAttribute("onclick", runCommand); </code></pre>
[ { "answer_id": 95801, "author": "Lark", "author_id": 8804, "author_profile": "https://Stackoverflow.com/users/8804", "pm_score": 1, "selected": false, "text": "<p>Did you try:</p>\n\n<pre>\n execBtn.setAttribute(\"onclick\", function() { runCommand() });\n</pre>\n" }, { "answer_id": 95859, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 2, "selected": false, "text": "<p>Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).</p>\n" }, { "answer_id": 96018, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 1, "selected": false, "text": "<p>Not relevant to the onclick issue, but also related:</p>\n\n<p>For html attributes whose name collide with javascript reserved words, an alternate name is chosen, eg. <code>&lt;div class=''&gt;</code>, but <code>div.className</code>, or <code>&lt;label for='...'&gt;</code>, but <code>label.htmlFor</code>.</p>\n\n<p>In reasonable browsers, this doesn't affect <code>setAttribute</code>. So in gecko and webkit you'd call <code>div.setAttribute('class', 'foo')</code>, but in IE you have to use the javascript property name instead, so <code>div.setAttribute('className', 'foo')</code>.</p>\n" }, { "answer_id": 98964, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 4, "selected": false, "text": "<p>There is a <strong>LARGE</strong> collection of attributes you <strong>can't set in IE</strong> using <strong>.setAttribute()</strong> which includes every inline event handler.</p>\n\n<p>See here for details:</p>\n\n<p><a href=\"http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html\" rel=\"noreferrer\">http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html</a></p>\n" }, { "answer_id": 561099, "author": "Shaike Katz", "author_id": 36899, "author_profile": "https://Stackoverflow.com/users/36899", "pm_score": 7, "selected": true, "text": "<p>to make this work in both FF and IE you must write both ways:</p>\n\n<pre><code>\n button_element.setAttribute('onclick','doSomething();'); // for FF\n button_element.onclick = function() {doSomething();}; // for IE\n</code></pre>\n\n<p>thanks to <a href=\"http://mcarthurgfx.com/blog/article/assigning-onclick-with-new-element-breaks-in-ie\" rel=\"noreferrer\">this post</a>.</p>\n\n<p><strong>UPDATE</strong>: \nThis is to demonstrate that sometimes it <em>is</em> necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden:</p>\n\n<pre><code>// get old onclick attribute\nvar onclick = button_element.getAttribute(\"onclick\"); \n\n// if onclick is not a function, it's not IE7, so use setAttribute\nif(typeof(onclick) != \"function\") { \n button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome\n\n// if onclick is a function, use the IE7 method and call onclick() in the anonymous function\n} else {\n button_element.onclick = function() { \n doSomething();\n onclick();\n }; // for IE7\n}\n</code></pre>\n" }, { "answer_id": 642929, "author": "David Berger", "author_id": 50272, "author_profile": "https://Stackoverflow.com/users/50272", "pm_score": 1, "selected": false, "text": "<p>Have you considered an event listener rather than setting the attribute? Among other things, it lets you pass parameters, which was a problem I ran into when trying to do this. You still have to do it twice for IE and Mozilla:</p>\n\n<pre><code>function makeEvent(element, callback, param, event) {\n function local() {\n return callback(param);\n }\n\n if (element.addEventListener) {\n //Mozilla\n element.addEventListener(event,local,false);\n } else if (element.attachEvent) {\n //IE\n element.attachEvent(\"on\"+event,local);\n }\n}\n\nmakeEvent(execBtn, alert, \"hey buddy, what's up?\", \"click\");\n</code></pre>\n\n<p>Just let event be a name like \"click\" or \"mouseover\".</p>\n" }, { "answer_id": 1070273, "author": "Marko", "author_id": 45516, "author_profile": "https://Stackoverflow.com/users/45516", "pm_score": 1, "selected": false, "text": "<p>I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the \"onclick\" attribute for this image I experienced the same problem, so I tried wrapping the image with an \"a\" element and making the reference point to the function like this.</p>\n\n<pre><code>var rowIndex = 1;\nvar linkDeleter = document.createElement('a');\nlinkDeleter.setAttribute('href', \"javascript:function(\" + rowIndex + \");\");\n\nvar imgDeleter = document.createElement('img');\nimgDeleter.setAttribute('alt', \"Delete\");\nimgDeleter.setAttribute('src', \"Imagenes/DeleteHS.png\");\nimgDeleter.setAttribute('border', \"0\");\n\nlinkDeleter.appendChild(imgDeleter);\n</code></pre>\n" }, { "answer_id": 1070313, "author": "cdmckay", "author_id": 62571, "author_profile": "https://Stackoverflow.com/users/62571", "pm_score": 3, "selected": false, "text": "<p>Or you could use jQuery and avoid all those issues:</p>\n\n<pre><code>var execBtn = $(\"&lt;input&gt;\", {\n type: \"button\",\n id: \"execBtn\",\n value: \"Execute\"\n })\n .click(runCommand); \n</code></pre>\n\n<p>jQuery will take care of all the cross-browser issues as well.</p>\n" }, { "answer_id": 1276399, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>In some cases the examples listed here didn't work out for me in Internet Explorer.</p>\n\n<p>Since you have to set the property with a method like this (without brackets)</p>\n\n<pre><code>HtmlElement.onclick = myMethod;\n</code></pre>\n\n<p>it won't work if you have to pass an object-name or even parameters. For the Internet Explorer you should create a new object in runtime:</p>\n\n<pre><code>HtmlElement.onclick = new Function('myMethod(' + someParameter + ')');\n</code></pre>\n\n<p>Works also on other browsers.</p>\n" }, { "answer_id": 3009590, "author": "Acorn", "author_id": 311220, "author_profile": "https://Stackoverflow.com/users/311220", "pm_score": 3, "selected": false, "text": "<p>This is an amazing function for cross-browser compatible event binding.</p>\n\n<p>Got it from <a href=\"http://js.isite.net.au/snippets/addevent\" rel=\"noreferrer\">http://js.isite.net.au/snippets/addevent</a></p>\n\n<p>With it you can just do <code>Events.addEvent(element, event, function);</code> and be worry free!</p>\n\n<p>For example: (<a href=\"http://jsfiddle.net/Zxeka/\" rel=\"noreferrer\">http://jsfiddle.net/Zxeka/</a>)</p>\n\n<pre><code>function hello() {\n alert('Hello');\n}\n\nvar button = document.createElement('input');\nbutton.value = \"Hello\";\nbutton.type = \"button\";\n\nEvents.addEvent(input_0, \"click\", hello);\n\ndocument.body.appendChild(button);\n</code></pre>\n\n<p>Here's the function:</p>\n\n<pre><code>// We create a function which is called immediately,\n// returning the actual function object. This allows us to\n// work in a separate scope and only return the functions\n// we require.\nvar Events = (function() {\n\n // For DOM2-compliant browsers.\n function addEventW3C(el, ev, f) {\n // Since IE only supports bubbling, for\n // compatibility we can't use capturing here.\n return el.addEventListener(ev, f, false);\n }\n\n function removeEventW3C(el, ev, f) {\n el.removeEventListener(ev, f, false);\n }\n\n // The function as required by IE.\n function addEventIE(el, ev, f) {\n // This is to work around a bug in IE whereby the\n // current element doesn't get passed as context.\n // We pass it via closure instead and set it as the\n // context using call().\n // This needs to be stored for removeEvent().\n // We also store the original wrapped function as a\n // property, _w.\n ((el._evts = el._evts || [])[el._evts.length]\n = function(e) { return f.call(el, e); })._w = f;\n\n // We prepend \"on\" to the event name.\n return el.attachEvent(\"on\" + ev,\n el._evts[el._evts.length - 1]);\n }\n\n function removeEventIE(el, ev, f) {\n for (var evts = el._evts || [], i = evts.length; i--; )\n if (evts[i]._w === f)\n el.detachEvent(\"on\" + ev, evts.splice(i, 1)[0]);\n }\n\n // A handler to call all events we've registered\n // on an element for legacy browsers.\n function addEventLegacyHandler(e) {\n var evts = this._evts[e.type];\n for (var i = 0; i &lt; evts.length; ++i)\n if (!evts[i].call(this, e || event))\n return false;\n }\n\n // For older browsers. We basically reimplement\n // attachEvent().\n function addEventLegacy(el, ev, f) {\n if (!el._evts)\n el._evts = {};\n\n if (!el._evts[ev])\n el._evts[ev] = [];\n\n el._evts[ev].push(f);\n\n return true;\n }\n\n function removeEventLegacy(el, ev, f) {\n // Loop through the handlers for this event type\n // and remove them if they match f.\n for (var evts = el._evts[ev] || [], i = evts.length; i--; )\n if (evts[i] === f)\n evts.splice(i, 1);\n }\n\n // Select the appropriate functions based on what's\n // available on the window object and return them.\n return window.addEventListener\n ? {addEvent: addEventW3C, removeEvent: removeEventW3C}\n : window.attachEvent\n ? {addEvent: addEventIE, removeEvent: removeEventIE}\n : {addEvent: addEventLegacy, removeEvent: removeEventLegacy};\n})();\n</code></pre>\n\n<p>If you don't want to use such a big function, this should work for almost all browsers, including IE:</p>\n\n<pre><code>if (el.addEventListener) { \n el.addEventListener('click', function, false); \n} else if (el.attachEvent) { \n el.attachEvent('onclick', function); \n} \n</code></pre>\n\n<p>In response to Craig's question. You're going to have to make a new element and copy over the attributes of the old element. This function should do the job: (<a href=\"http://www.universalwebservices.net/web-programming-resources/javascript/change-input-element-type-using-javascript\" rel=\"noreferrer\">source</a>)</p>\n\n<pre><code>function changeInputType(oldObject, oType) {\n var newObject = document.createElement('input');\n newObject.type = oType;\n if(oldObject.size) newObject.size = oldObject.size;\n if(oldObject.value) newObject.value = oldObject.value;\n if(oldObject.name) newObject.name = oldObject.name;\n if(oldObject.id) newObject.id = oldObject.id;\n if(oldObject.className) newObject.className = oldObject.className;\n oldObject.parentNode.replaceChild(newObject,oldObject);\n return newObject;\n}\n</code></pre>\n" }, { "answer_id": 9684524, "author": "Titus", "author_id": 1266526, "author_profile": "https://Stackoverflow.com/users/1266526", "pm_score": 4, "selected": false, "text": "<p>works great!</p>\n\n<p>using both ways seem to be unnecessary now: </p>\n\n<pre><code>execBtn.onclick = function() { runCommand() };\n</code></pre>\n\n<p>apparently works in every current browser.</p>\n\n<p>tested in current Firefox, IE, Safari, Opera, Chrome on Windows; Firefox\nand Epiphany on Ubuntu; not tested on Mac or mobile systems.</p>\n\n<ul>\n<li>Craig: I'd try \"document.getElementById(ID).type='password';</li>\n<li>Has anyone checked the \"AddEventListener\" approach with different engines?</li>\n</ul>\n" }, { "answer_id": 14922726, "author": "Medyancev", "author_id": 2080704, "author_profile": "https://Stackoverflow.com/users/2080704", "pm_score": 2, "selected": false, "text": "<pre><code>function CheckBrowser(){\n if(navigator.userAgent.match(/Android/i)!=null||\n navigator.userAgent.match(/BlackBerry/i)!=null||\n navigator.userAgent.match(/iPhone|iPad|iPod/i)!=null||\n navigator.userAgent.match(/Nokia/i)!=null||\n navigator.userAgent.match(/Opera M/i)!=null||\n navigator.userAgent.match(/Chrome/i)!=null)\n {\n return 'OTHER';\n }else{\n return 'IE';\n }\n}\n\n\nfunction AddButt(i){\n var new_butt = document.createElement('input');\n new_butt.setAttribute('type','button');\n new_butt.setAttribute('value','Delete Item');\n new_butt.setAttribute('id', 'answer_del_'+i);\n if(CheckBrowser()=='IE'){\n new_butt.setAttribute(\"onclick\", function() { DelElemAnswer(i) });\n }else{\n new_butt.setAttribute('onclick','javascript:DelElemAnswer('+i+');');\n }\n}\n</code></pre>\n" }, { "answer_id": 18990475, "author": "Karl", "author_id": 2812568, "author_profile": "https://Stackoverflow.com/users/2812568", "pm_score": 2, "selected": false, "text": "<p>Actually, as far as I know, dynamically created inline event-handlers DO work perfectly within Internet Explorer 8 when created with the <code>x.setAttribute()</code> command; you just have to position them properly within your JavaScript code. I stumbled across the solution to your problem (and mine) <a href=\"http://javascriptjedi.com/HTMLElement/setAttributeExperiment.html\" rel=\"nofollow\">here</a>. </p>\n\n<p>When I moved all of my statements containing <code>x.appendChild()</code> to their correct positions (i.e., immediately following the last setAttribute command within their groups), I found that EVERY single setAttribute worked in IE8 as it was supposed to, including all form input attributes (including \"name\" and \"type\" attributes, as well as my \"onclick\" event-handlers). </p>\n\n<p>I found this quite remarkable, since all I got in IE before I did this was garbage rendered across the screen, and one error after another. In addition, I found that every setAttribute still worked within the other browsers as well, so if you just remember this simple coding-practice, you'll be good to go in most cases. </p>\n\n<p>However, this solution won't work if you have to change any attributes on the fly, since they cannot be changed in IE once their HTML element has been appended to the DOM; in this case, I would imagine that one would have to delete the element from the DOM, and then recreate it and its attributes (in the correct order, of course!) for them to work properly, and not throw any errors. </p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13289/" ]
Ran into this problem today, posting in case someone else has the same issue. ``` var execBtn = document.createElement('input'); execBtn.setAttribute("type", "button"); execBtn.setAttribute("id", "execBtn"); execBtn.setAttribute("value", "Execute"); execBtn.setAttribute("onclick", "runCommand();"); ``` Turns out to get IE to run an onclick on a dynamically generated element, we can't use setAttribute. Instead, we need to set the onclick property on the object with an anonymous function wrapping the code we want to run. ``` execBtn.onclick = function() { runCommand() }; ``` **BAD IDEAS:** You can do ``` execBtn.setAttribute("onclick", function() { runCommand() }); ``` but it will break in IE in non-standards mode according to @scunliffe. You can't do this at all ``` execBtn.setAttribute("onclick", runCommand() ); ``` because it executes immediately, and sets the result of runCommand() to be the onClick attribute value, nor can you do ``` execBtn.setAttribute("onclick", runCommand); ```
to make this work in both FF and IE you must write both ways: ``` button_element.setAttribute('onclick','doSomething();'); // for FF button_element.onclick = function() {doSomething();}; // for IE ``` thanks to [this post](http://mcarthurgfx.com/blog/article/assigning-onclick-with-new-element-breaks-in-ie). **UPDATE**: This is to demonstrate that sometimes it *is* necessary to use setAttribute! This method works if you need to take the original onclick attribute from the HTML and add it to the onclick event, so that it doesn't get overridden: ``` // get old onclick attribute var onclick = button_element.getAttribute("onclick"); // if onclick is not a function, it's not IE7, so use setAttribute if(typeof(onclick) != "function") { button_element.setAttribute('onclick','doSomething();' + onclick); // for FF,IE8,Chrome // if onclick is a function, use the IE7 method and call onclick() in the anonymous function } else { button_element.onclick = function() { doSomething(); onclick(); }; // for IE7 } ```
95,760
<p>In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?</p> <p>Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here. </p>
[ { "answer_id": 97072, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 6, "selected": true, "text": "<p>For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions:</p>\n\n<ol>\n<li>mlint</li>\n<li>dependency report and </li>\n<li>coverage report</li>\n</ol>\n\n<p>Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies. To use profile, you could do </p>\n\n<pre><code>&gt;&gt; profile on % turn profiling on\n&gt;&gt; foo; % entry point to your matlab function or script\n&gt;&gt; profile off % turn profiling off\n&gt;&gt; profview % view the report\n</code></pre>\n\n<p>If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a):</p>\n\n<ol>\n<li>depfun</li>\n<li>depdir</li>\n</ol>\n\n<p>For example, </p>\n\n<pre><code>&gt;&gt; deps = depfun('foo');\n</code></pre>\n\n<p>gives a structure, deps, that contains all the dependencies of foo.m.</p>\n\n<p>From answers <a href=\"https://stackoverflow.com/a/29049918/4612\">2</a>, and <a href=\"https://stackoverflow.com/a/34621308/4612\">3</a>, newer versions of MATLAB (post 2015a) use <code>matlab.codetools.requiredFilesAndProducts</code> instead.</p>\n\n<p>See answers </p>\n\n<p>EDIT:</p>\n\n<p>Caveats thanks to @Mike Katz comments</p>\n\n<blockquote>\n <ul>\n <li><p>Remember that the Profiler will only\n show you files that were actually used\n in those runs, so if you don't go\n through every branch, you may have\n additional dependencies. The\n dependency report is a good tool, but\n only resolves static dependencies on\n the path and just for the files in a\n single directory. </p></li>\n <li><p>Depfun is more reliable but gives you\n every possible thing it can think of,\n and still misses LOAD's and EVAL's.</p></li>\n </ul>\n</blockquote>\n" }, { "answer_id": 29049918, "author": "Jonas Stein", "author_id": 1749675, "author_profile": "https://Stackoverflow.com/users/1749675", "pm_score": 3, "selected": false, "text": "<p>For <code>MATLAB 2015a</code> and later you should preferably look at <a href=\"http://www.mathworks.com/help/matlab/ref/matlab.codetools.requiredfilesandproducts.html\" rel=\"noreferrer\">matlab.codetools.requiredFilesAndProducts</a></p>\n\n<p>or <code>doc matlab.codetools.requiredFilesAndProducts</code></p>\n\n<p>because <code>depfun</code> is marked to be removed in a future release.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17231/" ]
In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this? Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here.
For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions: 1. mlint 2. dependency report and 3. coverage report Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies. To use profile, you could do ``` >> profile on % turn profiling on >> foo; % entry point to your matlab function or script >> profile off % turn profiling off >> profview % view the report ``` If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a): 1. depfun 2. depdir For example, ``` >> deps = depfun('foo'); ``` gives a structure, deps, that contains all the dependencies of foo.m. From answers [2](https://stackoverflow.com/a/29049918/4612), and [3](https://stackoverflow.com/a/34621308/4612), newer versions of MATLAB (post 2015a) use `matlab.codetools.requiredFilesAndProducts` instead. See answers EDIT: Caveats thanks to @Mike Katz comments > > * Remember that the Profiler will only > show you files that were actually used > in those runs, so if you don't go > through every branch, you may have > additional dependencies. The > dependency report is a good tool, but > only resolves static dependencies on > the path and just for the files in a > single directory. > * Depfun is more reliable but gives you > every possible thing it can think of, > and still misses LOAD's and EVAL's. > > >
95,767
<p>We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.</p>
[ { "answer_id": 95823, "author": "Karl", "author_id": 17613, "author_profile": "https://Stackoverflow.com/users/17613", "pm_score": 0, "selected": false, "text": "<p>There are two ways:</p>\n\n<ol>\n<li>/* Install a Thread.UncaughtExceptionHandler on the EDT */</li>\n<li>Set a system property:\nSystem.setProperty(\"sun.awt.exception.handler\",MyExceptionHandler.class.getName());</li>\n</ol>\n\n<p>I don't know if the latter works on non-SUN jvms.</p>\n\n<p>--</p>\n\n<p>Indeed, the first is not correct, it's only a mechanism for detecting a crashed thread.</p>\n" }, { "answer_id": 97176, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 4, "selected": true, "text": "<p>There is a distinction between uncaught exceptions in the EDT and outside the EDT.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java#75439\">Another question has a solution for both</a> but if you want just the EDT portion chewed up...</p>\n\n<pre><code>class AWTExceptionHandler {\n\n public void handle(Throwable t) {\n try {\n // insert your exception handling code here\n // or do nothing to make it go away\n } catch (Throwable t) {\n // don't let the exception get thrown out, will cause infinite looping!\n }\n }\n\n public static void registerExceptionHandler() {\n System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName())\n }\n}\n</code></pre>\n" }, { "answer_id": 107439, "author": "Roland Schneider", "author_id": 16515, "author_profile": "https://Stackoverflow.com/users/16515", "pm_score": 2, "selected": false, "text": "<p>A little addition to <i>shemnon</i>s anwer:<br>\nThe first time an uncaught RuntimeException (or Error) occurs in the EDT it is looking for the property \"sun.awt.exception.handler\" and tries to load the class associated with the property. EDT needs the Handler class to have a default constructor, otherwise the EDT will not use it.<br>\nIf you need to bring a bit more dynamics into the handling story you are forced to do this with static operations, because the class is instantiated by the EDT and therefore has no chance to access other resources other than static. Here is the exception handler code from our Swing framework we are using. It was written for Java 1.4 and it worked quite fine there:</p>\n\n<pre><code>public class AwtExceptionHandler {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AwtExceptionHandler.class);\n\n private static List exceptionHandlerList = new LinkedList();\n\n /**\n * WARNING: Don't change the signature of this method!\n */\n public void handle(Throwable throwable) {\n if (exceptionHandlerList.isEmpty()) {\n LOGGER.error(\"Uncatched Throwable detected\", throwable);\n } else {\n delegate(new ExceptionEvent(throwable));\n }\n }\n\n private void delegate(ExceptionEvent event) {\n for (Iterator handlerIterator = exceptionHandlerList.iterator(); handlerIterator.hasNext();) {\n IExceptionHandler handler = (IExceptionHandler) handlerIterator.next();\n\n try {\n handler.handleException(event);\n if (event.isConsumed()) {\n break;\n }\n } catch (Throwable e) {\n LOGGER.error(\"Error while running exception handler: \" + handler, e);\n }\n }\n }\n\n public static void addErrorHandler(IExceptionHandler exceptionHandler) {\n exceptionHandlerList.add(exceptionHandler);\n }\n\n public static void removeErrorHandler(IExceptionHandler exceptionHandler) {\n exceptionHandlerList.remove(exceptionHandler);\n }\n\n}\n</code></pre>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 27859016, "author": "ToYonos", "author_id": 2003986, "author_profile": "https://Stackoverflow.com/users/2003986", "pm_score": 4, "selected": false, "text": "<p>Since Java 7, you have to do it differently as the <code>sun.awt.exception.handler</code> hack does not work anymore.</p>\n\n<p><a href=\"https://stackoverflow.com/a/27858065/2003986\">Here is the solution</a> (from <a href=\"http://www.javaspecialists.eu/archive/Issue196.html\" rel=\"noreferrer\">Uncaught AWT Exceptions in Java 7</a>).</p>\n\n<pre><code>// Regular Exception\nThread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());\n\n// EDT Exception\nSwingUtilities.invokeAndWait(new Runnable()\n{\n public void run()\n {\n // We are in the event dispatching thread\n Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());\n }\n});\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18117/" ]
We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.
There is a distinction between uncaught exceptions in the EDT and outside the EDT. [Another question has a solution for both](https://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java#75439) but if you want just the EDT portion chewed up... ``` class AWTExceptionHandler { public void handle(Throwable t) { try { // insert your exception handling code here // or do nothing to make it go away } catch (Throwable t) { // don't let the exception get thrown out, will cause infinite looping! } } public static void registerExceptionHandler() { System.setProperty('sun.awt.exception.handler', AWTExceptionHandler.class.getName()) } } ```
95,820
<p>Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say <pre>if($hash{X}) { ... }</pre></p> <p>Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.</p>
[ { "answer_id": 95826, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 8, "selected": true, "text": "<pre><code>%hash = map { $_ =&gt; 1 } @array;\n</code></pre>\n\n<p>It's not as short as the \"@hash{@array} = ...\" solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.</p>\n\n<p>What this does is take each element in the array and pair it up with a \"1\". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.</p>\n" }, { "answer_id": 95888, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 5, "selected": false, "text": "<pre><code>@hash{@keys} = undef;\n</code></pre>\n\n<p>The syntax here where you are referring to the hash with an <code>@</code> is a hash slice. We're basically saying <code>$hash{$keys[0]}</code> AND <code>$hash{$keys[1]}</code> AND <code>$hash{$keys[2]}</code> ... is a list on the left hand side of the =, an lvalue, and we're assigning to that list, which actually goes into the hash and sets the values for all the named keys. In this case, I only specified one value, so that value goes into <code>$hash{$keys[0]}</code>, and the other hash entries all auto-vivify (come to life) with undefined values. [My original suggestion here was set the expression = 1, which would've set that one key to 1 and the others to <code>undef</code>. I changed it for consistency, but as we'll see below, the exact values do not matter.]</p>\n\n<p>When you realize that the lvalue, the expression on the left hand side of the =, is a list built out of the hash, then it'll start to make some sense why we're using that <code>@</code>. [Except I think this will change in Perl 6.]</p>\n\n<p>The idea here is that you are using the hash as a set. What matters is not the value I am assigning; it's just the existence of the keys. So what you want to do is not something like:</p>\n\n<pre><code>if ($hash{$key} == 1) # then key is in the hash\n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>if (exists $hash{$key}) # then key is in the set\n</code></pre>\n\n<p>It's actually more efficient to just run an <code>exists</code> check than to bother with the value in the hash, although to me the important thing here is just the concept that you are representing a set just with the keys of the hash. Also, somebody pointed out that by using <code>undef</code> as the value here, we will consume less storage space than we would assigning a value. (And also generate less confusion, as the value does not matter, and my solution would assign a value only to the first element in the hash and leave the others <code>undef</code>, and some other solutions are turning cartwheels to build an array of values to go into the hash; completely wasted effort).</p>\n" }, { "answer_id": 95998, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "<p>Raldi's solution can be tightened up to this (the '=>' from the original is not necessary):</p>\n\n<pre><code>my %hash = map { $_,1 } @array;\n</code></pre>\n\n<p>This technique can also be used for turning text lists into hashes:</p>\n\n<pre><code>my %hash = map { $_,1 } split(\",\",$line)\n</code></pre>\n\n<p>Additionally if you have a line of values like this: \"foo=1,bar=2,baz=3\" you can do this:</p>\n\n<pre><code>my %hash = map { split(\"=\",$_) } split(\",\",$line);\n</code></pre>\n\n<p>[EDIT to include]</p>\n\n<hr>\n\n<p>Another solution offered (which takes two lines) is:</p>\n\n<pre><code>my %hash;\n#The values in %hash can only be accessed by doing exists($hash{$key})\n#The assignment only works with '= undef;' and will not work properly with '= 1;'\n#if you do '= 1;' only the hash key of $array[0] will be set to 1;\n@hash{@array} = undef;\n</code></pre>\n" }, { "answer_id": 96088, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 5, "selected": false, "text": "<pre><code> @hash{@array} = (1) x @array;\n</code></pre>\n\n<p>It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.</p>\n\n<p>From <a href=\"http://perldoc.perl.org/perldata.html#Slices\" rel=\"noreferrer\">the docs</a>:</p>\n\n<blockquote>\n <p>If you're confused about why you use\n an '@' there on a hash slice instead\n of a '%', think of it like this. The\n type of bracket (square or curly)\n governs whether it's an array or a\n hash being looked at. On the other\n hand, the leading symbol ('$' or '@')\n on the array or hash indicates whether\n you are getting back a singular value\n (a scalar) or a plural one (a list).</p>\n</blockquote>\n" }, { "answer_id": 96543, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<p>You could also use <a href=\"http://search.cpan.org/~cfranks/Perl6-Junction-1.40000/lib/Perl6/Junction.pm\" rel=\"nofollow noreferrer\">Perl6::Junction</a>.</p>\n\n<pre><code>use Perl6::Junction qw'any';\n\nmy @arr = ( 1, 2, 3 );\n\nif( any(@arr) == 1 ){ ... }\n</code></pre>\n" }, { "answer_id": 98128, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 3, "selected": false, "text": "<p>In perl 5.10, there's the close-to-magic ~~ operator:</p>\n\n<pre><code>sub invite_in {\n my $vampires = [ qw(Angel Darla Spike Drusilla) ];\n return ($_[0] ~~ $vampires) ? 0 : 1 ;\n}\n</code></pre>\n\n<p>See here: <a href=\"http://dev.perl.org/perl5/news/2007/perl-5.10.0.html\" rel=\"nofollow noreferrer\">http://dev.perl.org/perl5/news/2007/perl-5.10.0.html</a></p>\n" }, { "answer_id": 98382, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 4, "selected": false, "text": "<p>Note that if typing <code>if ( exists $hash{ key } )</code> isn’t too much work for you (which I prefer to use since the matter of interest is really the presence of a key rather than the truthiness of its value), then you can use the short and sweet</p>\n\n<pre><code>@hash{@key} = ();\n</code></pre>\n" }, { "answer_id": 99579, "author": "arclight", "author_id": 13366, "author_profile": "https://Stackoverflow.com/users/13366", "pm_score": 3, "selected": false, "text": "<p>There is a presupposition here, that the most efficient way to do a lot of &quot;Does the array contain X?&quot; checks is to convert the array to a hash. Efficiency depends on the scarce resource, often time but sometimes space and sometimes programmer effort. You are at least doubling the memory consumed by keeping a list and a hash of the list around simultaneously. Plus you're writing more original code that you'll need to test, document, etc.</p>\n<p>As an alternative, look at the List::MoreUtils module, specifically the functions <code>any()</code>, <code>none()</code>, <code>true()</code> and <code>false()</code>. They all take a block as the conditional and a list as the argument, similar to <code>map()</code> and <code>grep()</code>:</p>\n<p><code>print &quot;At least one value undefined&quot; if any { !defined($_) } @list;</code></p>\n<p>I ran a quick test, loading in half of /usr/share/dict/words to an array (25000 words), then looking for eleven words selected from across the whole dictionary (every 5000th word) in the array, using both the array-to-hash method and the <code>any()</code> function from List::MoreUtils.</p>\n<p>On Perl 5.8.8 built from source, the array-to-hash method runs almost 1100x faster than the <code>any()</code> method (1300x faster under Ubuntu 6.06's packaged Perl 5.8.7.)</p>\n<p>That's not the full story however - the array-to-hash conversion takes about 0.04 seconds which in this case kills the time efficiency of array-to-hash method to 1.5x-2x faster than the <code>any()</code> method. Still good, but not nearly as stellar.</p>\n<p>My gut feeling is that the array-to-hash method is going to beat <code>any()</code> in most cases, but I'd feel a whole lot better if I had some more solid metrics (lots of test cases, decent statistical analyses, maybe some big-O algorithmic analysis of each method, etc.) Depending on your needs, List::MoreUtils may be a better solution; it's certainly more flexible and requires less coding. Remember, premature optimization is a sin... :)</p>\n" }, { "answer_id": 103615, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You might also want to check out <a href=\"http://search.cpan.org/~gsar/Tie-IxHash-1.21/lib/Tie/IxHash.pm\" rel=\"nofollow noreferrer\">Tie::IxHash</a>, which implements ordered associative arrays. That would allow you to do both types of lookups (hash and index) on one copy of your data.</p>\n" }, { "answer_id": 111645, "author": "zby", "author_id": 20028, "author_profile": "https://Stackoverflow.com/users/20028", "pm_score": 1, "selected": false, "text": "<p>If you do a lot of set theoretic operations - you can also use <a href=\"http://search.cpan.org/~jhi/Set-Scalar-1.22/lib/Set/Scalar.pm\" rel=\"nofollow noreferrer\">Set::Scalar</a> or similar module. Then <code>$s = Set::Scalar-&gt;new( @array )</code> will build the Set for you - and you can query it with: <code>$s-&gt;contains($m)</code>.</p>\n" }, { "answer_id": 111793, "author": "Keith", "author_id": 9444, "author_profile": "https://Stackoverflow.com/users/9444", "pm_score": 3, "selected": false, "text": "<p>I always thought that </p>\n\n<pre><code>foreach my $item (@array) { $hash{$item} = 1 }\n</code></pre>\n\n<p>was at least nice and readable / maintainable.</p>\n" }, { "answer_id": 264160, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 1, "selected": false, "text": "<p>You can place the code into a subroutine, if you don't want pollute your namespace.</p>\n\n<pre><code>my $hash_ref =\n sub{\n my %hash;\n @hash{ @{[ qw'one two three' ]} } = undef;\n return \\%hash;\n }-&gt;();\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>sub keylist(@){\n my %hash;\n @hash{@_} = undef;\n return \\%hash;\n}\n\nmy $hash_ref = keylist qw'one two three';\n\n# or\n\nmy @key_list = qw'one two three';\nmy $hash_ref = keylist @key_list;\n</code></pre>\n\n<p>If you really wanted to pass an array reference:</p>\n\n<pre><code>sub keylist(\\@){\n my %hash;\n @hash{ @{$_[0]} } = undef if @_;\n return \\%hash;\n}\n\nmy @key_list = qw'one two three';\nmy $hash_ref = keylist @key_list;\n</code></pre>\n" }, { "answer_id": 7415443, "author": "Mark Dibley", "author_id": 944469, "author_profile": "https://Stackoverflow.com/users/944469", "pm_score": 1, "selected": false, "text": "<pre><code>#!/usr/bin/perl -w\n\nuse strict;\nuse Data::Dumper;\n\nmy @a = qw(5 8 2 5 4 8 9);\nmy @b = qw(7 6 5 4 3 2 1);\nmy $h = {};\n\n@{$h}{@a} = @b;\n\nprint Dumper($h);\n</code></pre>\n\n<p>gives (note repeated keys get the value at the greatest position in the array - ie 8->2 and not 6)</p>\n\n<pre><code>$VAR1 = {\n '8' =&gt; '2',\n '4' =&gt; '3',\n '9' =&gt; '1',\n '2' =&gt; '5',\n '5' =&gt; '4'\n };\n</code></pre>\n" }, { "answer_id": 7615613, "author": "Tamzin Blake", "author_id": 650551, "author_profile": "https://Stackoverflow.com/users/650551", "pm_score": 3, "selected": false, "text": "<p>Also worth noting for completeness, my usual method for doing this with 2 same-length arrays <code>@keys</code> and <code>@vals</code> which you would prefer were a hash...</p>\n\n<p><code>my %hash = map { $keys[$_] =&gt; $vals[$_] } (0..@keys-1);</code></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say ``` if($hash{X}) { ... } ``` Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.
``` %hash = map { $_ => 1 } @array; ``` It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash. What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.
95,824
<p>I'm looking for a way to do a substring replace on a string in LaTeX. What I'd like to do is build a command that I can call like this:</p> <pre><code>\replace{File,New} </code></pre> <p>and that would generate something like</p> <pre><code>\textbf{File}$\rightarrow$\textbf{New} </code></pre> <p>This is a simple example, but I'd like to be able to put formatting/structure in a single command rather than everywhere in the document. I know that I could build several commands that take increasing numbers of parameters, but I'm hoping that there is an easier way. </p> <p><strong>Edit for clarification</strong></p> <p>I'm looking for an equivalent of </p> <pre><code>string.replace(",", "$\rightarrow$) </code></pre> <p>something that can take an arbitrary string, and replace a substring with another substring.</p> <p>So I could call the command with \replace{File}, \replace{File,New}, \replace{File,Options,User}, etc., wrap the words with bold formatting, and replace any commas with the right arrow command. Even if the "wrapping with bold" bit is too difficult (as I think it might be), just the replace part would be helpful.</p>
[ { "answer_id": 95959, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": -1, "selected": false, "text": "<p>OK, I withdraw this answer. Thanks for clarifying the question.</p>\n\n<hr>\n\n<p>I suspect this may not be what you want, but here goes anyway:</p>\n\n<pre><code>\\newcommand{\\replace}[2]{\\textbf{#1}$\\rightarrow$\\textbf{#2}} \n\\replace{File}{New} \n</code></pre>\n\n<p>If this isn't what you're looking for, could you clarify the question, please?</p>\n" }, { "answer_id": 101032, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 2, "selected": false, "text": "<p>There's a LaTeX package called <a href=\"http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=tokenizer\" rel=\"nofollow noreferrer\"><em>tokenizer</em></a> which may help you to do what you want.</p>\n\n<p>Here's a hack (but pure LaTeX, no internals) which gets close to what I think you want, but with some extraneous spaces I haven't quite been able to fix. Perhaps <a href=\"https://stackoverflow.com/users/4161/will-robertson\">Will Robertson</a> can advise further? Unlike his slightly more polished answer, I haven't parameterised the bits and pieces, Here goes:</p>\n\n<pre><code>\\usepackage{forloop} \n\\usepackage[trim]{tokenizer} \n... \n\\newcounter{rrCount} \n\\newcommand{\\replace}[1]{% \n \\GetTokens{rrFirst}{rrRest}{#1,}% \n \\textbf{\\rrFirst}% \n \\forloop{rrCount}{0}{\\value{rrCount} &lt; 100}{% \n \\ifthenelse{\\equal{\\rrRest}{}}{% \n \\setcounter{rrCount}{101}% \n }{% \n \\GetTokens{rrFirst}{rrRest}{\\rrRest}% \n $\\rightarrow$\\textbf{\\rrFirst}% \n }% \n }% \n}% \n% ----------------------------------------------------------------- \n\\replace{a1}\\\\ \n\\replace{a2,b2}\\\\ \n\\replace{a3,b3,c3}\\\\ \n</code></pre>\n" }, { "answer_id": 101403, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": true, "text": "<p>The general case is rather more tricky (when you're not using commas as separators), but the example you gave can be coded without too much trouble with some knowledge of the LaTeX internals.</p>\n\n<pre><code>\\documentclass[12pt]{article}\n\\makeatletter\n\\newcommand\\formatnice[1]{%\n \\let\\@formatsep\\@formatsepinit\n \\@for\\@ii:=#1\\do{%\n \\@formatsep\n \\formatentry{\\@ii}%\n }%\n}\n\\def\\@formatsepinit{\\let\\@formatsep\\formatsep}\n\\makeatother\n\\newcommand\\formatsep{,}\n\\newcommand\\formatentry[1]{#1}\n\\begin{document}\n\\formatnice{abc,def}\n\n\\renewcommand\\formatsep{\\,$\\rightarrow$\\,}\n\\renewcommand\\formatentry[1]{\\textbf{#1}}\n\\formatnice{abc,def}\n\\end{document}\n</code></pre>\n" }, { "answer_id": 971839, "author": "Paul Biggar", "author_id": 104021, "author_profile": "https://Stackoverflow.com/users/104021", "pm_score": 2, "selected": false, "text": "<p>Try the <a href=\"http://www.ctan.org/pkg/xstring\" rel=\"nofollow noreferrer\"><code>xstring</code> package</a>:</p>\n\n<pre><code>\\usepackage{xstring}\n\n[…]\n\n\\StrSubstitute{File,New}{,}{\\(\\rightarrow\\)}\n</code></pre>\n" }, { "answer_id": 5121142, "author": "Becheru Petru-Ioan", "author_id": 634651, "author_profile": "https://Stackoverflow.com/users/634651", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>it looks like your \"spaces\" problem is from a bug in that package. If you surround the \"\\GetTokens\" macro with, say, commas, then you'll see that the extra space is inserted by that macro.</p>\n</blockquote>\n\n<p>Yes there are bugs in tokenizer package. As I said on my <a href=\"http://b-p-i.blogspot.com/2011/02/bugfix-remove-unwanted-spaces-in.html\" rel=\"nofollow\">blog</a>, the bugfix is to use the following correcting code instead of just \"\\usepackage[trim]{tokenizer}\":</p>\n\n<pre><code>\\usepackage[trim]{tokenizer} \n\n\\def\\SH@GetTokens#1,#2\\@empty{%\n \\def\\SH@token{#1}%\n \\ifx\\SH@trimtokens\\SH@true% strip spaces if requested\n \\TrimSpaces\\SH@token%\n \\fi%\n \\SH@DefineCommand{\\SH@FirstArgName}{\\SH@token}%\n \\SH@DefineCommand{\\SH@SecondArgName}{#2}%\n }\n\\def\\SH@CheckTokenSep#1,#2\\@empty{%\n \\def\\SH@CTSArgTwo{#2}%\n \\ifx\\SH@CTSArgTwo\\@empty%\n \\edef\\SH@TokenValid{\\SH@false}%\n \\else%\n \\edef\\SH@TokenValid{\\SH@true}%\n \\fi%\n }\n</code></pre>\n\n<p>I will report this bugfix to the developer <a href=\"http://www.scmp.uni-koeln.de/mitarbeiter/herpers.htm\" rel=\"nofollow\">Sascha Herpers</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1322/" ]
I'm looking for a way to do a substring replace on a string in LaTeX. What I'd like to do is build a command that I can call like this: ``` \replace{File,New} ``` and that would generate something like ``` \textbf{File}$\rightarrow$\textbf{New} ``` This is a simple example, but I'd like to be able to put formatting/structure in a single command rather than everywhere in the document. I know that I could build several commands that take increasing numbers of parameters, but I'm hoping that there is an easier way. **Edit for clarification** I'm looking for an equivalent of ``` string.replace(",", "$\rightarrow$) ``` something that can take an arbitrary string, and replace a substring with another substring. So I could call the command with \replace{File}, \replace{File,New}, \replace{File,Options,User}, etc., wrap the words with bold formatting, and replace any commas with the right arrow command. Even if the "wrapping with bold" bit is too difficult (as I think it might be), just the replace part would be helpful.
The general case is rather more tricky (when you're not using commas as separators), but the example you gave can be coded without too much trouble with some knowledge of the LaTeX internals. ``` \documentclass[12pt]{article} \makeatletter \newcommand\formatnice[1]{% \let\@formatsep\@formatsepinit \@for\@ii:=#1\do{% \@formatsep \formatentry{\@ii}% }% } \def\@formatsepinit{\let\@formatsep\formatsep} \makeatother \newcommand\formatsep{,} \newcommand\formatentry[1]{#1} \begin{document} \formatnice{abc,def} \renewcommand\formatsep{\,$\rightarrow$\,} \renewcommand\formatentry[1]{\textbf{#1}} \formatnice{abc,def} \end{document} ```
95,834
<p>I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM.</p> <p>I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs.</p> <p>The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.</p>
[ { "answer_id": 96672, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": true, "text": "<p>I can not see what failure you have that does not calls the Dispose() method. I made a test with a sequential workflow that contains only a code activity which just throws an exception and the Dispose() method of my workflow is called twice (this is because of the standard WorkflowTerminated event handler). Check the following code:</p>\n\n<p>Program.cs</p>\n\n<pre><code> class Program\n {\n static void Main(string[] args)\n {\n using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())\n {\n AutoResetEvent waitHandle = new AutoResetEvent(false);\n workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) \n {\n waitHandle.Set();\n };\n workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)\n {\n Console.WriteLine(e.Exception.Message);\n waitHandle.Set();\n };\n\n WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));\n instance.Start();\n\n waitHandle.WaitOne();\n }\n Console.ReadKey();\n }\n }\n</code></pre>\n\n<p>Workflow1.cs</p>\n\n<pre><code> public sealed partial class Workflow1: SequentialWorkflowActivity\n {\n public Workflow1()\n {\n InitializeComponent();\n this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);\n }\n\n [DebuggerStepThrough()]\n private void codeActivity1_ExecuteCode(object sender, EventArgs e)\n {\n Console.WriteLine(\"Throw ApplicationException.\");\n throw new ApplicationException();\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n // Here you must free your resources \n // by calling your COM helper Dispose() method\n Console.WriteLine(\"Object disposed.\");\n }\n }\n }\n</code></pre>\n\n<p>Am I missing something? Concerning the lifecycle-related methods of an Activity (and consequently of a Workflow) object, please check this post: <a href=\"http://blogs.msdn.com/advancedworkflow/archive/2006/02/22/537412.aspx\" rel=\"nofollow noreferrer\">Activity \"Lifetime\" Methods</a>. If you just want a generic article about disposing, check <a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx\" rel=\"nofollow noreferrer\">this</a>.</p>\n" }, { "answer_id": 97059, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 0, "selected": false, "text": "<p>Basically, you should not rely on hand code to call Dispose() on your object at the end of the work. You probably have something like this right now:</p>\n\n<pre><code>MyComHelper helper = new MyComHelper();\nhelper.DoStuffWithExcel();\nhelper.Dispose();\n...\n</code></pre>\n\n<p>Instead, you need to use try blocks to catch any exception that might be triggered and call dispose at that point. This is the canonical way:</p>\n\n<pre><code>MyComHelper helper = new MyComHelper();\ntry\n{\n helper.DoStuffWithExcel();\n}\nfinally()\n{\n helper.Dispose();\n}\n</code></pre>\n\n<p>This is <em>so</em> common that C# has a special construct that generates <strong>the same exact code</strong> <em>[see note]</em> as shown above; this is what you should be doing most of the time (unless you have some special object construction semantics that make a manual pattern like the above easier to work with):</p>\n\n<pre><code>using(MyComHelper helper = new MyComHelper())\n{\n helper.DoStuffWithExcel();\n}\n</code></pre>\n\n<p><strong>EDIT</strong>:<br>\nNOTE: The actual code generated is a tiny bit more complicated than the second example above, because it also introduces a new local scope that makes the helper object unavailable after the <code>using</code> block. It's like if the second code block was surrounded by { }'s. That was omitted for clarify of the explanation.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7565/" ]
I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM. I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs. The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.
I can not see what failure you have that does not calls the Dispose() method. I made a test with a sequential workflow that contains only a code activity which just throws an exception and the Dispose() method of my workflow is called twice (this is because of the standard WorkflowTerminated event handler). Check the following code: Program.cs ``` class Program { static void Main(string[] args) { using(WorkflowRuntime workflowRuntime = new WorkflowRuntime()) { AutoResetEvent waitHandle = new AutoResetEvent(false); workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { waitHandle.Set(); }; workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine(e.Exception.Message); waitHandle.Set(); }; WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1)); instance.Start(); waitHandle.WaitOne(); } Console.ReadKey(); } } ``` Workflow1.cs ``` public sealed partial class Workflow1: SequentialWorkflowActivity { public Workflow1() { InitializeComponent(); this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode); } [DebuggerStepThrough()] private void codeActivity1_ExecuteCode(object sender, EventArgs e) { Console.WriteLine("Throw ApplicationException."); throw new ApplicationException(); } protected override void Dispose(bool disposing) { if (disposing) { // Here you must free your resources // by calling your COM helper Dispose() method Console.WriteLine("Object disposed."); } } } ``` Am I missing something? Concerning the lifecycle-related methods of an Activity (and consequently of a Workflow) object, please check this post: [Activity "Lifetime" Methods](http://blogs.msdn.com/advancedworkflow/archive/2006/02/22/537412.aspx). If you just want a generic article about disposing, check [this](http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx).
95,842
<p>The name of a temporary table such as #t1 can be determined using </p> <pre><code>select @TableName = [Name] from tempdb.sys.tables where [Object_ID] = object_id('tempDB.dbo.#t1') </code></pre> <p>How can I find the name of a table valued variable, i.e. one declared by</p> <pre><code>declare @t2 as table (a int) </code></pre> <p>the purpose is to be able to get meta-information about the table, using something like</p> <pre><code>select @Headers = dbo.Concatenate('[' + c.[Name] + ']') from sys.all_columns c inner join sys.tables t on c.object_id = t.object_id where t.name = @TableName </code></pre> <p>although for temp tables you have to look in <code>tempdb.sys.tables</code> instead of <code>sys.tables</code>. where do you look for table valued variables?</p> <hr> <p>I realize now that I can't do what I wanted to do, which is write a generic function for formatting table valued variables into html tables. For starters, in sql server 2005 you can't pass table valued parameters:</p> <p><a href="http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters" rel="nofollow noreferrer">http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters</a></p> <p>moreover, in sql server 2008, the parameters have to be strongly typed, so you will always know the number and type of columns.</p>
[ { "answer_id": 95874, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": -1, "selected": true, "text": "<p>I don't believe you can, as table variables are created in memory not in tempdb.</p>\n" }, { "answer_id": 96351, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 1, "selected": false, "text": "<p>From Books Online:</p>\n\n<p>A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared. </p>\n\n<p>Given this, there should be no need to look up this value at run-time because you have to know it at design-time.</p>\n" }, { "answer_id": 215844, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": -1, "selected": false, "text": "<p>On the topic of passing arbitrary lists/arrays into a SQL Server 2005 function or sproc, <br/>the least hokey way I know is to use an XML variable. If desired, that XML variable can be a strongly typed XML type that is associated w/ an XML Schema.</p>\n\n<p>Given a list passed into a procedure/function as XML, you can extract that list into a table variable or temp table via \"shredding\".\n\"To shred\" XML means to transform in the opposite direction--from XML to rowset(s). (The FOR XML clause causes a rowset to XML transformation.) </p>\n\n<p>In the user-defined table function </p>\n\n<pre><code>CREATE FUNCTION [dbo].[udtShredXmlInputBondIdList] \n( \n-- Add the parameters for the function here\n@xmlInputBondIdList xml\n)\nRETURNS \n@tblResults TABLE \n(\n-- Add the column definitions for the TABLE variable here\n BondId int \n)\nAS\nBEGIN\n-- Should add a schema validation for @xmlInputIssuerIdList here\n--Place validation here\n-- Fill the table variable with the rows for your result set\nINSERT @tblResults\nSELECT \nnref.value('.', 'int') as BondId\nFROM\[email protected]('//BondID') as R(nref)\nRETURN \nEND\n</code></pre>\n\n<p>if the @xmlInputBondIdList is an XML fragment of the expected structure like that immediately below and is invoked as follows</p>\n\n<pre><code>DECLARE @xmlInputBondIdList xml\nSET @xmlInputBondIdList =\n'&lt;XmlInputBondIdList&gt;\n\n&lt;BondID&gt;8681&lt;/BondID&gt;\n\n&lt;BondID&gt;8680&lt;/BondID&gt;\n\n&lt;BondID&gt;8684&lt;/BondID&gt;\n\n&lt;/XmlInputBondIdList&gt;\n'\n\nSELECT * \nFROM [CorporateBond].[dbo].[udtShredXmlInputBondIdList] \n (@xmlInputBondIdList)\n</code></pre>\n\n<p>the result will be the rowset </p>\n\n<p>BondId</p>\n\n<p>8681</p>\n\n<p>8680</p>\n\n<p>8684</p>\n\n<p>A couple other examples can be found at <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=678284&amp;SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=678284&amp;SiteID=1</a> </p>\n" }, { "answer_id": 8561729, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 3, "selected": false, "text": "<p>Table variable metadata is viewable in <code>tempdb.sys.tables</code> too. This is easily verifiable from the below</p>\n\n<pre><code>declare @t2 as table ( [38F055D8-25D9-4AA6-9571-F436FE] int)\n\nSELECT t.name, t.object_id\nFROM tempdb.sys.tables t\nJOIN tempdb.sys.columns c\nON t.object_id = c.object_id \nWHERE c.name = '38F055D8-25D9-4AA6-9571-F436FE'\n</code></pre>\n\n<p>Example Results</p>\n\n<pre><code>name object_id\n------------------------------ -----------\n#4DB4832C 1303675692\n</code></pre>\n\n<p>But you will notice the object name is auto generated and bears no relation to the variable name.</p>\n\n<p>If you do not have a guaranteed unique column name that you can use to filter on as above and the table variable has at least one row in it you can (from SQL Server 2008 onwards) use <code>%%physloc%%</code> and <code>DBCC PAGE</code> to determine this information. Example below.</p>\n\n<pre><code>DECLARE @t2 AS TABLE ( a INT)\n\nINSERT INTO @t2\nVALUES (1)\n\nDECLARE @DynSQL NVARCHAR(100)\n\nSELECT TOP (1) @DynSQL = 'DBCC PAGE(2,' + CAST(file_id AS VARCHAR) + ',' + \n CAST( page_id AS VARCHAR) +\n ',1) WITH TABLERESULTS'\nFROM @t2\n CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% )\n\nDECLARE @DBCCPage TABLE (\n [ParentObject] [VARCHAR](100) NULL,\n [Object] [VARCHAR](100) NULL,\n [Field] [VARCHAR](100) NULL,\n [VALUE] [VARCHAR](100) NULL )\n\nINSERT INTO @DBCCPage\nEXEC (@DynSQL)\n\nSELECT VALUE AS object_id,\n OBJECT_NAME(VALUE, 2) AS object_name\nFROM @DBCCPage\nWHERE Field = 'Metadata: ObjectId' \n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18116/" ]
The name of a temporary table such as #t1 can be determined using ``` select @TableName = [Name] from tempdb.sys.tables where [Object_ID] = object_id('tempDB.dbo.#t1') ``` How can I find the name of a table valued variable, i.e. one declared by ``` declare @t2 as table (a int) ``` the purpose is to be able to get meta-information about the table, using something like ``` select @Headers = dbo.Concatenate('[' + c.[Name] + ']') from sys.all_columns c inner join sys.tables t on c.object_id = t.object_id where t.name = @TableName ``` although for temp tables you have to look in `tempdb.sys.tables` instead of `sys.tables`. where do you look for table valued variables? --- I realize now that I can't do what I wanted to do, which is write a generic function for formatting table valued variables into html tables. For starters, in sql server 2005 you can't pass table valued parameters: <http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters> moreover, in sql server 2008, the parameters have to be strongly typed, so you will always know the number and type of columns.
I don't believe you can, as table variables are created in memory not in tempdb.
95,850
<p>I'm looking for the total <a href="http://en.wikipedia.org/wiki/Commit_charge" rel="nofollow noreferrer">commit charge</a>.</p>
[ { "answer_id": 96094, "author": "JustinD", "author_id": 12063, "author_profile": "https://Stackoverflow.com/users/12063", "pm_score": 1, "selected": false, "text": "<p>Here's an example using WMI:</p>\n\n<pre><code>strComputer = \".\"\n\nSet objSWbemServices = GetObject(\"winmgmts:\\\\\" &amp; strComputer)\nSet colSWbemObjectSet = _\n objSWbemServices.InstancesOf(\"Win32_LogicalMemoryConfiguration\")\n\nFor Each objSWbemObject In colSWbemObjectSet\n Wscript.Echo \"Total Physical Memory (kb): \" &amp; _\n objSWbemObject.TotalPhysicalMemory\n WScript.Echo \"Total Virtual Memory (kb): \" &amp; _\n objSWbemObject.TotalVirtualMemory\n WScript.Echo \"Total Page File Space (kb): \" &amp; _\n objSWbemObject.TotalPageFileSpace\nNext\n</code></pre>\n\n<p>If you run this script under CScript, you should see the number of kilobytes of physical memory installed on the target computer displayed in the command window. The following is typical output from the script:\nTotal Physical Memory (kb): 261676</p>\n\n<p><strong>Edit:</strong> Included total page file size property also</p>\n\n<p>taken from: <a href=\"http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx?mfr=true</a></p>\n" }, { "answer_id": 96240, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": true, "text": "<pre><code> public static long GetCommitCharge()\n {\n var p = new System.Diagnostics.PerformanceCounter(\"Memory\", \"Committed Bytes\");\n return p.RawValue;\n }\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
I'm looking for the total [commit charge](http://en.wikipedia.org/wiki/Commit_charge).
``` public static long GetCommitCharge() { var p = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes"); return p.RawValue; } ```
95,858
<p>I have a web application that is dynamically loading PDF files for viewing in the browser. Currently, it uses "innerHTML" to replace a div with the PDF Object. This works.</p> <p>But, is there a better way to get the ID of the element and set the "src" or "data" parameter for the Object / Embed and have it instantly load up a new document? I'm hoping the instance of Adobe Acrobat Reader will stay on the screen, but the new document will load into it.</p> <p>Here is a JavaScript example of the object:</p> <pre><code>document.getElementById(`divPDF`).innerHTML = `&lt;OBJECT id='objPDF' DATA="'+strFilename+'" TYPE="application/pdf" TITLE="IMAGING" WIDTH="100%" HEIGHT="100%"&gt;&lt;/object&gt;`; </code></pre> <p>Any insight is appreciated.</p>
[ { "answer_id": 96296, "author": "Lark", "author_id": 8804, "author_profile": "https://Stackoverflow.com/users/8804", "pm_score": 1, "selected": false, "text": "<p>I am not sure if this will work, as I have not tried this out in my projects.</p>\n\n<p>(Looking at your JS, I believe you are using jQuery. If not, please correct me)</p>\n\n<p>Once you have populated the divPDF with the object you might try the code below:</p>\n\n<pre><code>$(\"objPDF\").attr({\n data: \"dir/to/newPDF\"\n});\n</code></pre>\n\n<p>Again, I am not sure if this will work for your particular needs but if you attach this code to an event handler you can switch out the data of the object.</p>\n\n<p>You could also wrap it in a function to be used over and over again:</p>\n\n<pre><code>function pdfLoad(dirToPDF) {\n $(\"objPDF\").attr({\n data: dirToPDF\n });\n}\n</code></pre>\n" }, { "answer_id": 96416, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>If the handler for the PDF is acrobat (it doesn't have to be), it exposes a JS interface that is documented here:</p>\n\n<p><a href=\"http://www.adobe.com/devnet/acrobat/pdfs/js_api_reference.pdf\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/acrobat/pdfs/js_api_reference.pdf</a></p>\n\n<p>See if you can call openDoc(urlToPdf) on document.getElementById('objPDF') -- even if this works, it only works when Acrobat is being used to handle 'application/pdf'</p>\n" }, { "answer_id": 97306, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 0, "selected": false, "text": "<p>@lark\nA slight correction:</p>\n\n<pre><code>$('#objPDF').attr('data','dirToPDF');\n</code></pre>\n\n<p>The # specifies the objPDF is an ID and not an element name. Though I still don't know if this will work.</p>\n\n<p>@Tristan\nTake a look at the <a href=\"http://malsup.com/jquery/media/\" rel=\"nofollow noreferrer\">jQuery Media plugin</a>. It mentions support for PDF as well, though I have never used it.</p>\n" }, { "answer_id": 11385351, "author": "Daniel KUPPER", "author_id": 1510377, "author_profile": "https://Stackoverflow.com/users/1510377", "pm_score": 0, "selected": false, "text": "<p>Open a PDF-Link in a external window PDFN with a external <code>PDF-Reader.EXE</code>: </p>\n\n<p>Clicking on the following button:</p>\n\n<pre><code>&lt;FORM action=\"\"&gt; \n &lt;INPUT type=\"button\" value=\"PDF file\" \n onclick=\"window.open('http://www.Dku-betrieb.eu/Pdfn.html', \n 'PDFN', 'width=620, height=630')\"&gt;\n&lt;/FORM&gt;\n</code></pre>\n\n<p>opens this frameset <code>Pdfn.html</code> in an external window:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"&gt;\n&lt;html lang=\"de\"&gt;\n &lt;meta http-equiv=\"refresh\" content=\"12;url=http://www.dku-betrieb.eu/Pdfn1.html\"&gt;\n &lt;head&gt;\n &lt;title&gt;Reader&lt;/title&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"&gt;\n &lt;/head&gt;\n &lt;frameset&gt;\n &lt;frame src=\"http://www.dku-betrieb.eu/File.pdf\" frameborder=0 name=\"p1\"&gt;\n &lt;/frameset&gt;\n&lt;/HTML&gt;\n</code></pre>\n\n<p>which refreshes in 12 seconds to the download of the PDF-Reader:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\"&gt;\n&lt;html lang=\"de\"&gt;\n &lt;head&gt;\n &lt;title&gt;Reader&lt;/title&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"&gt;\n &lt;/head&gt;\n &lt;frameset &gt;\n &lt;frame src=\"http://www.dku-betrieb.eu/PDFReader.exe\" frameborder=0 name=\"p2\"&gt;\n &lt;/frameset&gt;\n&lt;/HTML&gt;\n</code></pre>\n\n<p>showing as result the PDF-file in the external window PDFN.</p>\n" }, { "answer_id": 43938694, "author": "onur", "author_id": 2037521, "author_profile": "https://Stackoverflow.com/users/2037521", "pm_score": 0, "selected": false, "text": "<pre><code>function pdfLoad(datasrc) {\n\n var x = document.getElementById('objPDF');\n x.data = datasrc;\n\n }\n</code></pre>\n\n<p>This worked for me</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a web application that is dynamically loading PDF files for viewing in the browser. Currently, it uses "innerHTML" to replace a div with the PDF Object. This works. But, is there a better way to get the ID of the element and set the "src" or "data" parameter for the Object / Embed and have it instantly load up a new document? I'm hoping the instance of Adobe Acrobat Reader will stay on the screen, but the new document will load into it. Here is a JavaScript example of the object: ``` document.getElementById(`divPDF`).innerHTML = `<OBJECT id='objPDF' DATA="'+strFilename+'" TYPE="application/pdf" TITLE="IMAGING" WIDTH="100%" HEIGHT="100%"></object>`; ``` Any insight is appreciated.
I am not sure if this will work, as I have not tried this out in my projects. (Looking at your JS, I believe you are using jQuery. If not, please correct me) Once you have populated the divPDF with the object you might try the code below: ``` $("objPDF").attr({ data: "dir/to/newPDF" }); ``` Again, I am not sure if this will work for your particular needs but if you attach this code to an event handler you can switch out the data of the object. You could also wrap it in a function to be used over and over again: ``` function pdfLoad(dirToPDF) { $("objPDF").attr({ data: dirToPDF }); } ```
95,866
<p>I have a simple table comments <code>(id INT, revision INT, comment VARCHAR(140))</code> with some content like this:</p> <pre><code>1|1|hallo1| 1|2|hallo2| 1|3|hallo3| 2|1|hallo1| 2|2|hallo2| </code></pre> <p>I'm searching for an SQL statement which will return each comment with the highest revision:</p> <pre><code>1|3|hallo3| 2|2|hallo2| </code></pre> <p>I've come up with this solution:</p> <pre><code>select id, revision, comment from comments where revision = ( select max(revision) from comments as f where f.id = comments.id ); </code></pre> <p>but it is very slow on large data sets. Are there any better queries to accomplish this?</p>
[ { "answer_id": 95914, "author": "nathaniel", "author_id": 11947, "author_profile": "https://Stackoverflow.com/users/11947", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p>Make sure you have your indexes set up appropriately. Indexing on id, revision would be good.</p></li>\n<li><p>Here's a different take on your query. Haven't checked its execution plan, but if you set up the index well it should help:</p>\n\n<pre><code>SELECT c.* \n FROM comments c\n INNER JOIN (\n SELECT id,max(revision) AS maxrev \n FROM comments \n GROUP BY id\n ) b\n ON c.id=b.id AND c.revision=b.maxrev\n</code></pre></li>\n</ol>\n\n<p>Editted to add:</p>\n\n<ol start=\"3\">\n<li>If you're on SQL Server, you might want to check out Indexed Views as well:<br>\n<a href=\"http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx</a></li>\n</ol>\n\n<p>Editted again to add info:</p>\n\n<pre><code>Subquery:\n25157 records\n2 seconds\nExecution plan includes an Index Seek (82%) base and a Segment (17%)\n\nLeft Outer Join:\n25160 records\n3 seconds\nExecution plan includes two Index Scans @ 22% each with a Right Outer Merge at 45% and a Filter at 11%\n</code></pre>\n\n<p>I'd still go with the sub query.</p>\n" }, { "answer_id": 95979, "author": "devinmoore", "author_id": 15950, "author_profile": "https://Stackoverflow.com/users/15950", "pm_score": 4, "selected": false, "text": "<p>Here's one way that with appropriate indexing will not be heinously slow and it doesn't use a subselect:</p>\n\n<pre><code>SELECT comments.ID, comments.revision, comments.comment FROM comments \nLEFT OUTER JOIN comments AS maxcomments \nON maxcomments.ID= comments.ID\nAND maxcomments.revision &gt; comments.revision\nWHERE maxcomments.revision IS NULL\n</code></pre>\n\n<p>Adapted from queries here:\n<a href=\"http://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/\" rel=\"noreferrer\">http://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/</a></p>\n\n<p>(From google search: max group by sql)</p>\n" }, { "answer_id": 96011, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 2, "selected": false, "text": "<p>Tested with one of our tables that has nearly 1 million rows total. Indexes exist on both fields FIELD2 AND FIELD3. Query returned 83953 rows in under 3 seconds on our dev box.</p>\n\n<pre><code>select\nFIELD1, FIELD2, FIELD3\nfrom\nOURTABLE (nolock) T1\nWHERE FIELD3 = \n(\nSELECT MAX(FIELD3) FROM \nOURTABLE T2 (nolock)\nWHERE T1.FIELD2=T2.FIELD2\n)\nORDER BY FIELD2 DESC\n</code></pre>\n" }, { "answer_id": 96516, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 0, "selected": false, "text": "<p>Idea from left field, but what about adding an extra field to the table:</p>\n\n<pre><code>CurrentRevision bit not null\n</code></pre>\n\n<p>Then when you make a change, set the flag on the new revision and remove it on all previous ones.</p>\n\n<p>Your query would then simply become:</p>\n\n<pre><code>select Id,\n Comment\nfrom Comments\nwhere CurrentRevision = 1\n</code></pre>\n\n<p>This would be much easier on the database and therefore much faster.</p>\n" }, { "answer_id": 101025, "author": "Rowan", "author_id": 2087, "author_profile": "https://Stackoverflow.com/users/2087", "pm_score": 0, "selected": false, "text": "<p>One quite clean way to do \"latest x by id\" type queries is this. It should also be quite easy to index properly.</p>\n\n<pre><code>SELECT id, revision, comment \nFROM comments\nWHERE (id, revision) IN (\n SELECT id, MAX(revision)\n FROM comments\n -- WHERE clause comes here if needed\n GROUP BY id\n)\n</code></pre>\n" }, { "answer_id": 111393, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 0, "selected": false, "text": "<p>For big tables I find that this solution can has a better performance:</p>\n\n<pre><code> SELECT c1.id, \n c1.revision, \n c1.comment \n FROM comments c1 \nINNER JOIN ( SELECT id, \n max(revision) AS max_revision\n FROM comments \n GROUP BY id ) c2\n ON c1.id = c2.id\n AND c1.revision = c2.max_revision\n</code></pre>\n" }, { "answer_id": 116070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Analytics would be my recommendation.</p>\n\n<pre><code>select id, max_revision, comment\nfrom (select c.id, c.comment, c.revision, max(c.revision)over(partition by c.id) as max_revision\n from comments c)\nwhere revision = max_revision;\n</code></pre>\n" }, { "answer_id": 11609805, "author": "Patrick Savalle", "author_id": 1199612, "author_profile": "https://Stackoverflow.com/users/1199612", "pm_score": 0, "selected": false, "text": "<p>Without subselects (or temporary tables):</p>\n\n<pre><code>SELECT c1.ID, c1.revision, c1.comment \nFROM comments AS c1\nLEFT JOIN comments AS c2 \n ON c1.ID = c2.ID\n AND c1.revision &lt; c2.revision\nWHERE c2.revision IS NULL\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a simple table comments `(id INT, revision INT, comment VARCHAR(140))` with some content like this: ``` 1|1|hallo1| 1|2|hallo2| 1|3|hallo3| 2|1|hallo1| 2|2|hallo2| ``` I'm searching for an SQL statement which will return each comment with the highest revision: ``` 1|3|hallo3| 2|2|hallo2| ``` I've come up with this solution: ``` select id, revision, comment from comments where revision = ( select max(revision) from comments as f where f.id = comments.id ); ``` but it is very slow on large data sets. Are there any better queries to accomplish this?
Here's one way that with appropriate indexing will not be heinously slow and it doesn't use a subselect: ``` SELECT comments.ID, comments.revision, comments.comment FROM comments LEFT OUTER JOIN comments AS maxcomments ON maxcomments.ID= comments.ID AND maxcomments.revision > comments.revision WHERE maxcomments.revision IS NULL ``` Adapted from queries here: <http://www.xaprb.com/blog/2007/03/14/how-to-find-the-max-row-per-group-in-sql-without-subqueries/> (From google search: max group by sql)
95,875
<p>How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?</p> <pre><code>if (!isObjectLoaded(someVar)) { someVar= loadObject(); } </code></pre>
[ { "answer_id": 95898, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "<p><code>typeof(obj)</code> would return \"object\" for an object of a class among other possible values.</p>\n" }, { "answer_id": 95901, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 5, "selected": false, "text": "<pre><code>if(typeof(o) != 'object') o = loadObject();\n</code></pre>\n" }, { "answer_id": 95935, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 6, "selected": true, "text": "<p>If it is an object then you should just be able to check to see if it is <a href=\"http://javascript.about.com/od/reference/g/rnull.htm\" rel=\"nofollow noreferrer\">null</a> or <a href=\"http://javascript.about.com/od/reference/g/sundefined.htm\" rel=\"nofollow noreferrer\">undefined</a> and then load it if it is.</p>\n\n<pre><code>if (myObject === null || myObject === undefined) {\n myObject = loadObject();\n}\n</code></pre>\n\n<p>Using the <a href=\"http://www.javascriptkit.com/javatutors/determinevar2.shtml\" rel=\"nofollow noreferrer\">typeof</a> function is also an option as it returns the type of the object provided. However, it will return <a href=\"http://www.javascriptkit.com/javatutors/determinevar2.shtml\" rel=\"nofollow noreferrer\">null or undefined</a> if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.</p>\n" }, { "answer_id": 95958, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<p>I'm not sure what you mean by \"loaded\"... does the variable <code>object</code> exist and simply doesn't have the type you want? In that case, you'll want something like:</p>\n\n<pre><code>function isObjectType(obj, type) {\n return !!(obj &amp;&amp; type &amp;&amp; type.prototype &amp;&amp; obj.constructor == type.prototype.constructor);\n}\n</code></pre>\n\n<p>and then use <code>if (isObjectType(object, MyType)) { object = loadObject(); }</code>.</p>\n\n<p>If <code>object</code> is not populated with anything before your test (ie - <code>typeof object === 'undefined'</code>) then you just need:</p>\n\n<pre><code>if ('undefined' === typeof object) { object = loadObject(); }\n</code></pre>\n" }, { "answer_id": 95969, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>You probably want to see if a given object is <em>defined</em> </p>\n\n<p>Especially if its done in an asynchronous thread with a setTimeout to check when it turns up.</p>\n\n<pre><code> var generate = function()\n { \n window.foo = {}; \n }; \n var i = 0;\n var detect = function()\n {\n if( typeof window.foo == \"undefined\" ) \n {\n alert( \"Created!\"); \n clearInterval( i );\n }\n };\n setTimeout( generate, 15000 ); \n i = setInterval( detect, 100 ); \n</code></pre>\n\n<p>should in theory detect when window.foo comes into existance. </p>\n" }, { "answer_id": 95970, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 2, "selected": false, "text": "<p>If you want to detect a custom object:</p>\n\n<pre><code>// craete a custom object\nfunction MyObject(){\n\n}\n\n// check if it's the right kind of object\nif(!(object instanceof MyObject)){\n object = new MyObject();\n}\n</code></pre>\n" }, { "answer_id": 95971, "author": "ScottKoon", "author_id": 1538, "author_profile": "https://Stackoverflow.com/users/1538", "pm_score": 2, "selected": false, "text": "<p>You can also just use a shortcut <code>if(obj)</code></p>\n" }, { "answer_id": 97034, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p>If by loaded you mean defined, you can check the type of the variable with the typeof function. <strong>HOWEVER</strong> typeof has a few quirks, and will identify an Object, an Array, and a <strong>null</strong> as an object</p>\n\n<pre><code>alert(typeof(null));\n</code></pre>\n\n<p>Identifying a null as a defined object would probably cause your program to fail, so check with something like</p>\n\n<pre><code>if(null !== x &amp;&amp; 'object' == typeof(x)){\n alert(\"Hey, It's an object or an array; good enough!\");\n}\n</code></pre>\n" }, { "answer_id": 4061756, "author": "Bruce", "author_id": 492556, "author_profile": "https://Stackoverflow.com/users/492556", "pm_score": 3, "selected": false, "text": "<pre><code>myObject = myObject || loadObject();\n</code></pre>\n" }, { "answer_id": 12548663, "author": "Mike Samuel", "author_id": 20394, "author_profile": "https://Stackoverflow.com/users/20394", "pm_score": 1, "selected": false, "text": "<pre><code>if (!(\"someVar\" in window)) {\n someVar = loadObject();\n}\n</code></pre>\n\n<p>will tell you whether any JS has previously assigned to the global <code>someVar</code> or declared a top-level <code>var someVar</code>.</p>\n\n<p>That will work even if the loaded value is <code>undefined</code>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following? ``` if (!isObjectLoaded(someVar)) { someVar= loadObject(); } ```
If it is an object then you should just be able to check to see if it is [null](http://javascript.about.com/od/reference/g/rnull.htm) or [undefined](http://javascript.about.com/od/reference/g/sundefined.htm) and then load it if it is. ``` if (myObject === null || myObject === undefined) { myObject = loadObject(); } ``` Using the [typeof](http://www.javascriptkit.com/javatutors/determinevar2.shtml) function is also an option as it returns the type of the object provided. However, it will return [null or undefined](http://www.javascriptkit.com/javatutors/determinevar2.shtml) if the object has not been loaded so it might boil down a bit to personal preference in regards to readability.
95,890
<p>When someone talks about a variables storage class specifier, what are they talking about?<br> They also often talk about variable linkage in the same context, what is that?</p>
[ { "answer_id": 95927, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 6, "selected": true, "text": "<p>The storage class specifier controls the <em>storage</em> and the <em>linkage</em> of your variables. These are two concepts that are different.\nC specifies the following specifiers for variables: auto, extern, register, static.</p>\n\n<p><strong>Storage</strong><br>\nThe storage duration determines how long your variable will live in ram.<br>\nThere are three types of storage duration: static, automatic and dynamic.</p>\n\n<p><em>static</em><br>\nIf your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.</p>\n\n<p><em>automatic</em><br>\nIf the variable is declared in a function, but <strong>without</strong> the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size).</p>\n\n<p><em>dynamic</em><br>\nIf you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.</p>\n\n<p><strong>Linkage</strong><br>\nLinkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.</p>\n\n<p><em>no linkage</em><br>\nThis variable is only visible where it was declared. Typically applies to variables declared in a function.</p>\n\n<p><em>internal linkage</em><br>\nThis variable will be visible to all the functions within the file (called a <a href=\"https://stackoverflow.com/questions/28160/multiple-classes-in-a-header-file-vs-a-single-header-file-per-class\">translation unit</a>), but other files will not know it exists.</p>\n\n<p><em>external linkage</em><br>\nThe variable will be visible to other translation units. These are often thought of as \"global variables\".</p>\n\n<p>Here is a table describing the storage and linkage characteristics based on the specifiers</p>\n\n<pre>\n Storage Class Function File \n Specifier Scope Scope \n-----------------------------------------------------\n none automatic static \n no linkage external linkage\n\n extern static static\n external linkage external linkage\n\n static static static\n no linkage internal linkage\n\n auto automatic invalid\n no linkage\n\nregister automatic invalid\n no linkage\n</pre>\n" }, { "answer_id": 96019, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 0, "selected": false, "text": "<p>Variable storage classes or type specifiers (like volatile, auto and static) define how/where variables are saved during program execution. For example, variables defined in functions are usually saved on the stack, which means that it will be lost after the function returns. Using the \"static\" keyword, you can force the compiler to put the variable in the data segment in memory, making the variables content persistent between calls to that function. The \"register\" keyword will cause the compiler to try as hard as possible to put the variable in a CPU register, useful for counters in loops etc. However, it's not guaranteed that it's actually in a register after all.</p>\n\n<p>Read more about type specifiers <a href=\"http://www.space.unibe.ch/comp_doc/c_manual/C/CONCEPT/storage_class.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
When someone talks about a variables storage class specifier, what are they talking about? They also often talk about variable linkage in the same context, what is that?
The storage class specifier controls the *storage* and the *linkage* of your variables. These are two concepts that are different. C specifies the following specifiers for variables: auto, extern, register, static. **Storage** The storage duration determines how long your variable will live in ram. There are three types of storage duration: static, automatic and dynamic. *static* If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables. *automatic* If the variable is declared in a function, but **without** the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function. Once you return, the variable no longer exist. Automatic storage is typically done on the stack. It is a very fast operation to create these variables (simply increment the stack pointer by the size). *dynamic* If you use malloc (or new in C++) you are using dynamic storage. This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically. **Linkage** Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage. *no linkage* This variable is only visible where it was declared. Typically applies to variables declared in a function. *internal linkage* This variable will be visible to all the functions within the file (called a [translation unit](https://stackoverflow.com/questions/28160/multiple-classes-in-a-header-file-vs-a-single-header-file-per-class)), but other files will not know it exists. *external linkage* The variable will be visible to other translation units. These are often thought of as "global variables". Here is a table describing the storage and linkage characteristics based on the specifiers ``` Storage Class Function File Specifier Scope Scope ----------------------------------------------------- none automatic static no linkage external linkage extern static static external linkage external linkage static static static no linkage internal linkage auto automatic invalid no linkage register automatic invalid no linkage ```
95,895
<p>I have two <code>DateTime</code> objects: <code>StartDate</code> and <code>EndDate</code>. I want to make sure <code>StartDate</code> is before <code>EndDate</code>. How is this done in C#?</p>
[ { "answer_id": 95921, "author": "Ryan Rinaldi", "author_id": 2278, "author_profile": "https://Stackoverflow.com/users/2278", "pm_score": 5, "selected": false, "text": "<pre><code>if(StartDate &lt; EndDate)\n{}\n</code></pre>\n\n<p>DateTime supports normal comparision operators.</p>\n" }, { "answer_id": 95924, "author": "EvilEddie", "author_id": 12986, "author_profile": "https://Stackoverflow.com/users/12986", "pm_score": 3, "selected": false, "text": "<p>Check out DateTime.Compare method </p>\n" }, { "answer_id": 95926, "author": "Rob Gray", "author_id": 5691, "author_profile": "https://Stackoverflow.com/users/5691", "pm_score": 3, "selected": false, "text": "<pre><code>StartDate &lt; EndDate\n</code></pre>\n" }, { "answer_id": 95928, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 9, "selected": true, "text": "<pre><code>if (StartDate &lt; EndDate)\n // code\n</code></pre>\n\n<p>if you just want the dates, and not the time</p>\n\n<pre><code>if (StartDate.Date &lt; EndDate.Date)\n // code\n</code></pre>\n" }, { "answer_id": 95933, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": false, "text": "<p>You can use the overloaded &lt; or > operators.</p>\n\n<p>For example:</p>\n\n<pre><code>DateTime d1 = new DateTime(2008, 1, 1);\nDateTime d2 = new DateTime(2008, 1, 2);\nif (d1 &lt; d2) { ...\n</code></pre>\n" }, { "answer_id": 95934, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": false, "text": "<pre><code>if (StartDate&gt;=EndDate)\n{\n throw new InvalidOperationException(\"Ack! StartDate is not before EndDate!\");\n}\n</code></pre>\n" }, { "answer_id": 95936, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 2, "selected": false, "text": "<pre><code> if (new DateTime(5000) &gt; new DateTime(1000))\n {\n Console.WriteLine(\"i win\");\n }\n</code></pre>\n" }, { "answer_id": 10873953, "author": "John J Smith", "author_id": 367698, "author_profile": "https://Stackoverflow.com/users/367698", "pm_score": 2, "selected": false, "text": "<p>I had the same requirement, but when using the accepted answer, it did not fulfill all of my unit tests. The issue for me is when you have a new object, with Start and End dates and you have to set the Start date ( at this stage your End date has the minimum date value of 01/01/0001) - this solution did pass all my unit tests:</p>\n\n<pre><code> public DateTime Start\n {\n get { return _start; }\n set\n {\n if (_end.Equals(DateTime.MinValue))\n {\n _start = value;\n }\n else if (value.Date &lt; _end.Date)\n {\n _start = value;\n }\n else\n {\n throw new ArgumentException(\"Start date must be before the End date.\");\n }\n }\n }\n\n\n public DateTime End\n {\n get { return _end; }\n set\n {\n if (_start.Equals(DateTime.MinValue))\n {\n _end = value;\n }\n else if (value.Date &gt; _start.Date)\n {\n _end = value;\n }\n else\n {\n throw new ArgumentException(\"End date must be after the Start date.\");\n }\n }\n }\n</code></pre>\n\n<p>It does miss the edge case where both Start and End dates can be 01/01/0001 but I'm not concerned about that.</p>\n" }, { "answer_id": 32119337, "author": "rottenbanana", "author_id": 5006471, "author_profile": "https://Stackoverflow.com/users/5006471", "pm_score": 3, "selected": false, "text": "<p>This is probably too late, but to benefit other people who might stumble upon this, I used an extension method do to this using <code>IComparable</code> like this: </p>\n\n<pre><code>public static class BetweenExtension\n {\n public static bool IsBetween&lt;T&gt;(this T value, T min, T max) where T : IComparable\n {\n return (min.CompareTo(value) &lt;= 0) &amp;&amp; (value.CompareTo(max) &lt;= 0);\n }\n }\n</code></pre>\n\n<p>Using this extension method with <code>IComparable</code> makes this method more generic and makes it usable with a wide variety of data types and not just dates.</p>\n\n<p>You would use it like this:</p>\n\n<pre><code>DateTime start = new DateTime(2015,1,1);\nDateTime end = new DateTime(2015,12,31);\nDateTime now = new DateTime(2015,8,20);\n\nif(now.IsBetween(start, end))\n{\n //Your code here\n}\n</code></pre>\n" }, { "answer_id": 43349468, "author": "sapbucket", "author_id": 855203, "author_profile": "https://Stackoverflow.com/users/855203", "pm_score": 0, "selected": false, "text": "<p>I'd like to demonstrate that if you convert to .Date that you don't need to worry about hours/mins/seconds etc:</p>\n\n<pre><code> [Test]\n public void ConvertToDateWillHaveTwoDatesEqual()\n {\n DateTime d1 = new DateTime(2008, 1, 1);\n DateTime d2 = new DateTime(2008, 1, 2);\n Assert.IsTrue(d1 &lt; d2);\n\n DateTime d3 = new DateTime(2008, 1, 1,7,0,0);\n DateTime d4 = new DateTime(2008, 1, 1,10,0,0);\n Assert.IsTrue(d3 &lt; d4);\n Assert.IsFalse(d3.Date &lt; d4.Date);\n }\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I have two `DateTime` objects: `StartDate` and `EndDate`. I want to make sure `StartDate` is before `EndDate`. How is this done in C#?
``` if (StartDate < EndDate) // code ``` if you just want the dates, and not the time ``` if (StartDate.Date < EndDate.Date) // code ```
95,910
<p>Given this class</p> <pre><code>class Foo { // Want to find _bar with reflection [SomeAttribute] private string _bar; public string BigBar { get { return this._bar; } } } </code></pre> <p>I want to find the private item _bar that I will mark with a attribute. Is that possible? </p> <p>I have done this with properties where I have looked for an attribute, but never a private member field.</p> <p>What are the binding flags that I need to set to get the private fields?</p>
[ { "answer_id": 95937, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "<p>Yes, however you will need to set your Binding flags to search for private fields (if your looking for the member outside of the class instance).</p>\n\n<p>The binding flag you will need is: System.Reflection.BindingFlags.NonPublic</p>\n" }, { "answer_id": 95948, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 4, "selected": false, "text": "<pre><code>typeof(MyType).GetField(\"fieldName\", BindingFlags.NonPublic | BindingFlags.Instance)\n</code></pre>\n" }, { "answer_id": 95964, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 7, "selected": false, "text": "<p>You can do it just like with a property:</p>\n\n<pre><code>FieldInfo fi = typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance);\nif (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)\n ...\n</code></pre>\n" }, { "answer_id": 95973, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 9, "selected": true, "text": "<p>Use <code>BindingFlags.NonPublic</code> and <code>BindingFlags.Instance</code> flags</p>\n\n<pre><code>FieldInfo[] fields = myType.GetFields(\n BindingFlags.NonPublic | \n BindingFlags.Instance);\n</code></pre>\n" }, { "answer_id": 96020, "author": "jammycakes", "author_id": 886, "author_profile": "https://Stackoverflow.com/users/886", "pm_score": 5, "selected": false, "text": "<p>One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.</p>\n" }, { "answer_id": 5499329, "author": "Gunner", "author_id": 45279, "author_profile": "https://Stackoverflow.com/users/45279", "pm_score": 2, "selected": false, "text": "<p>I came across this while searching for this on google so I realise I'm bumping an old post. However the GetCustomAttributes requires two params.</p>\n\n<pre><code>typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance)\n.Where(x =&gt; x.GetCustomAttributes(typeof(SomeAttribute), false).Length &gt; 0);\n</code></pre>\n\n<p>The second parameter specifies whether or not you wish to search the inheritance hierarchy</p>\n" }, { "answer_id": 8442803, "author": "Suriya", "author_id": 332437, "author_profile": "https://Stackoverflow.com/users/332437", "pm_score": 6, "selected": false, "text": "<p>Get private variable's value using Reflection:</p>\n\n<pre><code>var _barVariable = typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);\n</code></pre>\n\n<p>Set value for private variable using Reflection:</p>\n\n<pre><code>typeof(Foo).GetField(\"_bar\", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, \"newValue\");\n</code></pre>\n\n<p>Where objectForFooClass is a non null instance for the class type Foo.</p>\n" }, { "answer_id": 13539377, "author": "sa_ddam213", "author_id": 1849109, "author_profile": "https://Stackoverflow.com/users/1849109", "pm_score": 3, "selected": false, "text": "<p>I use this method personally</p>\n\n<pre><code>if (typeof(Foo).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Any(c =&gt; c.GetCustomAttributes(typeof(SomeAttribute), false).Any()))\n{ \n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 23953996, "author": "epsi1on", "author_id": 1106889, "author_profile": "https://Stackoverflow.com/users/1106889", "pm_score": 3, "selected": false, "text": "<p>Here is some extension methods for simple get and set private fields and properties (properties with setter):</p>\n\n<p>usage example:</p>\n\n<blockquote>\n<pre><code> public class Foo\n {\n private int Bar = 5;\n }\n\n var targetObject = new Foo();\n var barValue = targetObject.GetMemberValue(\"Bar\");//Result is 5\n targetObject.SetMemberValue(\"Bar\", 10);//Sets Bar to 10\n</code></pre>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Extensions methos for using reflection to get / set member values\n /// &lt;/summary&gt;\n public static class ReflectionExtensions\n {\n /// &lt;summary&gt;\n /// Gets the public or private member using reflection.\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj\"&gt;The source target.&lt;/param&gt;\n /// &lt;param name=\"memberName\"&gt;Name of the field or property.&lt;/param&gt;\n /// &lt;returns&gt;the value of member&lt;/returns&gt;\n public static object GetMemberValue(this object obj, string memberName)\n {\n var memInf = GetMemberInfo(obj, memberName);\n\n if (memInf == null)\n throw new System.Exception(\"memberName\");\n\n if (memInf is System.Reflection.PropertyInfo)\n return memInf.As&lt;System.Reflection.PropertyInfo&gt;().GetValue(obj, null);\n\n if (memInf is System.Reflection.FieldInfo)\n return memInf.As&lt;System.Reflection.FieldInfo&gt;().GetValue(obj);\n\n throw new System.Exception();\n }\n\n /// &lt;summary&gt;\n /// Gets the public or private member using reflection.\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj\"&gt;The target object.&lt;/param&gt;\n /// &lt;param name=\"memberName\"&gt;Name of the field or property.&lt;/param&gt;\n /// &lt;returns&gt;Old Value&lt;/returns&gt;\n public static object SetMemberValue(this object obj, string memberName, object newValue)\n {\n var memInf = GetMemberInfo(obj, memberName);\n\n\n if (memInf == null)\n throw new System.Exception(\"memberName\");\n\n var oldValue = obj.GetMemberValue(memberName);\n\n if (memInf is System.Reflection.PropertyInfo)\n memInf.As&lt;System.Reflection.PropertyInfo&gt;().SetValue(obj, newValue, null);\n else if (memInf is System.Reflection.FieldInfo)\n memInf.As&lt;System.Reflection.FieldInfo&gt;().SetValue(obj, newValue);\n else\n throw new System.Exception();\n\n return oldValue;\n }\n\n /// &lt;summary&gt;\n /// Gets the member info\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj\"&gt;source object&lt;/param&gt;\n /// &lt;param name=\"memberName\"&gt;name of member&lt;/param&gt;\n /// &lt;returns&gt;instanse of MemberInfo corresponsing to member&lt;/returns&gt;\n private static System.Reflection.MemberInfo GetMemberInfo(object obj, string memberName)\n {\n var prps = new System.Collections.Generic.List&lt;System.Reflection.PropertyInfo&gt;();\n\n prps.Add(obj.GetType().GetProperty(memberName,\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.FlattenHierarchy));\n prps = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where( prps,i =&gt; !ReferenceEquals(i, null)));\n if (prps.Count != 0)\n return prps[0];\n\n var flds = new System.Collections.Generic.List&lt;System.Reflection.FieldInfo&gt;();\n\n flds.Add(obj.GetType().GetField(memberName,\n System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.FlattenHierarchy));\n\n //to add more types of properties\n\n flds = System.Linq.Enumerable.ToList(System.Linq.Enumerable.Where(flds, i =&gt; !ReferenceEquals(i, null)));\n\n if (flds.Count != 0)\n return flds[0];\n\n return null;\n }\n\n [System.Diagnostics.DebuggerHidden]\n private static T As&lt;T&gt;(this object obj)\n {\n return (T)obj;\n }\n }\n</code></pre>\n" }, { "answer_id": 46488844, "author": "Bruno Zell", "author_id": 5185376, "author_profile": "https://Stackoverflow.com/users/5185376", "pm_score": 5, "selected": false, "text": "<h2>Nice Syntax With Extension Method</h2>\n<p>You can access any private field of an arbitrary type with code like this:</p>\n<pre><code>Foo foo = new Foo();\nstring c = foo.GetFieldValue&lt;string&gt;(&quot;_bar&quot;);\n</code></pre>\n<p>For that you need to define an extension method that will do the work for you:</p>\n<pre><code>public static class ReflectionExtensions {\n public static T GetFieldValue&lt;T&gt;(this object obj, string name) {\n // Set the flags so that private and public fields from instances will be found\n var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;\n var field = obj.GetType().GetField(name, bindingFlags);\n return (T)field?.GetValue(obj);\n }\n}\n</code></pre>\n" }, { "answer_id": 72934049, "author": "Ashwin Rajaram", "author_id": 14238575, "author_profile": "https://Stackoverflow.com/users/14238575", "pm_score": 0, "selected": false, "text": "<p>If your .Net framework is greater than 4.5. You can use GetRuntimeFields method.</p>\n<p>This method returns all fields that are defined on the specified type, including inherited, non-public, instance, and static fields.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.runtimereflectionextensions.getruntimefields?view=net-6.0\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.runtimereflectionextensions.getruntimefields?view=net-6.0</a></p>\n<pre><code>var foo = new Foo();\nvar fooFields = foo.GetType().GetRuntimeFields()\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
Given this class ``` class Foo { // Want to find _bar with reflection [SomeAttribute] private string _bar; public string BigBar { get { return this._bar; } } } ``` I want to find the private item \_bar that I will mark with a attribute. Is that possible? I have done this with properties where I have looked for an attribute, but never a private member field. What are the binding flags that I need to set to get the private fields?
Use `BindingFlags.NonPublic` and `BindingFlags.Instance` flags ``` FieldInfo[] fields = myType.GetFields( BindingFlags.NonPublic | BindingFlags.Instance); ```
95,912
<p>My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time? </p>
[ { "answer_id": 95918, "author": "Andrei Belogortseff", "author_id": 17037, "author_profile": "https://Stackoverflow.com/users/17037", "pm_score": 5, "selected": true, "text": "<p>The following C++ function can do that:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );\n\n/*\nParameters:\n\nptet\n [out] Pointer to a variable that receives the elevation type of the current process.\n\n The possible values are:\n\n TokenElevationTypeDefault - This value indicates that either UAC is disabled, \n or the process is started by a standard user (not a member of the Administrators group).\n\n The following two values can be returned only if both the UAC is enabled\n and the user is a member of the Administrator's group:\n\n TokenElevationTypeFull - the process is running elevated. \n\n TokenElevationTypeLimited - the process is not running elevated.\n\nReturn Values:\n\n If the function succeeds, the return value is S_OK. \n If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().\n\nImplementation:\n*/\n\nHRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet )\n{\n if ( !IsVista() )\n return E_FAIL;\n\n HRESULT hResult = E_FAIL; // assume an error occurred\n HANDLE hToken = NULL;\n\n if ( !::OpenProcessToken( \n ::GetCurrentProcess(), \n TOKEN_QUERY, \n &amp;hToken ) )\n {\n return hResult;\n }\n\n DWORD dwReturnLength = 0;\n\n if ( ::GetTokenInformation(\n hToken,\n TokenElevationType,\n ptet,\n sizeof( *ptet ),\n &amp;dwReturnLength ) )\n {\n ASSERT( dwReturnLength == sizeof( *ptet ) );\n hResult = S_OK;\n }\n\n ::CloseHandle( hToken );\n\n return hResult;\n}\n</code></pre>\n" }, { "answer_id": 114696, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 5, "selected": false, "text": "<p>For those of us working in C#, in the Windows SDK there is a \"UACDemo\" application as a part of the \"Cross Technology Samples\". They find if the current user is an administrator using this method:</p>\n\n<pre><code>private bool IsAdministrator\n{\n get\n {\n WindowsIdentity wi = WindowsIdentity.GetCurrent();\n WindowsPrincipal wp = new WindowsPrincipal(wi);\n\n return wp.IsInRole(WindowsBuiltInRole.Administrator);\n }\n}\n</code></pre>\n\n<p>(Note: I refactored the original code to be a property, rather than an \"if\" statement)</p>\n" }, { "answer_id": 21296802, "author": "Guy Glirbas", "author_id": 2137952, "author_profile": "https://Stackoverflow.com/users/2137952", "pm_score": 2, "selected": false, "text": "<p>I do not think elevation type is the answer you want. You just want to know if it is elevated. Use TokenElevation instead of TokenElevationType when you call GetTokenInformation. If the structure returns a positive value, the user is admin. If zero, the user is normal elevation.</p>\n\n<p>Here is a Delphi solution:</p>\n\n<pre><code>function TMyAppInfo.RunningAsAdmin: boolean;\nvar\n hToken, hProcess: THandle;\n pTokenInformation: pointer;\n ReturnLength: DWord;\n TokenInformation: TTokenElevation;\nbegin\n hProcess := GetCurrentProcess;\n try\n if OpenProcessToken(hProcess, TOKEN_QUERY, hToken) then try\n TokenInformation.TokenIsElevated := 0;\n pTokenInformation := @TokenInformation;\n GetTokenInformation(hToken, TokenElevation, pTokenInformation, sizeof(TokenInformation), ReturnLength);\n result := (TokenInformation.TokenIsElevated &gt; 0);\n finally\n CloseHandle(hToken);\n end;\n except\n result := false;\n end;\nend;\n</code></pre>\n" }, { "answer_id": 27988836, "author": "wqw", "author_id": 40691, "author_profile": "https://Stackoverflow.com/users/40691", "pm_score": 1, "selected": false, "text": "<p>Here is a VB6 implementation of a check if a (current) process is elevated</p>\n\n<pre><code>Option Explicit\n\n'--- for OpenProcessToken\nPrivate Const TOKEN_QUERY As Long = &amp;H8\nPrivate Const TokenElevation As Long = 20\n\nPrivate Declare Function GetCurrentProcess Lib \"kernel32\" () As Long\nPrivate Declare Function OpenProcessToken Lib \"advapi32\" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long\nPrivate Declare Function GetTokenInformation Lib \"advapi32\" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long\nPrivate Declare Function CloseHandle Lib \"kernel32\" (ByVal hObject As Long) As Long\n\n\nPublic Function IsElevated(Optional ByVal hProcess As Long) As Boolean\n Dim hToken As Long\n Dim dwIsElevated As Long\n Dim dwLength As Long\n\n If hProcess = 0 Then\n hProcess = GetCurrentProcess()\n End If\n If OpenProcessToken(hProcess, TOKEN_QUERY, hToken) &lt;&gt; 0 Then\n If GetTokenInformation(hToken, TokenElevation, dwIsElevated, 4, dwLength) &lt;&gt; 0 Then\n IsElevated = (dwIsElevated &lt;&gt; 0)\n End If\n Call CloseHandle(hToken)\n End If\nEnd Function\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ]
My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time?
The following C++ function can do that: ```cpp HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet ); /* Parameters: ptet [out] Pointer to a variable that receives the elevation type of the current process. The possible values are: TokenElevationTypeDefault - This value indicates that either UAC is disabled, or the process is started by a standard user (not a member of the Administrators group). The following two values can be returned only if both the UAC is enabled and the user is a member of the Administrator's group: TokenElevationTypeFull - the process is running elevated. TokenElevationTypeLimited - the process is not running elevated. Return Values: If the function succeeds, the return value is S_OK. If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError(). Implementation: */ HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet ) { if ( !IsVista() ) return E_FAIL; HRESULT hResult = E_FAIL; // assume an error occurred HANDLE hToken = NULL; if ( !::OpenProcessToken( ::GetCurrentProcess(), TOKEN_QUERY, &hToken ) ) { return hResult; } DWORD dwReturnLength = 0; if ( ::GetTokenInformation( hToken, TokenElevationType, ptet, sizeof( *ptet ), &dwReturnLength ) ) { ASSERT( dwReturnLength == sizeof( *ptet ) ); hResult = S_OK; } ::CloseHandle( hToken ); return hResult; } ```
95,950
<p>On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit.</p> <p>I was getting errors about loading the OCI dll, so I installed the 32 bit client into <code>C:\oracle32</code>.</p> <p>If I add this to the <code>PATH</code> environment variable, it works great. But I also want to run the Pylons app as a service (<a href="http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service" rel="nofollow noreferrer">using this recipe</a>) and don't want to put this 32-bit library on the path for all other applications. </p> <p>I tried using <code>sys.path.append("C:\\oracle32\\bin")</code> but that doesn't seem to work.</p>
[ { "answer_id": 96016, "author": "Moe", "author_id": 3051, "author_profile": "https://Stackoverflow.com/users/3051", "pm_score": 2, "selected": false, "text": "<p>sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH.</p>\n\n<p>I'm not sure that this will work, but you can try:</p>\n\n<pre><code>import os\nos.environ['PATH'] += os.pathsep + \"C:\\\\oracle32\\\\bin\"\n</code></pre>\n" }, { "answer_id": 125163, "author": "Aurelio Martin Massoni", "author_id": 20037, "author_profile": "https://Stackoverflow.com/users/20037", "pm_score": 0, "selected": false, "text": "<p>You need to append the c:\\Oracle32\\bin directory to the PATH variable of your environment before you execute python.exe.<br>\nIn Linux, I need to set up the LD_LIBRARY_PATH variable for similar reasons, to locate the Oracle libraries, before calling python. I use wrapper shell scripts that set the variable and then call Python.<br>\nIn your case, maybe you can call, in the service startup, a .cmd or .vbs script that sets the PATH variable and then calls python.exe with your .py script.</p>\n\n<p>I hope this helps!</p>\n" }, { "answer_id": 142775, "author": "JoshL", "author_id": 20625, "author_profile": "https://Stackoverflow.com/users/20625", "pm_score": 0, "selected": false, "text": "<p>If your Python application runs in the 64-bit space, you will need to access a 64-bit installation of Oracle's oci.dll, rather than the 32-bit version. Normally you would update the system path to include the appropriate Oracle Home bin directory, prior to running the script. The solution may also vary depending on what component you are using to access Oracle from Python.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1566663/" ]
On my desktop I have written a small Pylons app that connects to Oracle. I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit. I was getting errors about loading the OCI dll, so I installed the 32 bit client into `C:\oracle32`. If I add this to the `PATH` environment variable, it works great. But I also want to run the Pylons app as a service ([using this recipe](http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service)) and don't want to put this 32-bit library on the path for all other applications. I tried using `sys.path.append("C:\\oracle32\\bin")` but that doesn't seem to work.
sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH. I'm not sure that this will work, but you can try: ``` import os os.environ['PATH'] += os.pathsep + "C:\\oracle32\\bin" ```
95,954
<p>Suppose we have:</p> <pre><code>interface Foo { bool Func(int x); } class Bar: Foo { bool Func(int x) { return (x&gt;0); } } class Baz: Foo { bool Func(int x) { return (x&lt;0); } } </code></pre> <p>Now we can toss around Bar and Baz as a Foos and call their Func methods.</p> <p>Delegates simplify this a little bit:</p> <pre><code>delegate bool Foo(int x); bool Bar(int x) { return (x&lt;0); } bool Baz(int x) { return (x&gt;0); } </code></pre> <p>Now we can toss around Bar and Baz as Foo delegates.</p> <p>What is the real benefit of delegates, except for getting shorter code?</p>
[ { "answer_id": 95975, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>No, delegates are for method pointers. Then you can make sure that the signature of the method associated w/ the delegate is correct.</p>\n\n<p>Also, then you don't need to know the structure of the class. This way, you can use a method that you have written to pass into a method in another class, and define the functionality you want to have happen.</p>\n\n<p>Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx\" rel=\"nofollow noreferrer\">List&lt;> class with the Find method</a>. Now you get to define what determines if something is a match or not, without requiring items contained in the class to implement IListFindable or something similar.</p>\n" }, { "answer_id": 95980, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 2, "selected": false, "text": "<p>You can pass delegates as parameters in functions (Ok technically delegates become objects when compiled, but that's not the point here). You could pass an object as a parameter (obviously), but then you are tying that type of object to the function as a parameter. With delegates you can pass any function to execute in the code that has the same signature regardless of where it comes from. </p>\n" }, { "answer_id": 95991, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 0, "selected": false, "text": "<p>A delegate is a typed method pointer. This gives you more flexibility than interfaces because you can take advantage of covariance and contravariance, and you can modify object state (you'd have to pass the this pointer around with interface based functors).</p>\n\n<p>Also, delegates have lots of nice syntactic sugar which allows you to do things like combine them together easily.</p>\n" }, { "answer_id": 95992, "author": "GHad", "author_id": 11705, "author_profile": "https://Stackoverflow.com/users/11705", "pm_score": 1, "selected": false, "text": "<p>One can think of delegates as an interface for a method which defines what arguments and return type a method must have to fit the delegate</p>\n" }, { "answer_id": 96015, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 0, "selected": false, "text": "<p>Yes, a delegate can be thought of as an interface with one method.</p>\n" }, { "answer_id": 96045, "author": "Michael Barker", "author_id": 6365, "author_profile": "https://Stackoverflow.com/users/6365", "pm_score": 5, "selected": true, "text": "<p>There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed (via the constructor) references to the parts of the containing class that it may need to interact with during the callback. Delegates do not have this restriction therefore reduces the amount of code required to implement the callback.</p>\n\n<p>Shorter, more concise code is also a worthy benefit.</p>\n" }, { "answer_id": 96056, "author": "Rick Minerich", "author_id": 9251, "author_profile": "https://Stackoverflow.com/users/9251", "pm_score": 3, "selected": false, "text": "<p>From a Software Engineering perspective you are right, delegates are much like function interfaces in that they prototype a function interface.</p>\n\n<p>They can also be used much in the same kind of way: instead of passing a whole class in that contains the method you need you can pass in just a delegate. This saves a whole lot of code and creates much more readable code.</p>\n\n<p>Moreover, with the advent of lambda expressions they can now also be defined easily on fly which is a huge bonus. While it is POSSIBLE to build classes on the fly in C#, it's really a huge pain in the butt.</p>\n\n<p>Comparing the two is an interesting concept. I hadn't previously considered how much alike the ideas are from a use case and code structuring standpoint.</p>\n" }, { "answer_id": 96093, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>A delegate does share a lot in common with a interface reference that has a single method from the caller's point of view.</p>\n\n<p>In the first example, Baz and Bar are classes, which can be inherited and instantiated. In the second example, Baz and Bar are methods.</p>\n\n<p>You can't apply interface references to just any class that matches the interface contract. The class must explicitly declare that it supports the interface.\nYou can apply a delegate reference to any method that matches the signature.</p>\n\n<p>You can't include static methods in an interface's contract. (Although you can bolt static methods on with extension methods).\nYou can refer to static methods with a delegate reference.</p>\n" }, { "answer_id": 96142, "author": "Dan", "author_id": 8251, "author_profile": "https://Stackoverflow.com/users/8251", "pm_score": 0, "selected": false, "text": "<p>Interfaces and delegates are two utterly different things, although I understand the temptation to describe delegates in interface-like terms for ease of understanding...however, not knowing the truth may lead to confusion down the line.</p>\n\n<p>Delegates were inspired (partly) because of the black art of C++ method pointers being inadequate for certain purposes. A classic example is implementing a message-passing or event-handling mechanism. Delegates allow you to define a method signature without any knowledge of a class' types or interfaces - I could define a \"void eventHandler(Event* e)\" delegate and invoke it on any class that implemented it.</p>\n\n<p>For some insight into this classic problem, and why delegates are desirable <a href=\"http://www.codeproject.com/KB/cpp/FastDelegate.aspx\" rel=\"nofollow noreferrer\">read this</a> and then <a href=\"http://www.codeproject.com/KB/cpp/fd.aspx\" rel=\"nofollow noreferrer\">this</a>.</p>\n" }, { "answer_id": 615088, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 0, "selected": false, "text": "<p>In at least one proposal for adding closures (i.e. anonymous delegates) to Java, they are equivalent to interfaces with a single member method.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
Suppose we have: ``` interface Foo { bool Func(int x); } class Bar: Foo { bool Func(int x) { return (x>0); } } class Baz: Foo { bool Func(int x) { return (x<0); } } ``` Now we can toss around Bar and Baz as a Foos and call their Func methods. Delegates simplify this a little bit: ``` delegate bool Foo(int x); bool Bar(int x) { return (x<0); } bool Baz(int x) { return (x>0); } ``` Now we can toss around Bar and Baz as Foo delegates. What is the real benefit of delegates, except for getting shorter code?
There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed (via the constructor) references to the parts of the containing class that it may need to interact with during the callback. Delegates do not have this restriction therefore reduces the amount of code required to implement the callback. Shorter, more concise code is also a worthy benefit.
95,956
<p>using C++Builder 2007, the FindFirstFile and FindNextFile functions doesn't seem to be able to find some files on 64-bit versions of Vista and XP. My test application is 32-bit.</p> <p>If I use them to iterate through the folder C:\Windows\System32\Drivers they only find a handful of files although there are 185 when I issue a dir command in a command prompt. Using the same example code lists all files fine on a 32-bit version of XP.</p> <p>Here is a small example program:</p> <pre><code>int main(int argc, char* argv[]) { HANDLE hFind; WIN32_FIND_DATA FindData; int ErrorCode; bool cont = true; cout &lt;&lt; "FindFirst/Next demo." &lt;&lt; endl &lt;&lt; endl; hFind = FindFirstFile("*.*", &amp;FindData); if(hFind == INVALID_HANDLE_VALUE) { ErrorCode = GetLastError(); if (ErrorCode == ERROR_FILE_NOT_FOUND) { cout &lt;&lt; "There are no files matching that path/mask\n" &lt;&lt; endl; } else { cout &lt;&lt; "FindFirstFile() returned error code " &lt;&lt; ErrorCode &lt;&lt; endl; } cont = false; } else { cout &lt;&lt; FindData.cFileName &lt;&lt; endl; } if (cont) { while (FindNextFile(hFind, &amp;FindData)) { cout &lt;&lt; FindData.cFileName &lt;&lt; endl; } ErrorCode = GetLastError(); if (ErrorCode == ERROR_NO_MORE_FILES) { cout &lt;&lt; endl &lt;&lt; "All files logged." &lt;&lt; endl; } else { cout &lt;&lt; "FindNextFile() returned error code " &lt;&lt; ErrorCode &lt;&lt; endl; } if (!FindClose(hFind)) { ErrorCode = GetLastError(); cout &lt;&lt; "FindClose() returned error code " &lt;&lt; ErrorCode &lt;&lt; endl; } } return 0; } </code></pre> <p>Running it in the C:\Windows\System32\Drivers folder on 64-bit XP returns this:</p> <pre><code>C:\WINDOWS\system32\drivers&gt;t:\Project1.exe FindFirst/Next demo. . .. AsIO.sys ASUSHWIO.SYS hfile.txt raspti.zip stcp2v30.sys truecrypt.sys All files logged. </code></pre> <p>A dir command on the same system returns this:</p> <pre><code>C:\WINDOWS\system32\drivers&gt;dir/p Volume in drive C has no label. Volume Serial Number is E8E1-0F1E Directory of C:\WINDOWS\system32\drivers 16-09-2008 23:12 &lt;DIR&gt; . 16-09-2008 23:12 &lt;DIR&gt; .. 17-02-2007 00:02 80.384 1394bus.sys 16-09-2008 23:12 9.453 a.txt 17-02-2007 00:02 322.560 acpi.sys 29-03-2006 14:00 18.432 acpiec.sys 24-03-2005 17:11 188.928 aec.sys 21-06-2008 15:07 291.840 afd.sys 29-03-2006 14:00 51.712 amdk8.sys 17-02-2007 00:03 111.104 arp1394.sys 08-05-2006 20:19 8.192 ASACPI.sys 29-03-2006 14:00 25.088 asyncmac.sys 17-02-2007 00:03 150.016 atapi.sys 17-02-2007 00:03 106.496 atmarpc.sys 29-03-2006 14:00 57.344 atmepvc.sys 17-02-2007 00:03 91.648 atmlane.sys 17-02-2007 00:03 569.856 atmuni.sys 24-03-2005 19:12 5.632 audstub.sys 29-03-2006 14:00 6.144 beep.sys Press any key to continue . . . etc. </code></pre> <p>I'm puzzled. What is the reason for this?</p> <p>Brian</p>
[ { "answer_id": 96012, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p>Are you sure it is looking in the same directory as the dir command? They don't seem to have any files in common.</p>\n\n<p>Also, this isn't the issue, but the correct wild card for \"all files\" is *</p>\n\n<p>*.* means \"all files with at least one . in the name\"</p>\n" }, { "answer_id": 96034, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 4, "selected": true, "text": "<p>Is there redirection going on? See the remarks on Wow64DisableWow64FsRedirection <a href=\"http://msdn.microsoft.com/en-gb/library/aa365743.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-gb/library/aa365743.aspx</a></p>\n" }, { "answer_id": 96127, "author": "INS", "author_id": 13136, "author_profile": "https://Stackoverflow.com/users/13136", "pm_score": 0, "selected": false, "text": "<p>Are there any warnings when you compile? </p>\n\n<p>Have you turned <strong>ALL</strong> warnings on for this particular test (since it is not working)?</p>\n\n<p>Make sure first to solve the warnings.</p>\n" }, { "answer_id": 96140, "author": "JubbaJubba", "author_id": 18145, "author_profile": "https://Stackoverflow.com/users/18145", "pm_score": 0, "selected": false, "text": "<p>There are no problems with the example code. I have another application that fails too, written in Delphi. I think I found the answer based on Kris' answer about redirection:\n<a href=\"http://msdn.microsoft.com/en-gb/library/aa364418(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-gb/library/aa364418(VS.85).aspx</a></p>\n" }, { "answer_id": 96155, "author": "Ludvig A. Norin", "author_id": 16909, "author_profile": "https://Stackoverflow.com/users/16909", "pm_score": 2, "selected": false, "text": "<p>I found this on MSDN:</p>\n\n<p><em>If you are writing a 32-bit application to list all the files in a directory and the application may be run on a 64-bit computer, you should call the Wow64DisableWow64FsRedirectionfunction before calling FindFirstFile and call Wow64RevertWow64FsRedirection after the last call to FindNextFile. For more information, see File System Redirector.</em></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx\" rel=\"nofollow noreferrer\">Here's the link</a></p>\n\n<p>I'll have to update my code because of this :-)</p>\n" }, { "answer_id": 96179, "author": "JubbaJubba", "author_id": 18145, "author_profile": "https://Stackoverflow.com/users/18145", "pm_score": 1, "selected": false, "text": "<p>Got it:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-gb/library/aa384187(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-gb/library/aa384187(VS.85).aspx</a></p>\n\n<p>When a 32-bit application reads from one of these folders on a 64-bit OS:</p>\n\n<pre><code>%windir%\\system32\\catroot\n%windir%\\system32\\catroot2\n%windir%\\system32\\drivers\\etc\n%windir%\\system32\\logfiles\n%windir%\\system32\\spool \n</code></pre>\n\n<p>Windows actually lists the content of:</p>\n\n<pre><code>%windir%\\SysWOW64\\catroot\n%windir%\\SysWOW64\\catroot2\n%windir%\\SysWOW64\\drivers\\etc\n%windir%\\SysWOW64\\logfiles\n%windir%\\SysWOW64\\spool \n</code></pre>\n\n<p>Thanks for your input Kris, that helped me find out what is going on.</p>\n\n<p>EDIT: Thank you Ludvig too :-)</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18145/" ]
using C++Builder 2007, the FindFirstFile and FindNextFile functions doesn't seem to be able to find some files on 64-bit versions of Vista and XP. My test application is 32-bit. If I use them to iterate through the folder C:\Windows\System32\Drivers they only find a handful of files although there are 185 when I issue a dir command in a command prompt. Using the same example code lists all files fine on a 32-bit version of XP. Here is a small example program: ``` int main(int argc, char* argv[]) { HANDLE hFind; WIN32_FIND_DATA FindData; int ErrorCode; bool cont = true; cout << "FindFirst/Next demo." << endl << endl; hFind = FindFirstFile("*.*", &FindData); if(hFind == INVALID_HANDLE_VALUE) { ErrorCode = GetLastError(); if (ErrorCode == ERROR_FILE_NOT_FOUND) { cout << "There are no files matching that path/mask\n" << endl; } else { cout << "FindFirstFile() returned error code " << ErrorCode << endl; } cont = false; } else { cout << FindData.cFileName << endl; } if (cont) { while (FindNextFile(hFind, &FindData)) { cout << FindData.cFileName << endl; } ErrorCode = GetLastError(); if (ErrorCode == ERROR_NO_MORE_FILES) { cout << endl << "All files logged." << endl; } else { cout << "FindNextFile() returned error code " << ErrorCode << endl; } if (!FindClose(hFind)) { ErrorCode = GetLastError(); cout << "FindClose() returned error code " << ErrorCode << endl; } } return 0; } ``` Running it in the C:\Windows\System32\Drivers folder on 64-bit XP returns this: ``` C:\WINDOWS\system32\drivers>t:\Project1.exe FindFirst/Next demo. . .. AsIO.sys ASUSHWIO.SYS hfile.txt raspti.zip stcp2v30.sys truecrypt.sys All files logged. ``` A dir command on the same system returns this: ``` C:\WINDOWS\system32\drivers>dir/p Volume in drive C has no label. Volume Serial Number is E8E1-0F1E Directory of C:\WINDOWS\system32\drivers 16-09-2008 23:12 <DIR> . 16-09-2008 23:12 <DIR> .. 17-02-2007 00:02 80.384 1394bus.sys 16-09-2008 23:12 9.453 a.txt 17-02-2007 00:02 322.560 acpi.sys 29-03-2006 14:00 18.432 acpiec.sys 24-03-2005 17:11 188.928 aec.sys 21-06-2008 15:07 291.840 afd.sys 29-03-2006 14:00 51.712 amdk8.sys 17-02-2007 00:03 111.104 arp1394.sys 08-05-2006 20:19 8.192 ASACPI.sys 29-03-2006 14:00 25.088 asyncmac.sys 17-02-2007 00:03 150.016 atapi.sys 17-02-2007 00:03 106.496 atmarpc.sys 29-03-2006 14:00 57.344 atmepvc.sys 17-02-2007 00:03 91.648 atmlane.sys 17-02-2007 00:03 569.856 atmuni.sys 24-03-2005 19:12 5.632 audstub.sys 29-03-2006 14:00 6.144 beep.sys Press any key to continue . . . etc. ``` I'm puzzled. What is the reason for this? Brian
Is there redirection going on? See the remarks on Wow64DisableWow64FsRedirection <http://msdn.microsoft.com/en-gb/library/aa365743.aspx>
95,967
<p>Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.</p>
[ { "answer_id": 95982, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 2, "selected": false, "text": "<p>The system stored procedure <code>sp_help</code> will give you the information. Execute the following statement:</p>\n\n<pre><code>execute sp_help table_name\n</code></pre>\n" }, { "answer_id": 96049, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 8, "selected": true, "text": "<pre><code>SELECT Col.Column_Name from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, \n INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col \nWHERE \n Col.Constraint_Name = Tab.Constraint_Name\n AND Col.Table_Name = Tab.Table_Name\n AND Tab.Constraint_Type = 'PRIMARY KEY'\n AND Col.Table_Name = '&lt;your table name&gt;'\n</code></pre>\n" }, { "answer_id": 96072, "author": "Dwight T", "author_id": 2526, "author_profile": "https://Stackoverflow.com/users/2526", "pm_score": 3, "selected": false, "text": "<p>Is using MS SQL Server you can do the following:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>-- List all tables primary keys\nSELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS\nWHERE CONSTRAINT_TYPE = 'PRIMARY KEY'\n</code></pre>\n<p>You can also filter on the table_name column if you want a specific table.</p>\n" }, { "answer_id": 96079, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 0, "selected": false, "text": "<p>Give this a try:</p>\n\n<pre><code>SELECT\n CONSTRAINT_CATALOG AS DataBaseName,\n CONSTRAINT_SCHEMA AS SchemaName,\n TABLE_NAME AS TableName,\n CONSTRAINT_Name AS PrimaryKey\nFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \nWHERE CONSTRAINT_TYPE = 'Primary Key' and Table_Name = 'YourTable'\n</code></pre>\n" }, { "answer_id": 96366, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT t.name AS 'table', i.name AS 'index', it.xtype,\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 1 \n AND k.id = t.id)\n AS 'column1',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 2 \n AND k.id = t.id)\n AS 'column2',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 3\n AND k.id = t.id)\n AS 'column3',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 4\n AND k.id = t.id)\n AS 'column4',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 5\n AND k.id = t.id)\n AS 'column5',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 6\n AND k.id = t.id)\n AS 'column6',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 7\n AND k.id = t.id)\n AS 'column7',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 8 \n AND k.id = t.id)\n AS 'column8',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 9 \n AND k.id = t.id)\n AS 'column9',\n\n(SELECT c.name FROM syscolumns c INNER JOIN sysindexkeys k \n ON k.indid = i.indid \n AND c.colid = k.colid \n AND c.id = t.id \n AND k.keyno = 10\n AND k.id = t.id)\n AS 'column10',\n\nFROM sysobjects t\n INNER JOIN sysindexes i ON i.id = t.id \n INNER JOIN sysobjects it ON it.parent_obj = t.id AND it.name = i.name\n\nWHERE it.xtype = 'PK'\nORDER BY t.name, i.name\n</code></pre>\n" }, { "answer_id": 179210, "author": "user12861", "author_id": 12861, "author_profile": "https://Stackoverflow.com/users/12861", "pm_score": 3, "selected": false, "text": "<p>I like the INFORMATION_SCHEMA technique, but another I've used is:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>exec sp_pkeys 'table'\n</code></pre>\n" }, { "answer_id": 2098765, "author": "MartinC", "author_id": 171240, "author_profile": "https://Stackoverflow.com/users/171240", "pm_score": 1, "selected": false, "text": "<p>Thanks Guy.</p>\n\n<p>With a slight variation I used it to find all the primary keys for all the tables.</p>\n\n<pre><code>SELECT A.Name,Col.Column_Name from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, \n INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col ,\n (select NAME from dbo.sysobjects where xtype='u') AS A\nWHERE \n Col.Constraint_Name = Tab.Constraint_Name\n AND Col.Table_Name = Tab.Table_Name\n AND Constraint_Type = 'PRIMARY KEY '\n AND Col.Table_Name = A.Name\n</code></pre>\n" }, { "answer_id": 7551259, "author": "Manjunath C Bhat", "author_id": 964486, "author_profile": "https://Stackoverflow.com/users/964486", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT A.TABLE_NAME as [Table_name], A.CONSTRAINT_NAME as [Primary_Key]\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS A, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE B\n WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND A.CONSTRAINT_NAME = B.CONSTRAINT_NAME\n</code></pre>\n" }, { "answer_id": 7551392, "author": "Manjunath C Bhat", "author_id": 964486, "author_profile": "https://Stackoverflow.com/users/964486", "pm_score": 2, "selected": false, "text": "<p>--This is another Modified Version which is also an example for Co-Related Query</p>\n\n<pre><code>SELECT TC.TABLE_NAME as [Table_name], TC.CONSTRAINT_NAME as [Primary_Key]\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC\n INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU\n ON TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME\n WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND\n TC.TABLE_NAME IN\n (SELECT [NAME] AS [TABLE_NAME] FROM SYS.OBJECTS \n WHERE TYPE = 'U')\n</code></pre>\n" }, { "answer_id": 15797448, "author": "aked", "author_id": 1060656, "author_profile": "https://Stackoverflow.com/users/1060656", "pm_score": 2, "selected": false, "text": "<p><strong>This should list all the constraints ( primary Key and Foreign Keys ) and at the end of query put table name</strong></p>\n\n<pre><code>/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/\nWITH ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) \nAS\n(\nSELECT CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,\n CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,\n PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,\n PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,\n PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE, \n REFERENCE_TABLE_NAME='' ,\n REFERENCE_COL_NAME='' \n\nFROM sys.key_constraints as PKnUKEY\n INNER JOIN sys.tables as PKnUTable\n ON PKnUTable.object_id = PKnUKEY.parent_object_id\n INNER JOIN sys.index_columns as PKnUColIdx\n ON PKnUColIdx.object_id = PKnUTable.object_id\n AND PKnUColIdx.index_id = PKnUKEY.unique_index_id\n INNER JOIN sys.columns as PKnUKEYCol\n ON PKnUKEYCol.object_id = PKnUTable.object_id\n AND PKnUKEYCol.column_id = PKnUColIdx.column_id\n INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl\n ON oParentColDtl.TABLE_NAME=PKnUTable.name\n AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name\nUNION ALL\nSELECT CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,\n CONSTRAINT_TYPE='FK',\n PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,\n PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,\n PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE, \n REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,\n REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) \nFROM sys.foreign_key_columns FKC\n INNER JOIN sys.sysobjects oConstraint\n ON FKC.constraint_object_id=oConstraint.id \n INNER JOIN sys.sysobjects oParent\n ON FKC.parent_object_id=oParent.id\n INNER JOIN sys.all_columns oParentCol\n ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/\n AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/\n INNER JOIN sys.sysobjects oReference\n ON FKC.referenced_object_id=oReference.id\n INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl\n ON oParentColDtl.TABLE_NAME=oParent.name\n AND oParentColDtl.COLUMN_NAME=oParentCol.name\n INNER JOIN sys.all_columns oReferenceCol\n ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/\n AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/\n\n)\n\nselect * from ALL_KEYS_IN_TABLE\nwhere \n PARENT_TABLE_NAME in ('YOUR_TABLE_NAME') \n or REFERENCE_TABLE_NAME in ('YOUR_TABLE_NAME')\nORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;\n</code></pre>\n\n<p>For reference please read thru - <a href=\"http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx</a> </p>\n" }, { "answer_id": 24045346, "author": "KyleMit", "author_id": 1366033, "author_profile": "https://Stackoverflow.com/users/1366033", "pm_score": 3, "selected": false, "text": "<p>Here's another way from the question <a href=\"https://stackoverflow.com/q/3930338/1366033\">get table primary key using sql query</a>:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT COLUMN_NAME\nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA+'.'+CONSTRAINT_NAME), 'IsPrimaryKey') = 1\n AND TABLE_NAME = '<i>&lt;your table name&gt;</i>'\n</code></pre>\n<p>It uses <a href=\"http://msdn.microsoft.com/en-us/library/ms189789.aspx\" rel=\"noreferrer\"><code>KEY_COLUMN_USAGE</code></a> to determine the constraints for a given table<br />\nThen uses <a href=\"http://msdn.microsoft.com/en-us/library/ms176105.aspx\" rel=\"noreferrer\"><code>OBJECTPROPERTY(<i>id</i>, 'IsPrimaryKey')</code></a> to determine if each is a primary key</p>\n" }, { "answer_id": 30927788, "author": "Pricey", "author_id": 98706, "author_profile": "https://Stackoverflow.com/users/98706", "pm_score": 0, "selected": false, "text": "<p>I found this useful, gives a list of tables with a comma separate list of the columns and then also a comma separate list of which ones are the primary key</p>\n\n<pre><code>SELECT T.TABLE_SCHEMA, T.TABLE_NAME, \nSTUFF((\n SELECT ', ' + C.COLUMN_NAME\n FROM INFORMATION_SCHEMA.COLUMNS C\n WHERE C.TABLE_SCHEMA = T.TABLE_SCHEMA\n AND T.TABLE_NAME = C.TABLE_NAME\n FOR XML PATH ('')\n ), 1, 2, '') AS Columns,\nSTUFF((\nSELECT ', ' + C.COLUMN_NAME \nFROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC\n ON C.TABLE_SCHEMA = TC.TABLE_SCHEMA\n AND C.TABLE_NAME = TC.TABLE_NAME\n WHERE C.TABLE_SCHEMA = T.TABLE_SCHEMA\n AND T.TABLE_NAME = C.TABLE_NAME\n AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'\n FOR XML PATH ('')\n), 1, 2, '') AS [Key]\nFROM INFORMATION_SCHEMA.TABLES T\nORDER BY T.TABLE_SCHEMA, T.TABLE_NAME\n</code></pre>\n" }, { "answer_id": 31083875, "author": "Tanner Ornelas", "author_id": 4682491, "author_profile": "https://Stackoverflow.com/users/4682491", "pm_score": 2, "selected": false, "text": "<p>This one gives you the columns that are PK.</p>\n\n<pre><code>SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = 'TableName'\n</code></pre>\n" }, { "answer_id": 32511025, "author": "Dave Zych", "author_id": 1630665, "author_profile": "https://Stackoverflow.com/users/1630665", "pm_score": 5, "selected": false, "text": "<p>It's generally recommended practice now to use the <code>sys.*</code> views over <code>INFORMATION_SCHEMA</code> in SQL Server, so unless you're planning on migrating databases I would use those. Here's how you would do it with the <code>sys.*</code> views:</p>\n\n<pre><code>SELECT \n c.name AS column_name,\n i.name AS index_name,\n c.is_identity\nFROM sys.indexes i\n inner join sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id\n inner join sys.columns c ON ic.object_id = c.object_id AND c.column_id = ic.column_id\nWHERE i.is_primary_key = 1\n and i.object_ID = OBJECT_ID('&lt;schema&gt;.&lt;tablename&gt;');\n</code></pre>\n" }, { "answer_id": 37250483, "author": "SQL Police", "author_id": 2504785, "author_profile": "https://Stackoverflow.com/users/2504785", "pm_score": 5, "selected": false, "text": "<p>This is a solution which uses only <strong>sys</strong>-tables.</p>\n\n<p>It lists all the primary keys in the database. It returns <strong>schema, table name, column name</strong> and the correct <strong>column sort order</strong> for each primary key.</p>\n\n<p>If you want to get the primary key for a specific table, then you need to filter on <strong><code>SchemaName</code></strong> and <strong><code>TableName</code></strong>. </p>\n\n<p>IMHO, this solution is very generic and does not use any string literals, so it will run on any machine.</p>\n\n<pre><code>select \n s.name as SchemaName,\n t.name as TableName,\n tc.name as ColumnName,\n ic.key_ordinal as KeyOrderNr\nfrom \n sys.schemas s \n inner join sys.tables t on s.schema_id=t.schema_id\n inner join sys.indexes i on t.object_id=i.object_id\n inner join sys.index_columns ic on i.object_id=ic.object_id \n and i.index_id=ic.index_id\n inner join sys.columns tc on ic.object_id=tc.object_id \n and ic.column_id=tc.column_id\nwhere i.is_primary_key=1 \norder by t.name, ic.key_ordinal ;\n</code></pre>\n" }, { "answer_id": 39851081, "author": "Anjan Kant", "author_id": 919643, "author_profile": "https://Stackoverflow.com/users/919643", "pm_score": 1, "selected": false, "text": "<p>Below query will list <strong>primary keys</strong> of <strong>particular table</strong>:</p>\n\n<pre><code>SELECT DISTINCT\n CONSTRAINT_NAME AS [Constraint],\n TABLE_SCHEMA AS [Schema],\n TABLE_NAME AS TableName\nFROM\n INFORMATION_SCHEMA.KEY_COLUMN_USAGE\nWHERE\n TABLE_NAME = 'mytablename'\n</code></pre>\n" }, { "answer_id": 42985271, "author": "Soenhay", "author_id": 1339704, "author_profile": "https://Stackoverflow.com/users/1339704", "pm_score": 0, "selected": false, "text": "<p>This version displays the schema, the table name and an ordered, comma separated list of primary keys. Object_Id() does not work for link servers so we filter by the table name. </p>\n\n<p>Without the REPLACE(Si1.Column_Name, '', '') it would show the xml opening and closing tags for Column_Name on the database I was testing on. I am not sure why the database required a replace for 'Column_Name' so if someone knows then please comment.</p>\n\n<pre><code>DECLARE @TableName VARCHAR(100) = '';\nWITH Sysinfo\n AS (SELECT Kcu.Table_Name\n , Kcu.Table_Schema AS Schema_Name\n , Kcu.Column_Name\n , Kcu.Ordinal_Position\n FROM [LinkServer].Information_Schema.Key_Column_Usage Kcu\n JOIN [LinkServer].Information_Schema.Table_Constraints AS Tc ON Tc.Constraint_Name = Kcu.Constraint_Name\n WHERE Tc.Constraint_Type = 'Primary Key')\n SELECT Schema_Name\n ,Table_Name\n , STUFF(\n (\n SELECT ', '\n , REPLACE(Si1.Column_Name, '', '')\n FROM Sysinfo Si1\n WHERE Si1.Table_Name = Si2.Table_Name\n ORDER BY Si1.Table_Name\n , Si1.Ordinal_Position\n FOR XML PATH('')\n ), 1, 2, '') AS Primary_Keys\n FROM Sysinfo Si2\n WHERE Table_Name = CASE\n WHEN @TableName NOT IN( '', 'All')\n THEN @TableName\n ELSE Table_Name\n END\n GROUP BY Si2.Table_Name, Si2.Schema_Name;\n</code></pre>\n\n<p>And the same pattern using George's query:</p>\n\n<pre><code>DECLARE @TableName VARCHAR(100) = '';\nWITH Sysinfo\n AS (SELECT S.Name AS Schema_Name\n , T.Name AS Table_Name\n , Tc.Name AS Column_Name\n , Ic.Key_Ordinal AS Ordinal_Position\n FROM [LinkServer].Sys.Schemas S\n JOIN [LinkServer].Sys.Tables T ON S.Schema_Id = T.Schema_Id\n JOIN [LinkServer].Sys.Indexes I ON T.Object_Id = I.Object_Id\n JOIN [LinkServer].Sys.Index_Columns Ic ON I.Object_Id = Ic.Object_Id\n AND I.Index_Id = Ic.Index_Id\n JOIN [LinkServer].Sys.Columns Tc ON Ic.Object_Id = Tc.Object_Id\n AND Ic.Column_Id = Tc.Column_Id\n WHERE I.Is_Primary_Key = 1)\n SELECT Schema_Name\n ,Table_Name\n , STUFF(\n (\n SELECT ', '\n , REPLACE(Si1.Column_Name, '', '')\n FROM Sysinfo Si1\n WHERE Si1.Table_Name = Si2.Table_Name\n ORDER BY Si1.Table_Name\n , Si1.Ordinal_Position\n FOR XML PATH('')\n ), 1, 2, '') AS Primary_Keys\n FROM Sysinfo Si2\n WHERE Table_Name = CASE\n WHEN @TableName NOT IN('', 'All')\n THEN @TableName\n ELSE Table_Name\n END\n GROUP BY Si2.Table_Name, Si2.Schema_Name;\n</code></pre>\n" }, { "answer_id": 45452479, "author": "UJS", "author_id": 3373795, "author_profile": "https://Stackoverflow.com/users/3373795", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Sys.Objects Table contains row for each user-defined, schema-scoped\n object .</p>\n \n <p>Constraints created like Primary Key or others will be the <em>object</em> and\n Table name will be the <em>parent_object</em></p>\n \n <p>Query sys.Objects and collect the Object's Ids of Required Type</p>\n</blockquote>\n\n<pre><code>declare @TableName nvarchar(50)='TblInvoice' -- your table name\ndeclare @TypeOfKey nvarchar(50)='PK' -- For Primary key\n\nSELECT Name FROM sys.objects\nWHERE type = @TypeOfKey \nAND parent_object_id = OBJECT_ID (@TableName)\n</code></pre>\n" }, { "answer_id": 47091245, "author": "Bha15", "author_id": 8119464, "author_profile": "https://Stackoverflow.com/users/8119464", "pm_score": 3, "selected": false, "text": "<p>I am telling a simple Technic which I follow </p>\n\n<pre><code>SP_HELP 'table_name'\n</code></pre>\n\n<p>run this code as query. Mention your table name at place of table_name for which you want to know Primary Key (don't forget the single quotes). The result will show like attached Image. Hope it will help you</p>\n\n<p><a href=\"https://i.stack.imgur.com/fGpNu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fGpNu.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 48573015, "author": "Saxman", "author_id": 8206858, "author_profile": "https://Stackoverflow.com/users/8206858", "pm_score": 0, "selected": false, "text": "<p>May I suggest a more accurate simple answer to the original question below</p>\n\n<pre><code>SELECT \nKEYS.table_schema, KEYS.table_name, KEYS.column_name, KEYS.ORDINAL_POSITION \nFROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE keys\nINNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS \n ON cons.TABLE_SCHEMA = keys.TABLE_SCHEMA \n AND cons.TABLE_NAME = keys.TABLE_NAME \n AND cons.CONSTRAINT_NAME = keys.CONSTRAINT_NAME\nWHERE cons.CONSTRAINT_TYPE = 'PRIMARY KEY'\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li>Some of the answers above are missing a filter for just primary key\ncolumns!</li>\n<li>I'm using below in a CTE to join to a larger column\nlisting to provide the metadata from a source to feed BIML generation of staging tables and SSIS code</li>\n</ol>\n" }, { "answer_id": 49913195, "author": "Humayoun_Kabir", "author_id": 1427614, "author_profile": "https://Stackoverflow.com/users/1427614", "pm_score": 0, "selected": false, "text": "<p>Might be lately posted but hopefully this will help someone to see primary key list in sql server by using this t-sql query:</p>\n\n<pre><code>SELECT schema_name(t.schema_id) AS [schema_name], t.name AS TableName, \n COL_NAME(ic.OBJECT_ID,ic.column_id) AS PrimaryKeyColumnName,\n i.name AS PrimaryKeyConstraintName\nFROM sys.tables t \nINNER JOIN sys.indexes AS i on t.object_id=i.object_id \nINNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID\n AND i.index_id = ic.index_id \nWHERE OBJECT_NAME(ic.OBJECT_ID) = 'YourTableNameHere'\n</code></pre>\n\n<p>You can see the list of all foreign keys by using this query if you may want:</p>\n\n<pre><code>SELECT\nf.name as ForeignKeyConstraintName\n,OBJECT_NAME(f.parent_object_id) AS ReferencingTableName\n,COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ReferencingColumnName\n,OBJECT_NAME (f.referenced_object_id) AS ReferencedTableName\n,COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS \n ReferencedColumnName ,delete_referential_action_desc AS \nDeleteReferentialActionDesc ,update_referential_action_desc AS \nUpdateReferentialActionDesc\nFROM sys.foreign_keys AS f\nINNER JOIN sys.foreign_key_columns AS fc\nON f.object_id = fc.constraint_object_id\n --WHERE OBJECT_NAME(f.parent_object_id) = 'YourTableNameHere' \n --If you want to know referecing table details \n WHERE OBJECT_NAME(f.referenced_object_id) = 'YourTableNameHere' \n --If you want to know refereced table details \nORDER BY f.name\n</code></pre>\n" }, { "answer_id": 50014472, "author": "WEshruth", "author_id": 1699472, "author_profile": "https://Stackoverflow.com/users/1699472", "pm_score": 0, "selected": false, "text": "<p><strong>I found this from my friend, very effective if you are looking for all the table's primary keys under particular schema.</strong></p>\n\n<pre><code>SELECT tc.constraint_name AS IndexName,tc.table_name AS TableName,tc.table_schema\nAS SchemaName,kc.column_name AS COLUMN_NAME\nFROM information_schema.table_constraints tc,information_schema.key_column_usage kc\nWHERE tc.constraint_type = 'PRIMARY KEY' AND kc.table_name = tc.table_name AND kc.table_schema = tc.table_schema\nAND kc.constraint_name = tc.constraint_name AND tc.table_schema='&lt;SCHEMA_NAME&gt;'\n</code></pre>\n" }, { "answer_id": 50209394, "author": "user3248578", "author_id": 1051237, "author_profile": "https://Stackoverflow.com/users/1051237", "pm_score": 1, "selected": false, "text": "<p>If you are looking to do your own ORM or generate code from a given table, then this might be what you are looking form:</p>\n\n<pre><code>declare @table varchar(100) = 'mytable';\n\nwith cte as\n(\n select \n tc.CONSTRAINT_SCHEMA\n , tc.CONSTRAINT_TYPE\n , tc.TABLE_NAME\n , ccu.COLUMN_NAME\n , IS_NULLABLE\n , DATA_TYPE\n , CHARACTER_MAXIMUM_LENGTH\n , NUMERIC_PRECISION\n from \n INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \n inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu on tc.TABLE_NAME=ccu.TABLE_NAME and tc.TABLE_SCHEMA=ccu.TABLE_SCHEMA\n inner join information_schema.COLUMNS c on ccu.COLUMN_NAME=c.COLUMN_NAME and ccu.TABLE_NAME=c.TABLE_NAME and ccu.TABLE_SCHEMA=c.TABLE_SCHEMA\n where \n tc.table_name=@table\n and \n ccu.CONSTRAINT_NAME=tc.CONSTRAINT_NAME\n union \n select TABLE_SCHEMA,'COLUMN', TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@table\n and COLUMN_NAME not in (select COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = @table)\n)\nselect \n cast(iif(CONSTRAINT_TYPE='PRIMARY KEY',1,0) as bit) PrimaryKey\n ,cast(iif(CONSTRAINT_TYPE='FOREIGN KEY',1,0) as bit) ForeignKey\n ,cast(iif(CONSTRAINT_TYPE='COLUMN',1,0) as bit) NotKey\n ,COLUMN_NAME\n ,cast(iif(is_nullable='NO',0,1) as bit) IsNullable\n , DATA_TYPE\n , CHARACTER_MAXIMUM_LENGTH\n , NUMERIC_PRECISION \nfrom \n cte \norder by \n case CONSTRAINT_TYPE \n when 'PRIMARY KEY' then 1 \n when 'FOREIGN KEY' then 2 \n else 3 end\n , COLUMN_NAME\n</code></pre>\n\n<p>Here is what the result would look like:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> &lt;table cellspacing=0 border=1&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;PrimaryKey&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;ForeignKey&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NotKey&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;COLUMN_NAME&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;IsNullable&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;DATA_TYPE&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;CHARACTER_MAXIMUM_LENGTH&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NUMERIC_PRECISION&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;LectureNoteID&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;int&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NULL&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;10&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;LectureId&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;int&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NULL&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;10&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NoteTypeID&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;int&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NULL&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;10&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;Body&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;nvarchar&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;-1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NULL&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;tr&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;1&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;DisplayOrder&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;0&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;int&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;NULL&lt;/td&gt;\r\n &lt;td style=min-width:50px&gt;10&lt;/td&gt;\r\n &lt;/tr&gt;\r\n &lt;/table&gt;\r\n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 51226788, "author": "Hamed Nikzad", "author_id": 5974407, "author_profile": "https://Stackoverflow.com/users/5974407", "pm_score": 1, "selected": false, "text": "<p>If Primary Key and type needed, this query may be useful:</p>\n\n<pre><code>SELECT L.TABLE_SCHEMA, L.TABLE_NAME, L.COLUMN_NAME, R.TypeName\nFROM(\n SELECT COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1\n)L\nLEFT JOIN (\n SELECT\n OBJECT_NAME(c.OBJECT_ID) TableName ,c.name AS ColumnName ,t.name AS TypeName\n FROM sys.columns AS c\n JOIN sys.types AS t ON c.user_type_id=t.user_type_id\n)R ON L.COLUMN_NAME = R.ColumnName AND L.TABLE_NAME = R.TableName\n</code></pre>\n" }, { "answer_id": 57650846, "author": "Allan F", "author_id": 5315581, "author_profile": "https://Stackoverflow.com/users/5315581", "pm_score": 1, "selected": false, "text": "<p>For a comma separated list of primary key columns for a given TableName and Schema:</p>\n\n<pre><code>Select distinct SUBSTRING ( stuff(( select distinct ',' + [COLUMN_NAME] \n from INFORMATION_SCHEMA.KEY_COLUMN_USAGE \n where OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 \n AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema' \n order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,0,'' ) \n ,2,9999) \n</code></pre>\n" }, { "answer_id": 68347950, "author": "happybits", "author_id": 653281, "author_profile": "https://Stackoverflow.com/users/653281", "pm_score": 0, "selected": false, "text": "<p>Probably the simplest solution :)</p>\n<p><code>EXEC sp_pkeys YourTable</code></p>\n" }, { "answer_id": 69543595, "author": "Msfata", "author_id": 11402186, "author_profile": "https://Stackoverflow.com/users/11402186", "pm_score": -1, "selected": false, "text": "<p>If you need it in Oracle it is so simple.</p>\n<pre><code>SELECT `Constraint_Name`\n FROM `All_Constraints`\n WHERE `Constraint_Type` = `'P'`\n AND `Owner` = `'your schema here';`\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/736/" ]
Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.
``` SELECT Col.Column_Name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col WHERE Col.Constraint_Name = Tab.Constraint_Name AND Col.Table_Name = Tab.Table_Name AND Tab.Constraint_Type = 'PRIMARY KEY' AND Col.Table_Name = '<your table name>' ```
95,988
<p>I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor?</p> <pre><code>Create Table A (id int identity, Fname nvarchar(50), Lname nvarchar(50)) Create Table B (Fname nvarchar(50), Lname nvarchar(50), NewId int) Insert into A(fname, lname) SELECT fname, lname FROM B </code></pre> <p>I'm using MS SQL Server 2005.</p>
[ { "answer_id": 96021, "author": "Matt", "author_id": 17849, "author_profile": "https://Stackoverflow.com/users/17849", "pm_score": 0, "selected": false, "text": "<p>If you always want this behavior, you could put an AFTER INSERT trigger on TableA that will update table B.</p>\n" }, { "answer_id": 96048, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>You can get the by joining on the <a href=\"http://www.databasejournal.com/features/mssql/article.php/3572301\" rel=\"nofollow noreferrer\">row number</a>. This is possible because since it's an identity, it will just increment as you add items, which will be in the order that you are selecting them.</p>\n" }, { "answer_id": 96084, "author": "Cory", "author_id": 8207, "author_profile": "https://Stackoverflow.com/users/8207", "pm_score": 1, "selected": false, "text": "<p>As far as I understand it the issue you are having is that you want to INSERT into Table A, which has an identity column, and you want to preserve the identity from Table B which does not. </p>\n\n<p>In order to do that you should just have to turn on identity insert on table A. This will allow you to define your ID's on insert and as long as they don't conflict, you should be fine. Then you can just do:</p>\n\n<pre><code>Insert into A(identity, fname, lname) SELECT newid, fname, lname FROM B\n</code></pre>\n\n<p>Not sure what DB you are using but for sql server the command to turn on identity insert would be:</p>\n\n<pre><code>set identity_insert A on\n</code></pre>\n" }, { "answer_id": 96212, "author": "njr101", "author_id": 9625, "author_profile": "https://Stackoverflow.com/users/9625", "pm_score": 3, "selected": false, "text": "<p>Reading your question carefully, you just want to update table B based on the new identity values in table A.</p>\n\n<p>After the insert is finished, just run an update...</p>\n\n<pre><code>UPDATE B\nSET NewID = A.ID\nFROM B INNER JOIN A\n ON (B.FName = A.Fname AND B.LName = A.LName)\n</code></pre>\n\n<p>This assumes that the FName / LName combination can be used to key match the records between the tables. If this is not the case, you may need to add extra fields to ensure the records match correctly.</p>\n\n<p>If you don't have an alternate key that allows you to match the records then it doesn't make sense at all, since the records in table B can't be distinguished from one another.</p>\n" }, { "answer_id": 96232, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 1, "selected": false, "text": "<p>I suggest using uniqueidentifier type instead of identity. I this case you can generate IDs before insertion: </p>\n\n<pre><code>update B set NewID = NEWID()\n\ninsert into A(fname,lname,id) select fname,lname,NewID from B\n</code></pre>\n" }, { "answer_id": 96242, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": -1, "selected": true, "text": "<p>MBelly is right on the money - But then the trigger will always try and update table B even if that's not required (Because you're also inserting from table C?).</p>\n\n<p>Darren is also correct here, you can't get multiple identities back as a result set. Your options are using a cursor and taking the identity for each row you insert, or using Darren's approach of storing the identity before and after. So long as you know the increment of the identity this should work, so long as you make sure the table is locked for all three events.</p>\n\n<p>If it was me, and it wasn't time critical I'd go with a cursor.</p>\n" }, { "answer_id": 100669, "author": "Andy Irving", "author_id": 8553, "author_profile": "https://Stackoverflow.com/users/8553", "pm_score": 7, "selected": false, "text": "<p>Use the ouput clause from 2005:</p>\n\n<pre><code>DECLARE @output TABLE (id int)\n\nInsert into A (fname, lname)\nOUTPUT inserted.ID INTO @output\nSELECT fname, lname FROM B\n\nselect * from @output\n</code></pre>\n\n<p>now your table variable has the identity values of all the rows you insert.</p>\n" }, { "answer_id": 65305608, "author": "R.Akhlaghi", "author_id": 2830315, "author_profile": "https://Stackoverflow.com/users/2830315", "pm_score": 0, "selected": false, "text": "<pre><code>-- first create a table for show how its works\nCREATE TABLE [dbo].[myTable]\n (\n [id] [INT] IDENTITY(1, 1) NOT NULL,\n [text] [VARCHAR](10) NULL\n )\nON [PRIMARY]\n\nGO\n\n-- var table for keep new inserted id\nDECLARE @tblNewInserted TABLE\n (\n newids INT\n )\n\n--use the output clause in insert statement\nINSERT INTO [dbo].[myTable]\noutput inserted.id\nINTO @tblNewInserted\nVALUES ('aa'),('bb'),('cc')\n\nSELECT *\nFROM @tblNewInserted \n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/95988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2526/" ]
I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor? ``` Create Table A (id int identity, Fname nvarchar(50), Lname nvarchar(50)) Create Table B (Fname nvarchar(50), Lname nvarchar(50), NewId int) Insert into A(fname, lname) SELECT fname, lname FROM B ``` I'm using MS SQL Server 2005.
MBelly is right on the money - But then the trigger will always try and update table B even if that's not required (Because you're also inserting from table C?). Darren is also correct here, you can't get multiple identities back as a result set. Your options are using a cursor and taking the identity for each row you insert, or using Darren's approach of storing the identity before and after. So long as you know the increment of the identity this should work, so long as you make sure the table is locked for all three events. If it was me, and it wasn't time critical I'd go with a cursor.
96,003
<p>Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.</p> <p>Edit: Instructors and Students <em>must</em> be the same; instructors could be students in other classes, and vice versa.</p> <p>I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.</p>
[ { "answer_id": 96055, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 5, "selected": true, "text": "<p>There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance:</p>\n\n<pre><code>class Person &lt; ActiveRecord::Base; end # btw, model names are singular in rails\nclass Student &lt; Person; end\nclass Instructor &lt; Person; end\n</code></pre>\n\n<p>then</p>\n\n<pre><code>class Course &lt; ActiveRecord::Base # renamed here because class Class already exists in ruby\n has_many :students\n has_many :instructors\nend\n</code></pre>\n\n<p>Just remember that for single table inheritance to work, you need a <code>type</code> column in the <code>people</code> table.</p>\n\n<h3>using an association model might solve your issue</h3>\n\n<pre><code>class Course &lt; ActiveRecord::Base\n has_many :studentships\n has_many :instructorships\n has_many :students, :through =&gt; :studentships\n has_many :instructors, :through =&gt; :instructorships\nend\n\nclass Studentship &lt; ActiveRecord::Base\n belongs_to :course\n belongs_to :student, :class_name =&gt; \"Person\", :foreign_key =&gt; \"student_id\"\nend\n\nclass Instructorship &lt; ActiveRecord::Base\n belongs_to :course\n belongs_to :instructor, :class_name =&gt; \"Person\", :foreign_key =&gt; \"instructor_id\"\nend\n</code></pre>\n" }, { "answer_id": 5580850, "author": "Naveed", "author_id": 671046, "author_profile": "https://Stackoverflow.com/users/671046", "pm_score": 3, "selected": false, "text": "<p>in my case i have Asset and User model \nAsset can be create by an user and could be assigned to a user\nand User can create many assets and can have many Asset\nsolution of my problem was \n asset.rb</p>\n\n<pre><code>class Asset &lt; ActiveRecord::Base\n\nbelongs_to :creator ,:class_name=&gt;'User'\nbelongs_to :assigned_to, :class_name=&gt;'User' \n\nend\n</code></pre>\n\n<p>and </p>\n\n<pre><code>user.rb\n\nclass User &lt; ActiveRecord::Base\n\nhas_many :created_assets, :foreign_key =&gt; 'creator_id', :class_name =&gt; 'Asset'\nhas_many :assigned_assets , :foreign_key =&gt; 'assigned_to_id', :class_name =&gt; 'Asset'\n\nend\n</code></pre>\n\n<p>so your solution could be</p>\n\n<pre><code>class Course &lt; ActiveRecord::Base\nhas_many :students ,:foreign_key =&gt; 'student_id', :class_name =&gt; 'Person'\nhas_many :teachers, :foreign_key =&gt; 'teacher_id', :class_name =&gt; 'Person'\n\nend\n</code></pre>\n\n<p>and </p>\n\n<pre><code>class Person &lt; ActiveRecord::Base\nbelongs_to :course_enrolled,:class_name=&gt;'Course'\nbelongs_to :course_instructor,:class_name=&gt;'Course'\n\nend\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students. Edit: Instructors and Students *must* be the same; instructors could be students in other classes, and vice versa. I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.
There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance: ``` class Person < ActiveRecord::Base; end # btw, model names are singular in rails class Student < Person; end class Instructor < Person; end ``` then ``` class Course < ActiveRecord::Base # renamed here because class Class already exists in ruby has_many :students has_many :instructors end ``` Just remember that for single table inheritance to work, you need a `type` column in the `people` table. ### using an association model might solve your issue ``` class Course < ActiveRecord::Base has_many :studentships has_many :instructorships has_many :students, :through => :studentships has_many :instructors, :through => :instructorships end class Studentship < ActiveRecord::Base belongs_to :course belongs_to :student, :class_name => "Person", :foreign_key => "student_id" end class Instructorship < ActiveRecord::Base belongs_to :course belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id" end ```
96,027
<p>For example, given a type param method i'm looking for something like the part in bold</p> <blockquote> <p>void MyMethod&lt; T >() {<br> if ( <strong>typeof(T).Implements( <em>IMyInterface</em> )</strong> ) {</p> <pre><code> //Do something </code></pre> <p>else</p> <pre><code> //Do something else </code></pre> <p>}</p> </blockquote> <p>Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)</p>
[ { "answer_id": 96057, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx\" rel=\"noreferrer\">Type.IsAssignableFrom</a></p>\n\n<pre><code>if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))\n{\n // something\n}\nelse\n{\n // something else\n}\n</code></pre>\n" }, { "answer_id": 96065, "author": "MADMap", "author_id": 17558, "author_profile": "https://Stackoverflow.com/users/17558", "pm_score": 1, "selected": false, "text": "<p>I think </p>\n\n<pre><code>if (typeof (IMyInterFace).IsAssignableFrom(typeof(T))\n</code></pre>\n\n<p>should also work: but i don't see an advantage...</p>\n" }, { "answer_id": 96095, "author": "Ricardo Amores", "author_id": 10136, "author_profile": "https://Stackoverflow.com/users/10136", "pm_score": 0, "selected": false, "text": "<p>Ï've just tried using </p>\n\n<pre><code>if( typeof(T).Equals(typeof(IMyInterface) ) \n ...\n</code></pre>\n\n<p>And also works, but your answer seems more robust and was what I was looking for. Thanks!</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10136/" ]
For example, given a type param method i'm looking for something like the part in bold > > void MyMethod< T >() { > > if ( **typeof(T).Implements( *IMyInterface* )** ) > { > > > > ``` > //Do something > > ``` > > else > > > > ``` > //Do something else > > ``` > > } > > > Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)
[Type.IsAssignableFrom](http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx) ``` if(typeof(IMyInterface).IsAssignableFrom(typeof(T))) { // something } else { // something else } ```
96,029
<p>I have an ASP.Net page that will be hosted on a couple different servers, and I want to get the URL of the page (or even better: the site where the page is hosted) as a string for use in the code-behind. Any ideas?</p>
[ { "answer_id": 96052, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "<p>Request.Url.Host</p>\n" }, { "answer_id": 96063, "author": "Mikey", "author_id": 13347, "author_profile": "https://Stackoverflow.com/users/13347", "pm_score": 9, "selected": true, "text": "<p>Use this:</p>\n\n<pre><code>Request.Url.AbsoluteUri</code></pre>\n\n<p>That will get you the full path (including <a href=\"http://..\" rel=\"noreferrer\">http://..</a>.)</p>\n" }, { "answer_id": 96080, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "<p>Do you want the server name? Or the host name?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/96029/get-url-of-aspnet-page-in-code-behind#96052\">Request.Url.Host</a> ala Stephen</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.dns.gethostname.aspx\" rel=\"nofollow noreferrer\">Dns.GetHostName</a> - Server name</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.url.aspx\" rel=\"nofollow noreferrer\">Request.Url</a> will have access to most everything you'll need to know about the page being requested.</p>\n" }, { "answer_id": 1534478, "author": "William", "author_id": 98740, "author_profile": "https://Stackoverflow.com/users/98740", "pm_score": 7, "selected": false, "text": "<p>If you want only the scheme and authority part of the request (protocol, host and port) use</p>\n\n<pre><code>Request.Url.GetLeftPart(UriPartial.Authority)\n</code></pre>\n" }, { "answer_id": 1820060, "author": "pub", "author_id": 221370, "author_profile": "https://Stackoverflow.com/users/221370", "pm_score": 3, "selected": false, "text": "<p>I'm facing same problem and so far I found:</p>\n\n<pre><code>new Uri(Request.Url,Request.ApplicationPath)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath\n</code></pre>\n" }, { "answer_id": 1827149, "author": "corey", "author_id": 222224, "author_profile": "https://Stackoverflow.com/users/222224", "pm_score": 3, "selected": false, "text": "<pre><code>Request.Url.GetLeftPart(UriPartial.Authority) + Request.FilePath + \"?theme=blue\";\n</code></pre>\n\n<p>that will give you the full path to the page you are sitting on. I added in the querystring.</p>\n" }, { "answer_id": 3385986, "author": "Ivan Stefanov", "author_id": 364657, "author_profile": "https://Stackoverflow.com/users/364657", "pm_score": 5, "selected": false, "text": "<p>I am using</p>\n\n<pre><code>Request.Url.GetLeftPart(UriPartial.Authority) +\n VirtualPathUtility.ToAbsolute(\"~/\")\n</code></pre>\n" }, { "answer_id": 11000840, "author": "Ben Petersen", "author_id": 876796, "author_profile": "https://Stackoverflow.com/users/876796", "pm_score": 2, "selected": false, "text": "<p>If you want to include any unique string on the end, similar to example.com?id=99999, then use the following</p>\n\n<pre><code>Dim rawUrl As String = Request.RawUrl.ToString()\n</code></pre>\n" }, { "answer_id": 11184525, "author": "REEP", "author_id": 1479202, "author_profile": "https://Stackoverflow.com/users/1479202", "pm_score": 2, "selected": false, "text": "<p>Using a js file you can capture the following, that can be used in the codebehind as well:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n alert('Server: ' + window.location.hostname);\n alert('Full path: ' + window.location.href);\n alert('Virtual path: ' + window.location.pathname);\n alert('HTTP path: ' + \n window.location.href.replace(window.location.pathname, '')); \n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 12039172, "author": "Prescient", "author_id": 1303402, "author_profile": "https://Stackoverflow.com/users/1303402", "pm_score": 4, "selected": false, "text": "<p>I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] \n\"no-reply@\" + BaseSiteUrl\nWorks fine on any site.</p>\n\n<pre><code>// get a sites base urll ex: example.com\npublic static string BaseSiteUrl\n{\n get\n {\n HttpContext context = HttpContext.Current;\n string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');\n return baseUrl;\n }\n\n}\n</code></pre>\n\n<p>If you want to use it in codebehind get rid of context.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I have an ASP.Net page that will be hosted on a couple different servers, and I want to get the URL of the page (or even better: the site where the page is hosted) as a string for use in the code-behind. Any ideas?
Use this: ``` Request.Url.AbsoluteUri ``` That will get you the full path (including <http://..>.)
96,042
<p>I'm working on the creation of an ActiveX EXE using VB6, and the only example I got is all written in Delphi.</p> <p>Reading the example code, I noticed there are some functions whose signatures are followed by the <strong>safecall</strong> keyword. Here's an example:</p> <pre><code>function AddSymbol(ASymbol: OleVariant): WordBool; safecall; </code></pre> <p>What is the purpose of this keyword?</p>
[ { "answer_id": 96231, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 5, "selected": true, "text": "<p>Safecall passes parameters from right to left, instead of the pascal or register (default) from left to right </p>\n\n<p>With safecall, the procedure or function removes parameters from the stack upon returning (like pascal, but not like cdecl where it's up to the caller) </p>\n\n<p>Safecall implements exception 'firewalls'; esp on Win32, this implements interprocess COM error notification. It would otherwise be identical to stdcall (the other calling convention used with the win api)</p>\n" }, { "answer_id": 96646, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/96042/whats-safecall#96231\">What Francois said</a> and if it wasn't for safecall your COM method call would have looked like below and you would have to do your own error checking instead of getting exceptions.</p>\n\n<pre><code>function AddSymbol(ASymbol: OleVariant; out Result: WordBool): HResult; stdcall;\n</code></pre>\n" }, { "answer_id": 97107, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 4, "selected": false, "text": "<p>Additionally, the exception firewalls work by calling SetErrorInfo() with an object that supports IErrorInfo, so that the caller can get extended information about the exception. This is done by the TObject.SafeCallException override in both TComObject and TAutoIntfObject. Both of these types also implement ISupportErrorInfo to mark this fact.</p>\n\n<p>In the event of an exception, the safecall method's caller can query for ISupportErrorInfo, then query that for the interface whose method resulted in a failure HRESULT (high bit set), and if that returns S_OK, <a href=\"http://msdn.microsoft.com/en-us/library/ms221032.aspx\" rel=\"noreferrer\">GetErrorInfo()</a> can get the exception info (description, help, etc., in the form of the IErrorInfo implementation that was passed to <a href=\"http://msdn.microsoft.com/en-us/library/ms221409.aspx\" rel=\"noreferrer\">SetErrorInfo()</a> by the Delphi RTL in the SafeCallException overrides).</p>\n" }, { "answer_id": 50373314, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 2, "selected": false, "text": "<p>In COM, every method is a function that returns an <code>HRESULT</code>:</p>\n\n<pre><code>IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n</code></pre>\n\n<p>This is an absolute rule in COM:</p>\n\n<ul>\n<li>there are no exceptions in COM</li>\n<li>everything returns an HRESULT</li>\n<li>negative HRESULT indicates a failure</li>\n<li>in higher level languages, failures are mapped to exceptions</li>\n</ul>\n\n<p>It was the intention of the COM designers that higher level languages would automatically translate <strong>Failed</strong> methods into an exception.</p>\n\n<p>So in your own language, the COM invocation would be represented without the HRESULT. E.g.:</p>\n\n<ul>\n<li><strong>Delphi-like</strong>: <code>function AddSymbol(ASymbol: OleVariant): WordBool;</code></li>\n<li><strong>C#-like</strong>: <code>WordBool AddSymbol(OleVariant ASymbol);</code></li>\n</ul>\n\n<p>In Delphi you can choose to use the raw function signature:</p>\n\n<pre><code>IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n</code></pre>\n\n<p>And handle the raising of exceptions yourself:</p>\n\n<pre><code>bAdded: WordBool;\nthingy: IThingy;\nhr: HRESULT;\n\nhr := thingy.AddSymbol('Seven', {out}bAdded);\nif Failed(hr) then\n OleError(hr);\n</code></pre>\n\n<p>or the shorter equivalent:</p>\n\n<pre><code>bAdded: WordBool;\nthingy: IThingy;\nhr: HRESULT;\n\nhr := thingy.AddSymbol('Seven', {out}bAdded);\nOleCheck(hr);\n</code></pre>\n\n<p>or the shorter equivalent:</p>\n\n<pre><code>bAdded: WordBool;\nthingy: IThingy;\n\nOleCheck(thingy.AddSymbol('Seven'), {out}bAdded);\n</code></pre>\n\n<h2>COM didn't intend for you to deal with HRESULTs</h2>\n\n<p>But you can ask Delphi to hide that plumbing away from you, so you can get on with the programming:</p>\n\n<pre><code>IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant): WordBool; safecall;\nend;\n</code></pre>\n\n<p>Behind the scenes, the compiler will still check the return HRESULT, and throw an <code>EOleSysError</code> exception if the HRESULT indicated a failure (i.e. was negative). The compiler-generated <strong>safecall</strong> version is functionally equivalent to:</p>\n\n<pre><code>function AddSymbol(ASymbol: OleVariant): WordBool; safecall;\nvar\n hr: HRESULT;\nbegin\n hr := AddSymbol(ASymbol, {out}Result);\n OleCheck(hr);\nend;\n</code></pre>\n\n<p>But it frees you to simply call:</p>\n\n<pre><code>bAdded: WordBool;\nthingy: IThingy;\n\nbAdded := thingy.AddSymbol('Seven');\n</code></pre>\n\n<p>tl;dr: You can use either:</p>\n\n<pre><code>function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nfunction AddSymbol(ASymbol: OleVariant): WordBool; safecall;\n</code></pre>\n\n<p>But the former requires you to handle the HRESULTs every time.</p>\n\n<h2>Bonus Chatter</h2>\n\n<p>You almost never want to handle the HRESULTs yourself; it clutters up the program with noise that adds nothing. But sometimes you might want to check the HRESULT yourself (e.g. you want to handle a failure that isn't very exceptional). Never versions of Delphi have starting included translated Windows header interfaces that are declared both ways:</p>\n\n<pre><code>IThingy = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant; out RetValue: WordBool): HRESULT; stdcall;\nend;\n\nIThingySC = interface\n ['{357D8D61-0504-446F-BE13-4A3BBE699B05}']\n function AddSymbol(ASymbol: OleVariant): WordBool); safecall;\nend;\n</code></pre>\n\n<p>or from the RTL source:</p>\n\n<pre><code> ITransaction = interface(IUnknown)\n ['{0FB15084-AF41-11CE-BD2B-204C4F4F5020}']\n function Commit(fRetaining: BOOL; grfTC: UINT; grfRM: UINT): HResult; stdcall;\n function Abort(pboidReason: PBOID; fRetaining: BOOL; fAsync: BOOL): HResult; stdcall;\n function GetTransactionInfo(out pinfo: XACTTRANSINFO): HResult; stdcall;\n end;\n\n { Safecall Version }\n ITransactionSC = interface(IUnknown)\n ['{0FB15084-AF41-11CE-BD2B-204C4F4F5020}']\n procedure Commit(fRetaining: BOOL; grfTC: UINT; grfRM: UINT); safecall;\n procedure Abort(pboidReason: PBOID; fRetaining: BOOL; fAsync: BOOL); safecall;\n procedure GetTransactionInfo(out pinfo: XACTTRANSINFO); safecall;\n end;\n</code></pre>\n\n<p>The <strong>SC</strong> suffix stands for <strong>safecall</strong>. Both interfaces are equivalent, and you can choose which to declare your COM variable as depending on your desire:</p>\n\n<pre><code>//thingy: IThingy;\nthingy: IThingySC;\n</code></pre>\n\n<p>You can even cast between them:</p>\n\n<pre><code>thingy: IThingSC;\nbAdded: WordBool;\n\nthingy := CreateOleObject('Supercool.Thingy') as TThingySC;\n\nif Failed(IThingy(thingy).AddSymbol('Seven', {out}bAdded) then\nbegin\n //Couldn't seven? No sixty-nine for you\n thingy.SubtractSymbol('Sixty-nine');\nend;\n</code></pre>\n\n<h2>Extra Bonus Chatter - C#</h2>\n\n<p>C# by default does the equivalent of Delphi <strong>safecall</strong>, except in C#:</p>\n\n<ul>\n<li>you have to opt-out of safecall mapping</li>\n<li>rather than opt-in</li>\n</ul>\n\n<p>In C# you would declare your COM interface as:</p>\n\n<pre><code>[ComImport]\n[Guid(\"{357D8D61-0504-446F-BE13-4A3BBE699B05}\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IThingy\n{\n WordBool AddSymbol(OleVariant ASymbol);\n WordBool SubtractSymbol(OleVariant ASymbol);\n}\n</code></pre>\n\n<p>You'll notice that the COM <code>HRESULT</code> is hidden from you. The C# compiler, like the Delphi compiler, will automatically check the returned HRESULT and throw an exception for you.</p>\n\n<p>And in C#, as in Delphi, you can choose to handle the HRESULTs yourself:</p>\n\n<pre><code>[ComImport]\n[Guid(\"{357D8D61-0504-446F-BE13-4A3BBE699B05}\")]\n[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\npublic interface IThingy\n{\n [PreserveSig]\n HRESULT AddSymbol(OleVariant ASymbol, out WordBool RetValue);\n\n WordBool SubtractSymbol(OleVariant ASymbol);\n}\n</code></pre>\n\n<p>The <a href=\"https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.preservesig%28v=vs.110%29.aspx?f=255&amp;MSPPError=-2147217396\" rel=\"nofollow noreferrer\"><strong>[PreserveSig]</strong></a> tells the compiler to preserve the method signature exactly as is:</p>\n\n<blockquote>\n <p>Indicates whether unmanaged methods that have <strong>HRESULT</strong> or <strong>retval</strong> return values are directly translated or whether <strong>HRESULT</strong> or <strong>retval</strong> return values are automatically converted to exceptions.</p>\n</blockquote>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431/" ]
I'm working on the creation of an ActiveX EXE using VB6, and the only example I got is all written in Delphi. Reading the example code, I noticed there are some functions whose signatures are followed by the **safecall** keyword. Here's an example: ``` function AddSymbol(ASymbol: OleVariant): WordBool; safecall; ``` What is the purpose of this keyword?
Safecall passes parameters from right to left, instead of the pascal or register (default) from left to right With safecall, the procedure or function removes parameters from the stack upon returning (like pascal, but not like cdecl where it's up to the caller) Safecall implements exception 'firewalls'; esp on Win32, this implements interprocess COM error notification. It would otherwise be identical to stdcall (the other calling convention used with the win api)
96,054
<p>I have huge 3D arrays of numbers in my .NET application. I need to convert them to a 1D array to pass it to a COM library. Is there a way to convert the array without making a copy of all the data?</p> <p>I can do the conversion like this, but then I use twice the ammount of memory which is an issue in my application:</p> <pre><code> double[] result = new double[input.GetLength(0) * input.GetLength(1) * input.GetLength(2)]; for (i = 0; i &lt; input.GetLength(0); i++) for (j = 0; j &lt; input.GetLength(1); j++) for (k = 0; k &lt; input.GetLength(2); k++) result[i * input.GetLength(1) * input.GetLength(2) + j * input.GetLength(2) + k)] = input[i,j,l]; return result; </code></pre>
[ { "answer_id": 96081, "author": "Yes - that Jake.", "author_id": 5287, "author_profile": "https://Stackoverflow.com/users/5287", "pm_score": 3, "selected": false, "text": "<p>Unfortunately, C# arrays aren't guaranteed to be in contiguous memory like they are in closer-to-the-metal languages like C. So, no. There's no way to convert double[,,] to double[] without an element-by-element copy.</p>\n" }, { "answer_id": 96089, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 4, "selected": true, "text": "<p>I don't believe the way C# stores that data in memory would make it feasible the same way a simple cast in C would. Why not use a 1d array to begin with and perhaps make a class for the type so you can access it in your program as if it were a 3d array?</p>\n" }, { "answer_id": 96092, "author": "Robert Jeppesen", "author_id": 9436, "author_profile": "https://Stackoverflow.com/users/9436", "pm_score": 1, "selected": false, "text": "<p>Without knowing details of your COM library, I'd look into creating a facade class in .Net and exposing it to COM, if necessary.<br>\nYour facade would take a double[,,] and have an indexer that will map from [] to [,,].</p>\n\n<p>Edit: I agree about the points made in the comments, Lorens suggestion is better.</p>\n" }, { "answer_id": 96097, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 1, "selected": false, "text": "<p>As a workaround you could make a class which maintains the array in one dimensional form (maybe even in closer to bare metal form so you can pass it easily to the COM library?) and then overload operator[] on this class to make it usable as a multidimensional array in your C# code.</p>\n" }, { "answer_id": 96603, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 2, "selected": false, "text": "<p>Consider abstracting access to the data with a <a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"nofollow noreferrer\">Proxy</a> (similar to iterators/smart-pointers in C++). Unfortunately, syntax isn't as clean as C++ as operator() not available to overload and operator[] is single-arg, but still close.</p>\n\n<p>Of course, this extra level of abstraction adds complexity and work of its own, but it would allow you to make minimal changes to existing code that uses double[,,] objects, while allowing you to use a single double[] array for both interop and your in-C# computation.</p>\n\n<pre><code>class Matrix3\n{\n // referece-to-element object\n public struct Matrix3Elem{\n private Matrix3Impl impl;\n private uint dim0, dim1, dim2;\n // other constructors\n Matrix3Elem(Matrix3Impl impl_, uint dim0_, uint dim1_, uint dim2_) {\n impl = impl_; dim0 = dim0_; dim1 = dim1_; dim2 = dim2_;\n }\n public double Value{\n get { return impl.GetAt(dim0,dim1,dim2); }\n set { impl.SetAt(dim0, dim1, dim2, value); }\n }\n }\n\n // implementation object\n internal class Matrix3Impl\n {\n private double[] data;\n uint dsize0, dsize1, dsize2; // dimension sizes\n // .. Resize() \n public double GetAt(uint dim0, uint dim1, uint dim2) {\n // .. check bounds\n return data[ (dim2 * dsize1 + dim1) * dsize0 + dim0 ];\n }\n public void SetAt(uint dim0, uint dim1, uint dim2, double value) {\n // .. check bounds\n data[ (dim2 * dsize1 + dim1) * dsize0 + dim0 ] = value;\n }\n }\n\n private Matrix3Impl impl;\n\n public Matrix3Elem Elem(uint dim0, uint dim1, uint dim2){\n return new Matrix2Elem(dim0, dim1, dim2);\n }\n // .. Resize\n // .. GetLength0(), GetLength1(), GetLength1()\n}\n</code></pre>\n\n<p>And then using this type to both read and write -- 'foo[1,2,3]' is now written as 'foo.Elem(1,2,3).Value', in both reading values and writing values, on left side of assignment and value expressions.</p>\n\n<pre><code>void normalize(Matrix3 m){\n\n double s = 0;\n for (i = 0; i &lt; input.GetLength0; i++) \n for (j = 0; j &lt; input.GetLength(1); j++) \n for (k = 0; k &lt; input.GetLength(2); k++)\n {\n s += m.Elem(i,j,k).Value;\n }\n for (i = 0; i &lt; input.GetLength0; i++) \n for (j = 0; j &lt; input.GetLength(1); j++) \n for (k = 0; k &lt; input.GetLength(2); k++)\n {\n m.Elem(i,j,k).Value /= s;\n }\n}\n</code></pre>\n\n<p>Again, added development costs, but shares data, removing copying overhead and copying related developtment costs. It's a tradeoff.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15454/" ]
I have huge 3D arrays of numbers in my .NET application. I need to convert them to a 1D array to pass it to a COM library. Is there a way to convert the array without making a copy of all the data? I can do the conversion like this, but then I use twice the ammount of memory which is an issue in my application: ``` double[] result = new double[input.GetLength(0) * input.GetLength(1) * input.GetLength(2)]; for (i = 0; i < input.GetLength(0); i++) for (j = 0; j < input.GetLength(1); j++) for (k = 0; k < input.GetLength(2); k++) result[i * input.GetLength(1) * input.GetLength(2) + j * input.GetLength(2) + k)] = input[i,j,l]; return result; ```
I don't believe the way C# stores that data in memory would make it feasible the same way a simple cast in C would. Why not use a 1d array to begin with and perhaps make a class for the type so you can access it in your program as if it were a 3d array?
96,059
<p>Suppose I want to store many small configuration objects in XML, and I don't care too much about the format. The <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html" rel="nofollow noreferrer">XMLDecoder</a> class built into the JDK would work, and from what I hear, <a href="http://xstream.codehaus.org/" rel="nofollow noreferrer">XStream</a> works in a similar way.</p> <p>What are the advantages to each library?</p>
[ { "answer_id": 96148, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 1, "selected": false, "text": "<p>If you are planning on storing all those configuration objects in a single file, and that file will be quite large, both the options you've outlined above could be quite memory intensive, as they both require the entire file to be read into memory to be deserialized.</p>\n\n<p>If memory usage is a concern (the file containing the XML will be very large), I recommend <a href=\"http://www.saxproject.org/\" rel=\"nofollow noreferrer\">SAX</a>.</p>\n\n<p>If memory usage is not a concern (the file containing the XML will not be very large), I'd use whatever is included with the default JRE (in this case XMLDecoder) just to remove 3rd party dependencies.</p>\n" }, { "answer_id": 97182, "author": "Jay R.", "author_id": 5074, "author_profile": "https://Stackoverflow.com/users/5074", "pm_score": 3, "selected": false, "text": "<p>I really like the <a href=\"http://xstream.codehaus.org/\" rel=\"noreferrer\">XStream</a>\nlibrary. It does a really good job of outputting fairly simple xml\nas a result of a provided Java object. It works great for reproducing\nthe object back from the xml as well. And, one of our 3rd party libraries\nalready depended on it anyway.</p>\n\n<ul>\n<li><p>We chose to use it because we wanted\nour xml to be human readable. Using\nthe alias function makes it much\nnicer.</p></li>\n<li><p>You can extend the library if you\nwant some portion of an object to\ndeserialize in a nicer fashion. We\ndid this in one case so the file\nwould have a set of degrees,\nminutes, and seconds for a latitude\nand longitude, instead of two\ndoubles.</p></li>\n</ul>\n\n<p>The two minute tutorial sums up the basic usage, but in the \ninterest of keeping the information in one spot, I'll try to sum it \nup here, just a little shorter.</p>\n\n<pre><code>// define your classes\npublic class Person {\n private String firstname;\n private PhoneNumber phone;\n // ... constructors and methods\n}\n\npublic class PhoneNumber {\n private int code;\n private String number;\n // ... constructors and methods\n}\n</code></pre>\n\n<p>Then use the library for write out the xml.</p>\n\n<pre><code>// initial the libray\nXStream xstream = new XStream();\nxstream.alias(\"person\", Person.class); // elementName, Class\nxstream.alias(\"phone\", PhoneNumber.class); \n\n// make your objects\nPerson joe = new Person(\"Joe\");\njoe.setPhone(new PhoneNumber(123, \"1234-456\"));\n\n// convert xml\nString xml = xstream.toXML(joe);\n</code></pre>\n\n<p>You output will look like this:\n<pre><code>&lt;person>\n &lt;firstname>Joe&lt;/firstname>\n &lt;phone>\n &lt;code>123&lt;/code>\n &lt;number>1234-456&lt;/number>\n &lt;/phone>\n&lt;/person>\n</pre></code></p>\n\n<p>To go back:\n<pre><code>Person newJoe = (Person)xstream.fromXML(xml);</pre></code></p>\n\n<p>The XMLEncoder is provided for Java bean serialization. The last time I used it, \nthe file looked fairly nasty. If really don't care what the file looks like, it could\nwork for you and you get to avoid a 3rd party dependency, which is also nice. I'd expect the possibility of making the serialization prettier would be more a challenge with the XMLEncoder as well.</p>\n\n<p>XStream outputs the full class name if you don't alias the name. If the Person class above had <pre><code>package example;</code></pre> the xml would have \"example.Person\" instead of just \"person\".</p>\n" }, { "answer_id": 100359, "author": "Christoph Metzendorf", "author_id": 3570, "author_profile": "https://Stackoverflow.com/users/3570", "pm_score": 1, "selected": false, "text": "<p>I'd also prefer <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">XStream</a> as it is really easy to use and to extend. You can quickly start if you're going with the default setup. If you need to customize the behavior it has a very clean API and a lot of extension points, so you have really fine grained control over the things you want to tweak without interfering with other parts of the marshalling process.</p>\n\n<p>As the XML that is created by XStream looks nice, manual editing is also simple. If the output doesn't fulfill your needs and the long list of available <a href=\"http://xstream.codehaus.org/converters.html\" rel=\"nofollow noreferrer\">Converters</a> doesn't contain the one you need, it's fairly simple to write your own.</p>\n\n<p>A big plus is also the good documentation on their <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">homepage</a>.</p>\n" }, { "answer_id": 534143, "author": "StaxMan", "author_id": 59501, "author_profile": "https://Stackoverflow.com/users/59501", "pm_score": 2, "selected": false, "text": "<p>Another suggestion: consider using JAXB (<a href=\"http://jaxb.dev.java.net\" rel=\"nofollow noreferrer\">http://jaxb.dev.java.net</a>). If you are using JDK 1.6, it comes bundled, check out \"javax.xml.bind\" for details, so no need for additional external jars.</p>\n\n<p>JAXB is rather fast. I like XStream too, but it's bit slower. Also, XMLEncoder is bit of a toy (compared to other options)... but if it works, there's no harm in using it.</p>\n\n<p>Also: one benefit of JAXB is that you can also bind partial document (sub-trees) with it; no need to create object(s) for the whole file. For this you need to use Stax (XMLStreamReader) to point to root element of the sub-tree, then bind. No need to use SAX, even for most large files, as long as it can be processed chunk by chunk.</p>\n" }, { "answer_id": 1467774, "author": "whatnick", "author_id": 176958, "author_profile": "https://Stackoverflow.com/users/176958", "pm_score": 0, "selected": false, "text": "<p>Java also has a new utility class aimed at storing Key-Value paired sets typical to configurations. It is the old style but very simple and handy. This is done via the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Properties.html\" rel=\"nofollow noreferrer\">java.util.Properties</a> class, a Map object with serialization options. This might be all you need unless you are storing entire objects.</p>\n" }, { "answer_id": 1467795, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "<p>I always find XStream very tempting, because it's so easy to get going. However, invariably I end up replacing it. It's really quite buggy, and its collection handling could use a lot of work.</p>\n\n<p>As a result, I usually switch to JAXB. It's an awful lot more robust, it's pretty much bug-free, and a more flexible than XStream.</p>\n" }, { "answer_id": 2517831, "author": "mrm", "author_id": 1268016, "author_profile": "https://Stackoverflow.com/users/1268016", "pm_score": -1, "selected": false, "text": "<p>You should avoid XMLEncoder/XMLDecoder like the plague if you're going to be persisting a non-trivial number of objects or your system needs to be multithreaded. See <a href=\"http://matthew.mceachen.us/blog/do-not-want-xmlencoder-129.html\" rel=\"nofollow noreferrer\">http://matthew.mceachen.us/blog/do-not-want-xmlencoder-129.html</a> for the grisly details.</p>\n\n<p>If you must use XML, XStream is great. But ask yourself if you really need to use XML. Here's a serialization benchmark project that might turn you on to better solutions:</p>\n\n<p><a href=\"http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking\" rel=\"nofollow noreferrer\">http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking</a></p>\n" }, { "answer_id": 23431074, "author": "Elf", "author_id": 2404453, "author_profile": "https://Stackoverflow.com/users/2404453", "pm_score": 1, "selected": false, "text": "<p>Addition to @jay answer with example:</p>\n\n<p>Code:</p>\n\n<pre><code>PortfolioAlternateIdentifier identifier = new PortfolioAlternateIdentifier();\nidentifier.setEffectiveDate(new Date());\nidentifier.setSchemeCode(\"AAA\");\nidentifier.setIdentifier(\"123456\");\n</code></pre>\n\n<p><strong>The output using XStream:</strong></p>\n\n<pre><code>&lt;PortfolioAlternateIdentifier&gt;\n &lt;effectiveDate&gt;2014-05-02 20:14:15.961 IST&lt;/effectiveDate&gt;\n &lt;schemeCode&gt;AAA&lt;/schemeCode&gt;\n &lt;identifier&gt;123456&lt;/identifier&gt;\n&lt;/PortfolioAlternateIdentifier&gt; \n</code></pre>\n\n<p><strong>The output using XMLEncoder:</strong></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; \n &lt;java version=\"1.6.0_38\" class=\"java.beans.XMLDecoder\"&gt; \n &lt;object class=\"PortfolioAlternateIdentifier\"&gt; \n &lt;void property=\"effectiveDate\"&gt; \n &lt;object class=\"java.util.Date\"&gt; \n &lt;long&gt;1399041855961&lt;/long&gt; \n &lt;/object&gt; \n &lt;/void&gt; \n &lt;void property=\"identifier\"&gt; \n &lt;string&gt;123456&lt;/string&gt; \n &lt;/void&gt; \n &lt;void property=\"schemeCode\"&gt; \n &lt;string&gt;AAA&lt;/string&gt; \n &lt;/void&gt; \n &lt;/object&gt; \n&lt;/java&gt; \n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3474/" ]
Suppose I want to store many small configuration objects in XML, and I don't care too much about the format. The [XMLDecoder](http://java.sun.com/j2se/1.5.0/docs/api/java/beans/XMLDecoder.html) class built into the JDK would work, and from what I hear, [XStream](http://xstream.codehaus.org/) works in a similar way. What are the advantages to each library?
I really like the [XStream](http://xstream.codehaus.org/) library. It does a really good job of outputting fairly simple xml as a result of a provided Java object. It works great for reproducing the object back from the xml as well. And, one of our 3rd party libraries already depended on it anyway. * We chose to use it because we wanted our xml to be human readable. Using the alias function makes it much nicer. * You can extend the library if you want some portion of an object to deserialize in a nicer fashion. We did this in one case so the file would have a set of degrees, minutes, and seconds for a latitude and longitude, instead of two doubles. The two minute tutorial sums up the basic usage, but in the interest of keeping the information in one spot, I'll try to sum it up here, just a little shorter. ``` // define your classes public class Person { private String firstname; private PhoneNumber phone; // ... constructors and methods } public class PhoneNumber { private int code; private String number; // ... constructors and methods } ``` Then use the library for write out the xml. ``` // initial the libray XStream xstream = new XStream(); xstream.alias("person", Person.class); // elementName, Class xstream.alias("phone", PhoneNumber.class); // make your objects Person joe = new Person("Joe"); joe.setPhone(new PhoneNumber(123, "1234-456")); // convert xml String xml = xstream.toXML(joe); ``` You output will look like this: ``` <person> <firstname>Joe</firstname> <phone> <code>123</code> <number>1234-456</number> </phone> </person> ``` To go back: ``` Person newJoe = (Person)xstream.fromXML(xml); ``` The XMLEncoder is provided for Java bean serialization. The last time I used it, the file looked fairly nasty. If really don't care what the file looks like, it could work for you and you get to avoid a 3rd party dependency, which is also nice. I'd expect the possibility of making the serialization prettier would be more a challenge with the XMLEncoder as well. XStream outputs the full class name if you don't alias the name. If the Person class above had ``` package example; ``` the xml would have "example.Person" instead of just "person".
96,066
<p>I'm trying to incorporate some JavaScript unit testing into my automated build process. Currently JSUnit works well with JUnit, but it seems to be abandonware and lacks good support for Ajax, debugging, and timeouts.</p> <p>Has anyone had any luck automating (with <a href="https://en.wikipedia.org/wiki/Apache_Ant" rel="nofollow noreferrer">Ant</a>) a unit testing library such as <a href="https://en.wikipedia.org/wiki/Yahoo!_UI_Library" rel="nofollow noreferrer">YUI</a> test, jQuery's <a href="https://code.jquery.com/qunit/" rel="nofollow noreferrer">QUnit</a>, or <a href="http://code.google.com/p/jqunit/" rel="nofollow noreferrer">jQUnit</a>?</p> <p>Note: I use a custom built Ajax library, so the problem with Dojo's DOH is that it requires you to use their own Ajax function calls and event handlers to work with any Ajax unit testing.</p>
[ { "answer_id": 96115, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "<p>Look into <a href=\"http://developer.yahoo.com/yui/yuitest/\" rel=\"nofollow noreferrer\">YUITest</a></p>\n" }, { "answer_id": 96235, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 5, "selected": true, "text": "<p>There are many JavaScript unit test framework out there (JSUnit, scriptaculous, ...), but JSUnit is the only one I know that may be used with an automated build.</p>\n<p>If you are doing 'true' unit test you should not need AJAX support. For example, if you are using an <a href=\"https://en.wikipedia.org/wiki/Remote_procedure_call\" rel=\"nofollow noreferrer\">RPC</a> Ajax framework such as DWR, you can easily write a mock function:</p>\n<pre>\n function mockFunction(someArg, callback) {\n var result = ...; // Some treatments\n setTimeout(<br>\n function() { callback(result); },\n 300 // Some fake latency\n );\n }\n</pre>\n<p>And yes, JSUnit does handle timeouts: <em><a href=\"http://googletesting.blogspot.com/2007/03/javascript-simulating-time-in-jsunit.html\" rel=\"nofollow noreferrer\">Simulating Time in JSUnit Tests</a></em></p>\n" }, { "answer_id": 96571, "author": "Jason Wadsworth", "author_id": 11078, "author_profile": "https://Stackoverflow.com/users/11078", "pm_score": 0, "selected": false, "text": "<p>Another JavaScript testing framework that can be run with Ant is <a href=\"https://dev.thefrontside.net/crosscheck\" rel=\"nofollow noreferrer\">CrossCheck</a>. There's an example of running CrossCheck via Ant in the build file for the project.</p>\n<p>CrossCheck attempts, with limited success, to emulate a browser, including mock-style implementations of <a href=\"https://en.wikipedia.org/wiki/XMLHttpRequest\" rel=\"nofollow noreferrer\">XMLHttpRequest</a> and timeout/interval.</p>\n<p>It does not currently handle loading JavaScript from a web page, though. You have to specify the JavaScript files that you want to load and test. If you keep all of your JavaScript code separated from your HTML, it might work for you.</p>\n" }, { "answer_id": 96743, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 5, "selected": false, "text": "<p>I'm just about to start doing JavaScript <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">TDD</a> on a new project I am working on. My current plan is to use <a href=\"http://docs.jquery.com/QUnit\" rel=\"nofollow noreferrer\">QUnit</a> to do the unit testing. While developing the tests can be run by simply refreshing the test page in a browser.</p>\n<p>For continuous integration (and ensuring the tests run in all browsers), I will use <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a> to automatically load the test harness in each browser, and read the result. These tests will be run on every checkin to source control.</p>\n<p>I am also going to use <a href=\"http://siliconforks.com/jscoverage/\" rel=\"nofollow noreferrer\">JSCoverage</a> to get code coverage analysis of the tests. This will also be automated with Selenium.</p>\n<p>I'm currently in the middle of setting this up. I'll update this answer with more exact details once I have the setup hammered out.</p>\n<hr />\n<p>Testing tools:</p>\n<ul>\n<li><a href=\"http://docs.jquery.com/QUnit\" rel=\"nofollow noreferrer\">qunit</a></li>\n<li><a href=\"http://siliconforks.com/jscoverage/\" rel=\"nofollow noreferrer\">JSCoverage</a></li>\n<li><a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a></li>\n</ul>\n" }, { "answer_id": 139158, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 3, "selected": false, "text": "<p>I recently read an article by Bruno using JSUnit and creating a JsMock framework on top of that... very interesting. I'm thinking of using his work to start unit testing my JavaScript code.</p>\n<p><a href=\"http://brunofigueiredo.com/post/Mock-Javascript-or-How-to-unit-test-Javascript-outside-the-Browser-environment-Part-1.aspx\" rel=\"nofollow noreferrer\">Mock JavaScript or How to unit test JavaScript outside the Browser environment</a></p>\n" }, { "answer_id": 1668372, "author": "groodt", "author_id": 72985, "author_profile": "https://Stackoverflow.com/users/72985", "pm_score": 4, "selected": false, "text": "<p>I'm a big fan of <a href=\"http://code.google.com/p/js-test-driver/\" rel=\"nofollow noreferrer\">js-test-driver</a>.</p>\n<p>It works well in a <a href=\"https://en.wikipedia.org/wiki/Continuous_integration\" rel=\"nofollow noreferrer\">CI</a> environment and is able to capture actual browsers for cross-browser testing.</p>\n" }, { "answer_id": 1891305, "author": "Josh", "author_id": 224929, "author_profile": "https://Stackoverflow.com/users/224929", "pm_score": 2, "selected": false, "text": "<p>I am in agreement that JSUnit is kind of dying on the vine. We just finished up replacing it with YUI Test.</p>\n<p>Similar to the example using qUnit, we are running the tests using <a href=\"https://en.wikipedia.org/wiki/Selenium_%28software%29\" rel=\"nofollow noreferrer\">Selenium</a>. We are running this test independently from our other Selenium tests simply because it does not have the dependencies that the normal UI regression tests have (e.g. deploying the application to a server).</p>\n<p>To start out, we have a base JavaScript file that is included in all of our test HTML files. This handles setting up the YUI instance, the test runner, the YUI.Test.Suite object as well as the Test.Case. It has methods that can be accessed via Selenium to run the test suite, check to see if the test runner is still running (results are not available until after it's done), and get the test results (we chose JSON format):</p>\n<pre><code>var yui_instance; // The YUI instance\nvar runner; // The YAHOO.Test.Runner\nvar Assert; // An instance of YAHOO.Test.Assert to save coding\nvar testSuite; // The YAHOO.Test.Suite that will get run.\n\n/**\n * Sets the required value for the name property on the given template, creates\n * and returns a new YUI Test.Case object.\n *\n * @param template the template object containing all of the tests\n */\nfunction setupTestCase(template) {\n template.name = &quot;jsTestCase&quot;;\n var test_case = new yui_instance.Test.Case(template);\n return test_case;\n}\n\n/**\n * Sets up the test suite with a single test case using the given\n * template.\n *\n * @param template the template object containing all of the tests\n */\nfunction setupTestSuite(template) {\n var test_case = setupTestCase(template);\n testSuite = new yui_instance.Test.Suite(&quot;Bond JS Test Suite&quot;);\n testSuite.add(test_case);\n}\n\n/**\n * Runs the YAHOO.Test.Suite\n */\nfunction runTestSuite() {\n runner = yui_instance.Test.Runner;\n Assert = yui_instance.Assert;\n\n runner.clear();\n runner.add(testSuite);\n runner.run();\n}\n\n/**\n * Used to see if the YAHOO.Test.Runner is still running. The\n * test results are not available until it is done running.\n */\nfunction isRunning() {\n return runner.isRunning();\n}\n\n/**\n * Gets the results from the YAHOO.Test.Runner\n */\nfunction getTestResults() {\n return runner.getResults(yui_instance.Test.Format.JSON);\n}\n</code></pre>\n<p>As for the Selenium side of things, we used a parameterized test. We run our tests in both Internet Explorer and Firefox in the data method, parsing the test results into a list of Object arrays with each array containing the browser name, the test file name, the test name, the result (pass, fail or ignore) and the message.</p>\n<p>The actual test just asserts the test result. If it is not equal to &quot;pass&quot; then it fails the test with the message returned from the YUI Test result.</p>\n<pre><code>@Parameters\npublic static List&lt;Object[]&gt; data() throws Exception {\n yui_test_codebase = &quot;file:///c://myapppath/yui/tests&quot;;\n\n List&lt;Object[]&gt; testResults = new ArrayList&lt;Object[]&gt;();\n\n pageNames = new ArrayList&lt;String&gt;();\n pageNames.add(&quot;yuiTest1.html&quot;);\n pageNames.add(&quot;yuiTest2.html&quot;);\n\n testResults.addAll(runJSTestsInBrowser(IE_NOPROXY));\n testResults.addAll(runJSTestsInBrowser(FIREFOX));\n return testResults;\n}\n\n/**\n * Creates a Selenium instance for the given browser, and runs each\n * YUI Test page.\n *\n * @param aBrowser\n * @return\n */\nprivate static List&lt;Object[]&gt; runJSTestsInBrowser(Browser aBrowser) {\n String yui_test_codebase = &quot;file:///c://myapppath/yui/tests/&quot;;\n String browser_bot = &quot;this.browserbot.getCurrentWindow()&quot;\n List&lt;Object[]&gt; testResults = new ArrayList&lt;Object[]&gt;();\n selenium = new DefaultSelenium(APPLICATION_SERVER, REMOTE_CONTROL_PORT, aBrowser.getCommand(), yui_test_codebase);\n try {\n selenium.start();\n\n /*\n * Run the test here\n */\n for (String page_name : pageNames) {\n selenium.open(yui_test_codebase + page_name);\n //Wait for the YAHOO instance to be available\n selenium.waitForCondition(browser_bot + &quot;.yui_instance != undefined&quot;, &quot;10000&quot;);\n selenium.getEval(&quot;dom=runYUITestSuite(&quot; + browser_bot + &quot;)&quot;);\n\n // Output from the tests is not available until\n // the YAHOO.Test.Runner is done running the suite\n selenium.waitForCondition(&quot;!&quot; + browser_bot + &quot;.isRunning()&quot;, &quot;10000&quot;);\n String output = selenium.getEval(&quot;dom=getYUITestResults(&quot; + browser_bot + &quot;)&quot;);\n\n JSONObject results = JSONObject.fromObject(output);\n JSONObject test_case = results.getJSONObject(&quot;jsTestCase&quot;);\n JSONArray testCasePropertyNames = test_case.names();\n Iterator itr = testCasePropertyNames.iterator();\n\n /*\n * From the output, build an array with the following:\n * Test file\n * Test name\n * status (result)\n * message\n */\n while(itr.hasNext()) {\n String name = (String)itr.next();\n if(name.startsWith(&quot;test&quot;)) {\n JSONObject testResult = test_case.getJSONObject(name);\n String test_name = testResult.getString(&quot;name&quot;);\n String test_result = testResult.getString(&quot;result&quot;);\n String test_message = testResult.getString(&quot;message&quot;);\n Object[] testResultObject = {aBrowser.getCommand(), page_name, test_name, test_result, test_message};\n testResults.add(testResultObject);\n }\n }\n }\n } finally {\n // If an exception is thrown, this will guarantee that the selenium instance\n // is shut down properly\n selenium.stop();\n selenium = null;\n }\n return testResults;\n}\n\n/**\n * Inspects each test result and fails if the testResult was not &quot;pass&quot;\n */\n@Test\npublic void inspectTestResults() {\n if(!this.testResult.equalsIgnoreCase(&quot;pass&quot;)) {\n fail(String.format(MESSAGE_FORMAT, this.browser, this.pageName, this.testName, this.message));\n }\n}\n</code></pre>\n" }, { "answer_id": 3967905, "author": "Ingvald", "author_id": 8698, "author_profile": "https://Stackoverflow.com/users/8698", "pm_score": 3, "selected": false, "text": "<p>I just <a href=\"http://skaug.no/ingvald/2010/10/javascript-unit-testing.html\" rel=\"nofollow noreferrer\">got Hudson CI to run JasmineBDD</a> (headless), at least for pure JavaScript unit testing.</p>\n<p>(Hudson running Java via shell, running Envjs, running JasmineBDD.)</p>\n<p>I haven't got it to play nice with a big library yet, though, like prototype.</p>\n" }, { "answer_id": 4323476, "author": "Mat Ryer", "author_id": 117601, "author_profile": "https://Stackoverflow.com/users/117601", "pm_score": 1, "selected": false, "text": "<p>There's a new project that lets you run <a href=\"http://docs.jquery.com/Qunit\" rel=\"nofollow noreferrer\">QUnit</a> tests in a Java environment (like Ant) so you can fully integrate your client-side test suite with your other unit tests.</p>\n<p><a href=\"http://qunit-test-runner.googlecode.com\" rel=\"nofollow noreferrer\">http://qunit-test-runner.googlecode.com</a></p>\n<p>I've used it to unit test jQuery plugins, <a href=\"http://objx.googlecode.com\" rel=\"nofollow noreferrer\">objx</a> code, custom OO JavaScript and it works for everything without modification.</p>\n" }, { "answer_id": 8879091, "author": "Steven de Salas", "author_id": 448568, "author_profile": "https://Stackoverflow.com/users/448568", "pm_score": 1, "selected": false, "text": "<p>The project I'm working on uses <a href=\"http://code.google.com/p/js-test-driver/\" rel=\"nofollow noreferrer\">Js-Test-Driver</a> hosting <a href=\"http://pivotal.github.com/jasmine/\" rel=\"nofollow noreferrer\">Jasmine</a> on Chrome 10 with <a href=\"https://github.com/ibolmo/jasmine-jstd-adapter\" rel=\"nofollow noreferrer\">Jasmine-JSTD-Adapter</a> including making use of <a href=\"http://code.google.com/p/js-test-driver/wiki/CodeCoverage\" rel=\"nofollow noreferrer\">code coverage</a> tests included in JS-Test-Driver.</p>\n<p>While there are some problems each time we change or update browsers on the <a href=\"http://en.wikipedia.org/wiki/Continuous_integration\" rel=\"nofollow noreferrer\">CI environment</a> the Jasmine tests are running pretty smoothly with only minor issues with ansynchronous tests, but as far as I'm aware these can be worked around using Jasmine Clock, but I haven't had a chance to patch them yet.</p>\n" }, { "answer_id": 9886420, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 1, "selected": false, "text": "<p>I've published <a href=\"https://github.com/liammclennan/browsertest\" rel=\"nofollow noreferrer\">a little library</a> for verifying browser-dependent JavaScript tests without having to use a browser. It is a Node.js module that uses zombie.js to load the test page and inspect the results. I've wrote about it <a href=\"http://hackingon.net/post/Testing-Browser-dependent-JavaScript.aspx\" rel=\"nofollow noreferrer\">on my blog</a>. Here is what the automation looks like:</p>\n<pre><code>var browsertest = require('../browsertest.js').browsertest;\n\ndescribe('browser tests', function () {\n\n it('should properly report the result of a mocha test page', function (done) {\n browsertest({\n url: &quot;file:///home/liam/work/browser-js-testing/tests.html&quot;,\n callback: function() {\n done();\n }\n });\n });\n\n});\n</code></pre>\n" }, { "answer_id": 10903727, "author": "Phil Mander", "author_id": 200113, "author_profile": "https://Stackoverflow.com/users/200113", "pm_score": 0, "selected": false, "text": "<p>I've written an Ant task which uses <a href=\"http://phantomjs.org/\" rel=\"nofollow noreferrer\">PhantomJS</a>, a headless <a href=\"https://en.wikipedia.org/wiki/WebKit\" rel=\"nofollow noreferrer\">WebKit</a> browser, to run QUnit HTML test files within an Ant build process. It can also fail the build if any tests fail.</p>\n<p><a href=\"https://github.com/philmander/ant-jstestrunner\" rel=\"nofollow noreferrer\">https://github.com/philmander/ant-jstestrunner</a></p>\n" }, { "answer_id": 17597288, "author": "Alexvx", "author_id": 1256677, "author_profile": "https://Stackoverflow.com/users/1256677", "pm_score": 0, "selected": false, "text": "<p>This is a good evaluation of several testing tools.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/300855/looking-for-a-better-javascript-unit-test-tool\">JavaScript unit test tools for TDD</a></p>\n\n<p>I personally prefer \n<a href=\"https://code.google.com/p/js-test-driver/\" rel=\"nofollow noreferrer\">https://code.google.com/p/js-test-driver/</a></p>\n" }, { "answer_id": 22473491, "author": "lastboy", "author_id": 2739571, "author_profile": "https://Stackoverflow.com/users/2739571", "pm_score": 1, "selected": false, "text": "<p>I looked on your question date and back then there were a few good JavaScript testing libraries and frameworks.</p>\n<p>Today you can find much more and in different focus like <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">TDD</a>, <a href=\"https://en.wikipedia.org/wiki/Behavior-driven_development\" rel=\"nofollow noreferrer\">BDD</a>, Assetion and with/without runners support.</p>\n<p>There are <em>many</em> players in this game, like <a href=\"https://en.wikipedia.org/wiki/Mocha_(JavaScript_framework)\" rel=\"nofollow noreferrer\">Mocha</a>, <a href=\"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#JavaScript\" rel=\"nofollow noreferrer\">Chai</a>, <a href=\"https://code.jquery.com/qunit/\" rel=\"nofollow noreferrer\">QUnit</a>, <a href=\"https://en.wikipedia.org/wiki/Jasmine_(JavaScript_testing_framework)\" rel=\"nofollow noreferrer\">Jasmine</a>, etc...</p>\n<p>You can find some more information in <a href=\"http://catjs.blogspot.co.il/\" rel=\"nofollow noreferrer\">this</a> blog about JavaScript, mobile, and web testing...</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18146/" ]
I'm trying to incorporate some JavaScript unit testing into my automated build process. Currently JSUnit works well with JUnit, but it seems to be abandonware and lacks good support for Ajax, debugging, and timeouts. Has anyone had any luck automating (with [Ant](https://en.wikipedia.org/wiki/Apache_Ant)) a unit testing library such as [YUI](https://en.wikipedia.org/wiki/Yahoo!_UI_Library) test, jQuery's [QUnit](https://code.jquery.com/qunit/), or [jQUnit](http://code.google.com/p/jqunit/)? Note: I use a custom built Ajax library, so the problem with Dojo's DOH is that it requires you to use their own Ajax function calls and event handlers to work with any Ajax unit testing.
There are many JavaScript unit test framework out there (JSUnit, scriptaculous, ...), but JSUnit is the only one I know that may be used with an automated build. If you are doing 'true' unit test you should not need AJAX support. For example, if you are using an [RPC](https://en.wikipedia.org/wiki/Remote_procedure_call) Ajax framework such as DWR, you can easily write a mock function: ``` function mockFunction(someArg, callback) { var result = ...; // Some treatments setTimeout( function() { callback(result); }, 300 // Some fake latency ); } ``` And yes, JSUnit does handle timeouts: *[Simulating Time in JSUnit Tests](http://googletesting.blogspot.com/2007/03/javascript-simulating-time-in-jsunit.html)*
96,086
<p>I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript. What's the best way to go about this?</p> <p>Is it best to separate the visual from the functional? Do you develop the visual elements first, and then write tests and then code for functionality?</p>
[ { "answer_id": 96221, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 0, "selected": false, "text": "<p>This is the primary reason I switched to the Google Web Toolkit ... I develop and test in Java and have a reasonable expectation that the compiled JavaScript will function properly on a variety of browsers. Since TDD is primarily a unit testing function, most of the project can be developed and tested before compilation and deployment.</p>\n\n<p>Integration and Functional test suites verify that the resulting code is functioning as expected after it's deployed to a test server.</p>\n" }, { "answer_id": 96644, "author": "Desty", "author_id": 2161072, "author_profile": "https://Stackoverflow.com/users/2161072", "pm_score": 2, "selected": false, "text": "<p>I've never successfully TDDed UI code. The closest we came was indeed to separate UI code as much as possible from the application logic. This is one reason why the model-view-controller pattern is useful - the model and controller can be TDDed without much trouble and without getting too complicated.</p>\n\n<p>In my experience, the view was always left for our user-acceptance tests (we wrote web applications and our UATs used Java's HttpUnit). However, at this level it's really an integration test, without the test-in-isolation property we desire with TDD. Due to this setup, we had to write our controller/model tests/code first, then the UI and corresponding UAT. However, in the Swing GUI code I've been writing lately, I've been writing the GUI code first with stubs to explore my design of the front end, before adding to the controller/model/API. YMMV here though.</p>\n\n<p>So to reiterate, the only advice I can give is what you already seem to suspect - separate your UI code from your logic as much as possible and TDD them.</p>\n" }, { "answer_id": 96676, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 0, "selected": false, "text": "<p>I'm just about to start doing Javascript TDD on a new project I am working on. My current plan is to use <a href=\"http://docs.jquery.com/QUnit\" rel=\"nofollow noreferrer\">qunit</a> to do the unit testing. While developing the tests can be run by simply refreshing the test page in a browser.</p>\n\n<p>For continuous integration (and ensuring the tests run in all browsers), I will use <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a> to automatically load the test harness in each browser, and read the result. These tests will be run on every checkin to source control.</p>\n\n<p>I am also going to use <a href=\"http://siliconforks.com/jscoverage/\" rel=\"nofollow noreferrer\">JSCoverage</a> to get code coverage analysis of the tests. This will also be automated with Selenium.</p>\n\n<p>I'm currently in the middle of setting this up. I'll update this answer with more exact details once I have the setup hammered out.</p>\n\n<hr>\n\n<p>Testing tools:</p>\n\n<ul>\n<li><a href=\"http://docs.jquery.com/QUnit\" rel=\"nofollow noreferrer\">qunit</a></li>\n<li><a href=\"http://siliconforks.com/jscoverage/\" rel=\"nofollow noreferrer\">JSCoverage</a></li>\n<li><a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a></li>\n</ul>\n" }, { "answer_id": 98475, "author": "Kris Gray", "author_id": 1302167, "author_profile": "https://Stackoverflow.com/users/1302167", "pm_score": 5, "selected": true, "text": "<p>I've done some TDD with Javascript in the past, and what I had to do was make the distinction between Unit and Integration tests. Selenium will test your overall site, with the output from the server, its post backs, ajax calls, all of that. But for unit testing, none of that is important.</p>\n\n<p>What you want is just the UI you are going to be interacting with, and your script. The tool you'll use for this is basically <a href=\"https://github.com/pivotal/jsunit\" rel=\"nofollow noreferrer\">JsUnit</a>, which takes an HTML document, with some Javascript functions on the page and executes them in the context of the page. So what you'll be doing is including the Stubbed out HTML on the page with your functions. From there,you can test the interaction of your script with the UI components in the isolated unit of the mocked HTML, your script, and your tests.</p>\n\n<p>That may be a bit confusing so lets see if we can do a little test. Lets to some TDD to assume that after a component is loaded, a list of elements is colored based on the content of the LI. </p>\n\n<p><strong>tests.html</strong></p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script src=\"jsunit.js\"&gt;&lt;/script&gt;\n&lt;script src=\"mootools.js\"&gt;&lt;/script&gt;\n&lt;script src=\"yourcontrol.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;ul id=\"mockList\"&gt;\n &lt;li&gt;red&lt;/li&gt;\n &lt;li&gt;green&lt;/li&gt;\n &lt;/ul&gt; \n&lt;/body&gt;\n&lt;script&gt;\n function testListColor() {\n assertNotEqual( $$(\"#mockList li\")[0].getStyle(\"background-color\", \"red\") );\n\n var colorInst = new ColorCtrl( \"mockList\" );\n\n assertEqual( $$(\"#mockList li\")[0].getStyle(\"background-color\", \"red\") );\n }\n&lt;/script&gt;\n\n\n&lt;/html&gt;\n</code></pre>\n\n<p>Obviously TDD is a multi-step process, so for our control, we'll need multiple examples. </p>\n\n<p><strong>yourcontrol.js (step1)</strong></p>\n\n<pre><code>function ColorCtrl( id ) {\n /* Fail! */ \n}\n</code></pre>\n\n<p><strong>yourcontrol.js (step2)</strong></p>\n\n<pre><code>function ColorCtrl( id ) {\n $$(\"#mockList li\").forEach(function(item, index) {\n item.setStyle(\"backgrond-color\", item.getText());\n });\n /* Success! */\n}\n</code></pre>\n\n<p>You can probably see the pain point here, you have to keep your mock HTML here on the page in sync with the structure of what your server controls will be. But it does get you a nice system for TDD'ing with JavaScript.</p>\n" }, { "answer_id": 330469, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 2, "selected": false, "text": "<p>See also: <a href=\"https://stackoverflow.com/questions/300855/looking-for-a-better-unit-test-tool-for-javascript\">JavaScript unit test tools for TDD</a></p>\n" }, { "answer_id": 778556, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "<p>I've found the <a href=\"http://en.wikipedia.org/wiki/Model_View_Presenter\" rel=\"nofollow noreferrer\">MVP</a> architecture to be very suitable for writing testable UIs. Your <strong>Presenter</strong> and <strong>Model</strong> classes can simply be 100% unit tested. You only have to worry about the <strong>View</strong> (which should be a dumb, thin layer only that fires events to the Presenter) for UI testing (with Selenium etc.)</p>\n\n<p>Note that in the I'm talking about using MVP entirely in the UI context, without necessarily crossing to the server-side. Your UI can have its own Presenter and Model that lives entirely on the client-side. The Presenter drives the UI interaction/validation etc. logic while the Model keeps state information and provides a portal to the backend (where you can have a separate Model).</p>\n\n<p>You should also take a look at the <a href=\"http://www.atomicobject.com/pages/Presenter+First\" rel=\"nofollow noreferrer\">Presenter First</a> TDD technique.</p>\n" }, { "answer_id": 14914524, "author": "davidjnelson", "author_id": 217406, "author_profile": "https://Stackoverflow.com/users/217406", "pm_score": 0, "selected": false, "text": "<p>What I do is to poke the Dom to see if I'm getting what I expect. A great side effect of this is that in making your tests fast, you also make your app fast.</p>\n\n<p>I just released an open source toolkit which will help with JavaScript tdd immensely. It is a composition of many open source tools which gives you a working requirejs backbone app out of the box.</p>\n\n<p>It provides single commands to run: dev web server, jasmine single browser test runner, jasmine js-test-driver multi browser test runner, and concatenization/minification for JavaScript and CSS. It also outputs an unminified version of your app for production debugging, precompiles your handlebar templates, and supports internationalization.</p>\n\n<p>No setup is required. It just works.</p>\n\n<p><a href=\"http://github.com/davidjnelson/agilejs\" rel=\"nofollow\">http://github.com/davidjnelson/agilejs</a></p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18146/" ]
I've had a lot of trouble trying to come up with the best way to properly follow TDD principles while developing UI in JavaScript. What's the best way to go about this? Is it best to separate the visual from the functional? Do you develop the visual elements first, and then write tests and then code for functionality?
I've done some TDD with Javascript in the past, and what I had to do was make the distinction between Unit and Integration tests. Selenium will test your overall site, with the output from the server, its post backs, ajax calls, all of that. But for unit testing, none of that is important. What you want is just the UI you are going to be interacting with, and your script. The tool you'll use for this is basically [JsUnit](https://github.com/pivotal/jsunit), which takes an HTML document, with some Javascript functions on the page and executes them in the context of the page. So what you'll be doing is including the Stubbed out HTML on the page with your functions. From there,you can test the interaction of your script with the UI components in the isolated unit of the mocked HTML, your script, and your tests. That may be a bit confusing so lets see if we can do a little test. Lets to some TDD to assume that after a component is loaded, a list of elements is colored based on the content of the LI. **tests.html** ``` <html> <head> <script src="jsunit.js"></script> <script src="mootools.js"></script> <script src="yourcontrol.js"></script> </head> <body> <ul id="mockList"> <li>red</li> <li>green</li> </ul> </body> <script> function testListColor() { assertNotEqual( $$("#mockList li")[0].getStyle("background-color", "red") ); var colorInst = new ColorCtrl( "mockList" ); assertEqual( $$("#mockList li")[0].getStyle("background-color", "red") ); } </script> </html> ``` Obviously TDD is a multi-step process, so for our control, we'll need multiple examples. **yourcontrol.js (step1)** ``` function ColorCtrl( id ) { /* Fail! */ } ``` **yourcontrol.js (step2)** ``` function ColorCtrl( id ) { $$("#mockList li").forEach(function(item, index) { item.setStyle("backgrond-color", item.getText()); }); /* Success! */ } ``` You can probably see the pain point here, you have to keep your mock HTML here on the page in sync with the structure of what your server controls will be. But it does get you a nice system for TDD'ing with JavaScript.
96,107
<p>I'm working with an mpeg stream that uses a IBBP... GOP sequence. The <code>(DTS,PTS)</code> values returned for the first 4 AVPackets are as follows: <code>I=(0,3) B=(1,1) B=(2,2) P=(3,6)</code></p> <p>The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero.</p> <p>Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then?</p>
[ { "answer_id": 96939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Ok, scratch my previous confused reply.</p>\n\n<p>For a IBBPBBI movie, you'd expect the PTSes to look like this (in decoding order)</p>\n\n<pre><code>0, 3, 1, 2, 6, 4, 5, ...\n</code></pre>\n\n<p>corresponding to the frames</p>\n\n<pre><code>I, P, B, B, I, B, B, ...\n</code></pre>\n\n<p>So you appear to be missing an I at the start of your sequence but otherwise the timestamps look correct.</p>\n" }, { "answer_id": 104883, "author": "hobb0001", "author_id": 18156, "author_profile": "https://Stackoverflow.com/users/18156", "pm_score": 4, "selected": false, "text": "<p>I think I finally figured out what's going on based on a comment made in <a href=\"http://www.dranger.com/ffmpeg/tutorial05.html\" rel=\"noreferrer\">http://www.dranger.com/ffmpeg/tutorial05.html</a>:</p>\n\n<blockquote>\n <p>ffmpeg reorders the packets so that the DTS of the packet being processed by avcodec_decode_video() will <em>always be the same</em> as the PTS of the frame it returns</p>\n</blockquote>\n\n<p>Translation: If I feed a packet into avcodec_decode_video() that has a PTS of 12, avcodec_decode_video() will not return the decoded frame contained in that packet until I feed it a <em>later</em> packet that has a DTS of 12. If the packet's PTS is the same as its DTS, then the packet given is the same as the frame returned. If the packet's PTS is 2 frames later than its DTS, then avcodec_decode_video() will delay the frame and not return it until I provide 2 more packets. </p>\n\n<p>Based on this behavior, I'm guessing that av_read_frame() is maybe reordering the packets from IPBB to IBBP so that avcodec_decode_video() only has to buffer the P frames for 3 frames instead of 5. For example, the difference between the input and the output of the P frame with this ordering is 3 (6 - 3):</p>\n\n<pre><code>| I B B P B B P\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n</code></pre>\n\n<p>vs. a difference of 5 with the standard ordering (6 - 1):</p>\n\n<pre><code>| I P B B P B B\n| DTS: 0 1 2 3 4 5 6\n| decode() result: I B B P\n</code></pre>\n\n<p>&lt;shrug/> but that is pure conjecture.</p>\n" }, { "answer_id": 108466, "author": "Jere.Jones", "author_id": 19476, "author_profile": "https://Stackoverflow.com/users/19476", "pm_score": 0, "selected": false, "text": "<p>I'm fairly certain you are getting accurate values. It might help if you thing of an MPEG stream as, well, a stream. In that case, prior to the IBBPBB that you see there would normally be another GOP. Maybe something like this (using same notation as original question):</p>\n\n<pre><code>P(-3,-2) B(-2,-1) B(-1,0)\n</code></pre>\n\n<p>Basically the B frames after the I frames are based on the I frame and the last P frame from the <strong>previous</strong> GOP.</p>\n\n<p>While it makes logical sense for a video to start off with this:</p>\n\n<pre><code>Start GOP: IPBBPBBPBB...\n</code></pre>\n\n<p>Later on it must be</p>\n\n<pre><code>Start GOP: IBBPBBPBBPBB\nStart GOP: IBBPBBPBBPBB\nStart GOP: IBB... \n</code></pre>\n\n<p>Remember that decoding any B frame requires a complete frame before it and after it. So each pair of B frames should be displayed before the I or P frame just prior to it in the file.</p>\n\n<p>FFMPEG may just have forgone the \"special case\" of first GOP.</p>\n\n<p>Since the first two B frames don't have a prior frame to manipulate, you should be able to safely discard them. Just rebase your timestamps off of the first I frame and adjust the audio stream the same amount.</p>\n\n<p>Whether this will actually result in a loss of frames will depend on FFMPEG's implementation, but worse case scenario is that you lose 83 milliseconds (2 frames at 24 frames/sec).</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18156/" ]
I'm working with an mpeg stream that uses a IBBP... GOP sequence. The `(DTS,PTS)` values returned for the first 4 AVPackets are as follows: `I=(0,3) B=(1,1) B=(2,2) P=(3,6)` The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero. Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then?
I think I finally figured out what's going on based on a comment made in <http://www.dranger.com/ffmpeg/tutorial05.html>: > > ffmpeg reorders the packets so that the DTS of the packet being processed by avcodec\_decode\_video() will *always be the same* as the PTS of the frame it returns > > > Translation: If I feed a packet into avcodec\_decode\_video() that has a PTS of 12, avcodec\_decode\_video() will not return the decoded frame contained in that packet until I feed it a *later* packet that has a DTS of 12. If the packet's PTS is the same as its DTS, then the packet given is the same as the frame returned. If the packet's PTS is 2 frames later than its DTS, then avcodec\_decode\_video() will delay the frame and not return it until I provide 2 more packets. Based on this behavior, I'm guessing that av\_read\_frame() is maybe reordering the packets from IPBB to IBBP so that avcodec\_decode\_video() only has to buffer the P frames for 3 frames instead of 5. For example, the difference between the input and the output of the P frame with this ordering is 3 (6 - 3): ``` | I B B P B B P | DTS: 0 1 2 3 4 5 6 | decode() result: I B B P ``` vs. a difference of 5 with the standard ordering (6 - 1): ``` | I P B B P B B | DTS: 0 1 2 3 4 5 6 | decode() result: I B B P ``` <shrug/> but that is pure conjecture.
96,113
<p>I got a call from a tester about a machine that was failing our software. When I examined the problem machine, I quickly realized the problem was fairly low level: Inbound network traffic works fine. Basic outbound command like ping and ssh are working fine, but anything involving the <code>connect()</code> call is failing with "No route to host".</p> <p>For example - on <strong>this particular machine</strong> this program will fail on the <code>connect()</code> statement for any IP address other than <code>127.0.0.1</code>:</p> <pre><code>#!/usr/bin/perl -w use strict; use Socket; my ($remote,$port, $iaddr, $paddr, $proto, $line); $remote = shift || 'localhost'; $port = shift || 2345; # random port if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') } die "No port" unless $port; $iaddr = inet_aton($remote) || die "no host: $remote"; $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!"; connect(SOCK, $paddr) || die "connect: $!"; while (defined($line = &lt;SOCK&gt;)) { print $line; } close (SOCK) || die "close: $!"; exit; </code></pre> <p>Any suggestions about where this machine is broken? It's running SUSE-10.2.</p>
[ { "answer_id": 96158, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 1, "selected": false, "text": "<p>Is the firewall turned off?</p>\n" }, { "answer_id": 96163, "author": "axk", "author_id": 578, "author_profile": "https://Stackoverflow.com/users/578", "pm_score": 3, "selected": true, "text": "<p>I would check firewall configuration on that machine. It is possible for iptables (I guess your SUSE has iptables firewall) to be setup to let trough only ping ICMP packets.</p>\n" }, { "answer_id": 96380, "author": "Florian", "author_id": 2984, "author_profile": "https://Stackoverflow.com/users/2984", "pm_score": 0, "selected": false, "text": "<p>Firewall is always possible, but it does say that ssh can connect, so that seems unlikely.\nI'd say have a look at the routes (\"route\" command on Linux), and make sure you don't have like two default routes, or weird ones or whatever. All in all I'd say test ping and ssh and your program on the same distant IP, and if they all fail, you have a route problem. If only your program fails, you probably have either a firewall problem or program problem :) </p>\n" }, { "answer_id": 96674, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 0, "selected": false, "text": "<p>Try pointing connect() to the same host:port where your SSH command works. Also, keep in mind that some firewalls can apply different rules for different user accounts (and sometimes for different executables). Therefore, make sure you run ssh and your test app under the same user account and that SUID isn't set for SSH.</p>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565/" ]
I got a call from a tester about a machine that was failing our software. When I examined the problem machine, I quickly realized the problem was fairly low level: Inbound network traffic works fine. Basic outbound command like ping and ssh are working fine, but anything involving the `connect()` call is failing with "No route to host". For example - on **this particular machine** this program will fail on the `connect()` statement for any IP address other than `127.0.0.1`: ``` #!/usr/bin/perl -w use strict; use Socket; my ($remote,$port, $iaddr, $paddr, $proto, $line); $remote = shift || 'localhost'; $port = shift || 2345; # random port if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') } die "No port" unless $port; $iaddr = inet_aton($remote) || die "no host: $remote"; $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!"; connect(SOCK, $paddr) || die "connect: $!"; while (defined($line = <SOCK>)) { print $line; } close (SOCK) || die "close: $!"; exit; ``` Any suggestions about where this machine is broken? It's running SUSE-10.2.
I would check firewall configuration on that machine. It is possible for iptables (I guess your SUSE has iptables firewall) to be setup to let trough only ping ICMP packets.
96,114
<p>I'm currently modifying a Java script in Rational Functional Tester and I'm trying to tell RFT to wait for an object with a specified set of properties to appear. Specifically, I want to wait until a table with X number of rows appear. The only way I have been able to do it so far is to add a verification point that just verifies that the table has X number of rows, but I have not been able to utilize the wait for object type of VP, so this seems a little bit hacky. Is there a better way to do this?</p> <p>Jeff</p>
[ { "answer_id": 164822, "author": "Tom E", "author_id": 9267, "author_profile": "https://Stackoverflow.com/users/9267", "pm_score": 2, "selected": false, "text": "<p>No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty(\"rowCount\", x);</p>\n\n<p>Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method.</p>\n\n<p>The <code>find()</code> codesample below assumes that <code>doc</code> is an html document. Adjust this to be your parent java window.</p>\n\n<pre><code>TestObject[] tables = doc.find(atDescendant(\".rowCount\", x), false);\n</code></pre>\n\n<p>If you are not familiar with <code>find()</code>, do a search in the RFT API reference in the help menu. <code>find()</code> will be your best friend in RFT scripting.</p>\n" }, { "answer_id": 784820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can do one thing.... you can try getting the particular property and check that you are getting the desired value of that. If not then iterate in a IF loop.</p>\n\n<pre><code>while (!flag) {\n if (obj.getproperty(\".text\").equals(\"Desired Text\")) {\n flag = true\n }\n}\n</code></pre>\n" }, { "answer_id": 1659476, "author": "Rational ", "author_id": 200744, "author_profile": "https://Stackoverflow.com/users/200744", "pm_score": 0, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>getobject.gettext();\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17601/" ]
I'm currently modifying a Java script in Rational Functional Tester and I'm trying to tell RFT to wait for an object with a specified set of properties to appear. Specifically, I want to wait until a table with X number of rows appear. The only way I have been able to do it so far is to add a verification point that just verifies that the table has X number of rows, but I have not been able to utilize the wait for object type of VP, so this seems a little bit hacky. Is there a better way to do this? Jeff
No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty("rowCount", x); Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method. The `find()` codesample below assumes that `doc` is an html document. Adjust this to be your parent java window. ``` TestObject[] tables = doc.find(atDescendant(".rowCount", x), false); ``` If you are not familiar with `find()`, do a search in the RFT API reference in the help menu. `find()` will be your best friend in RFT scripting.
96,123
<pre><code>Shell ("explorer.exe www.google.com") </code></pre> <p>is how I'm currently opening my products ad page after successful install. However I think it would look much nicer if I could do it more like Avira does, or even a popup where there are no address bar links etc. Doing this via an inbrowser link is easy enough</p> <pre><code>&lt;a href="http://page.com" onClick="javascript:window.open('http://page.com','windows','width=650,height=350,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no'); return false")"&gt;Link text&lt;/a&gt; </code></pre> <p>But how would I go about adding this functionality in VB?</p>
[ { "answer_id": 164822, "author": "Tom E", "author_id": 9267, "author_profile": "https://Stackoverflow.com/users/9267", "pm_score": 2, "selected": false, "text": "<p>No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty(\"rowCount\", x);</p>\n\n<p>Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method.</p>\n\n<p>The <code>find()</code> codesample below assumes that <code>doc</code> is an html document. Adjust this to be your parent java window.</p>\n\n<pre><code>TestObject[] tables = doc.find(atDescendant(\".rowCount\", x), false);\n</code></pre>\n\n<p>If you are not familiar with <code>find()</code>, do a search in the RFT API reference in the help menu. <code>find()</code> will be your best friend in RFT scripting.</p>\n" }, { "answer_id": 784820, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can do one thing.... you can try getting the particular property and check that you are getting the desired value of that. If not then iterate in a IF loop.</p>\n\n<pre><code>while (!flag) {\n if (obj.getproperty(\".text\").equals(\"Desired Text\")) {\n flag = true\n }\n}\n</code></pre>\n" }, { "answer_id": 1659476, "author": "Rational ", "author_id": 200744, "author_profile": "https://Stackoverflow.com/users/200744", "pm_score": 0, "selected": false, "text": "<p>You can use:</p>\n\n<pre><code>getobject.gettext();\n</code></pre>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/96123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` Shell ("explorer.exe www.google.com") ``` is how I'm currently opening my products ad page after successful install. However I think it would look much nicer if I could do it more like Avira does, or even a popup where there are no address bar links etc. Doing this via an inbrowser link is easy enough ``` <a href="http://page.com" onClick="javascript:window.open('http://page.com','windows','width=650,height=350,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no'); return false")">Link text</a> ``` But how would I go about adding this functionality in VB?
No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty("rowCount", x); Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method. The `find()` codesample below assumes that `doc` is an html document. Adjust this to be your parent java window. ``` TestObject[] tables = doc.find(atDescendant(".rowCount", x), false); ``` If you are not familiar with `find()`, do a search in the RFT API reference in the help menu. `find()` will be your best friend in RFT scripting.