input
stringlengths
51
42.3k
output
stringlengths
18
55k
Cannot execute program if using boost (C++) libraries in debug-version on WinXP <p>I'm using boost for several C++ projects. I recently made a upgrade (1.33.1 to 1.36, soon to 1.37), since then I cannot run any debug-builds anymore.</p> <p>To be sure that no other project issues remain, I've created a minimum test-project, which only includes boost.thread, and uses it to start one method. The release build can be started, the debug build cannot, although the <em>Dependency Walker</em> shows that all required libraries are found (this also means that the required MS Debug CRT is found in the SxS directory).</p> <p>On startup I only get:</p> <blockquote> <p>Die Anwendung konnte nicht richtig initialisiert werden (0xc0150002). Klicken Sie auf "OK", um die Anwendung zu beenden.</p> </blockquote> <p>Which means nothing more than "failed to initialize app". An internet research primarily lead to <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B822520&amp;x=16&amp;y=11" rel="nofollow">an MS Office installation problem</a>, which recommends to perform a repair of WinXP.</p> <p>So, beside the repair setup (which I think will not help as I'm talking about debug-dll issues), any ideas?</p> <p>Ah, before I forget: Absolutely the same source-code leads to no errors on the build-machine (i.e., DLLs can be registered, means executed). So it's obviously an installation problem, but as the DLLs <em>are</em> there, and dependency-walker finds it, what else have I forgotten?</p> <p>(<strong>edit</strong>) Well, I have not yet resolved my problem, but thanks to deemok I'm a step further. For the sake of reducing misunderstandings I give some clarifications below:</p> <ul> <li>The program fails to run on the <em>developer</em>-machine</li> <li>I am working with an <em>installed</em> VS2005 (it's a VC++8 project)</li> <li>I used the boost-setup from <a href="http://www.boostpro.com/products/free" rel="nofollow">BoostPro</a>, compiled all possible build-versions, and I double-checked that they are there (otherwise I'd already get linker-errors during build).</li> <li>and I double-checked any corner of include/lib/bin configuration I can think of -- as boost uses auto-linking on windows, with a special naming convention, the build or start-up would have failed, with a much more comprehensible error-message.</li> <li>I <em>cannot</em> use <em>static linking</em>, as boost.thread requires dynamic linking for DLL projects (I maybe could mess around here, but as this problem seems to happen only on my machine, I do not want to mess with this, as I'm sure the boost-guys had a reason to place that check in there in the first place)</li> <li>As I wrote, I checked with Dependency Walker, and it says everything is just fine.</li> </ul> <p>Currently it seems to be an error in the boost-dll (maybe incorrect Manifest), will check that.</p>
<p>It's a <a href="http://blogs.msdn.com/rchiodo/archive/2007/04/09/the-next-level-of-dll-hell-sxs.aspx" rel="nofollow">Side-by-Side</a> (SxS) issue – simply copying the DLLs is not enough anymore.</p> <p>Regarding your specific problem concerning the Debug build, see: <a href="http://stackoverflow.com/questions/264385/running-vc2008-debug-builds-on-non-dev-machines">http://stackoverflow.com/questions/264385/running-vc2008-debug-builds-on-non-dev-machines</a></p> <p>Short answer:</p> <blockquote> <p>You can't, because there's no installer redist for the debug runtime (and in fact the software license forbids distributing it, so you'd be breaking the EULA even if you did get something put together). </p> </blockquote> <p>So, you'll need to install Visual Studio there. </p> <p>However, if you still want to try without taking that path, you could read <a href="http://stackoverflow.com/questions/264385/running-vc2008-debug-builds-on-non-dev-machines#264406">puetzk's answer</a> in its entirety.</p> <p>Or, you could try to <a href="http://stackoverflow.com/questions/264385/running-vc2008-debug-builds-on-non-dev-machines#264461">link everything statically</a>.</p>
Why are primes important in cryptography? <p>One thing that always strikes me as a non-cryptographer: Why is it so important to use Prime numbers? What makes them so special in cryptography?</p> <p>Does anyone have a <em>simple</em> short explanation? (I am aware that there are many primers and that Applied Cryptography is the Bible, but as said: I am not looking to implement my own cryptographic algorithm, and the stuff that I found just made my brain explode - no 10 pages of math formulas please :))</p> <p><strong>Thanks</strong> for all the answers. I've accepted the one that made the actual concept most clear to me.</p>
<p>Most basic and general explanation: cryptography is all about <a href="http://en.wikipedia.org/wiki/Number_theory">number theory</a>, and all integer numbers (except 0 and 1) are made up of primes, so you deal with primes a lot in number theory.</p> <p>More specifically, some important cryptographic algorithms such as <a href="http://en.wikipedia.org/wiki/RSA">RSA</a> critically depend on the fact that <a href="http://en.wikipedia.org/wiki/Integer_factorization">prime factorization</a> of large numbers takes a long time. Basically you have a "public key" consisting of a product of two large primes used to encrypt a message, and a "secret key" consisting of those two primes used to decrypt the message. You can make the public key public, and everyone can use it to encrypt messages to you, but only you know the prime factors and can decrypt the messages. Everyone else would have to factor the number, which takes too long to be practical, given the current state of the art of number theory.</p>
C# - Modifying a Data Table <p>I have a Data Table that is filled from a database connection. I would like to run checks on the Data Table like replacing the numbers with text and add my own data before binding it to the Data Grid for viewing. How do I access one piece of data in the Data Table? Thanks.</p>
<p>Just look in the table's <code>.Rows</code> collection, and access fields in each row using normal array ( <code>[]</code> ) notation using either column index or field name for the subscript.</p>
Make the C preprocessor ignore certain #include directives <p>I use a parser generator here, that unfortunately insists on putting a</p> <pre><code>#include &lt;some/file.h&gt; </code></pre> <p>at the top of every generated source file. The header has since long been renamed. While it is no problem forcing the compiler (gcc) to use the new header with <code>-include new/header.h</code>, removing the above directive from every generated file complicates the build-process.</p> <p>Is there a way to tell gcc to simply ignore <code>some/file.h</code>?</p>
<p>Replace <code>some/file.h</code> with an empty file.</p>
locale-independent way of getting standard windows registry security object <p>Is there a way to get the built-in "Everyone" registry security object in a locale-independent manner? I want to make a RegistryAccessRule without needing to translate "Everyone" to each language.</p>
<p>Use the constructor for SecurityIdentifier that takes a WellKnownSidType and use WellKnownSidType.WorldSid.</p>
Server-side Push in Rails <p>I'd like to implement a scalable chatroom in rails using AJAX. I know from research that the only scalability happens with a server-side push.</p> <p>My two questions are:</p> <p>1) In a reasonably efficient chat server, at what point does polling become prohibitive? 2) I really don't want to use Juggernaut. I don't know much about how comet works. I guess I'm wondering if this would be horribly difficult for me to build using Javascript (to create a client side server/poller) and another language (to provide efficient polling for clients behind a firewall, and an integration into the CGI). and 3) (yes, out of 2), whether I'm even going about it the right way?</p> <p>The simplest answer I could hope for is a quantified "yes, you put 5 lines of Javascript into the client and 20 lines of ruby into a CGI script, and call it a day".</p>
<p>I'm attempting to do the same right now. Juggernaut works well, but not for Rails 3, and if that isn't a requirement then I suggest using it, because it is dead easy to make a chat. My project uses Rails 3, and polls the server every 3 seconds(Campfire does 3 as well). I'm using Rails Metal to make the polling super fast. If you want to use Juggernaut, then great, 2 lines of client side js, and 1 or 2 of server side. Otherwise, get to work!</p>
Detect version of Java using JavaScript <p>Is there a reliable way of detecting what version of Java is installed on the client's machine using JavaScript?</p>
<p>Check out the code in the <a href="http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html#deplToolkit" rel="nofollow">Java Deployment Toolkit</a>.</p>
How do I create a strong password string in C++? <p>Would like to create a strong password in C++. Any suggestions?</p> <ul> <li><p>I assume it should use alpha (upper and lower), numeric, special characters.</p></li> <li><p>It would be good to be able to specify a minimum length.</p></li> <li><p>It would be great to avoid characters that are hard to visually distinguish like "O" and "O"</p></li> <li><p>It would be great to void all characters same, dictionary words, reversed words, names.</p></li> </ul> <p>Any other tips? Where could I find code like this?</p>
<p>There's a few ways. The easy isn't necessarily the best</p> <p>Create a string representing all the characters you want to define (meaning, no O's or 0s's, whatever), then fill a random-length string with random characters from that set.</p> <p>The next step is to keep generating until you pass all assertions. That is, check for dictionary words, reverse names, etc.</p> <p>There will be times where generation takes longer than expected, but should still be faster than you can notice.</p>
Implementing a "LazyProperty" class - is this a good idea? <p>I often find myself writing a property that is evaluated lazily. Something like:</p> <pre><code>if (backingField == null) backingField = SomeOperation(); return backingField; </code></pre> <p>It is not much code, but it does get repeated a lot if you have a lot of properties.</p> <p>I am thinking about defining a class called LazyProperty:</p> <pre><code>public class LazyProperty&lt;T&gt; { private readonly Func&lt;T&gt; getter; public LazyProperty(Func&lt;T&gt; getter) { this.getter = getter; } private bool loaded = false; private T propertyValue; public T Value { get { if (!loaded) { propertyValue = getter(); loaded = true; } return propertyValue; } } public static implicit operator T(LazyProperty&lt;T&gt; rhs) { return rhs.Value; } } </code></pre> <p>This would enable me to initialize a field like this:</p> <pre><code>first = new LazyProperty&lt;HeavyObject&gt;(() =&gt; new HeavyObject { MyProperty = Value }); </code></pre> <p>And then the body of the property could be reduced to:</p> <pre><code>public HeavyObject First { get { return first; } } </code></pre> <p>This would be used by most of the company, since it would go into a common class library shared by most of our products.</p> <p>I cannot decide whether this is a good idea or not. I think the solutions has some pros, like: </p> <ul><li>Less code</li> <li>Prettier code</li> </ul> <p>On the downside, it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class. </p> <p>What do you think ? Is this a good idea or should I abandon it ? Also, is the implicit operator a good idea, or would you prefer to use the Value property explicitly if you should be using this class ? </p> <p>Opinions and suggestions are welcomed :-)</p>
<p>Just to be overly pedantic: </p> <p>Your proposed solution to avoid repeating code:</p> <pre><code>private LazyProperty&lt;HeavyObject&gt; first = new LazyProperty&lt;HeavyObject&gt;(() =&gt; new HeavyObject { MyProperty = Value }); public HeavyObject First { get { return first; } } </code></pre> <p>Is actually more characters than the code that you did not want to repeat:</p> <pre><code>private HeavyObject first; public HeavyObject First { get { if (first == null) first = new HeavyObject { MyProperty = Value }; return first; } } </code></pre> <p>Apart from that, I think that the implicit cast made the code very hard to understand. I would not have guessed that a method that simply returns first, actually end up creating a HeavyObject. I would at least have dropped the implicit conversion and returned first.Value from the property.</p>
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x) <p>Is there any reason to prefer <code>unicode(somestring, 'utf8')</code> as opposed to <code>somestring.decode('utf8')</code>?</p> <p>My only thought is that <code>.decode()</code> is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.</p>
<p>It's easy to benchmark it:</p> <pre><code>&gt;&gt;&gt; from timeit import Timer &gt;&gt;&gt; ts = Timer("s.decode('utf-8')", "s = 'ééé'") &gt;&gt;&gt; ts.timeit() 8.9185450077056885 &gt;&gt;&gt; tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'") &gt;&gt;&gt; tu.timeit() 2.7656929492950439 &gt;&gt;&gt; </code></pre> <p>Obviously, <code>unicode()</code> is faster.</p> <p>FWIW, I don't know where you get the impression that methods would be faster - it's quite the contrary.</p>
How can Windows API calls to an application/service be monitored? <p>My company is looking at implementing a new VPN solution, but require that the connection be maintained programatically by our software. The VPN solution consists of a background service that seems to manage the physical connection and a command line/GUI utilty that initiates the request to connect/disconnect. I am looking for a way to "spy" on the API calls between the front-end utilty and back-end service so that our software can make the same calls to the service. Are there any recommended software solutions or methods to do this?</p>
<p>Typically, communications between a front-end application and back-end service are done through some form of IPC (sockets, named pipes, etc.) or through custom messages sent through the Service Control Manager. You'll probably need to find out which method this solution uses, and work from there - though if it's encrypted communication over a socket, this could be difficult.</p>
Reflection runtime performance - Java vs CLR <p>A related post <a href="http://stackoverflow.com/questions/435553/java-reflection-performance">here</a> pretty much established reflection in Java as a performance hog. Does that apply to the CLR as well? (C#, VB.NET, etc). </p> <p><strong><em>EDIT</em></strong>: How does the CLR compare to Java when it comes to reflection? Was that ever benchmarked?</p>
<p>I wouldn't really care about the instantiation performance of the object using reflection itself but the actual performance of methods and such since those are after all what I'll be using from the class anyway.</p> <p>Surely the instantiation takes a lot of time as can be seen in the linked post but since you're most likely using the object's methods instead of just instantiating it, you shouldn't worry too much about reflection performance - as long as you're not doing the method calls by invoking reflected <code>Method</code> objects!</p> <p>Besides you only need one reflected instance of the object, use <code>.clone()</code> and other clever tricks if you need to create more copies.</p>
Java sort String array of file names by their extension <p>I have an array of filenames and need to sort that array by the extensions of the filename. Is there an easy way to do this?</p>
<pre><code>Arrays.sort(filenames, new Comparator&lt;String&gt;() { @Override public int compare(String s1, String s2) { // the +1 is to avoid including the '.' in the extension and to avoid exceptions // EDIT: // We first need to make sure that either both files or neither file // has an extension (otherwise we'll end up comparing the extension of one // to the start of the other, or else throwing an exception) final int s1Dot = s1.lastIndexOf('.'); final int s2Dot = s2.lastIndexOf('.'); if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither s1 = s1.substring(s1Dot + 1); s2 = s2.substring(s2Dot + 1); return s1.compareTo(s2); } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first return -1; } else { // only s1 has an extension, so s1 goes second return 1; } } }); </code></pre> <p>For completeness: <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html"><code>java.util.Arrays</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html"><code>java.util.Comparator</code></a>.</p>
Silverlight Button Click Event <p>I have a silverlight page with a textblock and button on it. Like this:</p> <pre><code>&lt;TextBlock x:Name="txbNote" Margin="50,50" Text="Hello"/&gt; &lt;Button x:Name="btnCheck" Height="40" Click="btnCheck_Click" ClickMode="Press" Margin="50,50,50,50" Content="Check Service"/&gt; </code></pre> <p>Here is the handler for the click event:</p> <pre><code>Private Sub btnCheck_Click(ByVal sender As Object, ByVal e As EventArgs) 'Handles btnCheck.Click txbNote.Text = "I Was Clicked" End Sub </code></pre> <p>It works... but... Why doesn't this work?</p> <pre><code>&lt;Button x:Name="btnCheck" Height="40" Click="btnCheck_Click" ClickMode="Press" Margin="50,50,50,50" Content="Check Service"/&gt; &lt;TextBlock x:Name="txbNote" Margin="50,50" Text="Hello"/&gt; </code></pre> <p>The only change is the relative position of the textblock and button. The button's click event (and every other event I tried) just doesn't fire unless the textblock is before the button in the xaml.</p>
<p>You may need to post more code as this could be an issue with the surrounding tags, such as the container that these controls are in.</p> <p>If you're unable to paste it all to StackOverflow, use <a href="http://www.dpaste.com" rel="nofollow">www.dpaste.com</a> or <a href="http://www.pastebin.com" rel="nofollow">www.pastebin.com</a>.</p>
How do I build project files and packages for Borland C++ Builder 5 from the command line? <p>How do I build Borland C++ project files (bpr) and package files (bpk) from the command line? Project groups (bpg) are apparently make files and can be compile with make. But bpks and bprs are xml based and the Export to Makefile won't compile with make. If I put a project in a bpg, make can't seem to find any of the files specified in the bpg since they all appear to be relative references. I changed the references to absolutes and make reports: Fatal: Unable to open makefile</p>
<p>You don't need to directly compile a bpr. Just create a bpk which just includes that single bpr, and you can use make to compile it.</p> <pre><code>"c:\program files\borland\cbuilder5\bin\make" -B -s -fabc.bpg </code></pre> <p>If you also have other borland compilers installed, do not call the make.exe from the other compiler. </p> <p>EDIT: execute the make command in the directory where the bpg and bpr is located.</p>
How do I detect if jQuery is in a document navigated to in the WinForm WebBrowser control? <p>I have a Windows Forms application in C#/Visual Studio 2008 with an IE WebBrowser control. In the DocumentCompleted event, I want to search the WebBrowser.Document or WebBrowser.DomDocument to see if jQuery is already present in the page.</p> <p>What's a good way to accomplish this?</p> <p>Thanks!</p>
<p>Did you try:</p> <pre><code>bool hasjQuery = webBrowser1.Document.InvokeScript("jQuery") != null; </code></pre>
Flash Video Players: Do people really use the volume control? <p>Im wondering if anyone has any input on this subject? Im building a flash video player, and I have added a mute volume icon, but Im wondering what everyone's thoughts are on adding a volume control too?</p>
<p>I consider a volume control to be an absolute requirement. Your idea of "normal levels" may be drastically different than mine. Besides, you may want to hear some of the moaning and squealing without sharing it with everyone else in your cube farm.</p>
How can i remove the sidebar in movable type? <p>im building a new side with movable type. And i want to remove the sidebar for a few pages, but not for all the pages.</p> <p>Any idea?</p> <p>Thanks.</p>
<p>In the archive template -> page </p> <p><code>&lt;mt:Var name="hide_sidebar" value="1"&gt;</code></p> <p>Thanks</p>
Quick way to change a property on many forms in a Delphi project? <p>I thought there was something in GExperts to do this, but I can't see it if there is.</p> <p>I have to change the SCALED property (from the default of TRUE to FALSE) in each form in a project that contains about 100 different forms. Because the default value of SCALED is TRUE, it doesn't actually appear as a line in the .DFM file (when viewing as text), so there isn't anything I can 'get' at with GREP (etc).</p> <p>Can anyone suggest a quick way of setting this property in all these forms? The forms are subclasses of various different classes and I really don't want to do make some kind of intermediate TForm descendant which overrides the SCALED property - partly because I tried (briefly) to do this and discovered that setting the SCALED property to be false <em>after</em> the inherited create made no difference to the form, and setting it <em>before</em> the inherited create caused an exception. :-)</p> <p>Anyone got any suggestions? I really want to avoid opening all those forms one by one if I can help it, if only because I'm bound to miss one!</p>
<p>I would recommend changing all your forms to descend from a common ancestor. Then in the future you can just change the base class and it will fix it everywhere. </p> <p>Generally I prefer to always use a custom descendant class over a stock one that I will be using frequently for this specific reason. </p>
Downloading files using Adobe AIR <p>When I download a file using URLStream and write to a file using FileStream, where else do the file gets cached? It definitely gets cached somewhere, as the second time I try to download the same file, it comes down like a lighting..</p>
<p>AIR is using the operating systems networking stack for this, so the cache location will depend on where the OS caches files.</p> <p>On Windows, check the Internet Explorer settings, on Mac check Safari. Im not sure about Linux.</p> <p>mike chambers</p>
Why am I getting 'System.__ComObject' from my LDAP property? <p>I'll be the first to admit that this is cut and past programming. I've never looked at AD before, and really don't understand it. I suppose that's my next study...</p> <p>Anyways, This is some test code, which should display the expiry date -- either as something readable, or in ticks -- it doesn't matter. (It's a web form, which is running on the dev webserver.)</p> <p>What I get instead is: "System.__ComObject "</p> <pre><code>DirectorySearcher searcher = new DirectorySearcher(); searcher.Filter = String.Format( "(SAMAccountName={0})", "TestA33" ); searcher.PropertiesToLoad.Add( "cn" ); SearchResult result = searcher.FindOne(); DirectoryEntry uEntry = result.GetDirectoryEntry(); String expiry = uEntry.Properties["accountExpires"].Value.ToString(); Response.Write( expiry ); </code></pre>
<p>It's because the property value is represented using the ADSI IADsLargeInteger COM interface and needs to be converted to a .NET date. Although I haven't tried it, there is a sample that shows how here: <a href="http://www.simple-talk.com/dotnet/.net-framework/building-active-directory-wrappers-in-.net/">http://www.simple-talk.com/dotnet/.net-framework/building-active-directory-wrappers-in-.net/</a></p>
Using "with" statement for CSV files in Python <p>Is it possible to use the <code>with</code> statement directly with CSV files? It seems natural to be able to do something like this:</p> <pre><code>import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader </code></pre> <p>But csv.reader doesn't provide the <code>__enter__</code> and <code>__exit__</code> methods, so this doesn't work. I can however do it in two steps:</p> <pre><code>import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader </code></pre> <p>Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?</p>
<p>The primary use of <code>with</code> statement is an exception-safe cleanup of an object used in the statement. <code>with</code> makes sure that files are closed, locks are released, contexts are restored, etc.</p> <p>Does <a href="http://docs.python.org/library/csv.html#csv.reader">csv.reader</a> have things to cleanup in case of exception?</p> <p>I'd go with:</p> <pre><code>with open("myfile.csv") as f: for row in csv.reader(f): # process row </code></pre> <p>You don't need to submit the patch to use <code>csv.reader</code> and <code>with</code> statement together.</p> <pre><code>import contextlib </code></pre> <p>Help on function contextmanager in module <a href="http://docs.python.org/library/contextlib.html">contextlib</a>:</p> <pre><code>contextmanager(func) @contextmanager decorator. </code></pre> <p>Typical usage:</p> <pre><code> @contextmanager def some_generator(&lt;arguments&gt;): &lt;setup&gt; try: yield &lt;value&gt; finally: &lt;cleanup&gt; </code></pre> <p>This makes this:</p> <pre><code> with some_generator(&lt;arguments&gt;) as &lt;variable&gt;: &lt;body&gt; </code></pre> <p>equivalent to this:</p> <pre><code> &lt;setup&gt; try: &lt;variable&gt; = &lt;value&gt; &lt;body&gt; finally: &lt;cleanup&gt; </code></pre> <p>Here's a concrete example how I've used it: <a href="http://stackoverflow.com/questions/327026/attribute-bold-doesnt-seem-to-work-in-my-curses#327072">curses_screen</a>.</p>
JavaBeans alternatives? <p>I hate the JavaBeans pattern with a passion that burns like the fire of a thousand suns. Why?</p> <ul> <li><strong>Verbose</strong>. It's 2009. I shouldn't have to write 7 LOC for a property. If they have event listeners then hold on to your hat.</li> <li><strong>No type-safe references</strong>. There is no type-safe way to reference a property. The whole point of Java is that it is type safe, and its most popular pattern is not at all typesafe.</li> </ul> <p>What I would like is something like:</p> <pre><code>class Customer { public Property&lt;String&gt; name = new Property(); } </code></pre> <p>I am a web developer mostly, so it needs JPA and Wicket support.</p> <p>Help me off the javabean train!</p>
<p>I think you're pretty close with the declaration you have there (see below for a sketch). However, by using a non-beans approach, you'll probably lose support provided by most tools that assume the JavaBeans protocol is in effect. Please be kind. The code below is off the top of my head...</p> <pre><code>public class Property&lt;T&gt; { public final String name; T value; private final PropertyChangeSupport support; public static &lt;T&gt; Property&lt;T&gt; newInstance(String name, T value, PropertyChangeSupport support) { return new Property&lt;T&gt;(name, value, support); } public static &lt;T&gt; Property&lt;T&gt; newInstance(String name, T value) { return newInstance(name, value, null); } public Property(String name, T value, PropertyChangeSupport support) { this.name = name; this.value = value; this.support = support; } public T getValue() { return value; } public void setValue(T value) { T old = this.value; this.value = value; if(support != null) support.firePropertyChange(name, old, this.value); } public String toString() { return value.toString(); } } </code></pre> <p>and then go ahead and use it:</p> <pre><code>public class Customer { private final PropertyChangeSupport support = new PropertyChangeSupport(); public final Property&lt;String&gt; name = Property.newInstance("name", "", support); public final Property&lt;Integer&gt; age = Property.newInstance("age", 0, support); ... declare add/remove listenener ... } Customer c = new Customer(); c.name.setValue("Hyrum"); c.age.setValue(49); System.out.println("%s : %s", c.name, c.age); </code></pre> <p>So, now declaring a property is a single line of code and property change support is included. I called the methods setValue() and getValue() so it would still look like a bean to code like Rhino and stuff, but for succinctness, you could add just get() and set(). The rest is left as an exercise for the reader:</p> <ul> <li>Properly handle serialization</li> <li>Handle null value checking</li> <li>Maybe add a specializations for atomic types if you care about autoboxing overhead.</li> <li>?? I'm sure there are more gotchas</li> </ul> <p>Also note that you can subclass (usually as an anonymous class) and override setValue() to provide additional parameter checking. </p> <p>I don't think you can really get away from "String references" since that's pretty much what reflection's all about.</p> <p>Sadly though, in this day and age, this is still kind of like programming in assembly... Groovy, C#, etc, etc may still be a better choice, if you have a choice.</p>
Unable to parse a DateTime <p>I'm trying to parse a date/time string using <code>DateTime.ParseExact</code>. It works everywhere, except on one machine - it just will not parse on that machine. The question is: Why? What could be different on that machine so that it will cause this behaviour?</p> <p>Here are some things that I've already looked at:</p> <ul> <li>The <code>CultureInfo</code> is passed to <code>DateTime.ParseExact</code>, namely <code>CultureInfo.InvariantCulture</code></li> <li>The regional settings on the rogue machine is the same as the settings on a machine where the parsing works.</li> <li>Yes, the string is in the correct format, which is <code>dd/MM/yyyy HH:mm:ss</code></li> </ul>
<p>I always find that regional settings can be tricky, and you can never assume that the users of your application will even have their machines setup correctly in the first place!</p> <p>A catch-all that I've been using to parse dates in if they have to be strings is to parse it in the "dd/MMM/yyyy" format, e.g. "14/JAN/2009" will translate nicely no matter what the settings are.</p> <p>Incidentally this trick also works with SQL Server as well :)</p>
Is a URL which uses a Rewrite URL still searchable by search engines? <p>My developer did the following:</p> <p>If someone types public.sample.com/user/chumbawumba it redirects to stage.sample.com/profile.php?username=chumbawumba</p> <p>I want to make sure that the content of the profile -- which contains company information for example, is searchable on the public.sample.com domain name.</p> <p>He used a Rewrite Rule. </p> <p>I guess I wasn't anticipating this approach, but as long as the pages can get spidered and ranked as more information is put in, I'm cool with it.</p> <p>I tried to run an online sitemap on the site and I don't think it came up with anything, thus my question. Thanks.</p>
<p>You could go to google and type "site: public.sample.com" to see all pages searched with google on your site. Also see <a href="https://www.google.com/webmasters/tools/" rel="nofollow">Google Webmaster tools</a>.</p> <p>Please tell is the rule redirets or rewrites request? So could you see in your browser "stage.sample.com/profile.php?username=chumbawumba" or "public.sample.com/user/chumbawumba".</p> <p>If all you could see is "public.sample.com/user/chumbawumba" - that is OK. If not - same will be seen with search bot.</p>
Seeking Example Delphi Prism ASP.Net Application using SQL Server <p>I'm an ASP.NET virgin and want to try creating an ASP.Net Application using SQL Server at the back end.</p> <p>I can't locate a single example application or code for doing this. Anyone have any pointers?</p> <p>TIA</p>
<p>Delphi Prism is just the language and connecting to a SQL database is exactly the same way you would do so C#. I would look for a C# example on doing so and convert the syntax to Delphi (very easy to do). If you plan on using Delphi Prism you will spend a lot of time converting C# syntax examples to Delphi so you should get some practice.</p>
About Memory Management in Java and C++ <p>Well, I've been given an assignment to basically figure out how memory allocation works for whatever language I'll be using. After some research, I have some questions and doubts which I'd like to get some insight in. For example:</p> <p>I read <a href="http://en.citizendium.org/wiki/Stack_frame" rel="nofollow">here</a> that Java specifies exactly how the stack contents are organized. Looking at the <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#17257" rel="nofollow">JVM spec structure</a>, it basically says the stack contains frames, and that the frames contain whatever is inside the class by properly allocating the variables and functions. Maybe I am missing something here, but I don't understand how this is any different than what C++ does. I ask because the first link says Java's specification of stack contents avoid compiler incompatibilities.</p> <p>Also, I have yet to find how the memory segments are exactly organized on top of each other. For example, I know the memory is divided into global variables, call stack, heap and code for C++, yet I don't know if the heap's address is higher than the stack's, or if that depends on the implementation. I also wonder whether a Java program has more than that, and how it would be laid out as well. I imagine there is a standard, since the JVM has to know where it all is to use it, though I suppose it could just have the pointers and leave the rest to the OS. I imagine too, that there must be at least a de facto standard.</p> <p>Another the thing I don't understand is the runtime constant pool. It's supposed to be "a per-class or per-interface runtime representation of the constant_pool table in a class file", but I don't think I understand what it does. It seems to have a tag to indicate what type the structure in question is? Then the name of the structure (given by the programmer or assigned by the underlying system?) Then it seems the rest of it varies with whatever the tag describes (a thread, an array, etc).</p> <p>If my interpretation of the runtime constant pool is right, then why are they necessary as well as stack frames? Is it because stack frames only take care of the stack segments, and the runtime constant pool must also have pointers for the heap allocated memory?</p>
<blockquote> <p>Looking at the JVM spec structure, it basically says the stack contains frames, and that the frames contain whatever is inside the class by properly allocating the variables and functions. Maybe I am missing something here, but I don't understand how this is any different than what C++ does. I ask because the first link says Java's specification of stack contents avoid compiler incompatibilities.</p> </blockquote> <p>In practice, C++ compilers follow the same basic strategy. However it's not considered a language issue by the Standards committee. Instead, C++ compilers follow this system because that's how most CPUs and operating systems are designed. The different platforms disagree on whether data is passed to functions on a stack or via registers (RISC machines), whether the stack grows up or down, whether there are different calling conventions allowing "normal" calls to use the stack and others to use somethign else (eg., <a href="http://msdn.microsoft.com/en-us/library/6xa169sk.aspx" rel="nofollow">__fastcall</a> and <a href="http://msdn.microsoft.com/en-us/library/5ekezyy2.aspx" rel="nofollow">naked</a>), whether there is such as thing as <a href="http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html" rel="nofollow">nested functions</a>, <a href="http://home.in.tum.de/~baueran/thesis/" rel="nofollow">tail call support</a>, etc.</p> <p>In fact, it is possible for a conforming C++ compiler to compile to something like a Scheme VM where "the stack" is much different because Scheme requires implementations to support both tail calls and continuations. I've never seen anything like that, but it would be legal.</p> <p><a href="http://blog.mozilla.com/jorendorff/2007/08/09/conservative-stack-scanning-101/" rel="nofollow">The "compiler incompatibilities" are most obvious if you try to write a garbage collector</a>:</p> <blockquote> <p>all local variables, both for the current function and all its callers, are in ["the" stack, but consider <a href="http://www.opengroup.org/onlinepubs/007908775/xsh/ucontext.h.html" rel="nofollow">ucontext.h</a> and <a href="http://msdn.microsoft.com/en-us/library/ms682661%28VS.85%29.aspx" rel="nofollow">Windows Fibers</a>]. For each platform (meaning, OS + CPU + compiler) there's a way to find out where ["the" stack] is. Tamarin does that, then it scans all that memory during GC to see where the locals point to. ...</p> <p>This magic lives in a macro, MMGC_GET_STACK_EXTENTS, defined in the header MMgc/GC.h. ... [T]here’s a separate implementation for each platform.</p> <p>At any given moment, some locals might be in CPU registers and not on the stack. To cope with this, the macro uses a few lines of assembly code to dump the contents of all the registers onto the stack. That way MMgc can just scan the stack and it’ll see all local variables.</p> </blockquote> <p><hr /></p> <p>Additionally, <em>objects</em> in Java aren't normally allocated on the stack. Instead references to them are. ints, doubles, booleans, and other primitive types do get allocated on the stack. In C++ anything can be allocated on the stack, which has its own list of pros and cons.</p> <blockquote> <p>Another the thing I don't understand is the runtime constant pool. It's supposed to be "a per-class or per-interface runtime representation of the constant_pool table in a class file", but I don't think I understand what it does.</p> </blockquote> <p>Consider:</p> <pre><code>String s = "Hello World"; int i = "Hello World".length(); int j = 5; </code></pre> <p>s, i, and j are all variables and can each be changed at some later point in the program. However, "Hello World" is an object of type String that cannot be changed, 5 is an int that cannot be changed, and "Hello World".length() can be determined at compile-time to always return 11. These constants are valid objects, and methods can be called on them (well, at least on the String) so they need to be allocated somewhere. But they cannot be changed, ever. If these constants belong to a class, then they are allocated in a per-class constant pool. Other constant data that is not part of a class (like the ID of the main() thread) is allocated in the per-runtime constant pool ("runtime" in this case meaning "instance of the JVM").</p> <p>The C++ standard has some language about a similar technique, but the implementation is left up to the binary format (ELF, a.out, COFF, PE, etc.). The Standard expects constants that are integral data types (bool, int, long, etc.) or c-style strings to be actually kept in a constant part of the binary, while other constant data (doubles, floats, classes) might be stored as a variable along with a flag saying that the "variable" is not modifiable (it's also acceptable to store them with integral and c-style string constants, but many binary formats don't make this an option).</p> <p>Generally speaking, the "constant data section" of a binary can be shared when more than one copy of a program is open at a time (because constant data will be identical in each copy of the program). <a href="http://wiki.osdev.org/ELF" rel="nofollow">On ELF this section is called the .rodata section</a>.</p>
How much time it saves code generators? <p>My question seems easy but is little more theoretical than it looks. There are Code Generation software or application building software that gets done without the use of a programming language. Application like VE Server and VE Designer from <a href="http://www.intelliun.com/" rel="nofollow">Intelliun</a> should accomplish this task. My question is, in reality have someone out there track the amount of real savings of this kind of tool versus having a development team and a source code evolutionary process.</p> <p>For the specific example of VE Designer the application gets done from the designer and you don't see code for it, you just run the app in VE Server. All code looks like XML Internal commands.</p>
<p>It depends on how we measure that time.</p> <p>If you compare two control groups - one that types in all the code by hand, and another that uses the code generator - I have no doubt at all that the group that uses the code generator will require less time, hands down. It depends on how far you want to go with the generator, of course, but there's little doubt that as the percentage of generated code goes up that the manual input looks worse and worse.</p> <p>The only concern I have has to do with where that code generator comes from and how much thought went into its design.</p> <p>If you don't want to touch the code that the wizard/code generator produces because you don't understand it, it ought to be counted against the code generator.</p> <p>If the code generator forces you into a bad design, it ought to be counted against the code generator.</p> <p>If the code generator spits out so many classes that nobody can follow what's happening, it ought to be counted against the code generator.</p> <p>If the code generator makes your maintenance life a hell on earth, it ought to be counted against the code generator.</p> <p>I like the idea of understanding and creating my own tools if I can. Wizards that are given by others can cause problems. The accounting for or against them ought to reflect the problems.</p>
Why does C# limit the set of types that can be declared as const? <p>Compiler error <a href="http://msdn.microsoft.com/en-us/library/ms228656(VS.80).aspx">CS0283</a> indicates that only the basic POD types (as well as strings, enums, and null references) can be declared as <code>const</code>. Does anyone have a theory on the rationale for this limitation? For instance, it would be nice to be able to declare const values of other types, such as IntPtr.</p> <p>I believe that the concept of <code>const</code> is actually syntactic sugar in C#, and that it just replaces any uses of the name with the literal value. For instance, given the following declaration, any reference to Foo would be replaced with "foo" at compile time.</p> <pre><code>const string Foo = "foo"; </code></pre> <p>This would rule out any mutable types, so maybe they chose this limitation rather than having to determine at compile time whether a given type is mutable?</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/aa645749(VS.71%29.aspx" rel="nofollow">C# specification, chapter 10.4 - Constants</a>:<br> <em>(10.4 in the C# 3.0 specification, 10.3 in the online version for 2.0)</em></p> <blockquote> <p>A constant is a class member that represents a constant value: a value that can be computed at compile time.</p> </blockquote> <p>This basically says that you can only use expressions that consists solely of literals. Any calls to any methods, constructors (that cannot be represented as pure IL literals) cannot be used, as there is no way for the compiler to do that execution, and thus compute the results, at compile time. Also, since there is no way to tag a method as invariant (ie. there is a one-to-one mapping between input and output), the only way for the compiler to do this would be to either analyze the IL to see if it depends on things other than the input parameters, special-case handle some types (like IntPtr), or just disallow every call to any code.</p> <p>IntPtr, as an example, though being a value type, is still a structure, and not one of the built-in literals. As such, any expression using an IntPtr will need to call code in the IntPtr structure, and this is what is not legal for a constant declaration.</p> <p>The only legal constant value type example I can think of would be one that is initialized with zeroes by just declaring it, and that's hardly useful.</p> <p>As for how the compiler treats/uses constants, it will use the computed value in place of the constant name in the code.</p> <p>Thus, you have the following effect:</p> <ul> <li>No reference to the original constant name, class it was declared in, or namespace, is compiled into the code in this location</li> <li>If you decompile the code, it will have magic numbers in it, simply because the original "reference" to the constant is, as mentioned above, not present, only the value of the constant</li> <li>The compiler can use this to optimize, or even remove, unnecessary code. For instance, <code>if (SomeClass.Version == 1)</code>, when SomeClass.Version has the value of 1, will in fact remove the if-statement, and keep the block of code being executed. If the value of the constant is not 1, then the whole if-statement and its block will be removed.</li> <li>Since the value of a constant is compiled into the code, and not a reference to the constant, using constants from other assemblies will not automagically update the compiled code in any way if the value of the constant should change (which it should not!)</li> </ul> <p>In other words, with the following scenario:</p> <ol> <li>Assembly A, contains a constant named "Version", having a value of 1</li> <li>Assembly B, contains an expression that analyzes the version number of assembly A from that constant and compares it to 1, to make sure it can work with the assembly</li> <li>Someone modifies assembly A, increasing the value of the constant to 2, and rebuilds A (but not B)</li> </ol> <p>In this case, assembly B, in its compiled form, will still compare the value of 1 to 1, because when B was compiled, the constant had the value 1.</p> <p>In fact, if that is the only usage of anything from assembly A in assembly B, assembly B will be compiled without a dependency on assembly A. Executing the code containing that expression in assembly B will not load assembly A.</p> <p>Constants should thus only be used for things that will never change. If it is a value that might or will change some time in the future, and you cannot guarantee that all other assemblies are rebuilt simultaneously, a readonly field is more appropriate than a constant.</p> <p>So this is ok:</p> <ul> <li>public const Int32 NumberOfDaysInAWeekInGregorianCalendar = 7;</li> <li>public const Int32 NumberOfHoursInADayOnEarth = 24;</li> </ul> <p>while this is not:</p> <ul> <li>public const Int32 AgeOfProgrammer = 25;</li> <li>public const String NameOfLastProgrammerThatModifiedAssembly = "Joe Programmer";</li> </ul> <hr> <p><strong>Edit May 27th 2016</strong></p> <p>OK, just got an upvote, so I re-read my answer here and this is actually slightly wrong.</p> <p>Now, the <em>intention</em> of the C# language specification is everything I wrote above. You're not supposed to use something that cannot be represented with a literal as a <code>const</code>.</p> <p>But can you? Well, yes....</p> <p>Let's take a look at the <code>decimal</code> type.</p> <pre><code>public class Test { public const decimal Value = 10.123M; } </code></pre> <p>Let's look at what this class looks like <em>really</em> when looked at with ildasm:</p> <pre><code>.field public static initonly valuetype [mscorlib]System.Decimal X .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(int8, uint8, uint32, uint32, uint32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 64 00 00 00 00 00 ) </code></pre> <p>Let me break it down for you:</p> <pre><code>.field public static initonly </code></pre> <p>corresponds to:</p> <pre><code>public static readonly </code></pre> <p>That's right, a <code>const decimal</code> is actually a <code>readonly decimal</code>.</p> <p>The real deal here is that the compiler will use that <code>DecimalConstantAttribute</code> to work its magic.</p> <p>Now, this is the only such magic I know of with the C# compiler but I thought it was worth mentioning.</p>
Is there an easy way to Spellcheck with TinyMCE in .NET <p>Is there any way to use TinyMCE in .NET and use the spellchecker without installing PHP as well?</p>
<p>You can always use <a href="http://www.loresoft.com/Applications/NetSpell/default.aspx" rel="nofollow">Netspell</a> spellchecker for .NET. We use it in conjunction with TinyMCE. It works well.</p>
Write a number with two decimal places SQL server <p>How do you write a number with two decimal places for sql server?</p>
<p>try this</p> <pre><code>SELECT CONVERT(DECIMAL(10,2),YOURCOLUMN) </code></pre>
How can I retrieve an assembly's qualified type name? <p>How can I generate a assembly qualified type name?</p> <p>For an example, when configuring a membership provider, I would have to provide a assembly qualified type name for "SqlMembershipProvider" (in this example, i have copied the below configuration from somewhere) in "type" attribute.</p> <p>How do you generate that assembly qualified type name? Does it have to be typed manually everytime by examining an assembly type?</p> <blockquote> <pre><code>&lt;membership&gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="LocalSqlServer"/&gt; &lt;/providers&gt; &lt;/membership&gt; </code></pre> </blockquote> <p><strong><em>[UPDATE]</em></strong>: <a href="http://stackoverflow.com/questions/622902/powershell-tips-tricks-for-net-developers/622976#622976">Simpler PowerShell version</a></p> <pre><code>PS&gt;([System.String]).AssemblyQualifiedName System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 </code></pre>
<p>This is a nice <a href="http://www.lennybacon.com/CommentView,guid,d571c376-42d0-427a-a7d0-ef9d22eab52c.aspx" rel="nofollow">handy tool</a> (shell extension with source code) for copying the fully qualified name to clipboard by right clicking on any assembly.</p> <p><strong>Update</strong>: After seeing the comment from dance2die, thought of putting together a sample powershell script to export the type name to a csv file.</p> <pre><code>&gt; [System.Reflection.Assembly]::LoadWithPartialName("System.Web") &gt; [System.Web.Security.SqlMembershipProvider] | select {$_.UnderlyingSystemType.AssemblyQualifiedName } | export-csv c:\typenames.csv </code></pre> <p>Using C#, if you want to generate the assembly qualified type name with all the references set, it is easy to build a test script using reflection..</p> <pre><code>using System; using System.Reflection; ........ Type ty = typeof(System.Web.Security.SqlMembershipProvider); string fullname = ty.AssemblyQualifiedName; //"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" </code></pre>
Django custom SQL to return QuerySet where each object has additional properties <p>Let's say I have the following objects: </p> <pre><code>squirrel_table - name - country_of_origin - id nut_table - id - squirrel_who_owns_me[fk to squirrel] </code></pre> <p>I want to retrieve a list of all squirrels in a particular country. The returned squirrel objects can be in a QuerySet, but do not need to be. A list will suffice. Each squirrel will have an additional property call nut_count. The SQL for this would be something like what follows (please note I use the subquery in order to not enumerate all of squirrel's columns, since in reality there will be many) (I use PostgreSQL):</p> <pre><code>select sq.*, nut_counts.nut_count from squirrel_table sq, (select sq2.id as squirrel_id, count(nuts) as nut_count from squirrel_table sq2, nut_table nuts where nuts.squirrel_who_owns_me = sq2.id and sq.country_of_origin = 'USA' group by sq2.id) as nut_counts where sq.id = nut_counts.squirrel_id </code></pre> <p>Is there a way to execute the SQL, take the cursor it generates, and turn it into a list of squirrel objects, and add the nut_count to each squirrel?</p>
<p>You probably want to read through <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow">the documentation for the "extra()" method</a>, which includes an example of a similar "select something else and append it onto each object" situation.</p>
How to stop Ideablade DevForce writing to C:\Program Files\AppName\debuglog.xml in Vista <p>I have an application that uses Ideablade Devforce as it's OR mapper. When the application starts up it wants to write to the debuglog.xml file in C:\Program Files\Application Name\ This works fine in Windows XP, but due to Vista's locked down write access to Program Files, the app throws and error.</p> <p>Is there a way to stop Ideablade wanting to write to this file?</p> <p>OR</p> <p>Is there another place that is recommended to install applications that want to write to files in their install path?</p>
<p>I fixed it by setting the logging file option to a blank string within the IdeaBlade.ibconfig file.</p> <p>It mentions in the help that if you don't supply a path it will save the file in the application's directory, but if you don't even supply the filename it will not save it anywhere.</p>
Equivalent? No, but why? <p>T-SQL:</p> <p>1(ANSI): <code>convert(varchar(10),@DueDate, 102) &lt; convert(varchar(10),getdate(), 102)</code></p> <p>2(USA): <code>convert(varchar(10),@DueDate, 101) &lt; convert(varchar(10),getdate(), 101)</code></p> <p>Notice that these will return different results when year is considered.</p> <p>Why?</p> <p>What's the difference? Why isn't the operator taking year into consideration when using #2?</p>
<p>What are you trying to do? You're comparing varchars, there. Look at the output from these statements:</p> <pre><code>print convert(varchar(10), getdate(), 101) print convert(varchar(10), getdate(), 102) </code></pre> <p>That prints this:</p> <pre><code>01/14/2009 2009.01.14 </code></pre> <p>Comparing the first form is only really going to be checking to see if the month of one date is less than the month of the current date.</p> <p>Is there a reason you need to convert the dates to varchar? Why not compare them directly?</p> <pre><code>@DueDate &lt; getdate() </code></pre>
Firefox and IE rendering same image differently! <p>This is an exact duplicate of: <a href="http://stackoverflow.com/questions/130161/ie6-issues-with-transparent-pngs">http://stackoverflow.com/questions/130161/ie6-issues-with-transparent-pngs</a></p> <p><hr></p> <p>Firefox:<img src="http://i377.photobucket.com/albums/oo218/prakashrajgopal/FirefoxP.jpg" alt="alt text" /></p> <p>IE 6:<img src="http://i377.photobucket.com/albums/oo218/prakashrajgopal/IEP.jpg" alt="alt text" /> The background for the image is transparent. Yet IE seems to screw it up. Any ideas?</p>
<p>IE6 does not render transparent PNGs properly. There's a javascript fix, or <a href="http://24ways.org/2007/supersleight-transparent-png-in-ie6" rel="nofollow">some such</a>, but it's easier if you just don't use PNGs.</p>
Need help handling documents using dom4j <pre><code>import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; public class Main { public static void main(String[] args){ Company cp17 = new Company(); Person ps1 = new Person("Barry","15900000000"); Person ps2 = new Person("Andy","15800000000"); cp17.employee.add(ps1); cp17.employee.add(ps2); Document document = DocumentHelper.createDocument(); Element companyElement = document.addElement("company"); for(Iterator&lt;Person&gt; personIter = cp17.employee.iterator();personIter.hasNext();){ Person nextEmployee = personIter.next(); Element employee = companyElement.addElement("employee"); employee.addAttribute("name",nextEmployee.name); employee.addAttribute("phoneNumber",nextEmployee.phoneNumber); } Document document2 = DocumentHelper.createDocument(); Element compnies = document.addElement("companies"); //move cp17 to document2 as a child of companies. //ERROR companies.add(cp17); XMLWriter xmlWriter = new XMLWriter(); try{ xmlWriter.write(document2); xmlWriter.close(); } catch(Exception e){ e.printStackTrace(); } } } </code></pre> <p>I creat two Document Object , now I want to move one Element and it's child Elements to another.How can i do that .Can anyone tell me, thank you.^_^</p>
<p>Use the standard DOM method Document.importNode to bring content from one document into another. <a href="http://www.dom4j.org/dom4j-1.6.1/apidocs/org/dom4j/dom/DOMDocument.html#importNode%28org.w3c.dom.Node,%20boolean%29" rel="nofollow">http://www.dom4j.org/dom4j-1.6.1/apidocs/org/dom4j/dom/DOMDocument.html#importNode%28org.w3c.dom.Node,%20boolean%29</a></p> <pre><code>Element companyElement2= document2.importNode(companyElement, true); companies.appendChild(companyElement2); </code></pre> <p>(Assuming that this line:</p> <pre><code>Element compnies = document.addElement("companies"); </code></pre> <p>is supposed to read:)</p> <pre><code>Element companies = document2.addElement("companies"); </code></pre>
Pre-populate an inline FormSet? <p>I'm working on an attendance entry form for a band. My idea is to have a section of the form to enter event information for a performance or rehearsal. Here's the model for the event table:</p> <pre><code>class Event(models.Model): event_id = models.AutoField(primary_key=True) date = models.DateField() event_type = models.ForeignKey(EventType) description = models.TextField() </code></pre> <p>Then I'd like to have an inline FormSet that links the band members to the event and records whether they were present, absent, or excused:</p> <pre><code>class Attendance(models.Model): attendance_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(Event) member_id = models.ForeignKey(Member) attendance_type = models.ForeignKey(AttendanceType) comment = models.TextField(blank=True) </code></pre> <p>Now, what I'd like to do is to pre-populate this inline FormSet with entries for all the current members and default them to being present (around 60 members). Unfortunately, Django <a href="http://groups.google.com/group/django-developers/browse_thread/thread/73af9e58bd7626a8">doesn't allow initial values in this case.</a></p> <p>Any suggestions?</p>
<p>So, you're not going to like the answer, partly because I'm not yet done writing the code and partly because it's a lot of work.</p> <p>What you need to do, as I discovered when I ran into this myself, is:</p> <ol> <li>Spend a lot of time reading through the formset and model-formset code to get a feel for how it all works (not helped by the fact that some of the functionality lives on the formset classes, and some of it lives in factory functions which spit them out). You will need this knowledge in the later steps.</li> <li>Write your own formset class which subclasses from <code>BaseInlineFormSet</code> and accepts <code>initial</code>. The really tricky bit here is that you <em>must</em> override <code>__init__()</code>, and you <em>must</em> make sure that it calls up to <code>BaseFormSet.__init__()</code> rather than using the direct parent or grandparent <code>__init__()</code> (since those are <code>BaseInlineFormSet</code> and <code>BaseModelFormSet</code>, respectively, and neither of them can handle initial data).</li> <li>Write your own subclass of the appropriate admin inline class (in my case it was <code>TabularInline</code>) and override its <code>get_formset</code> method to return the result of <code>inlineformset_factory()</code> using your custom formset class.</li> <li>On the actual <code>ModelAdmin</code> subclass for the model with the inline, override <code>add_view</code> and <code>change_view</code>, and replicate most of the code, but with one big change: build the initial data your formset will need, and pass it to your custom formset (which will be returned by your <code>ModelAdmin</code>'s <code>get_formsets()</code> method).</li> </ol> <p>I've had a few productive chats with Brian and Joseph about improving this for future Django releases; at the moment, the way the model formsets work just make this more trouble than it's usually worth, but with a bit of API cleanup I think it could be made extremely easy.</p>
How to manually install an artifact in Maven 2? <p>I've encountered some errors when I tried to install an artifact manually with Maven 2. I wanted to install a jar from a local directory with the command</p> <pre><code>mvn install:install-file -Dfile=jta-1.0.1B.jar </code></pre> <p>But Maven gave a build error which reads like:</p> <pre><code>Invalid task '.01B.jar': you must specify a valid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal </code></pre> <p>Is there a mistake with my command?</p>
<p>You need to indicate the groupId, the artifactId and the version for your artifact:</p> <pre><code>mvn install:install-file \ -DgroupId=javax.transaction \ -DartifactId=jta \ -Dpackaging=jar \ -Dversion=1.0.1B \ -Dfile=jta-1.0.1B.jar \ -DgeneratePom=true </code></pre>
Datagridview custom vscrollbar <p>I would like disable vertical scroll bar in datagridview and managing the scrolling using separate vscroll control. I am using c# 2.0. Any one can help....????</p>
<p>You can set DataGridView.ScrollBars property to ScrollBars.None or ScrollBars.Horizontal (to have just horizontal scrollbar). This way the vertical scrollbar will not be displayed and you can use yours</p>
CANopen PDOs and a communication profile <p>If the data contains more than one value, how do I know what these values represent? And how do I break up the data into individual values? Am I right to say that the relationship between the <a href="http://en.wikipedia.org/wiki/CANopen#Process_Data_Object_.28PDO.29_protocol" rel="nofollow">PDOs</a> and data to be transmitted are defined in the communication profile?</p> <p>(I thank Matli for having explained that the <a href="http://en.wikipedia.org/wiki/Controller_area_network" rel="nofollow">CAN</a> interface API probably has functions to retrieve the ID, data length and the data of a <a href="http://en.wikipedia.org/wiki/CANopen" rel="nofollow">CANopen</a> message. Based on the explanation, one could tell if the frame is a PDO and derive the sender node's ID from the COB-ID.)</p>
<p>The relationship between PDOs and data is defined in the PDO mapping entries in the Object Dictionary. But that is probably not the easiest way to find out.</p> <p>Since I don't know what device you are trying to communicate with, I cannot give you any information about its data output. You will have to consult the documentation for the device or ask the manufacturer. However, if you for example have a generic I/O module fully compliant with a specific Device Profile (e.g. 401 for generic I/O modules), it will probably have default mappings according to that device profile. </p> <p>I recommend that you read CiA DS 301 and also any applicable device profile. Those documents are available from <a href="http://www.can-cia.org/index.php?id=440" rel="nofollow">CiA</a></p>
mysql and check boxes <p>i have this table contains name and value, how can i convert the contents of</p> <p>$row=mysql_fetch_array($result);</p> <p>into check boxes</p>
<p>Assuming $row is an associative array mapping column name onto a boolean 1 or 0 value, you could do something like this:</p> <pre><code>foreach($row as $colname=&gt;$boolean) { //create a name for the checkbox which will produce a nice //PHP array of checked column names in $_POST['col'] $name="col[$colname]"; //create an id for the checkbox $id='col'.$colname; //now we output the checkbox - on form submission you will //see an element in $_POST['col'][$colname] if checked, and //no element at all if unchecked... echo '&lt;input type="checkbox" value="1" '. 'name="'.$name.'" id="'.$id.'" '. ($boolean?'checked="checked"':''). '&gt;'; //output a label - note we'd tied this to the id of the checkbox //which means you can click the label to tick the box echo "&lt;label for=\"$id\"&gt;colname&lt;/label&gt;&lt;br/&gt;"; } </code></pre> <p>When the form is submitted, you'll get an array in $_POST['col'] indexed by column name, but only for those boxes which are checked, so you'd set to false any columns which are not set.</p>
Why the functions doesn't execute completely? <p>When I try to debug the following function segment, the execution brakes (jumps out of the function) at line pCellTower->m_pCellTowerInfo = pCellInfo:</p> <pre><code>RILCELLTOWERINFO* pCellInfo = (RILCELLTOWERINFO*)lpData; CCellTower *pCellTower = (CCellTower*)cbData; if(pCellTower != NULL) { pCellTower-&gt;m_pCellTowerInfo = pCellInfo; } </code></pre> <p>(the pointer pCellInfo is not set)</p> <p>Then I tried to comment the line:</p> <pre><code>RILCELLTOWERINFO* pCellInfo = (RILCELLTOWERINFO*)lpData; CCellTower *pCellTower = (CCellTower*)cbData; if(pCellTower != NULL) { //pCellTower-&gt;m_pCellTowerInfo = pCellInfo; } </code></pre> <p>and this way the function executes normally.</p> <p>Does anyone know what could be wrong?</p>
<p>The most likely explanation is that pCellTower isn't set either. It could contain random bits, and end up pointing outside the memory allocated to your app. The OS cannot allow your program to write outside the space allocated to it, so it sends the program some kind of message (Windows:exception, Unix/Linux:signal) that the write was rejected.</p>
Is mixing WPF, LinqToSql and multiple threads a bad idea? <p>My situation is roughly similar to <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3227644&amp;SiteID=1" rel="nofollow">this guy</a> except that I don't need change notifications right now</p> <p>I have a WPF App displaying a hierarchy. The children for each node are retrieved using a LinqToSql query. The app works perfectly when there is one thread.</p> <p>Now I'd like to make things a bit faster.. by loading children asynchronously. Fire off a thread, to do the DB fetching, on completion create the corresponding tree nodes for the children. </p> <pre><code>&lt;HierarchicalDataTemplate DataType="{x:Type viewmodels:NodeDM}" ItemsSource="{Binding Path=Children}"&gt; </code></pre> <p>After some thrashing around yesterday, I found that WPF Data Binding allows this via an <code>IsAsync</code> property on the Binding. So I made the following change</p> <pre><code>&lt;HierarchicalDataTemplate .. ItemsSource="{Binding Path=Children, IsAsync=True}"&gt; </code></pre> <p>Now its mayhem, an initial bunch of nodes pass through the fire before exceptions run riot. Pasting the first one here...</p> <pre><code>System.Windows.Data Error: 16 : Cannot get 'Children' value (type 'ObservableCollection`1') from '' (type 'NodeDM'). BindingExpression:Path=Children; DataItem='NodeDM' (HashCode=29677729); target element is 'TreeViewItem' (Name=''); target property is 'ItemsSource' (type 'IEnumerable') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt; System.InvalidCastException: Specified cast is not valid. at System.Data.SqlClient.SqlBuffer.get_Int32() at System.Data.SqlClient.SqlBuffer.get_Value() at System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i) &lt;snipped around 20-30 lines&gt; at System.Data.Linq.Table`1.GetEnumerator() at System.Data.Linq.Table`1.System.Collections.Generic.IEnumerable&lt;TEntity&gt;.GetEnumerator() at System.Linq.Lookup`2.CreateForJoin(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer) at System.Linq.Enumerable.&lt;JoinIterator&gt;d__61`4.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at ICTemplates.Models.NodeDM.Load_Children() at ICTemplates.Models.NodeDM.get_Children() </code></pre> <p>Others include</p> <pre><code>System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first. </code></pre> <p>I have a deformed tree where some nodes have failed to load. I have a <strong>singleton instance</strong> of the almightly LinqToSql DataContext class, which talks to the DB. So I tried putting a lock so that multiple worker threads do not access it simultaneously.. but no luck.</p> <pre><code>partial class Node { public IEnumerable&lt;Segment&gt; Children { lock (MyDatabaseDataContext.m_lockObject) { return // LINQ Query to join 2 tables and return a result } } </code></pre> <p>Reverting the IsAsync change makes things all good again. Why is the IsAsync property messing up LinqToSql ? The WPF Treeview is enough to make normal people pull their hair out.</p>
<p>Your problem seems to come from using the same connection object for the reads. When you have syncronous data access one connection is usually enough if you remember to open/close between reads. Thy to change your GetChildren code to create new connections (and commands/data readers etc.) on each call so multiple threads would not step on each others toes. Also if the results are cached in memory in some structure try to syncronize access to that structure using locks. You don't want one thread to try to enumerate over your elements while another is trying to add new ones. </p>
Vim regular expression to remove all but last two digits of number <p>I have following text in a file</p> <pre><code>23456789 </code></pre> <p>When I tried to replace the above text using command </p> <pre><code>1,$s/\(\d\)\(\d\d\d\)\(\d\d\)*\&gt;/\3\g </code></pre> <p>I am getting <code>89</code>. Shouldn't it be <code>6789</code>? Can anyone tell me why it is <code>89</code>.</p>
<p>As written, your regex captures one digit, then three digits, then any number of groups of two digits each. The third match will, therefore, always be two digits if it exists. In your particular test case, the '89' is in \4, not \3.</p> <p>Changing the regex to</p> <pre><code> 1,$s/\(\d\)\(\d\d\d\)\(\d\d\+\)\&gt;/\3\g </code></pre> <p>will give you '6789' as the result, since it will capture two or more digits (up to as many as are there) in the third group.</p>
Best way to interact with Command Line application <p>I need to write a component for an application that interacts tightly with a command line application. The command line application asks a series of questions, performs some computations, then terminates (which i need to detect). Essentially, i want to wrap up this interaction in a wrapper class.</p> <p>Has any one achieved similar in the past? If so, how did you go about it? Did you notice a pattern, or maybe some good build in classes to use? Cheers!</p>
<p>You would need to redirect both the input and output streams, using <code>Process</code>; it is slightly trickier handling both, since you need to be careful that things aren't lost in the buffers (causing deadlock).</p> <ul> <li>MSDN : <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardinput.aspx">Redirecting input</a></li> <li>MSDN : <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx">Redirecting output</a></li> <li><a href="http://www.c-sharpcorner.com/UploadFile/edwinlima/SystemDiagnosticProcess12052005035444AM/SystemDiagnosticProcess.aspx">Here's</a> a basic alternative example.</li> </ul> <p>You might also want to look at <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx">OutputDataReceived</a> for event-based responses.</p>
How do I use a Perl package known only in runtime? <p>I have a Perl program, that needs to use packages (that I also write). Some of those packages are only chosen in Runtime (based on some environment variable). I don't want to put in my code a "use" line for all of those packages, of course, but only one "use" line, based on this variable, something like:</p> <pre><code>use $ENV{a}; </code></pre> <p>Unfortunately, this doesn't work, of course. Any ideas on how to do this?</p> <p>Thanks in advance, Oren</p>
<pre><code>eval "require $ENV{a}"; </code></pre> <p>"<code>use</code>" doesn't work well here because it only imports in the context of the <code>eval</code>.</p> <p>As @Manni said, actually, it's better to use require. Quoting from <code>man perlfunc</code>:</p> <pre> If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace. In other words, if you try this: require Foo::Bar; # a splendid bareword The require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the "" The require function will look for the "Foo::Bar" file in the @INC array and will complain about not finding "Foo::Bar" there. In this case you can do: eval "require $class"; </pre>
Single web server and ETags <p>Does anyone know if it is worth disabling ETags on an web application that is hosted on a single web server? Currently we don't make use of ETags in our application.</p> <p>If it is worth disabling them - why?</p> <p>Many thanks.</p>
<p>I don't know if this helps, but you can read about etags here: <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_11.html">http://developer.yahoo.net/blog/archives/2007/07/high_performanc_11.html</a></p> <p>and here is <a href="http://www.codinghorror.com/blog/archives/000932.html">what Jeff Atwood thinks</a> about ETags:</p> <blockquote> <p>ETags are a checksum field served up with each server file so the client can tell if the server resource is different from the cached version the client holds locally. Yahoo recommends turning ETags off because they cause problems on server farms due to the way they are generated with machine-specific markers. So unless you run a server farm, you should ignore this guidance. It'll only make your site perform worse because the client will have a more difficult time determining if its cache is stale or fresh. It is possible for the client to use the existing last-modified date fields to determine whether the cache is stale, but last-modified is a weak validator, whereas Entity Tag (ETag) is a strong validator. Why trade strength for weakness?</p> </blockquote> <p>also <a href="http://www.dotnetrocks.com/default.aspx?showNum=390">interview with Steve Souders</a> at .NET Rocks may help:</p> <blockquote> <p><strong>Steve Souders</strong>: ... the default implementation of IIS and Apache, they put both of those servers, put something in the e-tag that will make it very likely that if the user ever has to check the validity of that resource, the browsers are going to be incorrectly told that the resource is no longer valid. So in Apache’s case, what they put in the e-tag is the INO number of the file on that web server so that if you have more than one web servers hosting your site which most large websites do, that INO number is never going to match across two servers so if yesterday the user went to server one and today they tried to validate that resource and they go to server 2, the e-tag is not going to match, e-tag overrides last modified date so instead of just returning a 200-byte 304 response, the server has to return a 50k response of the entire image.</p> </blockquote>
How/Where to host an UDP based component? <p>I´m working on a project that basically will show some data collected from hardware devices through <strong>UDP</strong> protocol. the first idea of how to do this: implement a winService (to listen and persist the messages) and a wepApp to manage the data, based on .NET platform.</p> <p>I´m confused about if exists the possibility to rent a "windows service" hosting, to deploy the "udp listener" component. </p> <p>thanx,! Gorsh</p>
<p>A shared hosting setup will not allow you to have the permissions needed to run your service, look for a managed hosting service or a VPS on a cloud. Amazon EC2 or GoGrid currently have Microsoft Windows cloud offerings.</p>
Run script directly in 2 various browsers <p>I have created Ruby test script that use Selenium RC to test my web app directly in 2 browsers(IE, Firefox). My script runs - first on IE then continue on Firefox and then should be continued and finished in already opened IE browser. My problem is: I can't continue(reconnect) to run my script in already opened IE browser. I use:</p> <pre><code>@browser = RSpecSeleniumHelper.connect_browser("URL") </code></pre> <p>but it opens with new session (it needs to keep previous session).</p>
<p>Is there a particular reason you need to switch between browsers half way through?</p> <p>I have no idea how you'd fix the problem, but it seems like it would be best solved by running the tests in one browser at a time.</p>
Howto get filename from which class was included in PHP <p>I understand that the question is rather hard to understand, I didn't know how to ask it better, so I'll use this code example to make things more clear:<br /> If I have the following files:</p> <p>test.php:</p> <pre><code>&lt;?php include('include.php'); echo myClass::myStaticFunction(); ?&gt; </code></pre> <p>include.php</p> <pre><code>&lt;?php __autoload($classname){ include_once("class/".$classname.".php"); //normally checking of included file would happen } ?&gt; </code></pre> <p>class/myClass.php</p> <pre><code>&lt;?php class myClass{ public static function myStaticFunction(){ //I want this to return test.php, or whatever the filename is of the file that is using this class return SOMETHING; } ?&gt; </code></pre> <p>the magic FILE constant is not the correct one, it returns path/to/myClass.php</p>
<p>in case you need to get "test.php" see <code>$_SERVER['SCRIPT_NAME']</code></p>
From XML to object <p>I would like to define an asp.net page from xml, then parse/render it by calling a command name. Just like they do in Flex. Does someone has an idea how to do that?</p> <p>Like for example, from XML:</p> <pre><code>&lt;button onClick="DoJavascript()" text="Submit"/&gt; &lt;gridview ......./&gt; </code></pre> <p>To parse:</p> <pre><code>&lt;asp:button runat="server" onClick="DoJavascript()" text="Submit"/&gt; &lt;asp:gridview runat="server" ......./&gt; </code></pre>
<p>You could try XSLT, that's in general what is used to transform XML.</p>
How to do Unit Testing with Uncertainties? <p>We have several different optimization algorithms that produce a different result for each run. For example the goal of the optimization could be to find the minimum of a function, where 0 is the global minima. The optimization runs returns data like this:</p> <pre><code>[0.1, 0.1321, 0.0921, 0.012, 0.4] </code></pre> <p>Which is quite close to the global minima, so this is ok. Our first approach was to just choose a threshold, and let the unit test fail if a result occured that was too high. Unfortunately, this does not work at all: The results seem to have a gauss distribution, so, although unlikely, from time to time the test failed even when the algorithm is still fine and we just had bad luck. </p> <p>So, how can I test this properly? I think quite a bit of statistics are needed here. It is also important that tests are still fast, just letting the test run a few 100 times and then take the average will be too slow.</p> <p>Here are some further clarifications:</p> <ul> <li><p>For example I have an algorithm that fits a Circle into a set of points. It is extremly fast but does not always produce the same result. I want to write a Unit test to guarantee that in most cases it is good enough.</p></li> <li><p>Unfortunately I cannot choose a fixed seed for the random number generator, because I do not want to test if the algorithm produces the exact same result as before, but I want to test something like "With 90% certainty I get a result with 0.1 or better".</p></li> </ul>
<p>It sounds like your optimizer needs two kinds of testing: </p> <ol> <li>testing the overall effectiveness of the algorithm</li> <li>testing the integrity of your implementation of the algorithm</li> </ol> <p>Since the algorithm involves randomization, (1) is difficult to unit-test. Any test of a random process will fail some proportion of the time. You need to know some statistics to understand just how often it should fail. There are ways to trade off between how strict your test is and how often it fails.</p> <p>But there are ways to write unit tests for (2). For example, you could reset the seed to a particular value before running your unit tests. Then the output is deterministic. That would not allow you to assess the average effectiveness of the algorithm, but that's for (1). Such a test would serve as a trip wire: if someone introduced a bug into the code during maintenance, a deterministic unit test might catch the bug.</p> <p>There may be other things that could be unit tested. For example, maybe your algorithm is guaranteed to return values in a certain range no matter what happens with the randomized part. Maybe some value should always be positive, etc. </p> <p><strong>Update</strong>: I wrote a chapter about this problem in the book Beautiful Testing. See Chapter 10: <a href="http://www.johndcook.com/Beautiful_Testing_ch10.pdf" rel="nofollow">Testing a Random Number Generator</a>.</p>
Where can I find a Java to C# converter? <p>I needed to convert a Java 1.5se app to C# 2.0.</p> <p>Does anyone know of a tool (preferably free/open source) to do this?</p>
<p>Even if there is such a tool, I'd highly recommend you to do the conversion by hand. Automatic converters will often faithfully reproduce the code, but ignore idioms - because they'd be really, really hard to get right.</p> <p>Furthermore, the differences between generics in .NET and Java could lead to some very different decisions in the two codebases.</p> <p>Really, you'll be better off doing it by hand.</p>
Custom SharePoint feature in multiple scopes in document library - shows up as duplicates <p>I have a custom feature which is an Edit Control Block (ECB) action in a document library that gets deployed as a solution package (WSP). When you pull down the dropdown next to a file, you see the feature and when the ECB action is selected, the user is redirected to a custom application page.</p> <p>I allow this feature to be installed into all 4 different scopes: Farm, WebApplication, Site and Web. Each of them will be in a different solution package but share the same FeatureId, SolutionId etc. It is assumed that feature is only installed into one scope at a time. If an administrator deploys it, activates it and if we he/she wants to change the scope, deactivates it, everything works properly. If for some reason the administrator does not deactivate it first, the ECB action will have duplicate entries in the document library.</p> <p>For example, say we install it as Site scope (site collection) and later decides we want it in Farm scope instead and don't deactivate it first and instead just go to the Solution Management and retract and remove it. If we look at the site collection where it was previously available, we don't see the ECB action.</p> <p>If we then add the Farm scope solution package and deploy it, we will now see the ECB action in the site collection even though we have not deployed it and the feature.xml ActivateOnDefault attribute is set to false. If we then go ahead and activate it, we will now see two ECB actions.</p> <p>Does anyone have any ideas? I have added the feature.xml and elements.xml below.</p> <p>TIA, Magnus</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p> </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p> RegistrationType="List" RegistrationId="101"<br /> Location="EditControlBlock" Sequence="300"<br /> ImageUrl="/_layouts/images/MyFeature/MyOtherPic.gif" Title="My Feature"<br /> Description="My ECB feature" > </p>
<p>AFAIK, this behaviour is by design. You will need to add or extend a FeatureReceiver and override some of the methods, especially FeatureUninstalling where you need to deactivate your feature on every place where it is still activated.</p> <p>You could log each activation e.g. using (top level) web properties.</p> <p><a href="http://blog.tylerholmes.com/2008/03/walkthrough-creating-sharepoint-feature.html" rel="nofollow" title="Walkthrough: Creating a SharePoint Feature Receiver and Custom Link with WSS Extensions">Walkthrough: Creating a SharePoint Feature Receiver and Custom Link with WSS Extensions</a></p> <p>Good Luck!</p>
What are the major differences between C and C++ and when would you choose one over the other? <p>For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than the other. I know C++ is an "enhancement" of C, but it was created in '83 and hasn't completely replaced C so there must be something more to it.</p> <p>I know this question is subjective and I am not trying to start any religious war, so please try to be as objective as possible. Clear strengths and weaknesses and comparisons.</p>
<p>While C is a pure procedural language, C++ is a <em>multi-paradigm</em> language. It supports</p> <ul> <li>Generic programming: Allowing to write code once, and use it with different data-structures.</li> <li>Meta programming: Allowing to utilize templates to generate efficient code at compile time.</li> <li>Inspection: Allows to inspect certain properties at compile time: What type does an expression have? How many parameters does a function have? What type does each one have?</li> <li>Object oriented programming: Allowing the programmer to program object oriented, with sophisticated features such as multiple inheritance and private inheritance. </li> <li>Procedural programming: Allows the programmer to put functions free of any classes. Combined with advanced features such as ADL allows writing clean code decoupled from specifics of certain classes. </li> </ul> <p>Apart from those, C++ has largely kept compatibility with C code, but there are some differences. Those can be read about in Annex D of the C++ Standard, together with reasons and possible fixed to make C code valid C++ code. </p>
Insert row in table for each id in another table <p>I tried searching here for a similar solution but didn't see one so I was wondering what is the best way to accomplish the following.</p> <p>I have a table with 17 million + rows all have a unique ID. We have recently created a new table that will be used in conjunction with the previous table where the foreign key of the new table is the unique id of the old table.</p> <p>For ex.<br /> Table 1 - id, field1, field2, field3... table 2 - table1.id, field1 ...</p> <p>The problem is since we are migrating this into a live environment, we need to back fill table 2 with a row containing the id from table 1 for each row in table 1. ex, table 1 - 1, test, null table 2 now needs to have: 1, null, ... and so on for each row that is in table1. The main issue is that the ids are not all sequential in table 1 so we will have to read from table 1 and then insert based of the id of found into table 2.</p> <p>Is there any easier way to go about this? Thanks in advance Joe</p> <p>Also to clarify, table 2 will be new data and the only thing that it will contain from table 1 is the id to keep the foreign key relationship</p> <p>Also this is sql server 2000</p>
<p>If I understand correctly, you want one record in table2 for each record in table1. Also I believe that apart from the reference to table1, table2 should initially contain blank rows.</p> <p>So assuming</p> <pre><code>table1 (ID, field1, field2, ...) table2 (ID, table1_ID, fieldA, fieldB,...) -- where table1_ID is a reference to ID of table1 </code></pre> <p>After creating table2 you can simply run this insert statement</p> <pre><code>insert into table2(table1_ID) select ID from table1 </code></pre>
MethodInfo for EntityCollection instead of Queryable <p>I am manually creating the equivalent lambda:</p> <pre><code>var function = p =&gt; p.Child.Any(c =&gt; c.Field == "value"); </code></pre> <p>I have a MethodInfo reference to the "Any" method used with Expressions built in code.</p> <pre><code>MethodInfo method = typeof(Queryable).GetMethods() .Where(m =&gt; m.Name == "Any" &amp;&amp; m.GetParameters().Length == 2) .Single().MakeGenericMethod(typeof(Child)); </code></pre> <p>My entities are: Parent 1---* Child</p> <p>Child is a Navigation Property on Parent (p in the above lambda). The type of the property is EntityCollection as created by the designer.</p> <p>I was looking for the proper way to reference the Any method to create that call. Marc gave me the answer how to get this here: <a href="http://stackoverflow.com/questions/439172/calling-a-method-from-an-expression">http://stackoverflow.com/questions/439172/calling-a-method-from-an-expression</a></p> <p>But it doesn't work for the entity framework. EntityCollection does not implement IQueryable, so how should the Any method be referenced.</p>
<p><code>EntityCollection&lt;T&gt;</code> doesn't implement <code>IQueryable&lt;T&gt;</code> so it's not surprising that this doesn't work, IMO.</p> <p>Could you give more explanation of what you're trying to do? If you're expecting the query to be run on the database, my guess is that it's really not going to support that (given that <code>EntityCollection&lt;T&gt;</code> doesn't implement <code>IQueryable&lt;T&gt;</code>). If you want the query to be run locally, you should use Enumerable.Any instead of Queryably.Any.</p> <p>EDIT: Having seen the updated collection, I believe you just want Enumerable.Any instead of Queryable.Any. Don't forget that if this is being provided as an expression tree, you won't actually be <em>executing</em> that code anyway. Presumably the framework understands Enumerable.Any as applied to an <code>EntityCollection&lt;T&gt;</code></p>
Conversion between different units of measurement in SQL (in Access) <p>I'm trying to program an access database but I'm using SQL for all my querying. I've got the database almost complete but I have one query that has me stumped. It is a database which contains recipes. I have a table in which I have all the conversions for cooking (Tablespoon to Teaspoon, Teaspoon to Cup, etc.). The user needs to be able to put in an ingredient using whatever units the recipe calls for (in other words, I cannot standardize the units, I have to find what they are). Then I need to be able to convert these into a standardized unit. This is where I'm having the problem because things like vegetables can come in cups, tablespoons, etc. whereas things like meats come in ounces, pounds, etc. I want to avoid creating a bunch of vb if/then's. I feel like there must be a way to do this with SQL but I can't seem to figure it out.</p>
<p>I would think about this differently. You have different types of measures (volume, weight, count, etc.). Each of those measures has different, convertible units. Choosing a measure (ounces, for example), choose both a measure type and a particular unit. I'd have a way of converting between units of the same measure type -- to support resizing recipes -- but I wouldn't worry about converting between different measure types.</p> <p>Once you know the type, you can store all values in the database in terms of a base unit for that measure type. Based on the value, and perhaps user preference, you can translate that to a suitable display unit when you show it. I don't think this would be particularly easy to do in SQL and I wouldn't be afraid of doing the conversion in code. You simply need to have a different display formatter for each measure type that chooses the appropriate unit and does the conversion.</p>
How to provoke a timer trigger in glassfish? <p>We need some consistency in our functional test cases. The best we can do currently is to wait for an estimated time before the Java EE timers in the product should have been triggered. It would be much more predictable if the test cases could trigger the timers programmatically, probably with JMX.</p> <p>How can this be done? Is there a JMX interface to the Glassfish Timer facility which we can use?</p>
<p>Its apparently impossible, since the question remain unanswered for almost three months.</p> <p>However, I realized that for testing purposes it is enough to be notified when the triggering has actually occured. (Triggering it actively will only buy me time at the trade for quality)</p> <p>I'm adding monitoring for event completions instead, but thanks for letting me know that it's actually impossible;)</p>
Creating a specific XML document using namespaces in C# <p>We were given a sample document, and need to be able to reproduce the structure of the document exactly for a vendor. However, I'm a little lost with how C# handles namespaces. Here's a sample of the document:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Doc1 xmlns="http://www.sample.com/file" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sample.com/file/long/path.xsd"&gt; &lt;header&gt; &lt;stuff&gt;data&lt;/stuff&gt; &lt;morestuff&gt;data&lt;/morestuff&gt; &lt;/header&gt; &lt;/Doc1&gt; </code></pre> <p>How I'd usually go about this is to load a blank document, and then start populating it:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.LoadXml("&lt;Doc1&gt;&lt;/Doc1&gt;"); // Add nodes here with insert, etc... </code></pre> <p>Once I get the document started, how do I get the namespace and schema into the Doc1 element? If I start with the namespace and schema in the Doc1 element by including them in the LoadXml(), then <em>all</em> of the child elements have the namespace on them -- and that's a no-no. The document is rejected.</p> <p>So in other words, I have to produce it EXACTLY as shown. (And I'd rather not just write text-to-a-file in C# and hope it's valid XML).</p>
<p>You should try it that way</p> <pre><code> XmlDocument doc = new XmlDocument(); XmlSchema schema = new XmlSchema(); schema.Namespaces.Add("xmlns", "http://www.sample.com/file"); doc.Schemas.Add(schema); </code></pre> <p>Do not forget to include the following namespaces:</p> <pre><code>using System.Xml.Schema; using System.Xml; </code></pre>
Is there a way to name columns in an INSERT statement? <p>When I do SELECT statements in PHP code I always select named columns, like:</p> <pre><code>SELECT id, name from users; </code></pre> <p>rather than using:</p> <pre><code>SELECT * from users; </code></pre> <p>This has the advantage of being more informative and readable, and also avoids problems later if new columns are added to the table.</p> <p>What I'm wondering is, is it possible to use the same idea in an INSERT statement? I'm imagining it might be something like this:</p> <pre><code>INSERT into people values (id=1, name="Fred"); </code></pre> <p>The syntax as I've shown in this example doesn't work, but I wonder if something equivalent is possible? If not, does anyone know why not? Is it a deliberate omission?</p>
<pre><code>INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) INSERT INTO people (id, name) VALUES (1, 'Fred'); </code></pre>
Is it impossible to perform initialization before calling a superclass's constructor? <p>I'd like for a subclass of a certain superclass with certain constructor parameters to load an XML file containing information that I'd then like to pass to the superconstructor. Is this impossible to achieve?</p>
<p>How about using a factory method instead? Maybe something like:</p> <pre><code>private MyObject(ComplexData data) { super(data); } public static MyObject createMyObject(String someParameter) { ComplexData data = XMLParser.createData(someParameter); return new MyObject(data); } </code></pre>
How can I get greasemonkey to call a function on a page after it loads <p>I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work</p> <pre><code>window.setTimeout(function() { alert('test') // This alert works, but nothing after it does myFunction() // undefined window.myFunction() // undefined document.myFunction() // undefined }, 1000); </code></pre>
<p>Try using: unsafeWindow.myFunction();</p> <p>More details and info - <a href="http://wiki.greasespot.net/UnsafeWindow">http://wiki.greasespot.net/UnsafeWindow</a></p>
Are incrementers / decrementers (var++, var--) etc thread safe? <p>Inspired by this question: <a href="http://stackoverflow.com/questions/443423/in-complexity-analysis-why-is-considered-to-be-2-operations">http://stackoverflow.com/questions/443423/in-complexity-analysis-why-is-considered-to-be-2-operations</a></p> <p>Take the following psuedo code:</p> <pre><code>class test { int _counter; void Increment() { _counter++; } } </code></pre> <p>Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe? </p>
<p>No, incrementing is not thread-safe. Neither are the <code>INC</code> and <code>DEC</code> instructions. They all require a load and a store, and a thread running on another CPU could do its own load or store on the same memory location interleaved between those operations.</p> <p>Some languages have built-in support for thread synchronization, but it's usually something you have to ask for, not something you get automatically on every variable. Those that don't have built-in support usually have access to a library that provides similar functionality.</p>
Decode/extract smime.p7m file contents (email with embedded files) with OpenSSL? <p>We have an old process (VBScript) that reads a common mailbox and processes certain emails into a database.</p> <p>New regulations have all messages with attachments now being digitally signed.</p> <p>The process now only extracts one file (smime.p7m). Using a GUI-based viewer, I can see the embedded files and extract them with no problem. However, what I <em>really</em> need is a command-line based extracter that will write out the embedded files (PDFs, DOCs, XLSs) - they're not encrypted, just signed. I tested this by using a laptop that had no certificates and simply opened the smime.p7m file with the aforementioned viewer.</p> <p>It looks like OpenSSL will decode/extract this and someone managed to get a version compiled on Windows. However, a lot of trial and error testing of the executable has been frustrating because I can't find the right combination of flags to just say "open the smime.p7m file and write out all the embedded files you find". "openssl smime" always seems to want a "cert.pem" after all the options and I haven't got that.</p> <p>What am I missing? Thanks in advance.</p>
<p>Did you try the "-noverify" option of openssl?</p> <p>For a signed-only message, you can use "openssl smime -verify -in -noverify -out /tmp/blob"</p> <p>Then you can use a RFC822-like parser to get the body and attachment(s) out of that "blob". That means that your parser has to be capable of encodings like quoted-printable and base64.</p>
HttpListener.Start() AccessDenied error on Vista <p>Running this code as a regular user throws HttpListenerException (access denied). Snippet runs ok as an administator</p> <pre><code>class Program { static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://myip:8080/app/"); listener.Start(); //.... and so on } } </code></pre> <p>i went ahead and added the uri using netsh (netsh http show lists the uri)</p> <pre><code>netsh http add urlacl url=http://+:8080/app user=domain\user </code></pre> <p>still getting the same error. Adding ACLs did work for other projects (they didn't use HttpListener though). I tried multiple port/application name combinations, nothing works.</p> <p>Any ideas what might be the cause?</p> <p>Running .Net 3.5 SP1 on Vista</p>
<p>I do not understand why but here it is. It seems that the cause is that my network card is configured with 2 IPs.</p> <p>if in the code i specify one of the ips (like i did in question above)</p> <pre><code>listener.Prefixes.Add("http://myip1:8080/app/"); </code></pre> <p>then to avoid exception i need to register it with IP-bound weak wildcard</p> <pre><code>netsh http add urlacl url=http://myip1:8080/app user=domain\user </code></pre> <p>however if i add prefix with the strong wildcard (plus sign)</p> <pre><code>listener.Prefixes.Add("http://+:8080/app/"); </code></pre> <p>and register with the same wild card</p> <pre><code>netsh http add urlacl url=http://+:8080/app user=domain\user </code></pre> <p>then there is no error and i can access my app from both ip.</p>
Django template ifequal comparison of decimals <p>So, I have a decimalfield that can be 3 different values. In my view, I pass in a dictionary of values that contains the appropriate decimal values as keys.</p> <pre><code>{% for item in booklist %} {% for key, value in numvec.items %} {{item.number}} {% ifequals item.number {{key}} %} {{value}} {% endifequals %} {% endfor %} {% endfor %} </code></pre> <p>this is the dict I pass in as numvec:</p> <pre><code>numvec = {"TEST":Decimal("0.999"), "TEST2":Decimal("0.500"), </code></pre> <p>"TEST3":Decimal("0.255")}</p> <p>the number field was defined as having these choices in my model:</p> <pre><code>BOOK_CHOICES=((Decimal("0.999"), 'TEST'),(Decimal("0.500"), 'TEST2'),(Decimal("0.255"), 'TEST3'),) </code></pre> <p>The item number prints out just fine in the view if I compare the dict with the attribute, but for some reason the ifequals cannot properly compare two decimals together. Is this a bug, or am I doing something wrong in my template with ifequals? </p>
<p>It is not a bug and <strong>it is possible</strong> to achieve what you're trying to do. </p> <p>However, first of all few remarks about your code:</p> <ul> <li>There is no "ifequals/endifequals" operator. You either use <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#ifequal">"ifequal/endifequal"</a> or <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#operator">"if/endif"</a>.</li> <li>Second thing. Your code <code>{% ifequal item.number {{key}} %}</code> would cause TemplateSyntaxError Exception if you leave double curly brackets inside the "ifequal" or "if" operator.</li> </ul> <p><strong>Now the solution</strong>:</p> <ol> <li>Just simply use <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat">"stringformat"</a> filter to convert your decimal values to string.</li> <li>Skip curly brackets when you use variables inside operators.</li> <li>Don't forget that variable inside an "if" or "ifequal" operator is always represented as a string.</li> </ol> <p>Here is an <em>example</em>:</p> <pre><code>{% for item in decimals %} {% if item|stringformat:"s" == variable %} {{ variable }} {% endif %} {% endfor %} </code></pre>
Div with horizontal scrolling only <p>I have a fixed width DIV containing a table with many columns, and need to allow the user to scroll the table horizontally within the DIV.</p> <p>This needs to work on IE6 and IE7 only (internal client application).</p> <p>The following works in IE7:</p> <pre><code>overflow-x: scroll; </code></pre> <p>Can anyone help with a solution that works in IE6 as well?</p>
<p>I couldn't get the selected answer to work but after a bit of <a href="http://www.htmlhelpcentral.com/messageboard/showthread.php?13621-Horizontal-scrolling-div">research</a>, I found that the horizontal scrolling div must have <code>white-space: nowrap</code> in the css. </p> <p>Here's complete working code:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Something&lt;/title&gt; &lt;style type="text/css"&gt; #scrolly{ width: 1000px; height: 190px; overflow: auto; overflow-y: hidden; margin: 0 auto; white-space: nowrap } img{ width: 300px; height: 150px; margin: 20px 10px; display: inline; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='scrolly'&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;img src='img/car.jpg'&gt;&lt;/img&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
Java toString() using reflection? <p>I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.</p> <p>Getting the field names is fairly simple, here is what a co-worker came up with:</p> <pre><code>public static List initFieldArray(String className) throws ClassNotFoundException { Class c = Class.forName(className); Field field[] = c.getFields(); List&lt;String&gt; classFields = new ArrayList(field.length); for (int i = 0; i &lt; field.length; i++) { String cf = field[i].toString(); classFields.add(cf.substring(cf.lastIndexOf(".") + 1)); } return classFields; } </code></pre> <p>Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.</p> <p>Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.</p>
<p>Apache commons-lang <a href="http://commons.apache.org/proper/commons-lang//apidocs/org/apache/commons/lang3/builder/ReflectionToStringBuilder.html">ReflectionToStringBuilder</a> does this for you. </p> <pre><code>import org.apache.commons.lang3.builder.ReflectionToStringBuilder // your code goes here public String toString() { return ReflectionToStringBuilder.toString(this); } </code></pre>
error when trying to install MSMQ <p>Have VS-2003, VS-2005, VS-2008</p> <p>Tried enabling MSMQ in Add/Remove Windows Components and get this</p> <p>'A local user is authenticated as an anonymous user and cannot access active directory. You need to log on as a domain user to access Active directory.'</p> <p>I am trying to do development on my machine and want to set up a private Q so that I can develop a MSMQ application.</p> <p>This is similar to this situation: I am on my machine as an admin. Am logged into VPN and trying the above.</p> <p><a href="http://groups.google.com/group/microsoft.public.msmq.setup/browse_thread/thread/5819165067560863" rel="nofollow">link text</a></p>
<p>Uncheck the "active directory integration" option in the "add windows component" gui. It is not needed for private queues.</p>
How to host an asp.net mvc app on a domain that points to a subfolder? <p>I have the folowing scenario:</p> <p>www.somedomain.com -> this points to a folder on a shared host, say /MyFolder1 www.otherdomain.com -> this points to another folder on the same shared host, say /MyFolder2</p> <p>With asp.net mvc my urls get mapped to:</p> <p>www.somedomain.com/MyFolder1/Action www.somedomain.com/MyFolder2/Action</p> <p>I (obviosly) dont't want to have "MyFolder1" and "MyFolder2" on my URLs. How do i solve this on asp.net MVC?</p> <p>I want to have:</p> <p>www.somedomain.com/Action www.somedomain.com/Action</p> <p>But i need to keep the subfolders on IIS (or some other solution that allows me to have two sites, with different domains on the same hosting).</p> <p>Help is very much appreciated. </p> <p>Thanks</p>
<p>The best way to handle this IMO is to use rewriting at the IIS level. I just did this on a site using IIS 7 URL Rewrite. If you don't have this module installed on your host provider, you can try to use one of the other URL rewriting tools. But, for example on DiscountASP you can use IIS 7 URL rewrite.</p> <p>First you need to point all your domains to your current site. Then when you download the tool: <a href="http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx" rel="nofollow">http://blogs.iis.net/bills/archive/2008/05/31/urlrewrite-module-for-iis7.aspx</a>, it provides a GUI for editing the rules. Ultimately the rules are placed into your web.config file. You want your rules to look something like this:</p> <pre><code> &lt;rewrite&gt; &lt;rewriteMaps&gt; &lt;rewriteMap name="otherdomain" /&gt; &lt;/rewriteMaps&gt; &lt;rules&gt; &lt;rule name="otherdomain" stopProcessing="false"&gt; &lt;match url=".*" /&gt; &lt;conditions&gt; &lt;add input="{HTTP_HOST}" pattern="otherdomain.com" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" url="/site_folder/otherdomain/{R:0}" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; </code></pre> <p>If you are using ISAPI rewrite, I'll probably have that one soon as well for another host that I'm using that doesn't support IIS rewrite</p>
Download time remaning predictor <p>Are there any widgets for predicting when a download (or any other process) will finish based on percent done history?</p> <p>The trivial version would just do a 2 point fit based on the start time, current time and percent done but better option are possible.</p> <p>A GUI widgest would be nice but a class that just returns the value would be just fine.</p>
<p>For the theoretical algorithm that I would attempt, if I would write such a widget, would be something like:</p> <ol> <li>Record the amount of data transferred within a one second period (a literal <a href="http://en.wikipedia.org/wiki/Kibibyte" rel="nofollow">KiB</a>/s)</li> <li>Remember the last 5 or 10 such periods (to get an an recent average KiB/s)</li> <li>Subtract the total size from the transferred size (to get a "bytes remaining")</li> <li>???</li> <li>Widget!</li> </ol> <p>That oughta do it...</p> <p>(the missing step being: kibibytes remaining divided by average KiB/s)</p>
where should I save a complex MVC application UI state? <p>I've been having a look at several MVC frameworks (like rails, merb, cakephp, codeignitier, and similars...)</p> <p>All the samples I've seen are basically plain and simple CRUD pages, carrying all the infr needed in the querystring and the posted field values.</p> <p>I've got a couple of apps made with some sort of framework built with classic asp.</p> <p>This framework handles some CRUD stuff a little more complex than the examples I found.</p> <p>Something like master-detail, filtering by example, paging, sorting and similars.</p> <p>I have a controller class that it's just a finite state machine, that goes thru diferent states (like new, browse, filter, show, etc.), then performs the appropiate action depending on the event raised and finally retrieves the neede info to the calling page.</p> <p>To achieve this I have several hidden inputs to keep the state of the web page (like current id, filter criterias, order criterias, previous state, previous event, well, you get the idea)</p> <p>What do you think would be the finnest approach to achieve this kind of funcionality?</p> <p>hidden inputs built in the view and used from the controller??? (I guess that would be the equivalent of what I'm doing right now in classi asp)</p> <p>--</p> <p>(added in response to tvanfosson)</p> <p>basically, my question refers to the third category, the context-dependent setting (in respect to the other two categories I agree with you) the info I was storing in hidden fields to store them on the querystring, I guess that when you click on the "next page" you include everything you need to save in the querystring, right? so that piece of query string gets appended in each and every link that performns some kind of action...</p> <p>I'm not sure, what are the advantages and disadvantages of using the querystring instead of hidden inputs???</p>
<p>I use different strategies depending on the character of the actual data. Things that are preferences, like default page size, I keep in a Preferences object (table) that is associated with the current logged in user and retrieve from there when needed.</p> <p>Persistent settings associated with the current logon, like filter settings for a page, are stored in the user's session. Generally these are things that if a user sets them in the current session they should remain sticky. I think filter settings and visibility are like this. If I filter a list, navigate away from it to drill down into a particular item, then come back to the list, I want my filter settings to be reapplied -- so I make it part of the session.</p> <p>Context-dependent settings -- like the current sort column or page number, are controlled using query parameters. Paging and sort controls (links) are built with the appropriate query parameters to "do the right thing" when clicked and pass any necessary query parameters to maintain or update the current context of the control. Using the query parameters allows you to use an HTTP GET, which is bookmarkable, rather than a POST. Using hidden form parameters makes it much harder for the user to save or enter a URL that takes them directly where they want to go. This is probably more useful for sorting than it is for paging, but the principle applies equally.</p>
Why don't Django admin "Today" and "Now" buttons show up in Safari? <p>I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png" alt="alt text" /></p> <p>This is as expected. However, when I deploy to my webserver and use the application from there, I get this:</p> <p><img src="http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png" alt="alt text" /></p> <p>The application on the server is <em>exactly</em> the same as my local copy, <em>except</em> that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?</p> <p><hr /></p> <h2>Update</h2> <ul> <li>The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).</li> <li>I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget: <ul> <li><code>RelatedObjectLookup.js</code></li> <li><code>DateTimeShortcuts.js</code></li> <li><code>icon_calendar.gif</code></li> <li><code>icon_clock.gif</code></li> </ul></li> </ul>
<p>I think you have to look at what is different between your firefox configuration and safary config</p> <p>Off the top of my head:</p> <ul> <li><p>One could be configured to use a proxy (messing with the trafic) the other not. Make sure the configuration is the same in both.</p></li> <li><p>Safari could have cached the error clear the cache before testing again.</p></li> <li><p>Try to access the gif files directly from the browser (by inputting the full url of the images) and run wireshark on the wire comparing both GET requests and responses. Something WILL be different that will help you to track the problem.</p></li> </ul>
Why can't enum's constructor access static fields? <p>Why can't enum's constructor access static fields and methods? This is perfectly valid with a class, but is not allowed with an enum.</p> <p>What I'm trying to do is store my enum instances in a static Map. Consider this example code which allows lookup by abbreivation:</p> <pre><code>public enum Day { Sunday("Sun"), Monday("Mon"), Tuesday("Tue"), Wednesday("Wed"), Thursday("Thu"), Friday("Fri"), Saturday("Sat"); private final String abbreviation; private static final Map&lt;String, Day&gt; ABBREV_MAP = new HashMap&lt;String, Day&gt;(); private Day(String abbreviation) { this.abbreviation = abbreviation; ABBREV_MAP.put(abbreviation, this); // Not valid } public String getAbbreviation() { return abbreviation; } public static Day getByAbbreviation(String abbreviation) { return ABBREV_MAP.get(abbreviation); } } </code></pre> <p>This will not work as enum doesn't allow static references in its constructor. It however works just find if implemented as a class:</p> <pre><code>public static final Day SUNDAY = new Day("Sunday", "Sun"); private Day(String name, String abbreviation) { this.name = name; this.abbreviation = abbreviation; ABBREV_MAP.put(abbreviation, this); // Valid } </code></pre>
<p>The constructor is called before the static fields have all been initialized, because the static fields (including those representing the enum values) are initialized in textual order, and the enum values always come before the other fields. Note that in your class example you haven't shown where ABBREV_MAP is initialized - if it's <em>after</em> SUNDAY, you'll get an exception when the class is initialized.</p> <p>Yes, it's a bit of a pain and could probably have been designed better.</p> <p>However, the usual answer in my experience is to have a <code>static {}</code> block at the end of all the static initializers, and do all static initialization there, using <code>EnumSet.allOf</code> to get at all the values.</p>
What is the WCF equivalent of HttpContext.Current.Request.RawUrl? <p>I've got some RESTful services running in a pure WCF context (i.e. ASP.NET compatibility is not enabled, and thus there is no <code>HttpContext.Current</code> object available).</p> <p>The URLs to the services are rewritten at the start of the request using an <code>IHttpModule</code> (which at that point does have an <code>HttpContext</code> and rewrites it using <code>HttpContext.Current.RewritePath</code>) to get rid of things like the <code>.svc</code> extension from the URL.</p> <p>However, I need to access the original URL that was requested from within the WCF infrastructure. Is there an equivalent to <code>HttpContext.Current.Request.RawUrl</code> on the <code>OperationContext</code> or <code>WebOperationContext</code> classes anywhere? Using <code>WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri</code> returns the rewritten URL not the original one.</p>
<p>You can get the endpoint currently targeted and the Uri for it by doing:</p> <pre><code>OperationContext.Current.RequestContext.RequestMessage.Headers.To </code></pre> <p>which I think is the same thing as:</p> <pre><code>OperationContext.Current.IncomingMessageHeaders.To </code></pre> <p>This is a <code>System.Uri</code> object, and I believe you can just get the <code>OriginalString</code> or <code>PathAndQuery</code>, or whatever parts you want from it.</p>
Do you recommend using semicolons after every statement in JavaScript? <p>In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?</p> <p>If you're unfamiliar with the rules, there's a description of semicolon insertion on the <a href="http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html" rel="nofollow">Mozilla site</a>. Here's the key point:</p> <blockquote> <p>If the first through the n<sup>th</sup> tokens of a JavaScript program form are grammatically valid but the first through the n+1<sup>st</sup> tokens are not and there is a line break between the n<sup>th</sup> tokens and the n+1<sup>st</sup> tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the n<sup>th</sup> and the n+1<sup>st</sup> tokens.</p> </blockquote> <p>That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)</p> <p><a href="http://stackoverflow.com/questions/42247/are-semicolons-needed-after-an-object-literal-assignment-in-javascript">This stackoverflow question</a> is related, but only talks about a specific scenario.</p>
<p>Yes, you should use semicolons after every statement in JavaScript.</p>
MS-SQL 2000: Turn off logging during stored procedure <p>Here's my scenario:</p> <p>I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows. This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.</p> <p>This process in turn is unbareably slow due to the trigger, and the table is also locked during this process. So here are my two questions:</p> <ol> <li>I'm guessing a decent part of the slowdown is due to the transaction log. Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?</li> <li>Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?</li> </ol> <p>Thanks!</p> <p><em>edit</em> - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure. The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved. Thanks!</p>
<p>1) no, also you are not doing a minimally logged operation like TRUNCATE or BULK INSERT</p> <p>2) No, how would you prevent corruption otherwise?</p>
Object Oriented questions in Javascript <p>I've been using javascript for a while, but have never learned the language past the basics. I am reading John Resig's "Pro Javascript Techniques" - I'm coming up with some questions, but I'm not finding the answers to them in the book or on google, etc.</p> <p>John gives this example in his book:<br /> <strong>Function #1</strong></p> <pre><code>function User( name, age ){ this.name = name; this.age = age; } // Add a new function to the object prototype User.prototype.getName = function(){ return this.name; }; User.prototype.getAge = function(){ return this.age; }; var user = new User( "Bob", 44 ); console.log("User: " + user.getName() + ", Age: " + user.getAge()); </code></pre> <p>I'm still learning about the <em>prototype</em> property, so I tried writing something similar:<br /> <strong>Function #2</strong></p> <pre><code>function User (name, age ) { this.name = name; this.age = age; this.getName = function() { return this.name; }; this.getAge = function() { return this.age; }; } var user = new User( "Bob", 44 ); console.log("User: " + user.getName() + ", Age: " + user.getAge()); </code></pre> <p>It doesn't use the <em>prototype</em> property to create the getName and getAge functions, but the output is the same as John's example.</p> <p>I took it one step further, and created this:<br /> <strong>Function #3</strong></p> <pre><code>var User = { name: "", age: 0, setName: function(name) { this.name = name; }, setAge: function(age) { this.age = age; }, getName: function() { return this.name; }, getAge: function() { return this.age; } }; User.setName("Bob"); User.setAge(44); console.log("User: " + User.getName() + ", Age: " + User.getAge()); </code></pre> <p>Again - it looks different than John's example (and I had to add setter methods), but the output is the same.</p> <p><strong>Question #1</strong> - what is the difference between the 3 functions? What is the advantage of the prototype property, and is Function #2 doing anything incorrectly, because it seems more straight forward to code #2 instead of #1 (although I'm sure #1 is doing it better seeing as John created it).</p> <p><strong>Question #2</strong> - How could I modify function #3 to not use the setName and setAge methods, but still keep the {...} shorthand? Can the {...} shorthand have constructors?</p> <p>Thanks in advance for helping me learn!</p> <p><strong>EDIT</strong> I think my 2nd question was a little confusing. I meant how could I use the {...} shorthand to create a User object, but then after I create the object, say something like:</p> <pre><code>var user = new User("Bob", 44); </code></pre> <p>Just like in Function #1 - or is that not possible?</p> <p><strong>EDIT #2</strong> Wow! Thanks everyone for the awesome answers. That really makes it a lot more clear to me. So if I understand correctly, the difference between #1 and #2 aren't too much. If I only ever create one "User" object - they probably aren't different at all. But if my program creates many User objects, #1 would most likely be more efficient and use less memory since all objects will share the same functions.</p> <p>I really appreciate all of the great answers - Thanks!</p>
<p>Every time a function() {} is evaluated, it creates a new function object. Therefore, in #1 all of the User objects are sharing the same getName and getAge functions, but in #2 and #3, each object has its own copy of getName and getAge. All of the different getName functions all behave exactly the same, so you can't see any difference in the output.</p> <p>The {...} shorthand <em>is</em> a constructor. When evaluated, it constructs a new "Object" with the given properties. When you run "new User(...)", it constructs a new "User". You happen to have created an Object with the same behavior as a User, but they are of different types.</p> <p>Response to comment:</p> <p>You can't, directly. You could make a function that creates a new object as per #3. For example:</p> <pre><code>function make_user(name, age) { return { name: name, age: age, getName: function() { return name; }, getAge: function() { return age; }, }; } var user = make_user("Joe", "18"); </code></pre>
How do I send emails outside my domain with Exchange 2007 and c# <p>I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain.</p> <p>As soon as I try to send emails outside the domain I get:</p> <p>Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Unable to relay</p> <p>How can I get exchange to accept my email and send it out to the internet?</p>
<p>Try #2... How about using a <a href="http://www.msexchange.org/articles_tutorials/exchange-server-2007/management-administration/exchange-pickup-folder.html">Exchange Pickup Folder</a> instead? They are a faster way to send emails through Exchange because it just creates the email and drops it in the folder, no waiting to connect to the server or waiting for a reply. Plus I think it skips the whole relay issue.</p> <p>Configure youur SmtpClient like so:</p> <pre><code>SmtpClient srv = new SmtpClient("exchsrv2007", 25) { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = "\\exchsrv2007\PickupFolder" } ... </code></pre>
Can you use the asp.net membership provider in a windows application? <p>The Asp.Net membership provider has some clear uses in a web app. I am thinking about trying to leverage some of the features in a windows application (more specifically WPF). Does anyone know if it is possible to use the core features in a windows app? I am mostly just looking for it to create my database tables, and maintain users, roles, and profiles. I obviously do not need to use the built-in web controls (e.g. Login).</p>
<p>Yes. Membership, roles and profiles are all features of Visual Studio 2008 Client Application Services (Services tab of a project properties)</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb384297.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb384297.aspx</a></p> <p><a href="http://channel9.msdn.com/posts/DanielMoth/Client-Application-Services-with-Visual-Studio-2008/" rel="nofollow">http://channel9.msdn.com/posts/DanielMoth/Client-Application-Services-with-Visual-Studio-2008/</a></p>
Is there an advantage to upgrade Binutils from 2.16.1 to 2.19? Why? <p>In the PSPSDK (Homebrew) we are using the Binutils 2.16.1 to assemble and link the code for the PlayStation Portable, however that release is getting quite outdated (3 versions have superseded it). The community and me have been updating the GCC and newlib to the latest stable versions and everything seems to work with the old binutils.</p> <p>Will GCC produce better code with binutils 2.19? Why? Will binutils 2.19 produce better elf files and libs than 2.16.1? Why?</p>
<p><code>binutils</code> 2.19 has a new ELF linker called <a href="http://sourceware.org/ml/binutils/2008-03/msg00162.html"><code>gold</code></a> which is multi-threaded, written in modern C++, and quite a bit faster than the usual <code>ld</code> linker. I'm not sure however about the work involved to adapt it. </p> <p>Other than that, well new versions always are a good idea. Performance and bug fixes are likely to have been included, of course. I think i would certainly try it and if something goes wrong you can still backstep. </p>
Is there a streaming API for JSON? <p>Is DOM the only way to parse JSON?</p>
<p>Some JSON parsers do offer incremental ("streaming") parser; for Java, at least following parsers from json.org page offer such an interface:</p> <ul> <li><a href="http://wiki.fasterxml.com/JacksonInFiveMinutes">Jackson</a> (pull interface)</li> <li><a href="http://code.google.com/p/json-simple/">Json-simple</a> (SAX-style push interface)</li> </ul> <p>(in addition to Software Monkey's parser referred to by <a href="http://stackoverflow.com/a/444579/8946">another answer</a>)</p> <p>Actually, it is kind of odd that so many JSON parsers do NOT offer this simple low-level interface -- after all, they already need to implement low-level parsing, so why not expose it.</p> <p>EDIT (June 2011): Gson too has its own <a href="http://sites.google.com/site/gson/streaming">streaming API</a> (with gson 1.6)</p>
How do I focus a foreign window? <p>I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:</p> <pre><code> System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses(); System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess(); foreach (System.Diagnostics.Process p in myProcesses) { if (p.ProcessName == me.ProcessName) if (p.Id != me.Id) { //if already running, abort this copy. return; } } //launch the application. //... </code></pre> <p>It works fine. I would also like it to be able to focus the form of the already-running copy. That is, before returning, I want to bring the other instance of this application into the foreground.</p> <p>How do I do that?</p> <p>Re: SetForeGroundWindow:</p> <p>SetForeGroundWindow works, to a point:</p> <pre><code> [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); //... if (p.Id != me.Id) { //if already running, focus it, and then abort this copy. SetForegroundWindow(p.MainWindowHandle); return; } //... </code></pre> <p>This does bring the window to the foreground if it is not minimized. Awesome. If the window IS minimized, however, it remains minimized.</p> <p>It needs to un-minimize.</p> <p>Solution via SwitchToThisWindow (Works!):</p> <pre><code> [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); [STAThread] static void Main() { System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess(); System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName); foreach (System.Diagnostics.Process p in myProcesses) { if (p.Id != me.Id) { SwitchToThisWindow(p.MainWindowHandle, true); return; } } //now go ahead and start our application ;-) </code></pre>
<p>I had the same problem and <a href="http://msdn.microsoft.com/en-us/library/ms633553.aspx">SwitchToThisWindow()</a> worked the best for me. The only limitation is that you must have XP sp1 installed. I played with SetForegroundWindow, ShowWindow, and they both had problems pulling the window into view.</p>
Dynamically add multiple instances of the same user control type when button is clicked <p>Is it possible to add instances of the same user control when an "add" button is clicked and maintain ViewState?</p> <p>The user interface here is similar to the Gmail file-attachment process, where the user can click "attach another file" and another file upload box appears.</p> <p>My page is surrounded by an UpdatePanel. I am able to get 1 control to load, but the button's click event fires after the Placeholder_Init method. I tried storing an integer in the ViewState that kept track of the number of user controls that should be rendered, but the Init method is also fired before the ViewState is restored.</p> <p>Thanks!</p>
<p>Adding multiple controls dynamically is easy in ASP.NET. Let's say you have a panel named Panel declared in your ASPX file and you have a custom control called MyControl.</p> <p>In your Page_Load function (or indeed pretty much anywhere), add something like the following:</p> <pre><code>for (int i = 0; i &lt; NumberOfAttachments; i++) { Panel.Controls.Add(new MyControl()); } </code></pre> <p>This works for UpdatePanels, too, but you'll need to call the .Update() function to get it to update on the client side if you don't have it to update on child postback.</p>
What is a fractal? <p>Duplicate of <a href="http://stackoverflow.com/questions/425953/how-to-program-a-fractal">How to program a fractal</a></p> <p><hr /></p> <p>What are fractals? </p> <p>Is this is one of the concepts that is brought over from Mathematics to programming to simplify or solve a particular set of problems?</p> <p> I am closing this question and have posted a related <a href="http://stackoverflow.com/questions/444628/programming-fractals"> question </a></p>
<p>If you want to know about fractals in a general non-programming way, I would suggest looking at a general non-programming site. Wikipedia has <a href="http://en.wikipedia.org/wiki/Fractal" rel="nofollow">a good article on them</a>. If you want to know about programming fractals, I would suggest looking at this already asked question:</p> <p><a href="http://stackoverflow.com/questions/425953/how-to-program-a-fractal">How to program a fractal</a></p> <p>It even has a fractal tag.</p>
Custom dynamically created Menus producing some strange errors <p>The background is I have a custom control that is a asp:Menu that is linked to an xmldatasource. The xmldatasource is created dynamically depending on the user privies. Here is the load event for the custom control:</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { string userId = (string)Session["userId"]; if (userId != null) { DataSet ds = dal.RetrieveApplications(userId); ds.DataSetName = "Menus"; ds.Tables[0].TableName = "Menu"; DataRelation relation = new DataRelation ("ParentChild", ds.Tables["Menu"].Columns["Folder_Id"], ds.Tables["Menu"].Columns["Parent_Folder_ID"], true); relation.Nested = true; ds.Relations.Add(relation); xmlDataSource1.Data = ds.GetXml(); } } </code></pre> <p>This works perfectly for the first user that uses it. But it seems that every subsequent user is actually getting the first user's menu. I have walked it through and verified that my dataset is getting created fine and when I examine the XMLDatasource.data at the end of the load the xml is correct. </p> <p>I am really stuck.</p>
<p>I found the answer and though I would leave it out here for others who might search for this:</p> <p>But I had to set the "ENABLECACHING" to false on the xmldatasource.</p>
Javascript: Lazy Load Images In Horizontal Div? <p>I have a div that has a bunch of thumbnails showing horizontally (with a horizontal scrollbar). Is there a way to lazy load these thumbnails and only show them once the user horizontally scrolls to their position? All the examples I've seen check the browser window, not a div.</p> <p>This is for contest entries so sometimes there are hundreds of entries, which drastically affects performance.</p> <p>Thanks in advance.</p>
<p><del>I forked the <a href="http://plugins.jquery.com/project/lazyload" rel="nofollow">lazy load plugin</a> for jQuery and added support for lazy-loading images in a container div.</del> The <a href="http://plugins.jquery.com/project/lazyload" rel="nofollow">lazy load plugin</a> for jQuery now supports this directly. It shouldn't be too hard to remove the dependency on jQuery or adapt it to another library if you need to.</p> <p><del>You can get my forked project from github: <a href="http://github.com/silentmatt/jquery_lazyload/tree/master" rel="nofollow">http://github.com/silentmatt/jquery_lazyload/tree/master</a>.</del></p> <p>To use it, call lazyload on the images just like in the original, except you need to add a "container" option with the scrolling div element. So if your HTML looks like this:</p> <pre><code>&lt;div id="container" style="width: 765px; overflow: scroll;"&gt; &lt;img src="image1.jpg" width="765" height="574"&gt; &lt;img src="image2.jpg" width="765" height="574"&gt; &lt;img src="image3.jpg" width="765" height="574"&gt; ... &lt;/div&gt; </code></pre> <p>you would call lazyload like this:</p> <pre><code>$("#container img").lazyload({ container: $("#container") }); </code></pre>
Spring.net Drop all adotemplate connections? <p>I have an application which is connected to a database through a spring.net AdoTemplate. I am charged with creating a restore database method which keeps the app running but drops the network connections so as to drop the old database and bring up the new one. My question is how do I drop all the current connections that this application has to this AdoTemplate? I do not see any public method in spring 1.1 to drop the network connections.</p>
<p>there is no physical "connection" between AdoTemplate and the SQL database. Leaving transactions aside, AdoTemplate creates a new SqlConnection object for each method that is executed from ADO.NET, executes a command and disposes the SqlConnection object after that. Under the hoods, ADO.NET caches physical connections to the database in a pool. When you create a new SqlConnection object, 1 of those cached physical connections is obtained from the pool to serve that SqlConnection. This means, that you will need a different strategy for solving your problem. One strategy coming to my mind is to obtain the list of active connections from the sysprocesses database and execute the KILL statement on them. Short googling brought up this <a href="http://www.sqlservercentral.com/scripts/Maintenance+and+Management/30024/" rel="nofollow">article</a>. Note, that this article refers to mssql 2000. I'm pretty sure, that you need to google a bit more to find a solution for 2005. Since 2005 it isn't allowed to access system tables anymore asfair.</p> <p>hth, Erich</p>
Can intellisense be exported or extracted from Visual Studio to a text file? <p>I'm trying to write some documentation for a webservice that has been provided by one of our vendors for an application we're integrating. A bunch of the interface is custom objects defined in the web service itself. The vendor has put up significant resistance to providing any documentation for this application and so I've taken it upon myself to do their job for them [against my better judgement].</p> <p>The documentation they <em>have</em> provided frankly is embarassing and I'm trying to make as short work of this as I possibly can to put some good quality docs together. I know that as I don't have access to their source, I can't just run it through nDoc/Sandcastle to spit out an API doc, but I was wondering if (as a half way house) there was an easy way to export the intellisense to a text file without me having to write a utility to specificially iterate through each of the object types defined and reflect the members out to text? </p> <p>If I could do this, it would at least make sure that I have a good quality document structure where I can just fill in the blanks. Having to skip back and forth to Visual Studio to check the intellisense for every class member is a very laborious way of doing this.</p> <p>Does anyone have any ideas?</p>
<p>If it is a web service that you are trying to document, couldnt you then parse out the WSDL?</p>
Left outer join on two columns performance issue <p>I'm using a SQL query that is similar to the following form:</p> <pre><code>SELECT col1, col2 FROM table1 LEFT OUTER JOIN table2 ON table1.person_uid = table2.person_uid AND table1.period = table2.period </code></pre> <p>And it's either way too slow or something's deadlocking because it takes at least 4 minutes to return. If I were to change it to this:</p> <pre><code>SELECT col1, col2 FROM table1 LEFT OUTER JOIN table2 ON table1.person_uid = table2.person_uid WHERE table1.period = table2.period </code></pre> <p>then it works fine (albeit not returning the right number of columns). Is there any way to speed this up?</p> <p><strong>UPDATE</strong>: It does the same thing if I switch the last two lines of the latter query:</p> <pre><code>SELECT col1, col2 FROM table1 LEFT OUTER JOIN table2 ON table1.period = table2.period WHERE table1.person_uid = table2.person_uid </code></pre> <p><strong>UPDATE 2:</strong> These are actually views that I'm joining. Unfortunately, they're on a database I don't have control over, so I can't (easily) make any changes to the indexing. I am inclined to agree that this is an indexing issue though. I'll wait a little while before accepting an answer in case there's some magical way to tune this query that I don't know about. Otherwise, I'll accept one of the current answers and try to figure out another way to do what I want to do. Thanks for everybody's help so far.</p>
<p>Bear in mind that statements 2 and 3 are different to the first one.</p> <p>How? Well, you're doing a left outer join and your WHERE clause isn't taking that into account (like the ON clause does). At a minimum, try:</p> <pre><code>SELECT col1, col2 FROM table1, table2 WHERE table1.person_uid = table2.person_uid (+) AND table1.period = table2.period (+) </code></pre> <p>and see if you get the same performance issue.</p> <p>What indexes do you have on these tables? Is this relationship defined by a foreign key constraint?</p> <p>What you probably need is a composite index on both person_uid and period (on both tables).</p>
jQuery scope or race condition in AJAX/getJSON <p>I have a piece of jQuery code which invokes several <code>getJSON()</code> calls in quick succession:</p> <pre><code>var table = $("table#output"); for (var i in items) { var thisItem = items[i]; $.getJSON("myService", { "itemID": thisItem }, function(json) { var str = "&lt;tr&gt;"; str += "&lt;td&gt;" + thisItem + "&lt;/td&gt;"; str += "&lt;td&gt;" + json.someMember + "&lt;/td&gt;"; str += "&lt;/tr&gt;"; table.append(str); }); } </code></pre> <p>When I run this against a laggy server, the table gets populated with the expected <code>json.someMember</code> values (they arrive out of order: I don't mind that), but the <code>thisItem</code> column is populated with an unpredictable mixture of values from various iterations.</p> <p>I'm assuming this is something to do with scope and timing - the callback function is reading <code>thisItem</code> from a wider scope? Am I right? How do I prevent this?</p> <p>My current workaround is for the JSON service to return a copy of its inputs - which is unsatisfying to say the least.</p>
<p>Seems like a scoping issue due to the loop. Try this:</p> <pre><code>var table = $("table#output"); for (var i in items) { var thisItem = items[i]; $.getJSON("myService", { "itemID": thisItem }, (function(thisItem) { return function(json) { var str = "&lt;tr&gt;"; str += "&lt;td&gt;" + thisItem + "&lt;/td&gt;"; str += "&lt;td&gt;" + json.someMember + "&lt;/td&gt;"; str += "&lt;/tr&gt;"; table.append(str); } })(thisItem)); } </code></pre> <p><em>Edit</em>: all I did was scope <code>thisItem</code> to the <code>$.getJSON</code> callback.</p>
How can I cache objects in ASP.NET MVC? <p>I'd like to cache objects in ASP.NET MVC. I have a <code>BaseController</code> that I want all Controllers to inherit from. In the BaseController there is a <code>User</code> property that will simply grab the User data from the database so that I can use it within the controller, or pass it to the views.</p> <p>I'd like to cache this information. I'm using this information on every single page so there is no need to go to the database each page request.</p> <p>I'd like something like:</p> <pre><code>if(_user is null) GrabFromDatabase StuffIntoCache return CachedObject as User </code></pre> <p>How do I implement simple caching in ASP.NET MVC?</p>
<p>You can still use the cache (shared among all responses) and session (unique per user) for storage. </p> <p>I like the following "try get from cache/create and store" pattern (c#-like pseudocode):</p> <pre><code>public static class CacheExtensions { public static T GetOrStore&lt;T&gt;(this Cache cache, string key, Func&lt;T&gt; generator) { var result = cache[key]; if(result == null) { result = generator(); cache[key] = result; } return (T)result; } } </code></pre> <p>you'd use this like so:</p> <pre><code>var user = HttpRuntime .Cache .GetOrStore&lt;User&gt;( $"User{_userId}", () =&gt; Repository.GetUser(_userId)); </code></pre> <p>You can adapt this pattern to the Session, ViewState (ugh) or any other cache mechanism. You can also extend the ControllerContext.HttpContext (which I think is one of the wrappers in System.Web.Extensions), or create a new class to do it with some room for mocking the cache.</p>
Pacman in Java questions <p>For my university assignment I have to make a networkable version of pacman. I thought I would best approach this problem with making a local copy of pacman first and then extend this functionality for network play. </p> <p>I would have to say that I am relatively new to java GUI development and utilizing such features within java.</p> <ul> <li><a href="http://www.planetalia.com/cursos/Java-Invaders/" rel="nofollow">http://www.planetalia.com/cursos/Java-Invaders/</a></li> <li><a href="http://javaboutique.internet.com/PacMan/source.html" rel="nofollow">http://javaboutique.internet.com/PacMan/source.html</a></li> </ul> <p>I have started following the above links with regards to game development within java and an example of the pacman game.</p> <p>I decided to represent the maze as an int array with different values meaning different things. However when the paint method inside the main game loop is run i am redrawing the whole maze with this method.</p> <pre><code> for (int i : theGame.getMaze()) { if (i == 4) { g.setColor(mazeWallColour); g.fillRect(curX, curY, cellSize, cellSize); curX += 25; } else { curX += cellSize; } index++; // Move to new row if (index == 25) { index = 0; curX = 10; curY += cellSize; } } </code></pre> <p>However this is providing me with less then 1fps. Although i've noticed the example linked above uses a similar way of redrawing each time the paint method is called and i believe does this on a image that is not viewable (kinda like double buffering [I've used a BufferStrategy like the first link explains]) What would be a better way to redraw the maze? </p> <p>Any pointers/advice with this would be useful. </p> <p>Thank you for your time.</p> <p><a href="http://pastebin.com/m25052d5a" rel="nofollow">http://pastebin.com/m25052d5a</a> - for the main game class.</p> <p>Edit: I have just noticed something very weird happening after trying to see what code was taking so long to execute.</p> <p>In the paintClear(Graphics g) method i have added </p> <pre><code>ocean = sprites.getSprite("oceano.gif"); g.setPaint(new TexturePaint(ocean, new Rectangle(0,t,ocean.getWidth(),ocean.getHeight()))); g.fillRect(10, 10,getWidth() - 20,getHeight() - 110); </code></pre> <p>which made the whole thing run smoothly - however when i removed these lines the whole thing slowed down? What could have caused this?</p> <p><a href="http://pastebin.com/m15d0d70" rel="nofollow">Updated code</a></p>
<p>First off, I'd recommend that you use named constants rather than having random magic numbers in your code and consider using enums for your cell types. While it won't make your code run any faster, it certainly will make it easier to understand. Also, 'i' is normally used as a counter, not for a return value. You should probably call it <code>cellType</code> or something similar. I'd also recommend that you use a 2D array for your stage map since it makes a number of things easier, both logistically and conceptually.</p> <p>That said, here are a few things to try:</p> <p>Pull the <code>setColor()</code> out of the loop and do it once. The compiler might be able to do loop-invariant hoisting and thus do this for you (and probably will), but conceptually, you should probably do this anyway since it appears you want all of your walls to be one color anyway.</p> <p>Try calling <code>drawRect()</code> instead of <code>fillRect()</code> and see if that draws faster. I don't think it will, but it is worth a shot, even if it looks uglier. Similarly, you can try creating an <code>Image</code> and then drawing that. This has the advantage that it is really easy to tell your Graphics object to implement a transform on your image. Also, consider taking this out completely and make sure that it is being a significant performance hit.</p> <p>Also, normally you don't need to ask for the parent for its Graphics object and implement painting directly on it. Rather, you should override its <code>paintComponent()</code> method and just utilize the Graphics given to you (possibly calling helper methods as you do). Swing components are double-buffered by default, so you don't need to implement that yourself; just let the swing object do its job and let you know when to paint.</p> <p>Also, you end up repainting the entire screen, which is something of overkill. If you call <code>repaint(Rectangle)</code>, Swing can choose to redraw only the sections of your board that are explicitly marked dirty. When you update one of your sprites, call repaint(r) only on the area of the sprite's old and new locations. When you complete a level and need a new board, then you can call repaint() (without parameters) to redraw the entire map.</p> <p>You should also look at <a href="http://java.sun.com/products/jfc/tsc/articles/painting/" rel="nofollow">Sun's tutorial</a> to get some tips for efficiency in Swing.</p>
Where can I find a good treeview control for Flex that supports checkboxes? <p>To my best knowledge the out-of-the-box Flex 3 treeview control does not support checkboxes. Where can I find a good treeview control that supports checkboxes on any and all nodes. I would prefer open source software but commercial components are not out of the question.</p>
<p>check out the following <a href="http://www.sephiroth.it/test/components/flex2/treecheckbox/test.swf" rel="nofollow">http://www.sephiroth.it/test/components/flex2/treecheckbox/test.swf</a></p> <p><a href="http://www.sephiroth.it/index.php" rel="nofollow">http://www.sephiroth.it/index.php</a></p> <p><a href="http://www.sephiroth.it/weblog/archives/2006/09/flex2_again_checkbox_3state.php" rel="nofollow">http://www.sephiroth.it/weblog/archives/2006/09/flex2_again_checkbox_3state.php</a></p>
Why do my Button send two postbacks when downloading zip file? <p>I've got a problem on a <em>WebForms</em> application where a user selects some criteria from drop downs on the page and hits a button on the page which calls this method:</p> <pre><code>protected void btnSearch_Click(object sender, EventArgs e) </code></pre> <p>They then click on button to download a zip file based on the criteria which calls this method:</p> <pre><code>protected void btnDownload_Click(object sender, EventArgs e) </code></pre> <p>In IE, they are prompted with the bar at the top of the browser that tells them:</p> <blockquote> <p>"To help protect your security, Internet Explorer blocked this site from downloading files to your computer".</p> </blockquote> <p>When they click on that bar to download the file, it fires the <code>btnSearch_Click</code> event again.</p> <p><code>Response.ContentType</code> and <code>Response.AddHeader</code> has been set up correctly.</p> <p>The problem is, that <code>btnSearch</code> appends criteria so basically it is being appended twice and causing problems.</p> <p>Is there something I can do to prevent this?</p> <p>This is a VS2008 web application using C# 3.5 for what it's worth.</p>
<p>When they click the download button, do a Redirect to the ZIP file handler (page?) to download the file. i.e. use the Post-Redirect-Get pattern: <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow">http://en.wikipedia.org/wiki/Post/Redirect/Get</a></p>
What is the equivalant of a 'friend' keyword in C Sharp? <p>What is the equivalant of a 'friend' keyword in C Sharp?</p> <p>How do I use the 'internal' keyword?</p> <p>I have read that 'internal' keyword is a replacement for 'friend' in C#.</p> <p>I am using a dll in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods?</p>
<ol> <li><p>You can use the keyword access modifier <a href="http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx"><code>internal</code></a> to declare a type or type member as accessible to code in the same assembly only.</p></li> <li><p>You can use the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx"><code>InternalsVisibleToAttribute</code></a> class defined in <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.aspx"><code>System.Rutime.CompilerServices</code></a> to declare a type as accessible to code in the same assembly or a specified assembly only.</p></li> </ol> <p>You use the first as you use any other <a href="http://msdn.microsoft.com/en-us/library/ms173121.aspx">access modifier</a> such as <code>private</code>. To wit:</p> <pre><code>internal class MyClass { ... } </code></pre> <p>You use the second as follows:</p> <pre><code>[assembly:InternalsVisibleTo("MyFriendAssembly", PublicKey="...")] internal class MyVisibleClass { ... } </code></pre> <p>Both of these can rightly be considered the equivalent of <code>friend</code> in C#.</p> <p>Methods that are <a href="http://msdn.microsoft.com/en-us/library/bcd5672a.aspx"><code>protected</code></a> are already available to derived classes.</p>
Can you specify which svn branches with git svn? <p>I think my question is somewhat similar to <a href="http://stackoverflow.com/questions/258590/how-do-i-import-svn-branches-rooted-in-different-directories-into-git-using-git-s" rel="nofollow" title="How do I import svn branches rooted in different directories into git using git-svn?">CaptainPicard's</a> but dissimilar enough that I feel compelled to ask so here goes.</p> <p>I have an old SVN repository with around 7500 revisions and part of those 7500 revisions are some pretty large .fla files. And these .fla files exist in a number of the branches which have been created. As a result of this my .git directory after import is pretty large, something like 3.5 GB if I get the whole trunk, all the branches and all the tags. In an effort to pair this down some I did another svn clone of just the directory in trunk I wanted to work with but including all branches obviously pulls down all the history and objects for those.</p> <p>So my question is this, is there some way to tell git to only fetch certain branches. For example only fetch branches starting with some identifier (e.g. mybranch)?</p> <p><strong><em>Update for clarity:</em></strong> I know I can point git svn init/clone at a single specific branch. What I want to be able to do is point it at a set of branches. For example, instead of matching branches/* only branches matching mybranchset*</p>
<p>In <code>git svn</code> commands, you can only use the asterisk wildcard to specify all members of a directory (<code>directoryname/*</code>) and not filename variations (<code>fileprefix*</code>). That may change in the future if <code>git svn</code> is revised to make use of SVN's new merge tracking.</p> <p>Because Git only stores a pointer to a commit for each branch (rather than a duplicate directory of the relevant files), your Git repo will be substantially smaller once you have repacked it, as the anonymous answer says. Unfortuately, Git can't store changesets for your Flash files like it does for text file commits, so they will be duplicated when they change.</p> <p>I suggest you use </p> <pre><code>$ git gc --aggressive </code></pre> <p>to repack your repo. It prunes duplicates and handles more optimizations than <code>git repack</code>.</p>
How do I write a User Defined Function? <p>I would like to write this as a user defined function:</p> <pre><code>private double Score(Story s){ DateTime now = DateTime.Now; TimeSpan elapsed = now.Subtract(s.PostedOn); double daysAgo = elapsed.TotalDays; return s.Votes.Count + s.Comments.Count - daysAgo; } </code></pre> <p>Is this possible to do with a UDF?</p>
<p>You can, but if you're using SQL Server 2000, you'll have to pass in the value of "now"--UDFs can't generate any non-deterministic values themselves <a href="http://wardyit.com/blog/blog/archive/2006/02/15/84.aspx" rel="nofollow">in SQL Server 2000</a>.</p> <p>This untested stab at it might be close:</p> <pre><code>CREATE FUNCTION dbo.GetStoryScore ( @Now DATETIME, @Posted DATETIME, @Votes INT, @Comments INT ) RETURNS FLOAT AS BEGIN RETURN @Votes + @Comments - DATEDIFF(HOUR, @Posted, @Now)/24.0 END </code></pre> <p>Example usage:</p> <pre><code>SELECT S.ID, dbo.GetStoryScore(GETDATE(), S.Posted, S.Votes, S.Comments) AS Score FROM Stories AS S WHERE ... </code></pre> <p>Notes: </p> <ul> <li><p>The datediff is performed in hours (not days) because the integer result gives you a little more precision when you use finer units.</p></li> <li><p>I passed in all the values because I've found lookups within functions to be a really, really bad thing for performance.</p></li> <li><p>When referenced in SQL, don't forget the <code>dbo.</code> in front of the function name.</p></li> <li><p>If you're using SQL Server 2005, you can remove the @Now variable and use GETDATE() inline, instead.</p></li> </ul>