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 tha...
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...
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": ...
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 tim...
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 \\*...
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 ow...
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 Syst...
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 serializ...
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\ntr...
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": "kc...
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 ...
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></p...
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></p...
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 conte...
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 ...
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....
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 o...
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)....
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> v...
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;john.doe@johnmail.com&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...
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">john.doe@johnmail.com</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 i...
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 Th...
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><...
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":...
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 \norde...
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 ...
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"...
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 diffe...
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 ...
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 ...
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 Mit...
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. ...
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...
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 hid...
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 dire...
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...
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 proc...
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 SQ...
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 v...
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...
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...
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>...
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_updateTe...
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-li...
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", ...
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\nS...
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...
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@domain.org:/home/directory:/bin/bash user2:x:1148:5002:User Two,Department2,email2@gmail.com,:/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...
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@domain.org:/home/directory:/bin/bash user2:x:1148:5002:User Two,Department2,email2@gmail.com,:/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...
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:=\"_TotalL...
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:=\"_TotalL...
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 \"uni...
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://e...
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, ...
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-...
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>\...
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 Ena...
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\" proble...
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...
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></p...
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 easie...
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 li...
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" }, ...
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 w...
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 ...
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 ab...
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 noreferr...
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 noreferr...
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" }, { "answe...
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>depend...
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 prop...
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, b...
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 wha...
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 c...
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": 96...
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:\\\\\"...
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 ar...
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...
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" }, {...
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 concep...
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" ...
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 ...
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 Get...
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'...
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 ...
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\...
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<pr...
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" }, {...
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 in...
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.IsAss...
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, "auth...
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...
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 langua...
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, b...
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" }, { ...
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...
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...
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_p...
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.waitForPro...
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.waitForPro...
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.