instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have two tables: articles and articletags</p> <pre><code>articles: id, author, date_time, article_text articletags: id, tag (article.id == articletags.id in a many-to-many relationship) </code></pre> <p>I am after the last time that something was published under each tag. To put it another way, for every tag, look through all the articles it is related to and find the most recent and return that.</p> <p>eg articles:</p> <pre><code>1, me, 12 Nov, Sometext 2, me, 13 Nov, Sometext 3, me, 14 Nov, Sometext </code></pre> <p>article tags</p> <pre><code>1, foo 1, bar 2, foo 3, bar </code></pre> <p>I want to get back:</p> <pre><code>foo, 13 Nov bar, 14 Nov </code></pre> <p>I can get as far as an inner join and then am stumped. I dont think a DISTINCT clause is what I am after and I am not familiar enough for subqueries to know if that would help.</p> <pre><code>SELECT date_time, tag FROM articles, articletags WHERE articles.id = articletags.id </code></pre> <p>Is this even possible?</p>
<pre><code>select t.tag, max(a.date_time) as latest from articles a inner join articletags t on t.id = a.id group by t.tag </code></pre>
<pre><code>SELECT date_time, tag FROM articles, articletags WHERE articles.id = articletags.id ORDER BY date_time DESC GROUP BY tag </code></pre>
37,622
<p>Recently I tried CodeSmith templates for NHibernate. As many of you might watched, there is a video explaining how to create a Petshop.Data using these templates. My question is what is the correct architecture in this approach? Should we have a BLL (or Services) layer to interact with this Petshop.Data or directly call ManagerFactory in our presentation layer? Also should our presentation layer be unaware of Business Objects in our Petshop.Data and shoud we have Business Entities in BLL again?</p>
<p>I would say that a presentation layer can be aware of your Business Objects, but should not be aware of how they get populated from the database (but NHibernate takes care of that for you anyways). If you do use a Service Layer it gives you one more point of flexibility/control. I always use one.</p>
<p>I have had a similar experience with CodeSmith. Here's a blog entry I made: <a href="http://hypertrends.com/Blog/post/2008/12/15/CodeSmith-to-create-NHibernate-Mappings-Honest-Thoughts.aspx" rel="nofollow noreferrer">http://hypertrends.com/Blog/post/2008/12/15/CodeSmith-to-create-NHibernate-Mappings-Honest-Thoughts.aspx</a></p>
37,576
<p>If I call <code>finalize()</code> on an object from my program code, will the <strong>JVM</strong> still run the method again when the garbage collector processes this object?</p> <p>This would be an approximate example:</p> <pre><code>MyObject m = new MyObject(); m.finalize(); m = null; System.gc() </code></pre> <p>Would the explicit call to <code>finalize()</code> make the <strong>JVM</strong>'s garbage collector not to run the <code>finalize()</code> method on object <code>m</code>?</p>
<p>According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:</p> <pre><code>private static class Blah { public void finalize() { System.out.println("finalizing!"); } } private static void f() throws Throwable { Blah blah = new Blah(); blah.finalize(); } public static void main(String[] args) throws Throwable { System.out.println("start"); f(); System.gc(); System.out.println("done"); } </code></pre> <p>The output is:</p> <blockquote> <p>start<br> finalizing!<br> finalizing!<br> done</p> </blockquote> <p>Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.</p>
<p>The finalize method is never invoked more than once by a JVM for any given object. You shouldn't be relying on finalize anyway because there's no guarantee that it will be invoked. If you're calling finalize because you need to execute clean up code then better to put it into a separate method and make it explicit, e.g:</p> <pre><code>public void cleanUp() { . . . } myInstance.cleanUp(); </code></pre>
4,847
<p><strong>Given:</strong> Constructing an ADO Connection object from one thread and giving it to another thread is <strong><em>forbidden</em></strong>. The two threads are different apartments, and even though the first thread will <strong>never</strong> touch it again (not even maintain a reference to it!), it doesn't matter. </p> <p>That ADO Connection object was created by ThreadA, ThreadA is the only thread, ever, under any circumstances, at all, ever, that is allowed to use that Connection object, ever.</p> <p>Now replace "ADO Connection" with "ADO.NET Connection". Does the same rule apply?</p> <hr> <p>i know that most objects in the .NET framework are not thread-safe. For example, the <a href="http://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx" rel="nofollow noreferrer">DictionaryEntry</a> structure in the SDK says: </p> <blockquote> <p><strong>Thread Safety</strong><br> Any public <strong>static</strong> members of this type are thread safe. Any instance members are not guaranteed to be thread safe.</p> </blockquote> <p>i understand that <strong>not thread-safe</strong> means that i have to synchronize access to the object if i am going to access it from different threads. That's all well and good, and i could ensure only one thread access the object at a time:</p> <pre><code>lock (myObject) { ... } </code></pre> <p>But there's something more than not being thread-safe. </p> <p>In COM, (some) objects are bound to the "<em>apartment</em>" that created it. Once the object has been constructed on one apartment, you are <strong><em>forbidden</em></strong> from accessing it from another apartment - no matter how much you protect that object from multiple simultaneous thread access.</p> <p>Does a similar concept exist in .NET? </p> <hr> <h2>More Information</h2> <p>i know you are forbidden from accessing Controls from threads other than the one that created it - even if you use it in a thread-safe manner. This is not documented on MSDN:</p> <blockquote> <p><strong>Thread Safety</strong></p> <p>Only the following members are thread safe: BeginInvoke, EndInvoke, Invoke, InvokeRequired, and CreateGraphics if the handle for the control has already been created. Calling CreateGraphics before the control's handle has been created on a background thread can cause illegal cross thread calls.</p> </blockquote> <p>There is no mention of Controls throwing exceptions when you create and use them from a single thread - when that thread is not the first thread that was created when the application started.</p> <p>But what about arbitrary objects? What about:</p> <pre><code>public class MyClass { int _number; public int Number { get { return _number; } set { _number = value; } } } MyClass myObject = new MyClass(); </code></pre> <p>As long as i synchronize access to myObject two threads are allowed to talk to it?</p> <hr> <p>The same goes for:</p> <pre><code>List&lt;Object&gt; sharedList = new List&lt;Object&gt;(); </code></pre> <p>Two threads can talk to the list, as long as they don't do it simultaneously, usually with:</p> <pre><code>lock (sharedList) { sharedList.Add(data); } </code></pre> <p>are two threads allowed to touch the same object?</p> <hr> <p>The same goes for:</p> <pre><code>IAsyncResult ar = BeginSetLabelToTheValueINeed(label1); ... EndSetLabelToTheValueINeed(ar); </code></pre> <hr> <p>The same goes for:</p> <pre><code>//Fetch image on connection that is an existing DB transaction public static Bitmap GetImageThumbnail(DbConnection conn, int imageID) { } </code></pre> <p>being converted into the asynchronous delegate pattern:</p> <pre><code>//Begin fetching an image on connection that is an existing DB transaction IAsyncResult ar = BeginGetImageThumbnuts(conn, imageID, callback, stateOjbect); ... //Finish fetching an image on connection that is an existing DB transaction Bitmap thumb = EndGetImageNumbthail(ar); </code></pre> <hr> <p>Rather than answering the question, people went off on a discussion about design patterns in ADO.NET. Please answer the question. Ignore the examples if they confuse and distract your squirrel brains.</p>
<p>SHOOTING for the bounty!</p> <p>Okay, some classes/frameworks of classes in .NET have methods that are apartment bound, but BY DESIGN ONLY. That means you have to SPECIFICALLY CODE to do this. Its not set by default. Coding for this is kinda kludgy. You have to get the thread ID you want to stick with and check it all the time. I don't think there are any facilities in the framework that makes this easy, other than those for UI components tracking the UI thread. That support framework is probably buried deep within the UI stack; I've never seen it in any MSDN docs.</p> <p>What IS more common is setting the thread apartment. Lots of parts of the entire framework are restricted to STA threads by design (<a href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" rel="nofollow noreferrer">STAThreadAttribute</a>). This is usually because they, deep down in their core, touch COM objects which often require that they are only used in STA threads. For example, the main thread in winforms apps is marked with the STAThreadAttribute, so that every UI component can only be touched within the same thread they are created, the UI thread. Interestingly, the XamlReader in WPF is aware of the current thread apartment and won't even deserialize UI components unless the thread its running in is an STA thread.</p> <p>"Does a standard POCO have thread affinity or care if its in a STA or MTA thread?" The answer is no, unless you code it to be so or mark its methods with the STAThreadAttribute <em>or if the object is instantiated in a call stack that, somewhere in its hierarchy, has a method marked with the STAThreadAttribute</em>.</p> <p>"Does an ADO.NET object have thread affinity, and is it apartment aware?" </p> <p>Well, a DbConnection extends from Component, which extends MarshalByRefObject. Component, MBRO, DbConnection and its descendents (i.e., SqlConnection) contain no methods that are marked with the STAThreadAttribute. A quick check of their major dependencies (such as DbTransaction) doesn't find that any of THOSE classes' methods are marked as STA only as well. Therefore they are not apartment aware.</p> <p>A quick browse with Reflector doesn't find any obvious thread-id watching. DbConnection does depend on Transaction, which seems like the most likely thread-fondler of the bunch.</p> <p>I busted out Reflector and checked out a few of these classes.<br> DbConnection - Doesn't care about the current thread's ID<br> SqlConnection - Does some thread tracking when debugging<br> SqlTransaction - Has a function called "ZombieCheck", but no thread watching<br> DbTransaction - Nothing here.</p> <p>So I think its safe to say that ADO.NET objects do NOT have thread affinity. I didn't even see them use <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.beginthreadaffinity.aspx" rel="nofollow noreferrer">Thread.Begin/EndThreadAffinity</a>. </p> <hr> <p><strong>EDIT</strong></p> <p>As pointed out in the comments by Jeremy, I kept talking about the CLASSES being marked with the attribute rather than the CLASSES' METHODS. HUUUGE mistake. I screwed up bigtime by giving the impression that I only looked at the class definitions rather than the entire class.</p> <p>I've edited this to clarify, and let me say it here to be absolutely clear: No class methods in System.Data are marked with the STAThreadAttribute. You can check this for yourself with the following hacky code:</p> <pre><code>SqlConnection sc = new SqlConnection(); var data = AppDomain.CurrentDomain.GetAssemblies() .Where(x =&gt; x.FullName.StartsWith("System.Data,")).First(); var dtypes = data.GetTypes(); var results = new List&lt;string&gt;(); foreach (var type in dtypes) foreach (var method in type.GetMethods()) foreach (var attr in method.GetCustomAttributes(true).OfType&lt;System.Attribute&gt;()) { results.Add(string.Format("{0} {1} {2}", type.Name, method.Name, attr.GetType().Name)); if (attr.GetType() == typeof(STAThreadAttribute)) throw new Exception("SHIII"); } </code></pre> <p>Also, UI classes in winforms also don't use the STAThreadAttribute; its the application where this attribute is used (as, again, Jeremy pointed out). </p> <p>There is a special case where I've run into a class being apartment aware. The XamlReader, which deserializes xaml and creates WPF UI classes, will throw an exception when its Load method is called on a MTA thread. Its not even in the docs, which is annoying... So, again, classes aren't apartment aware by default; you have to code it that way or you have to make their instances aware by newing them up in a method chain containing a method marked by the STAThreadAttribute. Whew. This stuff is harder to explain than understand...</p>
<p>Why would you want to create a connection on one thread and use it from another? </p> <p>The time between connection creation/open and close/dispose should be minimal as is possible, so handing it off to another thread does not sound like a good idea regardless of whether or not its possible. </p>
39,463
<p>Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.</p> <p>I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user and passed onto the function. Here is my basic read in function:</p> <pre><code>template &lt;class T, class U&gt; void get_list(vector&lt;T&gt;&amp; v, const char *inputFile, U) { ifstream myFile; T object; myFile.open("inputFile") while(!myFile.eof()) { myFile &gt;&gt; object; insert(v, object, U) } } </code></pre> <p>insert is just another function that will go through and insert the data into my data structure. I just want to make sure this is the best way to pass that data on if it will even work.</p>
<p>It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself?</p>
<p>Don't use <code>.eof()</code> on a stream in a <code>while</code>-condition. The condition will evaluate to true only <em>after</em> an attempt to read past the end of the file has been made. a better way is to do </p> <pre><code>while(myFile &gt;&gt; object) insert(v, object, U); </code></pre> <p>Your use of <code>U</code> is flawed. I have no idea what it is used for. One time it is used as a type, but then another time you pass it to the <code>insert</code> function as a value. </p>
35,785
<p>I'm building few command-line utilities in Xcode (plain C, no Cocoa). I want all of them to use my customized version of libpng, and I want to save space by sharing one copy of the library among all executables (I don't mind re-distributing <code>.dylib</code> with them).</p> <p>Do I need to do some magic to get libpng export symbols?</p> <p>Does <em>"Link Binary With Libraries"</em> build phase link statically? </p> <p>Apple's docs mention loading of libraries at run time with <code>dlopen</code>, but how I can make Xcode create executable without complaining about missing symbols?</p> <hr> <p>I think I've figured it out:</p> <ul> <li><p>libpng wasn't linking properly, because I've built 32/64-bit executables and 32-bit library. Build settings of the library and executables must match.</p></li> <li><p>libpng's config.h needs to have tons of defines like <code>#define FEATURE_XXX_SUPPORTED</code></p></li> <li><p><em>"Link Binary With Libraries"</em> build phase handles dynamic libraries just fine, and <code>DYLD_FALLBACK_LIBRARY_PATH</code> environmental variable is neccessary for loading <code>.dylib</code>s from application bundle.</p></li> </ul>
<p>Dynamic linking on Mac OS X, a tiny example</p> <p>Steps:</p> <ol> <li>create a library libmylib.dylib containing mymod.o</li> <li>compile and link a &quot;callmymod&quot; which calls it</li> <li>call mymod from callmymod, using DYLD_LIBRARY_PATH and DYLD_PRINT_LIBRARIES</li> </ol> <p>Problem: you &quot;just&quot; want to create a library for other modules to use. However there's a daunting pile of programs -- gcc, ld, macosx libtool, dyld -- with zillions of options, some well-rotted compost, and differences between MacOSX and Linux. There are tons of man pages (I count 7679 + 1358 + 228 + 226 lines in 10.4.11 ppc) but not much in the way of examples, or programs with a &quot;tell me what you're doing&quot; mode.</p> <p>(The most important thing in understanding is to make a simplified OVERVIEW for yourself: draw some pictures, run some small examples, explain it to someone else).</p> <p>Background: <a href="https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html" rel="nofollow noreferrer">apple OverviewOfDynamicLibraries</a>, <a href="http://en.wikipedia.org/wiki/Dynamic_library" rel="nofollow noreferrer">Wikipedia Dynamic_library</a></p> <hr /> <p>Step 1, create libmylib.dylib --</p> <pre><code>mymod.c: #include &lt;stdio.h&gt; void mymod( int x ) { printf( &quot;mymod: %d\n&quot;, x ); } gcc -c mymod.c # -&gt; mymod.o gcc -dynamiclib -current_version 1.0 mymod.o -o libmylib.dylib # calls libtool with many options -- see man libtool # -compatibility_version is used by dyld, see also cmpdylib file libmylib.dylib # Mach-O dynamically linked shared library ppc otool -L libmylib.dylib # versions, refs /usr/lib/libgcc_s.1.dylib </code></pre> <hr /> <p>Step 2, compile and link callmymod --</p> <pre><code>callmymod.c: extern void mymod( int x ); int main( int argc, char** argv ) { mymod( 42 ); } gcc -c callmymod.c gcc -v callmymod.o ./libmylib.dylib -o callmymod # == gcc callmymod.o -dynamic -L. -lmylib otool -L callmymod # refs libmylib.dylib nm -gpv callmymod # U undef _mymod: just a reference, not mymod itself </code></pre> <hr /> <p>Step 3, run callmymod linking to libmylib.dylib --</p> <pre><code>export DYLD_PRINT_LIBRARIES=1 # see what dyld does, for ALL programs ./callmymod dyld: loaded: libmylib.dylib ... mymod: 42 mv libmylib.dylib /tmp export DYLD_LIBRARY_PATH=/tmp # dir:dir:... ./callmymod dyld: loaded: /tmp/libmylib.dylib ... mymod: 42 unset DYLD_PRINT_LIBRARIES unset DYLD_LIBRARY_PATH </code></pre> <p>That ends one tiny example; hope it helps understand the steps.<br /> (If you do this a lot, see <a href="http://en.wikipedia.org/wiki/Libtool" rel="nofollow noreferrer">GNU Libtool</a> which is glibtool on macs, and <a href="http://www.scons.org" rel="nofollow noreferrer">SCons</a>.)</p>
<p>Are you aware of the Apple reference page <a href="http://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/DynamicLibraries/index.html" rel="nofollow noreferrer">Dynamic Library Programming Topics</a>? It should cover most of what you need. Be aware that there a shared libraries that get loaded unconditionally at program startup and dynamically loaded libraries (bundles, IIRC) that are loaded on demand, and the two are somewhat different on MacOS X from the equivalents on Linux or Solaris.</p>
23,633
<p>I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service. I'm running it with jdk 1.6.0_07.</p> <p>It runs when I start it with tomcat6.exe.</p> <p>I got a vague error in the System Event Log on Windows.</p> <p>The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).</p>
<p>I'll bite it :-)</p> <p>Tomcat Service on windows is dependent on the MS C Runtime library msvcr71.dll. As long as it is in the path, the service will start just fine.</p> <p>Just to prevent your other windows to be forced to use this version of the runtime library, you might want to copy the DLL to just the tomcat bin path instead of windows\system32.</p>
<p>I copied the msvcr71.dll from the java home directory to the bin directory of the apache-tomcat install, and the service started after that.</p>
17,085
<p>I'm attempting to write a Python C extension that reads packed binary data (it is stored as structs of structs) and then parses it out into Python objects. Everything works as expected on a 32 bit machine (the binary files are always written on 32bit architecture), but not on a 64 bit box. Is there a "preferred" way of doing this?</p> <hr> <p>It would be a lot of code to post but as an example:</p> <pre><code>struct { WORD version; BOOL upgrade; time_t time1; time_t time2; } apparms; File *fp; fp = fopen(filePath, "r+b"); fread(&amp;apparms, sizeof(apparms), 1, fp); return Py_BuildValue("{s:i,s:l,s:l}", "sysVersion",apparms.version, "powerFailTime", apparms.time1, "normKitExpDate", apparms.time2 ); </code></pre> <p>Now on a 32 bit system this works great, but on a 64 bit my time_t sizes are different (32bit vs 64 bit longs).</p> <hr> <p>Damn, you people are fast. </p> <p>Patrick, I originally started using the struct package but found it just way to slow for my needs. Plus I was looking for an excuse to write a Python Extension.</p> <p>I know this is a stupid question but what types do I need to watch out for?</p> <p>Thanks.</p>
<p>Explicitly specify that your data types (e.g. integers) are 32-bit. Otherwise if you have two integers next to each other when you read them they will be read as one 64-bit integer.</p> <p>When you are dealing with cross-platform issues, the two main things to watch out for are:</p> <ol> <li>Bitness. If your packed data is written with 32-bit ints, then all of your code must explicitly specify 32-bit ints when reading <em>and</em> writing.</li> <li>Byte order. If you move your code from Intel chips to PPC or SPARC, your byte order will be wrong. You will have to import your data and then byte-flip it so that it matches up with the current architecture. Otherwise 12 (<code>0x0000000C</code>) will be read as 201326592 (<code>0x0C000000</code>).</li> </ol> <p>Hopefully this helps.</p>
<p>Why aren't you using the <a href="http://docs.python.org/lib/module-struct.html" rel="nofollow noreferrer">struct</a> package?</p>
16,380
<p>I've done several flash projects working as the ActionScripter with a designer doing all the pretty things and animation. When starting out I found quite a lot of information about ActionScript coding and flash design. Most of the information available seems to focus on one or the other.</p> <p>I didn't find any information about building flash projects in a way that lets the coder do their thing AND gives the designer freedom as well.</p> <p>Hopefully more experienced people can share, these are some of the things i discovered after a few projects</p> <ul> <li>Version control is a must (as always) but can be difficult to explain to designers</li> <li>No ActionScript in the flash <code>.fla</code> files, they are binary and as a coder you want to try to keep away as much as possible</li> <li>Model View Controller is the best way I've found to isolate visual design changes</li> <li>Try to build the views so that they use frame labels, this allows the designer to decide what actually happens </li> </ul> <p>What are your experiences? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>I've been doing Flash for 9 years and I still find this a difficult thing to get right. </p> <p>There is a balance of power between designers and developers, which will inevitably tip one way or the other. </p> <p>If you work for a developer led studio, then you are lucky, as the designers will be instructed to make a design that fits your functionality. In Flex / MXML this is the only way to work.</p> <p>If, on the other hand, you work in a graphic design/creative/advertising studio, you will be instructed to build whatever the designer puts together in PhotoShop, whether or not it is feasible to build within the time.</p> <p>The key to getting around this is communication and education. Designers and design-focussed managers may not know what is involved in creating a particular piece of functionality, and if you explain to them why a particular thing is hard to do they <strong>might</strong> be persuaded to go and rethink their design. On the other hand, they may well think you're just a whiner! It never feels good when you have to tell someone "sorry, I can't really do that" when you know that you could make it work, given a few late nights!</p> <p>As well as the things you and others have already noted, like using FlashDevelop and external AS classes, here's some other things I recommend:</p> <ul> <li>Start with a site map / wireframe that both the developers and designers agree to.</li> <li>Load all your text from XML into dynamic text fields, and make sure your buttons etc are designed to expand to fit content</li> <li>Make sure your designers have some idea how to correctly cut-up graphics and lay them out in Flash. A developer shouldn't be messing about in PhotoShop when you're up against a deadline.</li> <li>Make sure you get all you graphics assets well before the deadline - inevitably there'll be things they've missed and things that need changing.</li> <li>Be firm and don't let your design team try to sneak in extra features at the last minute.</li> <li>Let the designers use the timeline for character animation etc, but for simple tweens use an ActionScript tweening engine.</li> </ul> <p>Hope these tips are some use!</p>
<p>On our team everyone uses TortoiseSVN and a Trac instance per project. Designers are using the standard Flash designer to edit .FLAs and developers are using <a href="http://www.flashdevelop.org/community/" rel="nofollow noreferrer">FlashDevelop</a> to manage ActionScript files and debug the project.</p> <p>The tool-chain works like this:</p> <ol> <li>Developers program the behavior of each window by hand-editing MXML files (it's not as hard as it sounds) and developing the corresponding .AS files at the same time.</li> <li>Designers make graphics for skins and other UI elements that get (link) exported and store them in .FLAs alongside the code.</li> <li>Developers [Import()] the resources in the .AS files.</li> </ol> <p>This way everything gets into source control and designers don't even look at a line of ActionScript. Off course I'm oversimplifying the process but I hope you'll get the idea.</p>
4,500
<p>I have ASP.Net code similar to the following (this is inside a FIELDSET):</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;... more of the same...&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I'm trying to keep my markup as clean as I possibly can, but I've decided that for various reasons, I need to wrap a DIV around everything in the list item after the first label, like this:</p> <pre><code>&lt;ol&gt; &lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;one or more form controls, ASP.Net controls, labels, etc.&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;div class="GroupThese"&gt; &lt;... more of the same...&gt; &lt;/div&gt; &lt;/li&gt; ... &lt;/ol&gt; </code></pre> <p>I would rather do this with "unobtrusive Javascript" via jQuery instead of littering my page with extra markup so I can keep the form semantically "clean".</p> <p>I know how to write a jQuery selector to get to the first label in each list item $("li+label") or use :first-child. I also know how to insert things after the selection.</p> <p>What I can't figure out (at least this late at night) is how to find everything after the first label in the list item (or basically everything in the list item except for the first label would be another way to put it) and wrap a DIV around that in the document ready function. </p> <p><strong>UPDATE:</strong></p> <p>Owen's code worked once I removed the single quotes from around: <pre>$('this')</pre> and set the proper decendent selector: <pre>$("li label:first-child")</pre> in order to only select the first label that occurs after a list item.</p> <p>Here is what I did:</p> <pre><code>$(document).ready(function() { $('li label:first-child').each(function() { $(this).siblings().wrapAll('&lt;div class="GroupThese"&gt;&lt;/div&gt;'); }); }); </code></pre>
<p><strong>edit</strong>: corrected code (see old code in revision history and comments for more info)</p> <p>ok this should work:</p> <pre><code>$('li label:first-child').each(function() { $(this).siblings().wrapAll('&lt;div class="li-non-label-child-wrapper"&gt;'); }); </code></pre> <p>from:</p> <pre><code>&lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;div&gt;stuff&lt;/div&gt; &lt;div&gt;other stuff&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;div&gt;stuff3&lt;/div&gt; &lt;/li&gt; </code></pre> <p>produces:</p> <pre><code>&lt;li&gt; &lt;label&gt;Some label&lt;/label&gt; &lt;div class="li-non-label-child-wrapper"&gt; &lt;div&gt;stuff&lt;/div&gt; &lt;div&gt;other stuff&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;label&gt;Another label&lt;/label&gt; &lt;div class="li-non-label-child-wrapper"&gt; &lt;div&gt;stuff3&lt;/div&gt; &lt;/div&gt; &lt;/li&gt; </code></pre>
<p>One approach would be to just wrap everything inside the &lt;li&gt; and then move the label out, e.g.</p> <pre><code>var $div = $('li').wrapInner('&lt;div&gt;&lt;/div&gt;').children('div'); $div.children('label').prependTo($div.parent()); </code></pre>
25,932
<p>I am developing an application with VS208 for different Oracle versions. I am wondering if I need to install different version of ODAC to do this, or does the latest release has backward compatibility? Thanks in advance,</p>
<p>According to the <a href="http://www.oracle.com/technology/software/tech/windows/odpnet/install11106.html" rel="noreferrer">system requirements</a>, it should work with 9i and up. I've accessed a 10g database using 11g before without problem. Although I should note that I didn't really do a whole lot with it.</p>
<p>ODAC 11g will work (is backward compatible) with databases back to version 9.2. In general, unless you have a very compelling reason, it is a good idea to use the latest version if ODAC that you can to take advantages of bug fixes and new features.</p> <p>Christian Shay</p> <p>Oracle</p>
37,363
<p>In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.</p> <p>I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?</p>
<p>This works for MSVC++ and <code>g++</code>: </p> <pre><code>#if defined(_M_X64) || defined(__amd64__) // code... #endif </code></pre>
<p>If your using Windows, your probably better to get the "PROCESSOR_ARCHITECTURE" environment variable from the registry because sizeof(PVOID) will equal 4 if its a 32bit process running on a 64bit operating system (aka WOW64):</p> <pre><code> if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SYSTEM\CurrentControlSet\\Control\\Session Manager\\Environment"), 0, KEY_READ, &amp;hKey) == ERROR_SUCCESS) { LPSTR szArch = new CHAR[100]; ZeroMemory(szArch, 100); if (RegQueryValueEx(hKey, _T("PROCESSOR_ARCHITECTURE"), NULL, NULL, (LPBYTE)szArch, &amp;dwSize) == ERROR_SUCCESS) { if (strcmp(szArch, "AMD64") == 0) this-&gt;nArchitecture = 64; else this-&gt;nArchitecture = 32; } else { this-&gt;nArchitecture = (sizeof(PVOID) == 4 ? 32 : 64); } RegCloseKey(hKey); } </code></pre>
19,718
<p>I'm trying to get a sampling of what people think are the best sign-up forms. Good design, usability. Smart engineering. Helpful feedback.</p>
<p>One of my all-time fave sign-up forms was the original <a href="http://www.vox.com/" rel="nofollow noreferrer">Vox</a> one, which has since been changed; there was <a href="http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html" rel="nofollow noreferrer">a great break-down</a> of it published online, and it goes into the things that made it so great to me. How they implemented the CSS layout of their forms, how they used in-form validation with pop-up tips, etc. -- it was nice.</p>
<p>A couple of examples I find interesting are <a href="http://www.tripit.com" rel="nofollow noreferrer">Tripit</a>, a site for organizing your travel plans. Although there is a link to Sign-up for the service the easiest and quickest way is to forward a confirmation email from a travel service (orbitz, travelocity, united.com, hertz.com etc), doing this will automatically sign you up and get you going (once you log in to the site it will ask for more info).</p> <p>Another quick and easy registration is Marco Arment's <a href="http://www.instapaper.com/user/register" rel="nofollow noreferrer">Instapaper</a>. All you need is to fill in your email address or username.</p>
13,123
<p>In other words may one use <code>/&lt;tag[^&gt;]*&gt;.*?&lt;\/tag&gt;/</code> regex to match the <code>tag</code> html element which does not contain nested <code>tag</code> elements?</p> <p>For example (lt.html):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;greater than sign in attribute value&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;1&lt;/div&gt; &lt;div title="&gt;"&gt;2&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Regex:</p> <pre><code>$ perl -nE"say $1 if m~&lt;div[^&gt;]*&gt;(.*?)&lt;/div&gt;~" lt.html </code></pre> <p>And screen-scraper:</p> <pre><code>#!/usr/bin/env python import sys import BeautifulSoup soup = BeautifulSoup.BeautifulSoup(sys.stdin) for div in soup.findAll('div'): print div.string $ python lt.py &lt;lt.html </code></pre> <p>Both give the same output:</p> <pre><code>1 "&gt;2 </code></pre> <p>Expected output:</p> <pre><code>1 2 </code></pre> <p><a href="http://www.w3.org/TR/html5/syntax.html#attributes2" rel="noreferrer" title="html attribute syntax">w3c</a> says:</p> <blockquote> <p>Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.</p> </blockquote>
<p>Yes, it is allowed (W3C Validator accepts it, only issues a warning).</p> <p>Unescaped <code>&lt;</code> and <code>&gt;</code> are also allowed inside comments, so such simple regexp can be fooled.</p> <p>If BeautifulSoup doesn't handle this, it could be a bug or perhaps a conscious design decision to make it more resilient to missing closing quotes in attributes. </p>
<pre><code>yeah except /&lt;tag[^&gt;]*&gt;.*?&lt;\/tag&gt;/ </code></pre> <p>Will not match a single tag, but match the first start-tag and the last end-tag for a given tag. Just like your first non-greedy tag-match, your in-between should be written non-greedy as well.</p>
12,012
<p>Normally when you update an object in linq2sql you get the object from a datacontext and use the same datacontext to save the object, right?</p> <p>What's the best way to update a object that hasn't been retreived by that datacontext that you use to perform the save operation, i.e. I'm using flourinefx to pass data between flex and asp.net and when object return from the client to be saved I don't know how to save the object?</p> <pre><code> public static void Save(Client client) { CompanyDataContext db = new CompanyDataContext(); Validate(client); if(client.Id.Equals(Guid.Empty)) { //Create (right?): client.Id = Guid.NewGuid(); db.Clients.InsertOnSubmit(client); db.SubmitChanges(); } else { //Update: OffertaDataContext db = new OffertaDataContext(); db.Clients.???? } } </code></pre> <p>Update: different approaches to use Attach doens't work in this case. So I guess a reflection based approach is required.</p>
<p>To update an existing but disconnected object, you need to "attach" it do the data context. This will re-use the existing primary key etc. You can control how to handle changes- i.e. treat as dirty, or treat as clean and track future changes, etc.</p> <p>The Attach method is on the table - i.e.</p> <pre><code>ctx.Customers.Attach(customer); // optional bool to treat as modified </code></pre>
<p>I am hoping you can help. I am developing a tiered website using Linq to Sql. I created a new class(or object) in DBML designer called memberState. This object is not an actual table in the database. I have this method in my middle layer:<br/><br/></p> <pre><code>public override IEnumerable(memberState) GetMembersByState(string @state)&lt;br/&gt; {&lt;br/&gt; using (BulletinWizardDataContext context = DataContext)&lt;br/&gt; {&lt;br/&gt; IEnumerable(memberState) mems = (from m in context.Members&lt;br/&gt; join ma in context.MemberAddresses&lt;br/&gt; on m.UserId equals ma.UserId&lt;br/&gt; join s in context.States&lt;br/&gt; on ma.StateId equals s.StateId&lt;br/&gt; where s.StateName == @state&lt;br/&gt; select new memberState&lt;br/&gt; {&lt;br/&gt; userId = m.UserID,&lt;br/&gt; firstName = m.FirstName,&lt;br/&gt; middleInitial = m.MiddleInitial,&lt;br/&gt; lastName = m.LastName,&lt;br/&gt; createDate = m.CreateDate,&lt;br/&gt; modifyDate = m.ModifyDate&lt;br/&gt; }).ToArray(memberState)();&lt;br/&gt; return mems; } } </code></pre> <p>The tables in my joins (Members, States, and MemberAddresses are actual tables in my Database). I created the object memberStates so I could use it in the query above (notice the <b>Select New memberState</b>. When the data is updated on the web page how do I persist the changes back to the Member Table? My Member Table consists of the following columns: UserId, FirstName, MiddleInitial, LastName, CreateDate, ModifyDate. I am not sure how save the changes back to the database.<br/><br/> </p> <p>Thanks,</p>
48,541
<p>Sure, we can use a simple bulleted list or a mindmap. But, there must be a better, more interactive way. What do you use when starting your website architecture?</p>
<p>From a physical and logical architecture standpoint, nothing beats the whiteboard, drawing up the layers/tiers of the application in boxes. Then create an electronic copy using Visio.</p> <p>After that, iteratively dive into each layer and design it using appropriate tools and techniques. Here are what I commonly use:</p> <ol> <li>Database: ERD</li> <li>Business Objects (and Service Contracts): UML class diagrams</li> <li>UI: prototypes &amp; wireframes</li> <li>Workflows and asynchronous operations: flowcharts and sequence diagrams</li> </ol>
<p>By "architecture", do you mean the initial site map? If not, please post a clarification and I'll edit my response.</p> <p>Our tech team starts development after our creative department has done their stuff. Part of what we get is output from the information architect. He passes off a graphical sitemap, a detailed sitemap as an Excel sheet, and a set of wireframes in a PDF.</p>
7,791
<p>What is a view in Oracle?</p>
<p>A <strong>View in Oracle</strong> and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query</p> <pre><code>SELECT customerid, customername FROM customers WHERE countryid='US'; </code></pre> <p>To create a view use the <strong>CREATE VIEW command</strong> as seen in this example</p> <pre><code>CREATE VIEW view_uscustomers AS SELECT customerid, customername FROM customers WHERE countryid='US'; </code></pre> <p>This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:</p> <pre><code>SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200; </code></pre> <p>And Oracle will transform the query into this:</p> <pre><code>SELECT * FROM (select customerid, customername from customers WHERE countryid='US') WHERE customerid BETWEEN 100 AND 200 </code></pre> <p><strong>Benefits of using Views</strong></p> <ul> <li>Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it’s less likely to require parsing. </li> <li>Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.</li> <li><a href="http://www.devx.com/tips/Tip/34429" rel="noreferrer">Predicate pushing</a></li> </ul> <p>You can find advanced topics in this article about "<a href="http://www.oracle-dba-online.com/sql/create_and_manage_views.htm" rel="noreferrer">How to Create and Manage Views in Oracle</a>."</p>
<p>A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.</p>
32,027
<p>How do you retrieve selected text using Regex in C#?</p> <p>I am looking for C# code that is equivalent to this Perl code:</p> <pre><code>$indexVal = 0; if($string =~ /Index: (\d*)/){$indexVal = $1;} </code></pre>
<pre><code>int indexVal = 0; Regex re = new Regex(@"Index: (\d*)") Match m = re.Match(s) if(m.Success) indexVal = int.TryParse(m.Groups[1].toString()); </code></pre> <p>I might have the group number wrong, but you should be able to figure it out from here.</p>
<pre><code>int indexVal = 0; Regex re = new Regex.Match(s, @"(&lt;?=Index: )(\d*)"); if(re.Success) { indexVal = Convert.ToInt32(re.Value); } </code></pre>
3,072
<p>I am writing my own control that will contain a panel with text, images and other media. What is the best way to render the text and images. The control may contain long texts and many images.<br> Should I add the text as labels and images as PictureBox or should I use the DrawString and DrawImage methods to render the text and images?<br> What's the best way to do this? </p>
<p>If you use labels, then you get all the labelly goodness for free.</p> <p>If you use DrawString, then it'll probably be (a little bit) faster, but it's a lot more complicated if you need to deal with things like the text changing.</p> <p>The OnPaint handler is a always a tricky one to write, and invalidating the client area is tricky to do efficiently. </p> <p>Why not let the labels handle it all for you?</p>
<p>I would use DrawString and DrawImage - you have less resources to worry about, but with added complexity.</p> <p>I don't think it's that bad drawing your own strings and images once you get into it.</p> <p>This is a nice introduction to it:</p> <p><a href="https://web.archive.org/web/20150116060854/http://bobpowell.net/" rel="nofollow noreferrer">https://web.archive.org/web/20150116060854/http://bobpowell.net/</a></p>
41,047
<p>I'm studying an introductory course in databases and one of the exercises is to work with MS-Access. However I'm using Linux at home and although I can use the computer classes at the university it is far from convenient (limited open time - my studying time is mostly nights).</p> <p>So how can I use an Access file (<code>*.mdb</code>) in Linux? By use I mean changing tables, writing queries and so on.</p> <p>Are there tools to convert it to another database format (mysql, postgresql or even gadfly)?</p> <p>Also what problems may I encounter?</p>
<p>Although a bit dated, I've had good success with <code>mdbtools</code> which is a set of command line tools for accessing and converting Access databases to other formats. I've used it for importing databases into PostgreSQL.</p> <p>If you're running an Ubuntu variant you can install it with:</p> <pre><code>sudo apt-get install mdbtools </code></pre> <p>or you can download it from <a href="http://sourceforge.net/projects/mdbtools/" rel="noreferrer">here</a>.</p>
<p>If you've got an assignment to work with Access, then frigging find a Windows computer and do your exercise on the native platform for Access. It's completely senseless to do anything else, as you won't be learning anything useful about Access.</p> <p>If the assignment is to use a Jet data store, then that's something of a different story. And if it is, then you should have worded your question differently. I wouldn't recommend using Jet on anything but a native Windows file system. Certainly if the project is to actually read/write data to a Jet data file then you're not really fulfilling the assignment if you're not using Windows at least as the ODBC host.</p>
49,398
<p>My page has two components that depend on JavaScript. On the left-hand side, there is attribute-based navigation (abn). And the right-hand side is the Result of the abn.</p> <p>There is an event handler for abn and an event handler for the result (both are on clicks) Whenever the user clicks on the abn, I do an Ajax call which returns a JSON object where the HTML result is a value of one of the key/value pair. The HTML is being inserted into the result component.</p> <p>The event handler for the result of the page works fine on a page refresh. It stops working when I insert the HTML content into the result slot after the Ajax call. I have verified that the result has all the divs and class that my JavaScript depends on.</p> <p>I think when I replaced the HTML content, the JavaScript handler just stop working. Can someone explain why this is happening and how I can solve this?</p>
<p>Did you insert an element with the same id (duplicate id)?</p>
<p>They are class, not div. And they have the same class. The event handler is not part of the result. The javascript is at the bottom of the page while the Result is at the top. So the javascript is sitll there. They are not being replaced.</p>
37,290
<p>I'm trying to take advantage of the constant memory, but I'm having a hard time figuring out how to nest arrays. What I have is an array of data that has counts for internal data but those are different for each entry. So based around the following simplified code I have two problems. First I don't know how to allocate the data pointed to by the members of my data structure. Second, since I can't use cudaGetSymbolAddress for constant memory I'm not sure if I can just pass the global pointer (which you cannot do with plain __device__ memory).</p> <pre><code> struct __align(16)__ data{ int nFiles; int nNames; int* files; int* names; }; __device__ __constant__ data *mydata; __host__ void initMemory(...) { cudaMalloc( (void **) &(mydata), sizeof(data)*dynamicsize ); for(int i=; i lessthan dynamicsize; i++) { cudaMemcpyToSymbol(mydata, &(nFiles[i]), sizeof(int), sizeof(data)*i, cudaMemcpyHostToDevice); //... //Problem 1: Allocate & Set mydata[i].files } } __global__ void myKernel(data *constDataPtr) { //Problem 2: Access constDataPtr[n].files, etc } int main() { //... myKernel grid, threads (mydata); } </code></pre> <p>Thanks for any help offered. :-)</p>
<p>I think constant memory is 64K and you cannot allocate it dynamically using <code>cudaMalloc</code>. It has to be declared constant, say,</p> <pre><code>__constant__ data mydata[100]; </code></pre> <p>Similarly you also don't need to free it. Also, you shouldn't pass the reference to it via pointer, just access it as a global variable. I tried doing a similar thing and it gave me segfault (in devicemu).</p>
<p>Why don't you just use the so-called "packed" data representation? This approach allows you to place all the data you need into one-dimension byte array. E.g., if you need to store</p> <pre><code>struct data { int nFiles; int nNames; int* files; int* names; } </code></pre> <p>You can just store this data in the array this way:</p> <pre><code>[struct data (7*4=28 bytes) [int nFiles=3 (4 bytes)] [int nNames=2 (4 bytes)] [file0 (4 bytes)] [file1 (4 bytes)] [file2 (4 bytes)] [name0 (4 bytes)] [name1 (4 bytes)] ] </code></pre>
34,110
<p>I am using a global named mutex for file access synchronization between an ASP.NET application and a console application.</p> <p>While running the ASP.NET application, the console application fails to acquire mutex - as expected. While running the console application, the ASP.NET application throws <code>UnauthorizedAccessException: Access to the path 'Global\TheNameOfTheMutex' is denied.</code> </p> <p>I will try to catch the exception and treat it like it failed to acquire the mutex, but I want to know why is it behaving like this? The ASP.NET application runs as expected if it is accessed from two different browsers and the console applications also runs as expected when running multiple instances.</p> <p><strong>Update:</strong> on Windows XP the exception is also thrown when the ASP.NET application is running and I try to start the console application.</p> <p>The code used for synchronization is in a common assembly:</p> <pre><code>using (Mutex m = new Mutex(false, "Global\\TheNameOfTheMutex")) // exception thrown { try { lock = m.WaitOne(0, false); } catch (AbandonedMutexException) { // ... } if(lock) { // ... m.ReleaseMutex(); } } </code></pre> <p>Environment: Windows Server 2008, IIS 7, ASP.NET 2.0</p>
<p>do you have the right user set up to access to the resources? using </p> <pre><code>MutexSecurity and MutexAccessRule ? </code></pre> <p>try looking at this on MSDN <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexsecurity.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexsecurity.aspx</a></p> <p>and <a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexaccessrule.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.mutexaccessrule.aspx</a></p> <p>p.s. I am awaiting a Jon Skeet answer to show my ignorance in the matter...=></p>
<p>Here the sample from <a href="https://stackoverflow.com/questions/778817/how-to-determine-if-a-previous-instance-of-my-application-is-running-c">How to determine if a previous instance of my application is running?</a> (see the <a href="https://stackoverflow.com/users/33080/romkyns">romkyns</a>' answer)</p> <pre><code> var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var mutexsecurity = new MutexSecurity(); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny)); mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny)); _mutex = new Mutex(false, "Global\\YourAppName-{add-your-random-chars}", out created, mutexsecurity); </code></pre>
46,382
<p>My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:</p> <pre><code>invoice.address_id = 1 invoice.address = some_address </code></pre> <p>Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling</p> <pre><code>attr_protected :address_id </code></pre> <p>is most likely not the solution since based on the documentation it only prevents mass assignments.</p> <p>Thanks!</p>
<p>You want <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001317" rel="noreferrer"><code>attr_readonly</code></a>.</p>
<p>Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable' method)</p> <pre><code>def address_id=(id) if new_record? write_attribute(:address_id, id) else raise 'address is immutable!' end end </code></pre>
16,632
<p>So I've got an application whose window behavior I would like to behave more like Photoshop CS. In Photoshop CS, the document windows always stay behind the tool windows, but are still top level windows. For MDI child windows, since the document window is actually a child, you can't move it outside of the main window. In CS, though, you can move your image to a different monitor fine, which is a big advantage over docked applications like Visual Studio, and over regular MDI applications.</p> <p>Anyway, here's my research so far. I've tried to intercept the WM_MOUSEACTIVATE message, and use the DeferWindowPos commands to do my own ordering of the window, and then return MA_NOACTIVATEANDEAT, but that causes the window to not be activated properly, and I believe there are other commands that "activate" a window without calling WM_MOUSEACTIVATE (like SetFocus() I think), so that method probably won't work anyway.</p> <p>I believe Windows' procedure for "activating" a window is 1. notify the unactivated window with the WM_NCACTIVATE and WM_ACTIVATE messages 2. move the window to the top of the z-order (sending WM_POSCHANGING, WM_POSCHANGED and repaint messages) 3. notify the newly activated window with WM_NCACTIVATE and WM_ACTIVATE messages.</p> <p>It seems the cleanest way to do it would be to intercept the first WM_ACTIVATE message, and somehow notify Windows that you're going to override their way of doing the z-ordering, and then use the DeferWindowPos commands, but I can't figure out how to do it that way. It seems once Windows sends the WM_ACTIVATE message, it's already going to do the reordering its own way, so any DeferWindowPos commands I use are overridden.</p> <p>Right now I've got a basic implementation quasy-working that makes the tool windows topmost when the app is activated, but then makes them non-topmost when it's not, but it's very quirky (it sometimes gets on top of other windows like the task manager, whereas Photoshop CS doesn't do that, so I think Photoshop somehow does it differently) and it just seems like there would be a more intuitive way of doing it.</p> <p>Anyway, does anyone know how Photoshop CS does it, or a better way than using topmost?</p>
<p>I havn't seen anything remarkable about Photoshop CS that requries anything close to this level of hacking that can't instead be done simply by specifying the correct owner window relationships when creating windows. i.e. any window that must be shown above some other window specifies that window as its owner when being created - if you have multiple document windows, each one gets its own set of owned child windows that you can dynamically show and hide as the document window gains and looses activation.</p>
<p>I would imagine they've, since they're not using .NET, rolled their own windowing code over the many years of its existence and it is now, like Amazon's original <a href="http://en.wikipedia.org/wiki/Obidos_(software)" rel="nofollow noreferrer">OBIDOS</a>, so custom to their product that off-the-shelf (aka .NET's MDI support) just aren't going to come close.</p> <p>I don't like answering without a real answer, but likely <strong>you'd have to spend a lot of time and effort to get something similar</strong> if Photoshop-like is truly your goal. Is it worth your time? Just remember <em>many</em> programmers over <em>many</em> years and versions have come together to get Photoshop's simple-seeming windowing behavior to work just right and to feel natural to you.</p> <p>It looks like you're already having to delve pretty deep into Win32 API functions and values to even glimpse at a "solution" and that should be your first red flag. Is it eventually possible? Probably. But depending on your needs and your time and a lot of other factors only you could decide, it may not be practical.</p>
18,556
<p>I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written...</p> <pre><code> for (var intElement = 0; intElement &lt; document.forms[0].elements.length; intElement = intElement + 1) { if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field { if (document.forms[0].elements[intElement].onblur()) { return false; break; } } } return true; </code></pre> <p>I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.</p> <p>The onblur method that is getting called looks like this...</p> <pre><code>function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode) { var tagCreditOrDebit; var tagIsTotal; var tagPercentageOrDecimal; eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal"); eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal"); if (tagPercentageOrDecimal.value == "P") { reaMax = Math.round((reaMax - 1) * 100); reaMin = Math.round((1 - reaMin) * 100); if (parseFloat(tagFactor.value) == 0) { alert("Please enter a value other than 0 or leave this field blank."); f_SetFocus(tagFactor); return false; } if (tagIsTotal.value == "True") { if (tagCreditOrDebit.checked) { if (parseFloat(tagFactor.value) &gt; reaMin) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } else { if (parseFloat(tagFactor.value) &gt; reaMax) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } } } return true; } </code></pre> <p><strong>EDIT:</strong> I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below...</p> <pre><code> if (!document.forms[0].elements[intElement].onblur()) </code></pre> <p>or</p> <pre><code> if (document.forms[0].elements[intElement].onblur()) </code></pre> <p>is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.</p>
<p>This question is a bit too involved for me at this time of the night, but I will give you this bit of advice:</p> <pre><code>eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); </code></pre> <p>This can be written in a MUCH better way:</p> <pre><code>tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"]; </code></pre> <p>In javascript, anywhere where you can use dotted syntax, you can use square brackets.</p> <pre><code>document.body; document['body']; var b = 'body'; document[b]; </code></pre> <p>Also, think about giving your forms some sort of identifier. I have no clue at all why <code>document.forms[0]</code> was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break!</p> <p>Other ways to do it include:</p> <pre><code>// HTML &lt;form name="myFormName"&gt; // Javascript var f = document.myFormName; </code></pre> <p>or</p> <pre><code>&lt;form id="myFormId"&gt; var f = document.getElementById("myFormId") </code></pre>
<p>First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that <a href="http://jquery.com" rel="nofollow noreferrer">jQuery</a> :)</p> <p>Second, start using a validation framework. For jQuery, <a href="http://docs.jquery.com/Plugins/Validation" rel="nofollow noreferrer">jQuery Validate</a> usually works really well. It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc.</p> <p><strong>Edit:</strong> As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. You should put this code on the onsubmit event instead.</p>
27,928
<p>I've created a webservice and when I want to use its methods I instantiate it in the a procedure, call the method, and I finally I dispose it, however I think also it could be okay to instantiate the webservice in the "private void Main_Load(object sender, EventArgs e)" event.</p> <p>The thing is that if I do it the first way I have to instantiate the webservice every time I need one of its methods but in the other way I have to keep a webservice connected all the time when I use it in a form for example. </p> <p>I would like to know which of these practices are better or if there's a much better way to do it</p> <p><strong>Strategy 1</strong></p> <pre><code>private void btnRead_Click(object sender, EventArgs e) { try { //Show clock this.picResult.Image = new Bitmap(pathWait); Application.DoEvents(); //Connect to webservice svc = new ForPocketPC.ServiceForPocketPC(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; svc.CallMethod(); ... } catch (Exception ex) { ShowError(ex); } finally { if (svc != null) svc.Dispose(); } } </code></pre> <p><strong>Strategy 2</strong></p> <pre><code>private myWebservice svc; private void Main_Load(object sender, EventArgs e) { //Connect to webservice svc = new ForPocketPC.ServiceForPocketPC(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; } private void btnRead_Click(object sender, EventArgs e) { try { //Show clock this.picResult.Image = new Bitmap(pathWait); Application.DoEvents(); svc.CallMethod(); ... } catch (Exception ex) { ShowError(ex); } } private void Main_Closing(object sender, CancelEventArgs e) { svc.Dispose(); } </code></pre>
<p>It depends on how often you are going to be calling the web service. If you're going to be calling it almost constantly, it would probably be better to use method #2. However, if it's not going to be getting called quite so often, you are better off using method #1, and only instantiating it when you need it.</p>
<p>Right now I made a solution for a mobile device and it turns to be used on irregular times, it could be used in 10 minutes, 1 hour, 4 hours its very variable, it seems that the better aproach is the first strategy.</p> <p>Last year we went on a project where we used webservices, the fact is that we instantiated our webservices at the Sub New() procedure and it run it very well, however, sometimes some users claimed at us that they woke up from their chairs and when they returned and tried to continue on the application they received a timeout error message and they had to re-login again.</p> <p>We thougth that maybe that was Ok because maybe the users went out for a very long time out of their seats, but once in a presentation of the application with the CEOs it happened exactly the same scenario and personally I didn't like that behaviour and that's why the question.</p> <p>Thanks for the answer.</p>
3,416
<p>Is it possible to programmatically push files to a wireless SD card - like a www.eye.fi card?</p> <p>I use a Mac and thought I could do this using some AppleScript - but have not found a way...</p> <p>Derek</p>
<p>The eye-fi card relies on image files being written to a specific directory in the card before they'll transfer them. Beyond that it works exactly like a memory card.</p> <p>Write a file to it as if you're writing a regular memory card, and as long as it's a jpg image file of reasonable size, and in an appropriate directory (something under \DCIM\ probably) and they should transfer.</p> <p>If you're having trouble, double check that it works with your camera, and find out where your camera puts the images on the card, and duplicate that. You might even try naming them similar names to the types of images your camera produces.</p> <p>-Adam</p>
<p>It looks like you can treat it just like an external hard drive (plug the memory card in and figure out where the mount point is).</p>
8,113
<p>For my apps, I store some configuration file in xml along with the assembly(exe), and something other temporary files for proccessing purpose. </p> <p>I found some quirk with <code>".\\"</code> and <code>Application.StartupPath</code>.</p> <p>I've been using </p> <pre><code>String configPath = ".\\config.xml"; </code></pre> <p>It works fine until I called <code>OpenFIleDialog</code> to open some files in other folders, the statement above failed. Apparently ".\" is referring to "CurrentDirectory", which changes every time when we browse to another folder.</p> <p>At some point, I was using </p> <pre><code>String configPath = Path.Combine(Application.StartupPath + "config.xml"); </code></pre> <p>At some point, when I need to execute this assembly from another folder by using <code>Process.Start()</code>, things start to fall apart. Apparently the working directory is not set properly, and <code>Application.StartupPath</code> is actually referring to working directory instead of the directory of which the assembly is executing, as I've assumed. So I have to resort to using ProcessInfo to setup the working directory to the assembly's directory. I also had problem with this when I was writing VSTO.</p> <p>So, my question is, what's the best, simplest and most assured way to get the current directory that the assembly is executing, without those quirks(or misunderstanding) that I've just mentioned?</p> <p>EDIT: I meant to get the directory which the assembly reside</p> <p>EDIT: According to MSDN on <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.basedirectory.aspx" rel="noreferrer">AppDomain.BaseDirectory</a>, it seems that it can be changes during runtime, which is what I don't want(Just to clarify, not that I don't want to allow changing BaseDirectory, but rather, when I retrieve it without knowing for sure whether it's been changed)</p> <p>EDIT: I've notice that a related question was posted much earlier. <a href="https://stackoverflow.com/questions/158219/what-would-cause-the-current-directory-of-an-executing-app-to-change">What would cause the current directory of an executing app to change?</a></p> <p>Thanks guys for the answer.</p>
<pre><code>System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) </code></pre>
<p>How about </p> <pre><code>string currentAssemblyFile = System.Reflection.Assembly.GetExecutingAssembly().Location; </code></pre> <p>and then figure it out from there...</p>
31,596
<p>Using the method <code>Application.Restart()</code> in C# should restart the current application: but it seems that this is not always working.</p> <p>Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?</p>
<p>There could be a lot of reasons for this. It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up. Two examples:</p> <ul> <li>The Closing event on a form can stop an app's shutdown</li> <li>If you're doing checking for an already-running process, the old one may not be closing fast enough to allow the new one to start up.</li> </ul> <p>Check your code for gotchas like that. If you're seeing this behaviour within a blank application, then that's more likely to be a problem with the actual function than your code.</p> <p>Check Microsoft's sourcecode of <a href="https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Application.cs,de3600ec6a11dcac" rel="nofollow noreferrer">application restart</a>.</p>
<p>I know this is an old thread, but I found a workaround. Hopefully this will help someone else in need. </p> <p>I needed a solution that would trigger the update sequence during a ClickOnce Application startup from code. <code>Applicatoin.Restart</code> did not do this. I wanted a way of being able to check for an update and then invoking the built in update manager so that I didn't have to write a custom one.</p> <pre><code> 'VB Code Sample Dim strStart As String = System.Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) &amp; "\Programs\Folder\YourApplication.appref-ms" Application.Exit() Try Process.Start(strStart) Catch ex As Exception 'Do something with the exception End Try </code></pre> <p>The only issue that I see with this workaround is that a user could delete the shortcut from the start menu. If that is a concern you could write some code to copy the start menu link to the some folder of your choosing, preferably in the ClickOnce application folder. This is important because the start menu icon for your application is not a .lnk or .exe, it is actually a .appref-ms link. See <a href="https://stackoverflow.com/questions/281173/clickonce-appref-ms-more-than-a-link-to-application-file">ClickOnce .appref-ms more than a link to .application file?</a> This link explains this in more detail.</p> <p>This code will work with ClickOnce SingleInstance Applications.</p>
12,072
<p>I got my Xampp server running and can run my html in subdirectories now, as well (can't have spaces in the subdirectory names).</p> <p><strong>SSI Includes or PHP Includes:</strong></p> <p>Xampp says SSI is deactivated. Tried uncommenting the lines for includes, but it doesn't change the deactivation.</p> <p>How do I activate SSI?</p> <p>Then, how do I implement either SSI include statements or PHP include statements into my html to call up html files that include html, images, javascript and commands that call other javascript menu files?</p>
<p>I don't know if Xampp has a special way of activating SSI or not, but the <a href="http://httpd.apache.org/docs/2.2/howto/ssi.html#configuring" rel="nofollow noreferrer">normal Apache way</a> should work.</p> <p>The normal way to include files in SSI is</p> <pre><code>&lt;!--#include virtual="/something/file.html" --&gt; </code></pre> <p>where the url to the file is actually <a href="http://www.example.com/something/file.html" rel="nofollow noreferrer">http://www.example.com/something/file.html</a> .</p>
<p>PHP includes are pretty straightforward. Just name your file something.php and do this:</p> <pre><code>&lt;?php include('path/to/file.php'); ?&gt; </code></pre> <p>The file will be parsed by php so it can contain the standard mix of PHP/HTML tags or whatever other text you'd like.</p>
40,419
<p>I have a form using multiple <code>&lt;cfinput type="datefield" ...&gt;</code>. They are positioned in such a way that the pop-up CSS calendar should appear over the field for others. However, the text fields for the other dates end up in front of the calendar.</p> <p>This is only an IE issue as Firefox and Safari work just fine.</p> <p>Is there a simple CSS hack or some other simple thing I can do to get the calendar to act as it should? Re-arranging the form is not very helpful.</p>
<p>Well, you have to encapsulate your datefield wirhin a div with both position:relative and Z-index value, as in :</p> <pre><code>&lt;div style="position:relative; z-index:3"&gt; &lt;cfinput type="dateField" name="info_dateDebutPub" value="#dateformat(info_dateDebutPub,'dd/mm/yy')#" mask="dd/mm/yy"&gt; &lt;/div&gt; </code></pre> <p>Defining Z-index within the Cfinput will not work.</p>
<p>My first inclination is to attempt to add a style for the text fields with a negative z-index. Alternately, you could attempt to apply a positive z-index to the popup.</p> <p>The first would probably be easier, given the way that the popups are written dynamically -- CF passes any unrecognized or unused attributes through to the browser, so you could just add a style. Something like:</p> <pre><code>&lt;cfinput type="datefiled" name="bob" value="" style="z-index: -1;"&gt; </code></pre> <p>Not tested, YYMV.</p>
25,709
<p>What is the differences between those 2 assuming I'm using SQL Server as my database? Are they the same?</p>
<p>This <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2008/07/01/linq-to-sql-more-useful-than-you-d-think.aspx" rel="nofollow noreferrer">post</a> points to some info. in particular 3 main differences:</p> <ul> <li><p>The ability to query relational stores other than Microsoft SQL Server</p></li> <li><p>A full textual query language not limited to LINQ's language support</p></li> <li><p>Advanced mapping facilities, such as mapping a single class to multiple tables</p></li> </ul>
<p>Long answer: google. Short answer: using entity framework, you will be able to create something based on classes (partial, that you can "extend") resembling domain objects (not true DDD though, that's why NHibernate still exists and linq to nhibernate is being developed), using sql you will be just thinking database and tables.</p>
38,489
<p><strong>Original Question</strong></p> <p>I am writting a logging class where the goal is to be able to do this:</p> <pre><code>// thread one Logger() &lt;&lt; "Some string" &lt;&lt; std::ios::hex &lt;&lt; 45; // thread two Logger() &lt;&lt; L"Some wide string" &lt;&lt; std::endl; </code></pre> <p>Currently my Logger header looks something like this:</p> <pre><code>#pragma once; #include &lt;ostream&gt; class Logger { public: Logger(); ~Logger(); std::ostream* out_stream; }; template &lt;typename T&gt; Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing) { *logger.out_stream &lt;&lt; thing; return logger; } </code></pre> <p>Some notes about this class:</p> <ol> <li>Cross platform compatibility is not an issue.</li> <li>Inside of Logger.cpp there is a singleton class that takes care of creating the "real" ostream.</li> <li>The Logger constructor and deconstructor perform the necessary locking of the singleton.</li> </ol> <p>I have three problems:</p> <ul> <li>How do I make the operator&lt;&lt; function a friend or member so I can set out_stream as private? </li> <li>How do I make the operator&lt;&lt; function work for manipulators?</li> <li>How can I add a specialization so that if T is a WCHAR* or std::wstring that it will convert it to char* or std::string before passing it to out_stream? (I can do the conversion. Losing high unicode characters isn't a problem in my case.)</li> </ul> <p><strong>Summary of things learned in answers:</strong></p> <ul> <li>Put template BEFORE friend instead of after.</li> <li>std::ios::hex is not a manipulator. std::hex is a manipulator.</li> </ul> <p><strong>End Result</strong></p> <pre><code>#pragma once #include &lt;ostream&gt; #include &lt;string&gt; std::string ConvertWstringToString(std::wstring wstr); class Logger { public: Logger(); ~Logger(); template &lt;typename T&gt; Logger&amp; operator&lt;&lt; (T data) { *out &lt;&lt; data; return *this; } Logger&amp; operator&lt;&lt; (std::wstring data) { return *this &lt;&lt; ConvertWstringToString(data); } Logger&amp; operator&lt;&lt; (const wchar_t* data) { std::wstring str(data); return *this &lt;&lt; str; } private: std::ostream* out; }; </code></pre>
<p>You can use friend definition, which will define the operator in the surrounding namespace of the class, and make it only visible to operator overloading resolution (not callable manually using the ::operator&lt;&lt;... syntax):</p> <pre><code>class Logger { public: Logger(); ~Logger(); std::ostream* out_stream; template &lt;typename T&gt; friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing) { *logger.out_stream &lt;&lt; thing; return logger; } /* special treatment for std::wstring. just overload the operator! No need * to specialize it. */ friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, const std::wstring &amp; wstr) { /* do something here */ } }; </code></pre> <p>The alternative, to keep your code as it is and just make the operator&lt;&lt; template a friend, you add this line into your class definition:</p> <pre><code>template &lt;typename T&gt; friend Logger&amp; operator&lt;&lt; (Logger&amp; logger, T thing); </code></pre> <p>For the manipulator problem, i will just give you my code i write some time ago:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; template&lt;typename Char, typename Traits = char_traits&lt;Char&gt; &gt; struct logger{ typedef std::basic_ostream&lt;Char, Traits&gt; ostream_type; typedef ostream_type&amp; (*manip_type)(ostream_type&amp;); logger(ostream_type&amp; os):os(os){} logger &amp;operator&lt;&lt;(manip_type pfn) { if(pfn == static_cast&lt;manip_type&gt;(std::endl)) { time_t t = time(0); os &lt;&lt; " --- " &lt;&lt; ctime(&amp;t) &lt;&lt; pfn; } else os &lt;&lt; pfn; return *this; } template&lt;typename T&gt; logger &amp;operator&lt;&lt;(T const&amp; t) { os &lt;&lt; t; return *this; } private: ostream_type &amp; os; }; namespace { logger&lt;char&gt; clogged(cout); } int main() { clogged &lt;&lt; "something with log functionality" &lt;&lt; std::endl; } </code></pre> <p>};</p> <p><b>Note that it is std::hex , but not std::ios::hex</b>. The latter is used as a manipulator flag for the <code>setf</code> function of streams. Note that for your example, tho, no special treatment of manipulators is required. The above special treatment of std::endl is only needed because i do stream the time in addition when std::endl is used.</p>
<p>why not do it the printf way and use the multi parameter method (with the three dots ...). This still gives you alot of formating power and doesnt make it that messy as when you are using the &lt;&lt;.</p> <p>For example:</p> <pre><code>Logger("This is my log msg %0X", 45); </code></pre> <p>Hang on two secs and ill pull up a code sample for you.</p> <p>Edit:</p> <pre><code>void Logger(const char* format, ...) { char szMsg[3000]; va_list args; va_start( args, format ); vsnprintf( szMsg, sizeof(szMsg) - 1, format, args ); va_end(args); // code to print szMsg to a file or whatever here } </code></pre> <p>If you want to use this as a class not a stand alone function you could overload the logger operator () and it will work just the same</p>
37,055
<p>Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed." I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it?</p>
<p>It sounds like an Add-in behaving badly. Can you launch it in safe mode?</p> <pre><code>devenv.exe /SafeMode </code></pre>
<p>Out of the blue i would guess a security/rights issue, eg. trying to create the solution on a drive/folder you don't have write access to, or has otherwise restricted rights.</p>
19,923
<p>How would you implement a GUI similar to the "My Computer" view in Windows Explorer?</p> <p>In particular the "Icons" view mode. Including the grouping of different item types (as Files Stored on This Computer/Hard Disk Drives/Devices with Removable Storage groups in Windows Explorer)</p> <p>In WinForms I would use a ListView for this thing but in WPF the only thing that has even come close is a listbox with a custom ControlTemplate but it seems like too much effort!</p>
<p>Have a TreeView with <a href="http://www.dev102.com/2007/12/27/how-to-use-hierarchical-datatemplate-in-wpf/" rel="nofollow noreferrer">HeirarchichalDataTemplate</a> defined for your FileSystem class</p>
<p>See FolderView, FileView, etc controls from <a href="http://www.ssware.com/megapack.htm" rel="nofollow noreferrer">Shell MegaPack.WPF</a></p> <p>It supports grouping and icons mode (among lots of other things).</p>
22,309
<p>I am trying to create a serial port in VB.net using code only. Because I am creating a class library I cannot use the built-in component. I have tried instantiating a new SeialPort() object, but that does not seem to be enough. I'm sure there is something simple I am missing and any help would be greatly appreciated! Thanks! </p> <p>P.S. I should add that the problem I am having at this time is getting the code to handle the datareceived event. Other than that it might be working, but I can't tell because of that problem.</p>
<p>If you want to use the events make sure you declare your serialPort object using the 'withevents'. The below example will allow you to connect to a serial port, and will raise an event with the received string. </p> <pre><code>Imports System.Threading Imports System.IO Imports System.Text Imports System.IO.Ports Public Class clsBarcodeScanner Public Event ScanDataRecieved(ByVal data As String) WithEvents comPort As SerialPort Public Sub Connect() Try comPort = My.Computer.Ports.OpenSerialPort("COM5", 9600) Catch End Try End Sub Public Sub Disconnect() If comPort IsNot Nothing AndAlso comPort.IsOpen Then comPort.Close() End If End Sub Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived Dim str As String = "" If e.EventType = SerialData.Chars Then Do Dim bytecount As Integer = comPort.BytesToRead If bytecount = 0 Then Exit Do End If Dim byteBuffer(bytecount) As Byte comPort.Read(byteBuffer, 0, bytecount) str = str &amp; System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1) Loop End If RaiseEvent ScanDataRecieved(str) End Sub End Class </code></pre>
<p>I have used the SerialPort .Net class in a past project and I worked fine. You really don't need anything else. Check the hardware setting in the control panel and make sure you instantiate the class with the same parameters.</p>
42,731
<p>I hate Physics, but I love software development. When I go back to school after Thanksgiving, I'll be taking two more quarters of Physics before I'm done with the horrid thing. I am currently reading postings on the F# units of measurement feature, but I've never used a language like F#. Would it be suitable to write applications so I can perhaps learn something about Physics while doing something I like?</p> <p>I'm interested in command-line applications (even those that I can just execute and have spit out an answer without needing inputs) for things like kinematics, planar motion, Newton's Laws, gravitation, work, energy, momentum and impulse, systems of particles, rotational kinematics and dynamics, angular momentum, static equilibrium, oscillatory motion, wave motion, sound, physical optics, electrostatics, Gauss' law, electric field and potential, capacitance, resistance, DC circuits, magnetic field, Ampere's law, and inductance.</p> <p>The reason I'm interested in F# is because of the units of measure functionality that the language provides.</p>
<p>In my biased opinion, F# is ideal for physics. It has a feature called Units of Measure which does dimensional analysis for you, providing errors if you get it wrong. For example if you write:</p> <pre><code>let distance : float&lt;meters&gt; = gravity * 3.0&lt;seconds&gt; </code></pre> <p>That would <strong>yield a compile-error</strong>, since gravity is &lt; meters/seconds^2 > and not &lt; meters >. This prevents a great deal of physics-related programming errors.</p> <p>For more information check out <a href="http://blogs.msdn.com/andrewkennedy/" rel="noreferrer">Andrew Kennedy's blog</a>.</p>
<p>Learning any computer language won't teach you physics, and you can learn physics by writing programs in any language.</p> <p>Dimensional analysis is a rather handy tool for physics problems, it can steer you away from being "not even wrong".</p> <p>I've always gained a certain perverse pleasure in getting an answer wrong by factors of 10^34 because I'd got my units wrong somewhere ;-)</p>
20,280
<p>I've read conflicting things on this.</p> <p>From Wikipedia:</p> <blockquote> <p>Controller Processes and responds to events, typically user actions, and may invoke changes on the model.</p> </blockquote> <p>It's the word TYPICALLY that is confusing. If not just user input, then what else?</p>
<p>I view the controller as a <em>Coordinator</em>, most of my code is usually in the controller. This is where the most of branches happen. In a View or Model, most of your code is going to deal with itself (a data object doesn't know anything about a view object). However a controller matches a data object (model) to a view object, hence my thoughts of it as a <em>coordinator</em>.</p> <p>A general 'test' one can apply to their application to see if they are following MVC enough: Is is very easy to re-skin your application? (Swap out the view without re-writing a whole bunch of code).</p> <p>Don't get caught up in all the religious debates and rigid 'rules' surrounding MVC, a product that makes money by only following 80% of MVC 'rules' is better than a product that isn't done yet and too complex to actually run right...</p>
<p>I call validating and sanitising user input part of the view.</p> <p>I call the controller the logic behind, the part that takes the validated, sanitised data, and does work with it. That way you can write a test harness that acts as the view, that supplies data to the controller and test the outcomes.</p>
46,544
<p>I have a <code>CMFCRibbonStatusBar</code> in my mainframe to which I add a <code>CMFCRibbonButtonsGroup</code> which again has a <code>CMFCRibbonButton</code>. This button has the same ID as a menu entry.</p> <p>Creating the button is done as follows:</p> <pre><code>CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup(); CMFCToolBarImages images; images.SetImageSize(CSize(32, 16)); // Non-square bitmaps if(images.Load(IDB_STATUSBAR_IMAGES)) { pBGroup-&gt;SetImages(&amp;images, NULL, NULL); } m_pStatusButton = new CMFCRibbonButton(ID_STATUS_SHOWSTATUS, _T(""), IMAGEINDEX_DEFAULTSTATUS); pBGroup-&gt;AddButton(m_pStatusButton); m_wndStatusBar.AddExtendedElement(pBGroup, _T("")); </code></pre> <p>I want to use this button as a status indicator.</p> <p>I want to display a tool tip in the following two cases:</p> <ul> <li>when the status changes and</li> <li>when the user moves the mouse over the button.</li> </ul> <p>I have no idea how to start in the first place. I have looked at the <code>ToolTipDemo</code> and <code>DlgToolTips</code> sample projects but couldn't figure out how to do it since all they do is display tooltips for the toolbar items or dialog buttons (<code>CWnd</code>-derived instead of <code>CMFCRibbonButton</code>).</p> <p>If you are familiar with the <code>ToolTipDemo</code> sample project: Since there seem to be several ways of doing things, I would prefer the tooltip to look like the "Extended Visual Manager-based" tool tip as <a href="http://img394.imageshack.us/my.php?image=tooltiptm7.png" rel="nofollow noreferrer">shown in this screenshot</a>.</p> <p>Thanks!</p>
<p>I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically.</p> <p>However if you want to have a nice looking tooltip like in your screenshot, you need to call <code>SetToolTipText</code> and <code>SetDescription</code>, like this:</p> <pre><code>CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, _T(""), 1); pBtn-&gt;SetToolTipText("This is the bold Title"); pBtn-&gt;SetDescription("This is the not-so-bold Description"); pGroup-&gt;AddButton(pBtn); </code></pre>
<p>I am using <code>CMFCRibbonButton</code> controls within a <code>CMFCRibbonButtonGroup</code>, which is added to the <code>CMFCRibbonStatusBar</code>. Take note of the 4th parameter in the <code>CMFCRibbonButton()</code> constructor, <code>bAlwaysShowDescription</code>, as this seems to affect the behavior depending upon whether <code>SetDescription()</code> has been called.</p> <p>Specifically, if <code>SetDescription()</code> has not been called, it doesn't matter whether <code>bAlwaysShowDescription</code> is TRUE or FALSE - the tool tip is displayed (as I would expect). If <code>SetDescription()</code> is set and <code>bAlwaysShowDescription</code> is FALSE, when hovering over the button the tool tip is displayed with the description below it.</p> <p>What seems counterintuitive given the name of this <code>bAlwaysShowDescription</code> parameter, is that when this is TRUE and <code>SetDescription()</code> is set, <strong>NEITHER</strong> the tool tip nor the description appear. I wonder if this is related to this post: <a href="https://connect.microsoft.com/VisualStudio/feedback/details/399646/cmfcribbonbutton-wont-show-tooltip-if-balwaysshowdescription-1" rel="nofollow">https://connect.microsoft.com/VisualStudio/feedback/details/399646/cmfcribbonbutton-wont-show-tooltip-if-balwaysshowdescription-1</a></p> <p>Hope this helps and you can achieve what you need with the different combinations of <code>bAlwaysShowDescription</code> parameter and whether <code>SetDescription()</code> is set.</p>
31,597
<p>I've notice an issue - it feels like a bug but I suspect a 'feature' - in SSMS in SQL Server 2008.</p> <p>I have various tabs open, for example an alter table script in one table and a SProc that queries that table in another tab, and when I execute my Alter Table script the changes are not reflected in Intellisense in the other tab.</p> <p>I can create new queries and the changes are still not reflected in Intellisense. If I open a new SSMS instance, the changes are reflected, until I make further changes, of course.</p> <p>However, if you over-rule Intellisense and push ahead with your modified tables and code, everything compiles without a grumble (as expected).</p> <p>Is this a bug? A feature? Is there a setting somewhere that alters this behaviour? I checked in the options but couldn't see anything</p>
<p><code>CTRL</code> + <code>SHIFT</code> + <code>R</code> to update the intellisense, for short.</p>
<p>Well done raising the issue - I have it frequently in VS 2008 SP1 but there coding the right name still produces an error squigly until the refresh happens - and I can't get it to do so at the moment. I suspect I need another shutdown/reload.</p>
45,458
<p>Which Eclipse package should I choose for Python development with <a href="http://www.pydev.org/" rel="nofollow noreferrer">PyDev</a>?</p> <p>Nothing on the Eclipse homepage tells me what to choose, and the PyDev documentation assumes I already have Eclipse installed. Does it matter which Eclipse package I choose?</p>
<p>If you just plan on doing Python dev, I'd just go with <a href="http://download.eclipse.org/eclipse/downloads/" rel="noreferrer">Platform Runtime Binary</a>.</p> <p>After that, I'd follow the instructions <a href="http://pydev.org/download.html" rel="noreferrer">http://pydev.org/download.html</a> and <a href="http://pydev.org/manual_101_root.html" rel="noreferrer">http://pydev.org/manual_101_root.html</a> to install PyDev.</p> <p>I use the same setup for Python development. I also have the RadRails plugin for Ruby on Rails development.</p>
<p>I use J2EE Eclipse for Python and Java development. It works well. But Classic Eclipse should be enought.</p>
30,237
<p>Which SQL statement is faster?</p> <pre><code>SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50 WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date ORDER BY c1.ID DESC OR SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price FROM (Table1 AS c1 INNER JOIN (Table2 AS c2 ........ INNER JOIN (Table49 AS c49 INNER JOIN Table50 AS c50 ON c49.Date = c50.Date) ........ ON c2.FullDate__ = c3.FullDate__) ON c1.FullDate__ = c2.FullDate__) ORDER BY c1.ID DESC"; </code></pre> <p>Basically I need to extract 2 rows from each table to produce a summary periodically. Which statement is faster?</p>
<p>What is faster is not having 50 tables to start with. Joining 50 tables might be ok, but it's a highly counter-intuitive design and probably not the most maintainable solution.</p> <p>Can you not store your data in rows (or columns) of a single (or fewer) tables rather than 50 tables??!</p>
<p>Ignore JOINs whenever possible. Performance wise, Join statements are not efficient at all.</p>
30,054
<p>For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.</p> <p>Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?</p> <p><strong>Edit:</strong> I wasn't specific enough to what I meant by fall-through. I use this type a lot:</p> <pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){ case 0: case 1: // Do something break; case 2: case 3: case 4: // Do something break; } </code></pre> <p>However, I'm concerned about something like this.</p> <pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){ case 0: case 1: // Do something, but fall through to the other cases // after doing it. case 2: case 3: case 4: // Do something else. break; } </code></pre> <p>This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.</p>
<p>It may depend on what you consider fallthrough. I'm ok with this sort of thing:</p> <pre class="lang-js prettyprint-override"><code>switch (value) { case 0: result = ZERO_DIGIT; break; case 1: case 3: case 5: case 7: case 9: result = ODD_DIGIT; break; case 2: case 4: case 6: case 8: result = EVEN_DIGIT; break; } </code></pre> <p>But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.</p> <p>And please note that I use the <a href="https://isocpp.org/wiki/faq" rel="noreferrer">C++ FAQ</a> definition of <a href="https://isocpp.org/wiki/faq/big-picture#defn-evil" rel="noreferrer">"evil"</a></p>
<p>In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.</p> <p>That being said, I've found them to be especially helpful when I know that <em>eventually</em> I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.</p> <p>It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no "reason" to.</p>
22,850
<p>I am fairly new to WPF and I am having a problem with inheriting from a user control.</p> <p>I created a User Control and now I need to inherit from that control and add some more functionality.</p> <p>Has anyone does this sort of thing before? Any help would be greatly appreciated.</p> <p>Thank you</p>
<p>Well .. you create your base control </p> <pre><code>public abstract class BaseUserControl : UserControl{...} </code></pre> <p>then in the XAML file :</p> <pre><code>&lt;Controls:BaseUserControl x:Class="Termo.Win.Controls.ChildControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Controls="clr-namespace:Namespace.Of.Your.BaseControl"&gt; </code></pre> <p>And that should work.</p> <p><strong>EDIT:</strong> Hmm.. this example is useful when you have a base control without XAML and then inherit from it. The other way around(from a base control with Xaml) - I'm not sure how you can go about it.</p> <p><strong>EDIT2:</strong> Apparently from <a href="http://michaelsync.net/2008/03/24/silverlight-2-beta1-user-control-inheritance" rel="noreferrer">this post + comments</a> i take that what you want might not be possible.</p>
<p>You can accomplish this by using a <code>delegate</code>.</p> <p>Essentially, you need to create an interface (<code>YourInterface</code>) which wraps up the functionality you want, then make both the user control and your class implement that interface.</p> <p>Next, make sure the user control has a reference to an object of type <code>IYourInterface</code>, so that when your user control attempts to invoke a method of the <code>Interface</code>, it calls your class' method.</p> <p>Because both the user control and class implement the same interface, they can be seen as the same kind of object - meaning you can put them both into a collection of objects of type <code>IYourInterface</code>. This should give you the behavior you want.</p> <p>In ASP.NET I use this technique often, by having my classes inherit from <code>abstract class</code> ancestors. I don't understand why WPF doesn't support this. :(</p>
33,794
<p>The following code is just a simplified example to demonstrate my problem:</p> <pre><code>using System; using System.IO; using System.Diagnostics; using System.Threading; namespace ConsoleApplication5 { class Program { static string LogFile = @"C:\test.log"; static void Main(string[] args) { for (int i = 0;i&lt;10;i++) { new Thread(new ParameterizedThreadStart(DoWork)).Start(i); } Console.ReadKey(); } static void DoWork(object param) { int count = (int)param; try { using (FileStream fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(DateTime.Now + " - Start " + count.ToString()); Thread.Sleep(2000); // simulate doing some work sw.WriteLine(DateTime.Now + " - End " + count.ToString()); } } catch (Exception e) { Console.WriteLine(count.ToString() + ": " + e.Message); return; } Console.WriteLine(count.ToString() + ": Done."); } } } </code></pre> <p>The problem here is that typically only one entry makes it into the file, even though I call the method 10 times. The file should be open to allow sharing. As far as I can tell no exceptions are thrown. What's going on?</p> <p>In the real code that this example shadows, each call to DoWork is actually in a separate process, though testing shows that the results are the same-- if I can fix it here I can fix it there.</p>
<p>There is nothing strange going on here. Imagine that you have a file "a.txt" and you open it in notepad 10 times. After that, you change the contents of the file and save it in every instance of notepad. Naturally, the last save you make is the one that is persisted to the file because it rewrites the previous 9 saves.</p> <p>I think you've got the same behavior here. All the files are opened at the same time because you have a Thread.Sleep in each processing. So the i file to be saved overwrites the previous save (i-1). </p> <p>EDIT: Try removing the Thread.Sleep(2000) and you'll have more logs in the file.</p>
<p>Use <code>SyncLock</code> which makes sure only one thread opens the file at a time. In the mean time the other processes do not crash but wait in a <code>queue</code>.</p>
37,892
<p>Is it possible in .NET to list files on a remote location like an URL? Much in the same way the System.IO classes work. All I need is the URLs to images that are on a remote server.</p>
<p><strong>Short answer:</strong> No, unless you have more control over that web-server</p> <p><strong>Long answer:</strong> Here are possible solutions...</p> <ol> <li><p>You will need server-side script that will do it locally and output this list in your preferred format.</p></li> <li><p>Most of the web-servers implement default file-browsing pages, so you could theoretically parse those but this solution will be very fragile and not very portable even between different versions of the same web-server.</p></li> <li><p>If you have FTP access...</p></li> </ol>
<blockquote> <p>Is it possible in .NET to list files on a remote location like an URL?</p> </blockquote> <p>You should specify which protocol we're talking about.</p> <p>For HTTP, lubos hasko provided the answer: no. HTTP has no concept of files; only of resources. If you have control over the web server, you can ask it to provide a directory listing, or, better yet, you can write code that lists the directory server-side for you. Without such control, you have to <em>rely</em> on the server to provide a listing, which 1) may be disabled for security reasons, 2) is non-standardized in its format, 3) will be, like lubos said, fragile to parse (<a href="http://en.wikipedia.org/wiki/Web_scraping" rel="nofollow noreferrer">"scrape"</a>).</p> <p>If you mean / if the server provides a protocol intended for file transfer, such as FTP, SMB/CIFS, etc., it'll be a lot easier. For example, for FTP, you'll want to look into <a href="http://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp.listdirectorydetails.aspx" rel="nofollow noreferrer">WebRequestMethods.Ftp.ListDirectoryDetails</a>.</p>
3,460
<p>I am calling a csh script that the first thing it does is starts a new group.</p> <p>I need to be able to see the standard output from the child process that is executed after the fork. I also want the parent process to 'hang' unitl the child process is finished.</p> <p>Here is the script (<code>razor_from_cgwin.sh</code>).</p> <p>(sort of)</p> <pre><code>newgrp name source /stuff/morestuff/stuffiwant razor -c thread -f Keil1403 -g lib . -o chmod +x * ./rz_build* &gt; server{me}:./razor_from_cgwin.sh &gt; server{me}: </code></pre> <p>What I want is this:</p> <pre><code>&gt;server{me}:./razor_from_cgwin &gt;(hang) &gt;any output from child forked process &gt;server{me}: </code></pre> <p>Razor is the CM I am using on the project I am working on. It is not important to this problem except that i need to start a new group to call it. I am calling the script (<code>./razor_from_cgwin.sh</code>) from a ssh session from CYGWIN :)</p>
<p>From your module you could call HttpContext.Current.Handler and see if it is a Page. You'd probably have to do this in the PostMapRequestHandler event or a later event in the life cycle.</p> <p>Alternatively, maybe you can check which HttpHandlerFactory is being used for the request. If it is the PageHandlerFactory, you can run your logic, and otherwise you can skip it.</p>
<p>IIS won't invoke the ASP.NET handler on images and scripts*, so a HTTPModule should only run on ASPX requests anyways.</p> <ul> <li>Unless you mean scripts served by as an embedded resource, ie webresource.axd.</li> </ul>
35,331
<p>How can I get list all the files within a folder recursively in Java? </p>
<p>Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles%28%29" rel="noreferrer">File.listFiles()</a> returns null for non-directories.</p> <pre><code>public static void main(String[] args) { Collection&lt;File&gt; all = new ArrayList&lt;File&gt;(); addTree(new File("."), all); System.out.println(all); } static void addTree(File file, Collection&lt;File&gt; all) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { all.add(child); addTree(child, all); } } } </code></pre> <p>Java 7 offers a couple of improvements. For example, <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29" rel="noreferrer">DirectoryStream</a> provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.</p> <pre><code>static void addTree(Path directory, Collection&lt;Path&gt; all) throws IOException { try (DirectoryStream&lt;Path&gt; ds = Files.newDirectoryStream(directory)) { for (Path child : ds) { all.add(child); if (Files.isDirectory(child)) { addTree(child, all); } } } } </code></pre> <p>Note that the dreaded null return value has been replaced by IOException.</p> <p>Java 7 also offers a <a href="http://docs.oracle.com/javase/tutorial/essential/io/walk.html" rel="noreferrer">tree walker</a>:</p> <pre><code>static void addTree(Path directory, final Collection&lt;Path&gt; all) throws IOException { Files.walkFileTree(directory, new SimpleFileVisitor&lt;Path&gt;() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { all.add(file); return FileVisitResult.CONTINUE; } }); } </code></pre>
<p>In JDK7, "more NIO features" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them. </p>
22,932
<p>We have two Tables:</p> <ul> <li>Document: id, title, document_type_id, showon_id</li> <li>DocumentType: id, name</li> <li>Relationship: DocumentType hasMany Documents. (Document.document_type_id = DocumentType.id)</li> </ul> <p>We wish to retrieve a list of all document types for one given ShowOn_Id. </p> <p>We see two possiblities:</p> <pre><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42 ); SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN ( SELECT Document.document_type_id FROM Document WHERE showon_id = 42 ); </code></pre> <p>Our question is: when and if is it better to use the DISTINCT to get the smaller record set versus retrieving the whole table and the IN statement walking the table to the first match. (We guess that's what it does ;-))</p> <p>Is this different for different databases, is there a common answer?</p> <p>Or is there a better way of doing it? (We are in .NET land)</p>
<p>You can use a join:</p> <pre><code>SELECT DISTINCT DocumentType.* FROM DocumentType INNER JOIN Document ON DocumentType.id=Document.document_type_id WHERE Document.showon_id = 42 </code></pre> <p>I think it's the best way to do it.</p>
<p>Follow up on <a href="https://stackoverflow.com/questions/181930/ms-sql-2k5-performance-distinct-or-full-table-in-where-in-statement#183155">Matt's answer</a>:</p> <p>I've enabled the query plan and tested the following four different queries that have come up so far:</p> <ul> <li><p><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN (SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42);</code></p></li> <li><p><code>SELECT DocumentType.* FROM DocumentType WHERE DocumentType.id IN (SELECT Document.document_type_id FROM Document WHERE showon_id = 42);</code></p></li> <li><p><code>SELECT DISTINCT DocumentType.* FROM DocumentType INNER JOIN Document ON DocumentType.id=Document.document_type_id WHERE Document.showon_id = 42;</code></p></li> <li><p><code>SELECT DocumentType.* FROM DocumentType WHERE EXISTS ( SELECT * FROM Document WHERE DocumentType.id=Document.document_type_id AND showon_id = 42);</code></p></li> </ul> <p>The query plan for all four queries turned out to be the same:</p> <pre><code> |--Hash Match(Right Semi Join, HASH:([Document].[document_type_id])=([DocumentType].[Id])) |--Hash Match(Inner Join, HASH:([Document].[Title], [Uniq1005])=([Document].[Title], [Uniq1005]), RESIDUAL:([Document].[Title] as [Document].[Title] = [Document].[Title] as [Document].[Title] AND [Uniq1005] = [Uniq1005])) | |--Index Seek(OBJECT:([Document].[IX_Document_3] AS [Document]), SEEK:([Document].[showon_id]=(1)) ORDERED FORWARD) | |--Index Scan(OBJECT:([Document].[IX_Document_1] AS [Document])) |--Table Scan(OBJECT:([DocumentType] AS [DocumentType])) </code></pre> <p>I am not sure what every line and element means, but it seems that from the performance perspective it does not matter how you construct the query for this kind of problem... </p>
21,975
<p>When writing j2me applications for cellphones, using <code>System.out.println()</code> prints on the console if using an emulator. However, when the code is deployed on a cellphone, where does the console output go?</p> <p>If it is impossible to see this in the untethered cellphone, is there a way to see it if the cellphone is still connected to the deploying PC [via USB] ?</p>
<p>I found <a href="https://stackoverflow.com/questions/120618/logging-in-j2me">this question</a> with answers on j2me logging. Maybe one can try this if nothing else works. A simple way to access <code>System.out.println()</code> would be nice though.</p>
<p>The only input I can offer is that this will differ greatly on each platform. I work mainly with BlackBerrys and System.err goes to the devices event log but I have no idea where System.out goes.</p>
15,453
<p>I have the whole MVC-Model set up and use HTML views as templates. But I have german strings in there that I would like to translate to other languages at some point.</p> <p>What is the best way to do this? I know I have to use Zend_Translate, but do I have to implement a single call to a translate function for every word that I have in my view templates?</p>
<p>First of all, I'd suggest to use complete phrases as the basis for your translation. With words you always have the problem that languages are not consistent when it comes to sentence structure. </p> <p>Then you have to choose one of the available Zend_Transalate adapters: Array, Csv, Gettext, Ini, Tbx, Tmx, Qt, Xliff or XmlTm. Most of them are adapters to industry standards for storing translation information, so it probably would suffice if you chose Array, Csv or Ini for the beginning and for the ease of use. Please see <a href="http://framework.zend.com/manual/en/zend.translate.adapter.html" rel="noreferrer">49.2.1. How to decide which translation adapter to use</a> in the Zend Framework manual.</p> <pre><code>// setup your translation $translate = new Zend_Translate('csv', '/my/path/source-de.csv', 'de'); $translate-&gt;addTranslation('/my/path/source-en.csv', 'en'); // add the translation adapter to the registry Zend_Registry::set('Zend_Translate', $translate); </code></pre> <p>As there is a <code>Zend_View_Helper_Translate</code> that access the standardized <code>Zend_Registry</code> entry <code>Zend_Translate</code> as the default translation source, you can use the following in your views:</p> <pre><code>[...] &lt;title&gt;&lt;?php echo this-&gt;translate('Title'); ?&gt;&lt;/title&gt; [...] &lt;p&gt;You can also do &lt;?php echo $this-&gt;translate('Hello %1$s', $this-&gt;userName); ?&gt;&lt;/p&gt; [...] </code></pre> <p>Please note that this only is a short introduction into <code>Zend_Translate</code> and by no means a complete presentation of the functionality provided by this component. For example there is a lot to be said about determining the locale the translation adapter will use.</p> <p>I'd suggest you read the following in the Zend Framework manual, because localization can be a complex issue and <code>Zend_Translate</code> can not be described entirely in here:</p> <ul> <li><a href="http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.translate" rel="noreferrer">53.4.1.13. Translate Helper</a> </li> <li><a href="http://framework.zend.com/manual/en/zend.translate.html" rel="noreferrer">Chapter 49. Zend_Translate</a></li> </ul>
<p>No, you don't have to translate every single word. The idea of translation in this sense is more a of a message translation idea.</p> <p>In my current project we do two types of translations. When it's just going to be a short text, we type that directly into the source code for purposes of readability.</p> <p>I.E.</p> <pre><code>&lt;?=$this-&gt;translate('Add');?&gt; &lt;?=$this-&gt;translate('Delete');?&gt; &lt;?=$this-&gt;translate('Are you sure you want to delete %1$s?', $thing);?&gt; </code></pre> <p>But if the message is much longer, we usually follow a standard to mark it for the translation system:</p> <pre><code>&lt;?=$this-&gt;translate('controller-action_form-information');?&gt; </code></pre> <p>The idea being that you can then replace that with a very long text in your translation tool and it keeps the view script tidy.</p>
39,537
<p>I have a table similar to this:</p> <pre><code>CREATE TABLE example ( id integer primary key, name char(200), parentid integer, value integer); </code></pre> <p>I can use the parentid field to arrange data into a tree structure.</p> <p>Now here's the bit I can't work out. Given a parentid, is it possible to write an SQL statement to add up all the value fields under that parentid and recurse down the branch of the tree ?</p> <p><strong>UPDATE:</strong> I'm using posgreSQL so the fancy MS-SQL features are not available to me. In any case, I'd like this to be treated as a generic SQL question.</p> <p>BTW, I'm very impressed to have 6 answers within 15 minutes of asking the question! Go stack overflow!</p>
<p>There are a few ways to do what you need in PostgreSQL.</p> <ul> <li><p>If you can install modules, look at the tablefunc contrib. It has a connectby() function that handles traversing trees. <a href="http://www.postgresql.org/docs/8.3/interactive/tablefunc.html" rel="noreferrer">http://www.postgresql.org/docs/8.3/interactive/tablefunc.html</a></p></li> <li><p>Also check out the ltree contrib, which you could adapt your table to use: <a href="http://www.postgresql.org/docs/8.3/interactive/ltree.html" rel="noreferrer">http://www.postgresql.org/docs/8.3/interactive/ltree.html</a></p></li> <li><p>Or you can traverse the tree yourself with a PL/PGSQL function.</p></li> </ul> <p>Something like this:</p> <pre><code>create or replace function example_subtree (integer) returns setof example as 'declare results record; child record; begin select into results * from example where parent_id = $1; if found then return next results; for child in select id from example where parent_id = $1 loop for temp in select * from example_subtree(child.id) loop return next temp; end loop; end loop; end if; return null; end;' language 'plpgsql'; select sum(value) as value_sum from example_subtree(1234); </code></pre>
<p>If you need to store arbitrary graphs, not just hierarchies, you could push Postgres to the side and try a graph database such as <a href="http://agraph.franz.com/support/learning/" rel="nofollow noreferrer">AllegroGraph</a>:</p> <p>Everything in the graph database is stored as a triple (source node, edge, target node) and it gives you first class support for manipulating the graph structure and querying it using a SQL like language. </p> <p>It doesn't integrate well with something like Hibernate or Django ORM but if you are serious about graph structures (not just hierarchies like the Nested Set model gives you) check it out. </p> <p>I also believe Oracle has finally added a support for real Graphs in their latest products, but I'm amazed it's taken so long, lots of problems could benefit from this model.</p>
7,653
<p>I've been making my way through <em>The Little Schemer</em> and I was wondering what environment, IDE or interpreter would be best to use in order to test any of the Scheme code I jot down for myself.</p>
<p><a href="http://racket-lang.org/" rel="noreferrer">Racket</a> (<a href="http://racket-lang.org/new-name.html" rel="noreferrer">formerly Dr Scheme</a>) has a nice editor, several different Scheme dialects, an attempt at visual debugging, lots of libraries, and can run on most platforms. It even has some modes specifically geared around learning the language.</p>
<p>LispMe works on a Palm Pilot, take it anywhere, and scheme on the go. GREAT way to learn scheme.</p>
8,402
<p>I've got many assemblies/projects in the same c#/.net solution. A setting needs to be saved by people using the web application gui, and then a console app and some test projects need to access the same file. Where should I put the file and how to access it?</p> <p>I've tried using "AppDomain.CurrentDomain.BaseDirectory" but that ends up being different for my assemblies. Also the "System.Reflection.Assembly.Get*Assembly.Location" fail to give me what I need.</p> <p>Maybe this isn't something I should but in a file, but rather the database? But it feels so complicated doing that for a few lines of configuration.</p>
<p>Put the file in </p> <pre><code> Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "[Company Name]\[Application Suite]"); </code></pre>
<p>Thought about storing it in the registry or in Isolated Storage? Not sure if multiple applications can share Isolated Storage or not, though.</p>
12,665
<p>This is a 3 part question regarding embedded RegEx into SQL statements. </p> <ol> <li><p>How do you embed a RegEx expression into an Oracle PL/SQL select statement that will parse out the “DELINQUENT” string in the text string shown below?</p></li> <li><p>What is the performance impact if used within a mission critical business transaction?</p></li> <li><p>Since embedding regex into SQL was introduced in Oracle 10g and SQL Server 2005, is it considered a recommended practice?</p></li> </ol> <hr> <p>Dear Larry :</p> <p>Thank you for using ABC's alert service.</p> <p>ABC has detected a change in the status of one of your products in the state of KS. Please review the information below to determine if this status change was intended.</p> <p>ENTITY NAME: Oracle Systems, LLC</p> <p>PREVIOUS STATUS: --</p> <p>CURRENT STATUS: DELINQUENT</p> <p>As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC so that we can discontinue our services.</p> <p>Kind regards,</p> <p>Service Team 1 ABC</p> <p>--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--</p> <p>Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information maintained by the responsible government agency or other sources of data upon which these alerts are based.</p>
<p>Why would you need regular expressions here? INSTR and SUBSTR will do the job perfectly.</p> <p>But if you convinced you need Regex'es you can use:</p> <p><a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions129.htm#i1239887" rel="nofollow noreferrer">REGEXP_INSTR</a><br> <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions130.htm#i1305521" rel="nofollow noreferrer">REGEXP_REPLACE</a><br> <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions131.htm#i1239858" rel="nofollow noreferrer">REGEXP_SUBSTR</a> </p> <p>(only available in Oracle 10g and up)</p> <pre><code>SELECT emp_id, text FROM employee_comment WHERE REGEXP_LIKE(text,'...-....'); </code></pre>
<p>Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightforward (and portable, since it's supported in older versions).</p> <p><a href="http://www.techonthenet.com/oracle/functions/instr.php" rel="nofollow noreferrer">http://www.techonthenet.com/oracle/functions/instr.php</a> and <a href="http://www.adp-gmbh.ch/ora/sql/substr.html" rel="nofollow noreferrer">http://www.adp-gmbh.ch/ora/sql/substr.html</a></p> <p><a href="http://www.databasejournal.com/features/mssql/article.php/3071531" rel="nofollow noreferrer">http://www.databasejournal.com/features/mssql/article.php/3071531</a> and <a href="http://msdn.microsoft.com/en-us/library/ms187748.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms187748.aspx</a></p>
9,868
<p>I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. </p> <p>Like this:</p> <pre><code>public interface IRepository&lt;T&gt; : IQueryable&lt;T&gt; { T Save(T entity); void Delete(T entity); } </code></pre> <p>Or this:</p> <pre><code>public interface IRepository&lt;T&gt; { T Save(T entity); void Delete(T entity); IQueryable&lt;T&gt; Query(); } </code></pre> <p>LINQ usage would be:</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;() where dos.Id == id select dos </code></pre> <p>Or...</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;().Query where dos.Id == id select dos </code></pre> <p>I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?</p>
<p>Depends on if you want a Has-A or an Is-A relationship.</p> <p>The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.</p>
<p>You could always quick write stuff against List, it's not mocking using a mock framework, but it sure works great.</p>
19,864
<p>I have seen two ways of implementing DAO-DVO design.</p> <p>1) DVO are objects and DAOs are instantiated using factories i.e DAOs are also objects 2) DVOs are again objects but in this case, DAOs are classes which contain only static methods which accept DVOs to perform tasks.</p> <p>I was wondering which way is better and more scalable.</p>
<p>Try the Spring Framework. DAOs are initialized via Dependency Injection and are just plain 'ole Java objects.</p> <p>Then, the methods on the DAO should just use Domain Objects that are used at all layers of the Application.</p>
<p>I would strongly recommend not using that many layers unless they are really layered physically. eg if you have something like a rich client where you need to send detached objects to update the GUI, otherwise, its a world of pain.</p>
4,428
<p>We have an <a href="http://www.r-project.org" rel="nofollow noreferrer">R Server</a> (R is a programming language used in statistical analysis) that basically takes a script and a csv file, processes some data and returns results as text.</p> <p>I need to write a service on the R server so that .net clients (could be .Net Windows Forms, or ASP.Net) can connect to the R server, submit the script and CSV file, and get the results back.</p> <p>I'm confused by the many different bindings available to me and information on the web seems to be sparse/scattered about what one to choose.</p> <p>Also, is it best to run the service in IIS, or as a separate "command line" type listener service (the latter seems ugly compared to IIS and I have no idea why anyone would choose to do this if they could run it in IIS)?</p>
<p>Personally, I'd recommend the simplest binding that gives what you need. I've done quite a lot of WCF (some quite complex), and I've never had to use anything other than BasicHttpBinding; this also allows that greatest possible compatibility with non-.NET clients, and lets you use things like MTOM for efficient binary transfer.</p> <p>Re hosting; IIS is indeed the simplest for a client/server setup; two particular strengths:</p> <ul> <li>easy to configure SSL (i.e. you just configure IIS, and WCF will use it)</li> <li>easy to load balance (just load balance your web farm)</li> </ul> <p>(I <em>believe</em> WCF running over BasicHttpProfile can also leverage your IIS compression [GZip/Deflate] setup, but don't quote me...)</p> <p>You might choose to use a standalone host (usually via a windows service) if (for example) you want a long-running stateful server. IIS has this habit (by design) of recycling the app-pools, which isn't good if you were keeping something in memory! Another example is where you want it to be already running for fast "first hit" performance (rather than waiting for IIS/ASP.NET to spin up). An example covering both of these might be hosting a WF (workflow) server.</p> <p>Again; if you don't need this complexity, go for the simplest option: hosting in IIS.</p>
<p>Extract from the book WCF4 of wros " All these built-in bindings are built on standars that work for specific scenarios, but will also work i you choose the wrong or less-efficient one. So how do you choose hich one is right for you?</p> <p>The most obvious decisión s if you need to interact with non-WCF applications. If your service is to communicate with WCF clients, then you can use on of the bindings prefixed with "net." Remember you can define several endpoints for the same service which would use different bindings. This allows you to take advantage of performance optimizations for WCF clients, but still provide support for ASMX services and WS-* standards. These provide further security and other features which many clients take advantage f.</p> <p>For example, if you want to establish a WCF to WCF communication, choosing a NetTcpBinding with a binary encoding akes the communication four or five time faster tan a BasicHttpBinding with text encoding.</p> <p>These WCF-provided bindings should cover most cases that you need:however, if you need to change or créate an entirely ne binding, WCF allows you do this very simply"</p>
29,418
<p>I know that to find all the <code>.h</code> files I need to use:</p> <pre><code>find . -name "*.h" </code></pre> <p>but how to find all the <code>.h</code> AND <code>.cpp</code> files?</p>
<pre><code>find . -name \*.h -print -o -name \*.cpp -print </code></pre> <p>or</p> <pre><code>find . \( -name \*.h -o -name \*.cpp \) -print </code></pre>
<pre><code>find . -regex ".*\.[cChH]\(pp\)?" -print </code></pre> <p>This tested fine for me in cygwin.</p>
35,093
<p>Address records are probably used in most database, but I've seen a number of slightly different sets of fields used to store them. The number of fields seems to vary from 3-7, and sometimes all fields are simple labelled address1..addressN, other times given specific meaning (town, city, etc).</p> <p>This is UK specific, though I'm open to comments about the rest of the world too. Here you need the first line of the address (actually just the number) and the post code to identify the address - everything else is mostly an added bonus.</p> <p>I'm currently favouring:</p> <ul> <li>Address 1</li> <li>Address 2</li> <li>Address 3</li> <li>Town</li> <li>County</li> <li>Post Code</li> </ul> <p>We could add Country if we ever needed it (unlikely).</p> <p>What do you think? Is this too little, too much?</p>
<p>The Post Office suggests (<a href="http://www.postoffice.co.uk/portal/po/content1?catId=19100182&amp;mediaId=19100267" rel="noreferrer">http://www.postoffice.co.uk/portal/po/content1?catId=19100182&amp;mediaId=19100267</a>) 7 lines: </p> <ul> <li>Addressees Name </li> <li>Company/Organisation</li> <li>Building Name </li> <li>Number of building and name of thoroughfare </li> <li>Locality Name</li> <li>Post Town </li> <li>Post Code</li> </ul> <p>They then say you do not need to include a County name provided the Post Town and Postcode are used.</p>
<p>It's very likely that a "UK" will be opened to Eire as well, and in some lines of business there will be legal differences, generally between Scotland / NI / the channel islands and England and Wales.</p> <p>In short, I would add country to the list. Otherwise it's fine (no fewer certainly), though of course any address is traceable from a building reference, a post code and a country alone.</p>
48,784
<p>I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.</p> <p>Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling on my home box or not ?</p> <p>What I am after is a way of defining a symbol, let's call it _ATHOME, automatically so I can do this:</p> <pre><code>#ifdef _ATHOME # define TEST_FILES "E:\\Test" # define TEST_SERVER "192.168.0.1" #else # define TEST_FILE "Z:\\Project\\Blah\\Test" # define TEST_SERVER "212.45.68.43" #endif </code></pre> <p><em>NB: This is for development and debugging purposes of course, I would never release software with hard coded constants like this.</em></p>
<p>On your home and work machines, set an environment variable <code>LOCATION</code> that is either "1" for home or "2" for work.</p> <p>Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable.</p> <p>Then in your code:</p> <pre><code>#if LOCATION==1 // home #else // work #endif </code></pre>
<p>I generally use config files, then just create a symlink to the appropriate configuration.</p>
14,489
<p>I have the following intentionally trivial function:</p> <pre><code>void ReplaceSome(ref string text) { StringBuilder sb = new StringBuilder(text); sb[5] = 'a'; text = sb.ToString(); } </code></pre> <p>It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?</p> <p>Or how else can I improve this?</p>
<p>C# strings are "immutable," which means that they can't be modified. If you have a string, and you want a similar but different string, you must create a new string. Using a StringBuilder as you do above is probably as easy a method as any.</p>
<p>I don't know if this is more efficient, but it works. Either way you'll have to recreate the string after each change since they're immutable.</p> <pre><code> string test = "hello world"; Console.WriteLine(test); test = test.Remove(5, 1); test = test.Insert(5, "z"); Console.WriteLine(test); </code></pre> <p>Or if you want it more concise:</p> <pre><code>string test = "hello world".Remove(5, 1).Insert(5, "z"); </code></pre>
30,437
<p>How to copy file(s) from one solaris 9 machine to another solaris 9 machine using only java?</p> <p>We have ssh access to both machines. The java program will run on one of those two machines.</p> <p>Update: rsync is not really an option. can't install it easily (UNIX team is, hum, hard to deal with)</p>
<p>.NET doesn't provide all Cultures/Regions out-of-the-box. Note the 'predefined' RegionInfos here: <a href="http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo(VS.80).aspx</a>. </p> <p>Unfortunately, if you want to use non-predefined Regions, you have to define them yourself. Here's the MSDN how-to: <a href="http://msdn.microsoft.com/en-us/library/ms172469(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms172469(VS.80).aspx</a>.</p>
<p><strike>Some</strike>All of the regions you missed are now supported (in newer versions of the .NET Framework and of the operating system).</p> <p>The following code finds all <code>RegionInfo</code> that are "reachable" from a specific culture:</p> <pre><code>foreach (var ri in CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(ci =&gt; new RegionInfo(ci.ToString())).OrderBy(x =&gt; x.TwoLetterISORegionName)) Console.WriteLine("{0,3}: {1,11}: {2} ({3})", ri.TwoLetterISORegionName, ri, ri.EnglishName, ri.NativeName); </code></pre> <p>On my machine right now it gives:</p> <p><PRE> 001: ar-001: World (العالم) 001: en-001: World (World) 001: eo-001: World (World) 001: ia-001: World (World) 001: la-001: World (World) 001: prg-001: World (swītai) 001: vo-001: World (World) 001: yi-001: World (וועלט) 029: en-029: Caribbean (Caribbean) 029: fr-029: Caribbean (caraïbes) 029: pap-029: Caribbean (Caribbean) 150: en-150: Europe (Europe) 419: es-419: Latin America (Latinoamérica) AD: ca-AD: Andorra (Andorra) AE: ar-AE: United Arab Emirates (الإمارات العربية المتحدة) AF: prs-AF: Afghanistan (افغانستان) AF: ps-AF: Afghanistan (افغانستان) AF: uz-Arab-AF: Afghanistan (افغانستان) AG: en-AG: Antigua and Barbuda (Antigua and Barbuda) AI: en-AI: Anguilla (Anguilla) AL: sq-AL: Albania (Shqipëri) AM: hy-AM: Armenia (Հայաստան) AO: ln-AO: Angola (Angóla) AO: pt-AO: Angola (Angola) AR: es-AR: Argentina (Argentina) AS: en-AS: American Samoa (American Samoa) AT: de-AT: Austria (Österreich) AT: en-AT: Austria (Austria) AU: en-AU: Australia (Australia) AW: nl-AW: Aruba (Aruba) AX: sv-AX: Åland Islands (Åland) AZ: az-Cyrl-AZ: Azerbaijan (Азәрбајҹан) AZ: az-Latn-AZ: Azerbaijan (Azərbaycan) BA: bs-Cyrl-BA: Bosnia and Herzegovina (Босна и Херцеговина) BA: bs-Latn-BA: Bosnia and Herzegovina (Bosna i Hercegovina) BA: hr-BA: Bosnia and Herzegovina (Bosna i Hercegovina) BA: sr-Cyrl-BA: Bosnia and Herzegovina (Босна и Херцеговина) BA: sr-Latn-BA: Bosnia and Herzegovina (Bosna i Hercegovina) BB: en-BB: Barbados (Barbados) BD: bn-BD: Bangladesh (বাংলাদেশ) BE: de-BE: Belgium (Belgien) BE: en-BE: Belgium (Belgium) BE: fr-BE: Belgium (Belgique) BE: nl-BE: Belgium (België) BF: fr-BF: Burkina Faso (Burkina Faso) BG: bg-BG: Bulgaria (България) BH: ar-BH: Bahrain (البحرين) BI: en-BI: Burundi (Burundi) BI: fr-BI: Burundi (Burundi) BI: rn-BI: Burundi (Uburundi) BJ: fr-BJ: Benin (Bénin) BJ: yo-BJ: Benin (Orílɛ́ède Bɛ̀nɛ̀) BL: fr-BL: Saint Barthélemy (Saint-Barthélemy) BM: en-BM: Bermuda (Bermuda) BN: ms-BN: Brunei (Brunei) BO: es-BO: Bolivia (Bolivia) BO: quz-BO: Bolivia (Bolivia) BQ: nl-BQ: Bonaire, Sint Eustatius and Saba (Bonaire, Sint Eustatius en Saba) BR: es-BR: Brazil (Brasil) BR: pt-BR: Brazil (Brasil) BS: en-BS: Bahamas (Bahamas) BT: dz-BT: Bhutan (འབྲུག) BW: en-BW: Botswana (Botswana) BW: tn-BW: Botswana (Botswana) BY: be-BY: Belarus (Беларусь) BY: ru-BY: Belarus (Беларусь) BZ: en-BZ: Belize (Belize) BZ: es-BZ: Belize (Belice) CA: en-CA: Canada (Canada) CA: fr-CA: Canada (Canada) CA: iu-Cans-CA: Canada (ᑲᓇᑕ) CA: iu-Latn-CA: Canada (Kanata) CA: moh-CA: Canada (Canada) CC: en-CC: Cocos (Keeling) Islands (Cocos (Keeling) Islands) CD: fr-CD: Congo (DRC) (Congo, République démocratique du) CD: ln-CD: Congo (DRC) (Republíki ya Kongó Demokratíki) CD: lu-CD: Congo (DRC) (Ditunga wa Kongu) CD: sw-CD: Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo) CF: fr-CF: Central African Republic (République centrafricaine) CF: ln-CF: Central African Republic (Repibiki ya Afríka ya Káti) CF: sg-CF: Central African Republic (Ködörösêse tî Bêafrîka) CG: fr-CG: Congo (Congo) CG: ln-CG: Congo (Kongo) CH: de-CH: Switzerland (Schweiz) CH: en-CH: Switzerland (Switzerland) CH: fr-CH: Switzerland (Suisse) CH: gsw-CH: Switzerland (Schwiiz) CH: it-CH: Switzerland (Svizzera) CH: pt-CH: Switzerland (Suíça) CH: rm-CH: Switzerland (Svizra) CH: wae-CH: Switzerland (Schwiz) CI: fr-CI: Côte d’Ivoire (Côte d’Ivoire) CK: en-CK: Cook Islands (Cook Islands) CL: arn-CL: Chile (Chile) CL: es-CL: Chile (Chile) CM: agq-CM: Cameroon (Kàmàlûŋ) CM: bas-CM: Cameroon (Kàmɛ̀rûn) CM: dua-CM: Cameroon (Cameroun) CM: en-CM: Cameroon (Cameroon) CM: ewo-CM: Cameroon (Kamərún) CM: ff-CM: Cameroon (Kameruun) CM: fr-CM: Cameroon (Cameroun) CM: jgo-CM: Cameroon (Kamɛlûn) CM: kkj-CM: Cameroon (Kamɛrun) CM: ksf-CM: Cameroon (kamɛrún) CM: mgo-CM: Cameroon (Kamalun) CM: mua-CM: Cameroon (kameruŋ) CM: nmg-CM: Cameroon (Kamerun) CM: nnh-CM: Cameroon (Kàmalûm) CM: yav-CM: Cameroon (Kemelún) CN: bo-CN: China (ཀྲུང་ཧྭ་མི་དམངས་སྤྱི་མཐུན་རྒྱལ་ཁབ།) CN: ii-CN: China (ꍏꉸꏓꂱꇭꉼꇩ) CN: mn-Mong-CN: China (ᠪᠦᠭᠦᠳᠡ ᠨᠠᠢᠷᠠᠮᠳᠠᠬᠤ ᠳᠤᠮᠳᠠᠳᠤ ᠠᠷᠠᠳ ᠣᠯᠣᠰ) CN: ug-CN: China (جۇڭخۇا خەلق جۇمھۇرىيىتى) CN: zh-CN: China (中国) CO: es-CO: Colombia (Colombia) CR: es-CR: Costa Rica (Costa Rica) CU: es-CU: Cuba (Cuba) CV: kea-CV: Cabo Verde (Kabu Verdi) CV: pt-CV: Cabo Verde (Cabo Verde) CW: nl-CW: Curaçao (Curaçao) CX: en-CX: Christmas Island (Christmas Island) CY: el-CY: Cyprus (Κύπρος) CY: en-CY: Cyprus (Cyprus) CY: tr-CY: Cyprus (Kıbrıs) CZ: cs-CZ: Czechia (Česko) DE: de-DE: Germany (Deutschland) DE: dsb-DE: Germany (Nimska) DE: en-DE: Germany (Germany) DE: hsb-DE: Germany (Němska) DE: ksh-DE: Germany (Doütschland) DE: nds-DE: Germany (Düütschland) DJ: aa-DJ: Djibouti (Yabuuti) DJ: ar-DJ: Djibouti (جيبوتي) DJ: fr-DJ: Djibouti (Djibouti) DJ: so-DJ: Djibouti (Jabuuti) DK: da-DK: Denmark (Danmark) DK: en-DK: Denmark (Denmark) DK: fo-DK: Denmark (Danmark) DM: en-DM: Dominica (Dominica) DO: es-DO: Dominican Republic (República Dominicana) DZ: ar-DZ: Algeria (الجزائر) DZ: fr-DZ: Algeria (Algérie) DZ: kab-DZ: Algeria (Lezzayer) DZ: tzm-Latn-DZ: Algeria (Djazaïr) EC: es-EC: Ecuador (Ecuador) EC: quz-EC: Ecuador (Ecuador) EE: et-EE: Estonia (Eesti) EG: ar-EG: Egypt (مصر) ER: aa-ER: Eritrea (Eretria) ER: ar-ER: Eritrea (إريتريا) ER: byn-ER: Eritrea (ኤርትራ) ER: en-ER: Eritrea (Eritrea) ER: ssy-ER: Eritrea (Eretria) ER: ti-ER: Eritrea (ኤርትራ) ER: tig-ER: Eritrea (ኤርትራ) ES: ast-ES: Spain (España) ES: ca-ES: Spain (Espanya) ES: ca-ES-valencia: Spain (Espanya) ES: es-ES: Spain (España) ES: eu-ES: Spain (Espainia) ES: gl-ES: Spain (España) ET: aa-ET: Ethiopia (Otobbia) ET: am-ET: Ethiopia (ኢትዮጵያ) ET: om-ET: Ethiopia (Itoophiyaa) ET: so-ET: Ethiopia (Itoobiya) ET: ti-ET: Ethiopia (ኢትዮጵያ) ET: wal-ET: Ethiopia (ኢትዮጵያ) FI: en-FI: Finland (Finland) FI: fi-FI: Finland (Suomi) FI: se-FI: Finland (Suopma) FI: smn-FI: Finland (Suomâ) FI: sms-FI: Finland (Lää´ddjânnam) FI: sv-FI: Finland (Finland) FJ: en-FJ: Fiji (Fiji) FK: en-FK: Falkland Islands (Falkland Islands) FM: en-FM: Micronesia (Micronesia) FO: fo-FO: Faroe Islands (Føroyar) FR: br-FR: France (Frañs) FR: ca-FR: France (França) FR: co-FR: France (Francia) FR: fr-FR: France (France) FR: gsw-FR: France (Frànkrisch) FR: ia-FR: France (Francia) FR: oc-FR: France (França) GA: fr-GA: Gabon (Gabon) GB: cy-GB: United Kingdom (Y Deyrnas Unedig) GB: en-GB: United Kingdom (United Kingdom) GB: gd-GB: United Kingdom (An Rìoghachd Aonaichte) GB: kw-GB: United Kingdom (Rywvaneth Unys) GD: en-GD: Grenada (Grenada) GE: ka-GE: Georgia (საქართველო) GE: os-GE: Georgia (Гуырдзыстон) GF: fr-GF: French Guiana (Guyane française) GG: en-GG: Guernsey (Guernsey) GH: ak-GH: Ghana (Gaana) GH: ee-GH: Ghana (Ghana nutome) GH: en-GH: Ghana (Ghana) GH: ha-Latn-GH: Ghana (Gana) GI: en-GI: Gibraltar (Gibraltar) GL: da-GL: Greenland (Grønland) GL: kl-GL: Greenland (Kalaallit Nunaat) GM: en-GM: Gambia (Gambia) GN: ff-GN: Guinea (Gine) GN: fr-GN: Guinea (Guinée) GN: nqo-GN: Guinea (ߖߌ߬ߣߍ߬ ߞߊ߲ߓߍ߲) GP: fr-GP: Guadeloupe (Guadeloupe) GQ: es-GQ: Equatorial Guinea (Guinea Ecuatorial) GQ: fr-GQ: Equatorial Guinea (Guinée équatoriale) GQ: pt-GQ: Equatorial Guinea (Guiné Equatorial) GR: el-GR: Greece (Ελλάδα) GT: es-GT: Guatemala (Guatemala) GT: quc-Latn-GT: Guatemala (Guatemala) GU: en-GU: Guam (Guam) GW: pt-GW: Guinea-Bissau (Guiné-Bissau) GY: en-GY: Guyana (Guyana) HK: en-HK: Hong Kong SAR (Hong Kong SAR) HK: zh-Hans-HK: Hong Kong SAR (香港特别行政区) HK: zh-HK: Hong Kong SAR (香港特別行政區) HN: es-HN: Honduras (Honduras) HR: hr-HR: Croatia (Hrvatska) HT: fr-HT: Haiti (Haïti) HU: hu-HU: Hungary (Magyarország) ID: en-ID: Indonesia (Indonesia) ID: id-ID: Indonesia (Indonesia) ID: jv-Java-ID: Indonesia (Indonesia) ID: jv-Latn-ID: Indonesia (Indonesia) IE: en-IE: Ireland (Ireland) IE: ga-IE: Ireland (Éire) IL: ar-IL: Israel (إسرائيل) IL: en-IL: Israel (Israel) IL: he-IL: Israel (ישראל) IM: en-IM: Isle of Man (Isle of Man) IM: gv-IM: Isle of Man (Ellan Vannin) IN: as-IN: India (ভাৰত) IN: bn-IN: India (ভারত) IN: bo-IN: India (རྒྱ་གར་) IN: brx-IN: India (भारत) IN: en-IN: India (India) IN: gu-IN: India (ભારત) IN: hi-IN: India (भारत) IN: kn-IN: India (ಭಾರತ) IN: kok-IN: India (भारत) IN: ks-Arab-IN: India (ہِنٛدوستان) IN: ks-Deva-IN: India (India) IN: ml-IN: India (ഇന്ത്യ) IN: mni-IN: India (India) IN: mr-IN: India (भारत) IN: ne-IN: India (भारत) IN: or-IN: India (ଭାରତ) IN: pa-IN: India (ਭਾਰਤ) IN: sa-IN: India (भारतम्) IN: sd-Deva-IN: India (India) IN: ta-IN: India (இந்தியா) IN: te-IN: India (భారత దేశం) IN: ur-IN: India (بھارت) IO: en-IO: British Indian Ocean Territory (British Indian Ocean Territory) IQ: ar-IQ: Iraq (العراق) IQ: ku-Arab-IQ: Iraq (عێراق) IQ: lrc-IQ: Iraq (Iraq) IR: fa-IR: Iran (ایران) IR: ku-Arab-IR: Iran (ئێران) IR: lrc-IR: Iran (Iran) IR: mzn-IR: Iran (ایران) IS: is-IS: Iceland (Ísland) IT: ca-IT: Italy (Itàlia) IT: de-IT: Italy (Italien) IT: fur-IT: Italy (Italie) IT: it-IT: Italy (Italia) JE: en-JE: Jersey (Jersey) JM: en-JM: Jamaica (Jamaica) JO: ar-JO: Jordan (الأردن) JP: ja-JP: Japan (日本) KE: dav-KE: Kenya (Kenya) KE: ebu-KE: Kenya (Kenya) KE: en-KE: Kenya (Kenya) KE: guz-KE: Kenya (Kenya) KE: kam-KE: Kenya (Kenya) KE: ki-KE: Kenya (Kenya) KE: kln-KE: Kenya (Emetab Kenya) KE: luo-KE: Kenya (Kenya) KE: luy-KE: Kenya (Kenya) KE: mas-KE: Kenya (Kenya) KE: mer-KE: Kenya (Kenya) KE: om-KE: Kenya (Keeniyaa) KE: saq-KE: Kenya (Kenya) KE: so-KE: Kenya (Kiiniya) KE: sw-KE: Kenya (Kenya) KE: teo-KE: Kenya (Kenia) KG: ky-KG: Kyrgyzstan (Кыргызстан) KG: ru-KG: Kyrgyzstan (Киргизия) KH: km-KH: Cambodia (កម្ពុជា) KI: en-KI: Kiribati (Kiribati) KM: ar-KM: Comoros (جزر القمر) KM: fr-KM: Comoros (Comores) KN: en-KN: Saint Kitts and Nevis (Saint Kitts and Nevis) KP: ko-KP: North Korea (조선민주주의인민공화국) KR: ko-KR: Korea (대한민국) KW: ar-KW: Kuwait (الكويت) KY: en-KY: Cayman Islands (Cayman Islands) KZ: kk-KZ: Kazakhstan (Қазақстан) KZ: ru-KZ: Kazakhstan (Казахстан) LA: lo-LA: Laos (ລາວ) LB: ar-LB: Lebanon (لبنان) LC: en-LC: Saint Lucia (Saint Lucia) LI: de-LI: Liechtenstein (Liechtenstein) LI: gsw-LI: Liechtenstein (Liächteschtäi) LK: si-LK: Sri Lanka (ශ්‍රී ලංකාව) LK: ta-LK: Sri Lanka (இலங்கை) LR: en-LR: Liberia (Liberia) LR: vai-Latn-LR: Liberia (Laibhiya) LR: vai-Vaii-LR: Liberia (ꕞꔤꔫꕩ) LS: en-LS: Lesotho (Lesotho) LS: st-LS: Lesotho (Lesotho) LT: lt-LT: Lithuania (Lietuva) LU: de-LU: Luxembourg (Luxemburg) LU: fr-LU: Luxembourg (Luxembourg) LU: lb-LU: Luxembourg (Lëtzebuerg) LU: pt-LU: Luxembourg (Luxemburgo) LV: lv-LV: Latvia (Latvija) LY: ar-LY: Libya (ليبيا) MA: ar-MA: Morocco (المملكة المغربية) MA: fr-MA: Morocco (Maroc) MA: shi-Latn-MA: Morocco (lmɣrib) MA: shi-Tfng-MA: Morocco (ⵍⵎⵖⵔⵉⴱ) MA: tzm-Arab-MA: Morocco (Morocco) MA: tzm-Latn-MA: Morocco (Meṛṛuk) MA: tzm-Tfng-MA: Morocco (ⵍⵎⵖⵔⵉⴱ) MA: zgh-Tfng-MA: Morocco (ⵍⵎⵖⵔⵉⴱ) MC: fr-MC: Monaco (Monaco) MD: ro-MD: Moldova (Republica Moldova) MD: ru-MD: Moldova (Молдова) ME: sr-Cyrl-ME: Montenegro (Црна Гора) ME: sr-Latn-ME: Montenegro (Crna Gora) MF: fr-MF: Saint Martin (Saint-Martin) MG: en-MG: Madagascar (Madagascar) MG: fr-MG: Madagascar (Madagascar) MG: mg-MG: Madagascar (Madagasikara) MH: en-MH: Marshall Islands (Marshall Islands) MK: mk-MK: Macedonia, FYRO (Република Македонија) MK: sq-MK: Macedonia, FYRO (Republika e Maqedonisë) ML: bm-Latn-ML: Mali (Mali) ML: fr-ML: Mali (Mali) ML: khq-ML: Mali (Maali) ML: ses-ML: Mali (Maali) MM: my-MM: Myanmar (မြန်မာ) MN: mn-MN: Mongolia (Монгол) MN: mn-Mong-MN: Mongolia (ᠮᠣᠩᠭᠣᠯ ᠣᠯᠣᠰ) MO: en-MO: Macao SAR (Macao SAR) MO: pt-MO: Macao SAR (RAE de Macau) MO: zh-Hans-MO: Macao SAR (澳门特别行政区) MO: zh-MO: Macao SAR (澳門特別行政區) MP: en-MP: Northern Mariana Islands (Northern Mariana Islands) MQ: fr-MQ: Martinique (Martinique) MR: ar-MR: Mauritania (موريتانيا) MR: ff-MR: Mauritania (Muritani) MR: fr-MR: Mauritania (Mauritanie) MS: en-MS: Montserrat (Montserrat) MT: en-MT: Malta (Malta) MT: mt-MT: Malta (Malta) MU: en-MU: Mauritius (Mauritius) MU: fr-MU: Mauritius (Maurice) MU: mfe-MU: Mauritius (Moris) MV: dv-MV: Maldives (ދިވެހި ރާއްޖެ) MW: en-MW: Malawi (Malawi) MX: es-MX: Mexico (México) MY: en-MY: Malaysia (Malaysia) MY: ms-MY: Malaysia (Malaysia) MY: ta-MY: Malaysia (மலேசியா) MZ: mgh-MZ: Mozambique (Umozambiki) MZ: pt-MZ: Mozambique (Moçambique) MZ: seh-MZ: Mozambique (Moçambique) NA: af-NA: Namibia (Namibië) NA: en-NA: Namibia (Namibia) NA: naq-NA: Namibia (Namibiab) NC: fr-NC: New Caledonia (Nouvelle-Calédonie) NE: dje-NE: Niger (Nižer) NE: fr-NE: Niger (Niger) NE: ha-Latn-NE: Niger (Nijar) NE: twq-NE: Niger (Nižer) NF: en-NF: Norfolk Island (Norfolk Island) NG: bin-NG: Nigeria (Nigeria) NG: en-NG: Nigeria (Nigeria) NG: ff-NG: Nigeria (Nigeria) NG: ha-Latn-NG: Nigeria (Najeriya) NG: ibb-NG: Nigeria (Nigeria) NG: ig-NG: Nigeria (Naịjịrịa) NG: kr-NG: Nigeria (Nigeria) NG: yo-NG: Nigeria (Orílẹ́ède Nàìjíríà) NI: es-NI: Nicaragua (Nicaragua) NL: en-NL: Netherlands (Netherlands) NL: fy-NL: Netherlands (Nederlân) NL: nds-NL: Netherlands (Nedderlannen) NL: nl-NL: Netherlands (Nederland) NO: nb-NO: Norway (Norge) NO: nn-NO: Norway (Noreg) NO: se-NO: Norway (Norga) NO: sma-NO: Norway (Nöörje) NO: smj-NO: Norway (Vuodna) NP: ne-NP: Nepal (नेपाल) NR: en-NR: Nauru (Nauru) NU: en-NU: Niue (Niue) NZ: en-NZ: New Zealand (New Zealand) NZ: mi-NZ: New Zealand (Aotearoa) OM: ar-OM: Oman (عمان) PA: es-PA: Panama (Panamá) PE: es-PE: Peru (Perú) PE: quz-PE: Peru (Perú) PF: fr-PF: French Polynesia (Polynésie française) PG: en-PG: Papua New Guinea (Papua New Guinea) PH: en-PH: Philippines (Philippines) PH: es-PH: Philippines (Filipinas) PH: fil-PH: Philippines (Pilipinas) PK: en-PK: Pakistan (Pakistan) PK: pa-Arab-PK: Pakistan (پاکستان) PK: sd-Arab-PK: Pakistan (پاکستان) PK: ur-PK: Pakistan (پاکستان) PL: pl-PL: Poland (Polska) PM: fr-PM: Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon) PN: en-PN: Pitcairn Islands (Pitcairn Islands) PR: en-PR: Puerto Rico (Puerto Rico) PR: es-PR: Puerto Rico (Puerto Rico) PS: ar-PS: Palestinian Authority (السلطة الفلسطينية) PT: pt-PT: Portugal (Portugal) PW: en-PW: Palau (Palau) PY: es-PY: Paraguay (Paraguay) PY: gn-PY: Paraguay (Paraguái) QA: ar-QA: Qatar (قطر) RE: fr-RE: Réunion (La Réunion) RO: ro-RO: Romania (România) RS: sr-Cyrl-RS: Serbia (Србија) RS: sr-Latn-RS: Serbia (Srbija) RU: ba-RU: Russia (Рәсәй) RU: ce-RU: Russia (Росси) RU: cu-RU: Russia (рѡссі́а) RU: os-RU: Russia (Уӕрӕсе) RU: ru-RU: Russia (Россия) RU: sah-RU: Russia (Россия) RU: tt-RU: Russia (Россия) RW: en-RW: Rwanda (Rwanda) RW: fr-RW: Rwanda (Rwanda) RW: rw-RW: Rwanda (U Rwanda) SA: ar-SA: Saudi Arabia (المملكة العربية السعودية) SB: en-SB: Solomon Islands (Solomon Islands) SC: en-SC: Seychelles (Seychelles) SC: fr-SC: Seychelles (Seychelles) SD: ar-SD: Sudan (السودان) SD: en-SD: Sudan (Sudan) SE: en-SE: Sweden (Sweden) SE: se-SE: Sweden (Ruoŧŧa) SE: sma-SE: Sweden (Sveerje) SE: smj-SE: Sweden (Svierik) SE: sv-SE: Sweden (Sverige) SG: en-SG: Singapore (Singapore) SG: ms-SG: Singapore (Singapura) SG: ta-SG: Singapore (சிங்கப்பூர்) SG: zh-SG: Singapore (新加坡) SH: en-SH: St Helena, Ascension, Tristan da Cunha (St Helena, Ascension, Tristan da Cunha) SI: en-SI: Slovenia (Slovenia) SI: sl-SI: Slovenia (Slovenija) SJ: nb-SJ: Svalbard and Jan Mayen (Svalbard og Jan Mayen) SK: sk-SK: Slovakia (Slovensko) SL: en-SL: Sierra Leone (Sierra Leone) SM: it-SM: San Marino (San Marino) SN: dyo-SN: Senegal (Senegal) SN: ff-Latn-SN: Senegal (Senegaal) SN: fr-SN: Senegal (Sénégal) SN: wo-SN: Senegal (Senegaal) SO: ar-SO: Somalia (الصومال) SO: so-SO: Somalia (Soomaaliya) SR: nl-SR: Suriname (Suriname) SS: ar-SS: South Sudan (جنوب السودان) SS: en-SS: South Sudan (South Sudan) SS: nus-SS: South Sudan (South Sudan) ST: pt-ST: São Tomé and Príncipe (São Tomé e Príncipe) SV: es-SV: El Salvador (El Salvador) SX: en-SX: Sint Maarten (Sint Maarten) SX: nl-SX: Sint Maarten (Sint-Maarten) SY: ar-SY: Syria (سوريا) SY: fr-SY: Syria (Syrie) SY: syr-SY: Syria (ܣܘܪܝܐ) SZ: en-SZ: Swaziland (Swaziland) SZ: ss-SZ: Swaziland (Swaziland) TC: en-TC: Turks and Caicos Islands (Turks and Caicos Islands) TD: ar-TD: Chad (تشاد) TD: fr-TD: Chad (Tchad) TG: ee-TG: Togo (Togo nutome) TG: fr-TG: Togo (Togo) TH: th-TH: Thailand (ไทย) TJ: tg-Cyrl-TJ: Tajikistan (Тоҷикистон) TK: en-TK: Tokelau (Tokelau) TL: pt-TL: Timor-Leste (Timor-Leste) TM: tk-TM: Turkmenistan (Türkmenistan) TN: ar-TN: Tunisia (تونس) TN: fr-TN: Tunisia (Tunisie) TO: en-TO: Tonga (Tonga) TO: to-TO: Tonga (Tonga) TR: tr-TR: Turkey (Türkiye) TT: en-TT: Trinidad and Tobago (Trinidad and Tobago) TV: en-TV: Tuvalu (Tuvalu) TW: zh-TW: Taiwan (台灣) TZ: asa-TZ: Tanzania (Tadhania) TZ: bez-TZ: Tanzania (Hutanzania) TZ: en-TZ: Tanzania (Tanzania) TZ: jmc-TZ: Tanzania (Tanzania) TZ: kde-TZ: Tanzania (Tanzania) TZ: ksb-TZ: Tanzania (Tanzania) TZ: lag-TZ: Tanzania (Taansanía) TZ: mas-TZ: Tanzania (Tansania) TZ: rof-TZ: Tanzania (Tanzania) TZ: rwk-TZ: Tanzania (Tanzania) TZ: sbp-TZ: Tanzania (Tansaniya) TZ: sw-TZ: Tanzania (Tanzania) TZ: vun-TZ: Tanzania (Tanzania) UA: ru-UA: Ukraine (Украина) UA: uk-UA: Ukraine (Україна) UG: cgg-UG: Uganda (Uganda) UG: en-UG: Uganda (Uganda) UG: lg-UG: Uganda (Yuganda) UG: nyn-UG: Uganda (Uganda) UG: sw-UG: Uganda (Uganda) UG: teo-UG: Uganda (Uganda) UG: xog-UG: Uganda (Yuganda) UM: en-UM: U.S. Outlying Islands (U.S. Outlying Islands) US: chr-Cher-US: United States (ᏌᏊ ᎢᏳᎾᎵᏍᏔᏅ ᏍᎦᏚᎩ) US: en-US: United States (United States) US: es-US: United States (Estados Unidos) US: haw-US: United States (ʻAmelika Hui Pū ʻIa) US: lkt-US: United States (Mílahaŋska Tȟamákȟočhe) UY: es-UY: Uruguay (Uruguay) UZ: uz-Cyrl-UZ: Uzbekistan (Ўзбекистон) UZ: uz-Latn-UZ: Uzbekistan (Oʻzbekiston) VA: it-VA: Vatican City (Città del Vaticano) VC: en-VC: Saint Vincent and the Grenadines (Saint Vincent and the Grenadines) VE: es-VE: Venezuela (Venezuela) VG: en-VG: British Virgin Islands (British Virgin Islands) VI: en-VI: U.S. Virgin Islands (U.S. Virgin Islands) VN: vi-VN: Vietnam (Việt Nam) VU: en-VU: Vanuatu (Vanuatu) VU: fr-VU: Vanuatu (Vanuatu) WF: fr-WF: Wallis and Futuna (Wallis-et-Futuna) WS: en-WS: Samoa (Samoa) XK: sq-XK: Kosovo (Kosovë) XK: sr-Cyrl-XK: Kosovo (Косово) XK: sr-Latn-XK: Kosovo (Kosovo) YE: ar-YE: Yemen (اليمن) YT: fr-YT: Mayotte (Mayotte) ZA: af-ZA: South Africa (Suid-Afrika) ZA: en-ZA: South Africa (South Africa) ZA: nr-ZA: South Africa (South Africa) ZA: nso-ZA: South Africa (Afrika Borwa) ZA: ss-ZA: South Africa (South Africa) ZA: st-ZA: South Africa (South Africa) ZA: tn-ZA: South Africa (Aforika Borwa) ZA: ts-ZA: South Africa (South Africa) ZA: ve-ZA: South Africa (South Africa) ZA: xh-ZA: South Africa (eMzantsi Afrika) ZA: zu-ZA: South Africa (iNingizimu Afrika) ZM: bem-ZM: Zambia (Zambia) ZM: en-ZM: Zambia (Zambia) ZW: en-ZW: Zimbabwe (Zimbabwe) ZW: nd-ZW: Zimbabwe (Zimbabwe) ZW: sn-Latn-ZW: Zimbabwe (Zimbabwe) </PRE></p> <p><strong>Edit:</strong> Updated to what is seen om my Windows 10 (version 1803 "April 2018 Update") machine, .NET Framework 4.7.2.</p>
27,611
<p>When creating a string using the following notation:</p> <pre><code>NSString *foo = @"Bar"; </code></pre> <p>Does one need to release <code>foo</code>? Or is <code>foo</code> autoreleased in this case?</p>
<p>Compiler allocated strings (of the format @"STRING") are constant, and so -retain, -release, and -autorelease messages to them are ignored. You don't have to release or autorelease foo in this case (but it won't hurt).</p>
<p>I agree with @Ben\ Gottlieb at "Compiler allocated strings (of the format @"STRING") are constants" but as you have not initialized them via passing an <code>alloc</code> or <code>retain</code> message, you must not pass <code>release</code> or <code>autorelease</code> message to them otherwise your app will crash with the following log </p> <blockquote> <p>"pointer being freed was not allocated"</p> </blockquote> <p><strong><a href="https://stackoverflow.com/questions/2713843/iphone-memory-management-a-newbie-question/2713941#2713941">NOTE</a></strong></p> <pre><code>NSString *str = [NSString string]; </code></pre> <p>is equivalent to:</p> <pre><code>NSString *str = [[[NSString alloc] init] autorelease]; </code></pre> <p>so <code>release</code> or <code>autorelease</code> must not be passed here too.</p>
42,748
<p>I have a user control where the XAML of the control can bind to the appropriate properties from the parent's data context like normal (the data context propagates in xaml). </p> <p>For example, I have a window whose DataContext I am setting to ObjectA for example. My user control within the window is then try to access the properties within the dataContext</p> <p>So my window's xaml and code behind can both see a non-null DataContext. </p> <p>My control that DataContext propagates to can see a non-null DataContext in the Xaml but not in the code behind.</p> <p>What is the proper way of handling this?</p>
<p>failing that if you need to check whether the DataContext is being set you can use the DataContextChanged</p> <pre><code>public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); DataContextChanged += new DependencyPropertyChangedEventHandler(UserControl1_DataContextChanged); } void UserControl1_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { // You can also validate the data going into the DataContext using the event args } } </code></pre> <p>Note it wont enter UserControl1_DataContextChanged until DataContext is changed from null to a different value.</p> <p>Not sure if this answers your question but can be quite handy to use in debugging issues.</p>
<p>I think you are checking the 'DataContext' in the constructor of the UserControl. It will be null at the Constructor since the user control hasnt yet created while execution is in the constructor code. But check the property at Loaded event you will see the object properly.</p> <pre><code>public partial class UserControl1 { public UserControl1() { this.InitializeComponent(); //DataContext will be null here this.Loaded += new RoutedEventHandler(UserControl1_Loaded); } void UserControl1_Loaded(object sender, RoutedEventArgs e) { //Check DataContext Property here - Value is not null } } </code></pre>
37,910
<p>I have a weird issue. I had a web service that was compiled under the 2.0 framework that was being consumed by a windows app that was compiled with the 1.1 framework. This worked just fine. Now, after upgrading the web service to the 3.5 framework, the windows app is no longer able to call it.</p> <p>Creating a little windows app in 3.5 as a test is able to call the web service without problems so I know it still works.</p> <p>Nothing has changed in the code at all, it's just compiled as a 3.5 project instead of a 2.0 project.</p> <p>For those who care what error I get back, it's this:</p> <blockquote> <p>An unhandled exception of type 'System.Net.WebException' occurred in system.web.services.dll</p> <p>Additional information: The underlying connection was closed: An unexpected error occurred on a receive.</p> </blockquote> <p>Is there anything I can do to the web service to make it backwards compatible (if that's even the issue)?</p> <p>[Edit] Responses to answers below (so far): Re-Discovering did not work, nor did removing and re-adding the webservice. I don't believe it's a SOAP issue becuase the WSDLs are identical (both show SOAP 1.2). Browsing to the webservice from the server works just fine.</p>
<p>Try 'rediscover' the web service in .NET 1.1 (possibly just a test app) and see if the problem persists.</p>
<p>Can you go the the web service directly on the IIS installation? If not, check the application configuration in IIS. You must switch the version of ASP.NET.</p>
34,262
<p>I have two characters displayed in a game I am writing, the player and the enemy. defined as such:</p> <pre><code>public void player(Graphics g) { g.drawImage(plimg, x, y, this); } public void enemy(Graphics g) { g.drawImage(enemy, 200, 200, this); } </code></pre> <p>Then called with:</p> <pre><code>player(g); enemy(g); </code></pre> <p>I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?</p>
<p>I think your problem is that you are not using good OO design for your player and enemies. Create two classes:</p> <pre><code>public class Player { int X; int Y; int Width; int Height; // Getters and Setters } public class Enemy { int X; int Y; int Width; int Height; // Getters and Setters } </code></pre> <p>Your Player should have X,Y,Width,and Height variables.</p> <p>Your enemies should as well.</p> <p>In your game loop, do something like this (C#):</p> <pre><code>foreach (Enemy e in EnemyCollection) { Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height); Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height); // Assuming there is an intersect method, otherwise just handcompare the values if (r.Intersects(p)) { // A Collision! // we know which enemy (e), so we can call e.DoCollision(); e.DoCollision(); } } </code></pre> <p>To speed things up, don't bother checking if the enemies coords are offscreen.</p>
<p>Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.</p> <p>Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'</p> <p>I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.</p> <p>Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.</p> <p>Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)</p> <p>edit: here we go</p> <p>boolean </p> <blockquote> <p>intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.</p> </blockquote> <p>So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)</p> <pre><code>Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height); Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height); //detects when the two rectangles hit if(rect1.intersects(rect2)) { System.out.println("game over, g"); } </code></pre> <p>obviously you'd need to fit that in somewhere.</p>
43,534
<p>I have a collection of ClickOnce packages in a publish folder on a network drive and need to move them all to another server (our DR machine). </p> <p>After copy/pasting the whole directory and running the setups on the new machine I get an error message stating that it cannot find the old path:</p> <blockquote> <p>Activation of ...MyClickOnceApp.application resulted in exception. Following failure messages were detected:</p> <p>+ Downloading file://oldMachine/c$/MyClickOnceApp.application did not succeed.</p> <p>+ Could not find a part of the path '\\oldMachine\c$\MyClickOnceApp.application'.</p> </blockquote> <p>Once I change the installation <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> to point at my new machine, I get another error:</p> <blockquote> <p>Manifest XML signature is not valid.</p> <p>+ The digital signature of the object did not verify.</p> </blockquote> <p>I've tried using <a href="http://msdn.microsoft.com/en-us/library/xhctdw55.aspx" rel="nofollow noreferrer">MageUI.exe</a>, to modify the deployment URL, but it asks for a certificate, which I don't have.</p> <p>What am I doing wrong and how do I successfully move published ClickOnce packages?</p>
<p>I found a solution:</p> <p>Firstly, using MageUI, I changed the &quot;Start Location&quot; under &quot;Deployment Options&quot;. On saving, it prompted me to sign with a key, which I created there and then. I then ran the <code>setup.exe</code> file, and it worked without fail.</p> <p>After checking which files had changed, I realised it was only the one file: the application manifest file (<code>myAppName.application</code>). The only things that changed in the file were the <em><strong>deployment provider</strong></em> and the <em><strong>signature</strong></em> (which is what I changed in MageUI).</p> <p>Once I realised this was how to do it, I used the command line version of MageUI called <code>Mage.exe</code>, which comes with the SDK.</p> <p>Below is the batch file I created to do all of this on the command line:</p> <blockquote> <p>REM Set the enviroment<br /> call &quot;C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat&quot;</p> <p>REM Update the deployment provider URL<br /> mage -Update %1.application -pu %2</p> <p>REM Sign the manifest with our key<br /> mage -Sign %1.application -CertFile C:\AppKey.pfx -Password myPw</p> </blockquote> <p>I can now use this to run against all of my published applications in a quick and easy way. I hope this helps.</p>
<p>I believe that you do have a certificate. You need one to create a ClickOnce deployment. Visual Studio may have autocreated a self-signed one for you. I'm not too familiar with the process, hopefully someone with a more definitive answer will chip in. Also, have you tried the MageUI tool, maybe it will be more obvious what you need to do using a GUI.</p>
21,067
<p>I realize there is a somewhat related thread on this here: <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">Loading assemblies and its dependencies</a></p> <p>But I am modifying something and this doesn't exactly apply. </p> <pre><code>string path = Path.GetDirectoryName( pathOfAssembly ); Environment.CurrentDirectory = path; Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly)); </code></pre> <p>Is there any really reason you would do it like this? Wouldn't it make more sense to just use:</p> <pre><code>Assembly.LoadFile(pathOfAssembly); </code></pre> <p>Any insight would be greatly appreciated.</p>
<p>Looks like the "Department of Redundancy Department."</p> <p>A lot more code than is necessary. Less is more!</p> <p><strong>Edit:</strong> On second thought, it could be that the assembly you are loading has dependencies that live in its own folder that may be required to use the first assembly. </p>
<p>This can be necessary when you are developping a windows service. The working dir of a service defaults to %WinDir%, so if you want to load an assembly from the dir that your service exe resides in, this is the way to go.</p>
16,466
<p>I'm relatively new to Nant, what i'd like to do is have a task that creates a new Website and AppPool in IIS6</p> <p>is there a way to do this in Nant?</p> <p>Essentially the task would need to set all the appropriate properties including the correct version of the .net Framework</p> <p>Ideally i'd also like to check if the site is already present in IIS.</p>
<p>Have you looked at <a href="http://nantcontrib.sourceforge.net/" rel="nofollow noreferrer">NantContrib</a>? It might provide some better IIS support without having to write your own task (or shelling out).</p> <p>It has some IIS specific tasks like <a href="http://nantcontrib.sourceforge.net/release/latest/help/tasks/iisapppool.html" rel="nofollow noreferrer">iisapppool</a> and <a href="http://nantcontrib.sourceforge.net/release/latest/help/tasks/mkiisdir.html" rel="nofollow noreferrer">mkiisdir</a>.</p>
<p>You can do this from the command line using ADSUTIL, you can find more information here:</p> <p><a href="http://blogs.msdn.com/david.wang/archive/2007/12/12/howto-create-custom-application-pool-by-commandline.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/david.wang/archive/2007/12/12/howto-create-custom-application-pool-by-commandline.aspx</a></p> <p>To do this in Nant you can use the exec task.</p> <p>How are you planning on deploying your application? Do you need this just for local installation? There may be a better solution if you can give us some more details.</p>
29,095
<p>After reading <a href="https://stackoverflow.com/questions/4689/recommended-fonts-for-programming">this</a> question I installed Consolas. The trouble is, now the text seems too small. I have to adjust it to size 12 to use it comfortably. Anyone else experience this when switching to Consolas (or any other font)? Do my eyes just have to adjust to this new font or is it a sign that my eyesight is deteriorating?</p> <p>My resolution is 1280x1024</p>
<p>I use Consolas, 11pt on my 1440x900 laptop (Windows XP). I've been using 10pt for some time but I found myself having eye strain so I've set 11pt for all the development tools, editors and shells I'm using. </p> <p>I would, however, be much hapier if 11pt Consolas would be a little smaller. I don't like that big difference between Consolas 10pt and 11pt.</p>
<p>I use consolas 9 pt @ 1280x800, 15.4 inch monitor (laptop)</p>
21,591
<p>I am creating a large table dynamically using Javascript. I have realised the time taken to add a new row grows exponentially as the number of rows increase.</p> <p>I suspect the Page is getting refreshed in each loop per row (I am also adding input elements of type text on each cell)</p> <p>Is there a way to stop the page "refreshing" until I am done with the whole table?</p> <p>Any suggestion on how to do this or go around it?</p> <hr> <p>I have tried all the suggestions above, but I am still getting the performance bottlenecks.</p> <p>I tried to analyse line after line, and I have noted that document.getElementById() is one of the lines taking a lot of time to execute when the table is very large. I am using getElementById() to dynamically access an HTML input of type text loaded on each cell of the table.</p> <p>Any ideas on which DOM method I should use instead of getElementById()?</p>
<p>You can create the table object without adding it to the document tree, add all the rows and then append the table object to the document tree. </p> <pre><code>var theTable = document.createElement("table"); // ... // add all the rows to theTable // ... document.body.appendChild(theTable); </code></pre>
<p>Did you try the &lt;tbody&gt; tag when you create the table? It is possible browsers optimize that and don't "refresh" the table while populating it.</p>
40,544
<p>I have two directories in the same parent directory. Call the parent directory <strong>base</strong> and the children directories <strong>alpha</strong> and <strong>bravo</strong>. I want to replace <strong>alpha</strong> with <strong>bravo</strong>. The simplest method is:</p> <pre><code>rm -rf alpha mv bravo alpha </code></pre> <p>The mv command is atomic, but the rm -rf is not. Is there a simple way in bash to atomically replace <strong>alpha</strong> with <strong>bravo</strong>? If not, is there a complicated way?</p> <p>ADDENDUM:</p> <p>By the by, it's not an insurmountable problem if the directory doesn't exist for a short period. There's only one place that tries to access alpha, and it checks if alpha exists before doing anything critical. If not, it gives an error message. But it would be nice if there was a way to do this. :) Maybe there's some way to modify the inodes directly, or something...</p>
<p>The final solution is combining the symlink- and the rename-approach:</p> <pre><code>mkdir alpha_real ln -s alpha_real alpha # now use "alpha" mkdir beta_real ln -s beta_real tmp # atomically rename "tmp" to "alpha" # use -T to actually replace "alpha" instead of moving *into* "alpha" mv -T tmp alpha </code></pre> <p>Of course, the application accessing alpha has to be able to deal with symlinks changing in the path.</p>
<p>Why don't you just do something like:</p> <pre><code>rm -rf alpha/* mv bravo/* alpha/ rm -rf bravo/ </code></pre> <p>That would mean that everything <em>in</em> alpha is destroyed, alpha <em>never</em> gets deleted, and all the contents get moved.</p>
39,567
<p><strong>Motivation</strong></p> <p>I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.</p> <p><strong>Possibility 1</strong></p> <p>Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?</p> <p><strong>Possibility 2</strong></p> <p>My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?</p>
<p>I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL:</p> <ul> <li><a href="http://marcocorvi.altervista.org/games/imgpr/rgb-hsl.htm" rel="noreferrer">from the "Fundamentals of Computer Graphics"</a></li> <li><a href="http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm" rel="noreferrer">some sourcecode in C#</a> - should be easy to adapt to other programming languages.</li> </ul>
<p>I would have tried number #1 first, but #2 sounds pretty good. Try doing it yourself and see if you're satisfied with the results, it sounds like it'll take you maybe 10 minutes to whip up a test.</p>
17,145
<p>I have a DataGridViewComboBoxColumn in a DataGridView that's based on a lookup table.</p> <p>The ValueMember and DisplayMember fields are bound to string columns in the DataTable. All rows have a value for both fields - except for a special record where the value field is deliberately set to NULL.</p> <p>However, when I choose this record an empty string is used instead of DBNull.Value in the DataTable bound to the DataGridView. This is happening at data entry time, before the data is pushed to the database. </p> <p>I've checked out the DataGridViewComboBoxColumn and DataGridView classes - there appears to be no simple way to customise this behaviour. Does anybody know if this is possible?</p>
<p>Well, I did come up with <em>a</em> solution. Because the DataGridView is data bound, I implemented the ColumnChanging event for the DataTable. Sample code:</p> <pre><code>void Schedule_ColumnChanging(object sender, DataColumnChangeEventArgs e) { if ( e.Column.ColumnName == "Site" &amp;&amp; e.ProposedValue is string &amp;&amp; e.ProposedValue as string == "" ) e.ProposedValue = DBNull.Value; } </code></pre> <p>This does the trick. Although I'd like to know if there is a solution that can be implemented at the DataGridView control level.</p>
<p>I use a typed dataset to provide the values for the dropdown. After filling values from the database I add <em>another</em> row to provide the null support. The final lines of the method that populates the datatable look like this...</p> <pre><code>// Fill dt from datatable... var nullRow = rv.NewRunDropDownEntryRow(); nullRow.SetIDNull(); nullRow.Title = "None"; rv.AddRunDropDownEntryRow(nullRow); rv.AcceptChanges(); </code></pre> <p>After that <em>it just works</em>! The null value displays as "None" in the dropdown, you can easily update to or from null in the bound row.</p> <p>HTH - Richard</p>
43,599
<p>Which ftp client or which syntax allows easy chmod for sub-directories?</p>
<p>LFTP allows for recursive CHMOD if the client allows it. You can accomplish this by logging in with LFTP from a Unix/Linux CLI and then run the following:</p> <pre><code>chmod -R 0755 /www/directory/* </code></pre> <p>You could also setup a real nifty Bash script for this:</p> <pre><code>#!/bin/bash lftp &lt;&lt;EOF set ftp:ssl-allow no set ftp:passive-mode true set ftp:list-options -a open -u [user],[password] [host] chmod -R 0777 /www/directory/* EOF </code></pre> <p>Of course LFTP does not distinguish between files and folders, for running this command on only files/folders respectively I would suggest using FileZilla. It allows this when running the command on a folder.</p>
<p>To chmod all subdirs from where you are (recursive):</p> <pre><code>chmod -R * </code></pre>
40,982
<p>I have already posted something similar <a href="https://stackoverflow.com/questions/118051/c-grid-binding-not-update">here</a> but I would like to ask the question more general over here.</p> <p>Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).</p> <p>Do you have any trick? </p>
<p>Use the <code>DataContractSerializer</code> and create a method for OnDeserialized</p> <pre><code>[OnDeserialized] private void OnDeserialized(StreamingContext c) {} </code></pre> <p>This will let you raise the PropertyChanged event when deserialization is complete</p>
<p>The trick of having it's own <a href="https://stackoverflow.com/questions/118051/c-grid-binding-not-update#118438">Event and binding it after serialization</a> works but is not elegant because require an other event that I would not like to have...</p>
14,901
<p>I have a table with columns</p> <blockquote> <p>Index, Date</p> </blockquote> <p>where an Index may have multiple Dates, and my goal is the following: select a list that looks like</p> <blockquote> <p>Index, MinDate, MaxDate</p> </blockquote> <p>where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present <em>in the entire table for that index</em>. That's easy enough, but then let's constrain this list to appear only for Indexes that are present in a given range of dates. </p> <p>So far, I have the following:</p> <pre><code>SELECT Index, MIN([Date]), MAX([Date]) FROM myTable WHERE Index IN (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') GROUP BY Index ORDER BY Index ASC </code></pre> <p>This is excruciatingly slow. Any way to speed this up? [I am running SQL Server 2000.]</p> <p>Thanks!</p> <p>Edited: For clarity.</p>
<p>I would recommend a derived table approach. Like this:</p> <pre><code>SELECT myTable.Index, MIN(myTable.[Date]), MAX(myTable.[Date]) FROM myTable Inner Join ( SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000') As AliasName On myTable.Index = AliasName.Index GROUP BY myTable.Index ORDER BY myTable.Index ASC </code></pre> <p>EDIT: Upon further review, there is another way you can create this query. The following query may be faster, slower, or execute in the same amount of time. This, of course, depends on how the table is indexed.</p> <pre><code>Select [Index], Min([Date]), Max([Date]) From myTable Group By [Index] Having Sum(Case When [Date] Between '1/1/2000' And '12/31/2000' Then 1 Else 0 End) &gt; 0 </code></pre> <p>Under the best circumstances, this query will cause an index scan (not a seek) to filter out rows you don't want to display. I encourage you to run both queries and pick this oen the executes the fastest.</p>
<p>You don't need the sub-select in the where clause. Also, you could add indexes to the date column. How many rows in the table?</p> <pre><code>SELECT [INDEX], MIN ( [Date] ), MAX ( [Date] ) FROM myTable WHERE [Date] Between '1/1/2000' And '12/31/2000' GROUP BY [Index] ORDER BY [INDEX] ASC </code></pre>
31,707
<p>I thought 2048 security violation error were mean to happen when trying to access other domains. </p> <p>I got:</p> <p><strong>"Security sandbox violation: <a href="http://127.0.0.1/site_media/main.swf" rel="nofollow noreferrer">http://127.0.0.1/site_media/main.swf</a> cannot load data from 127.0.0.1:80"</strong>, isn it the same domain? what is the solution ?</p> <p>on doing</p> <pre><code>var loader:MultipartLoader = new MultipartLoader("http://127.0.0.1/create/"); </code></pre> <p>Did i miss something ?</p>
<p>Despite being called "crossdomain" policy files, the policy actually applies to the combination of both the domain and port: localhost:80 and localhost:443 are not the same thing as far as FP's security policy is concerned. I also don't think that the Flash Player itself assumes a default port of 80 so "localhost" and "localhost:80" are not treated as the same either.</p>
<p>Try using, localhost. If that doesn't work just create a crossdomain file.</p>
47,728
<p>Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results.</p> <p>I have this interface;</p> <pre><code>IPrimaryKey { int ID { get; } } </code></pre> <p>and I have this extension method</p> <pre><code>public static IPrimaryKey GetByID(this IQueryable&lt;IPrimaryKey&gt; source, int id) { return source(obj =&gt; obj.ID == id); } </code></pre> <p>Let's say I have a class, SimpleObj which implements IPrimaryKey. When I have an IQueryable of SimpleObj the GetByID method doesn't exist, unless I explicitally cast as an IQueryable of IPrimaryKey, which is less than ideal.</p> <p>Am I missing something here?</p>
<p>It works, when done right. cfeduke's solution works. However, you don't have to make the <code>IPrimaryKey</code> interface generic, in fact, you don't have to change your original definition at all:</p> <pre><code>public static IPrimaryKey GetByID&lt;T&gt;(this IQueryable&lt;T&gt; source, int id) where T : IPrimaryKey { return source(obj =&gt; obj.ID == id); } </code></pre>
<p>This cannot work due to the fact that generics don't have the ability to follow inheritance patterns. ie. IQueryable&lt;SimpleObj&gt; is not in the inheritance tree of IQueryable&lt;IPrimaryKey&gt;</p>
10,820
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p> <p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p> <p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p> <p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
<p>As of 2017, an easy method to achieve this is the following:</p> <pre><code>import ctypes, sys def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): # Code of your program here else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) </code></pre> <p>If you are using Python 2.x, then you should replace the last line for:</p> <pre><code>ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1) </code></pre> <p>Also note that if you converted you python script into an executable file (using tools like <code>py2exe</code>, <code>cx_freeze</code>, <code>pyinstaller</code>) then you should use <code>sys.argv[1:]</code> instead of <code>sys.argv</code> in the fourth parameter.</p> <p>Some of the advantages here are:</p> <ul> <li>No external libraries required. It only uses <code>ctypes</code> and <code>sys</code> from standard library.</li> <li>Works on both Python 2 and Python 3.</li> <li>There is no need to modify the file resources nor creating a manifest file.</li> <li>If you don't add code below if/else statement, the code won't ever be executed twice.</li> <li>You can get the return value of the API call in the last line and take an action if it fails (code &lt;= 32). Check possible return values <a href="https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecutea?redirectedfrom=MSDN#return-value" rel="noreferrer">here</a>.</li> <li>You can change the display method of the spawned process modifying the sixth parameter.</li> </ul> <p>Documentation for the underlying ShellExecute call is <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx?f=255&amp;MSPPError=-2147217396" rel="noreferrer">here</a>. </p>
<p>If your script always requires an Administrator's privileges then: </p> <pre><code>runas /user:Administrator "python your_script.py" </code></pre>
15,882
<p>Quick question. What do you think, I have a few sites that use a 3 level drop-down menu that will be broken if IE8 released with its current CSS standards in IE8 beta2. So do I take the time to redo those drop downs now? I realize that the way they rendered CSS changed completely between beta 1 and 2, but 2 was/is supposed the be a general use beta and seeing as it is the final beta you would think something as crucial as CSS rendering would have been touched up to work properly.</p> <p>So what do you think, do you wait until 80% (random statistic) of ie7 users automatically update to IE8 and then worry about a broken navigation menu if it still exists. Or do you waste the time now. </p> <p>... if I had it my way all web developers would just make sure that their page did not work in IE8 and then Microsoft would be forced to properly handle CSS.... But I don't usually get things my way.</p>
<p>You can add the meta tag to force IE7 compatible rendering. Your site continues to work, no changes are made to the web site and life is happy for everyone.</p> <p>That said, i'm curious about the "forced to properly handle CSS" bit; IE8 has been pretty big win for CSS standards, but I could be missing the bandwagon. ;)</p> <p>HTML change necessary to force emulated IE7 rendering involves adding a meta tag immediately after the head node.</p> <pre><code>&lt;head&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/&gt; ... &lt;/head&gt; </code></pre>
<p>Personally I find that it really depends on the audience, and the level of effort needed to fix the issue.</p> <p>If I can make a quick, couple hour fix to make it compliant, even if it is for a small subset of users, great! However, if it is much more involved, then I start to balance the potential adoption rate, the potential for Microsoft to change the behavior again, etc.</p> <p>Will MS change the CSS? I don't think anyone really knows that answer....</p>
22,791
<p>Is there a way to check if a file has been opened by ReWrite in Delphi? </p> <p>Code would go something like this:</p> <pre><code>AssignFile(textfile, 'somefile.txt'); if not textFile.IsOpen then Rewrite(textFile); </code></pre>
<p>You can get the filemode. (One moment, I'll create an example).</p> <p>TTextRec(txt).Mode gives you the mode:</p> <pre><code>55216 = closed 55217 = open read 55218 = open write fmClosed = $D7B0; fmInput = $D7B1; fmOutput = $D7B2; fmInOut = $D7B3; </code></pre> <p>Search TTextRec in the system unit for more information.</p>
<p>Joseph's answer works perfectly - I called the function <code>filenotopen</code> and changed the line if </p> <pre><code>Result := (HFileRes = INVALID_HANDLE_VALUE); </code></pre> <p>to</p> <pre><code>Result := NOT (HFileRes = INVALID_HANDLE_VALUE); </code></pre> <p>I also removed the line 'if not(Result) then begin' (and the 'end') so that it ALWAYS closes the handle or subsequent assignments and reads give errors</p> <p>I now call it like this</p> <pre><code>if filenotopen(filename) then begin assignfile(f,filename); reset(f) etc; end else message('file open by a different program') </code></pre>
17,069
<p>To summarize, as we all know,</p> <p>a) Silverlight is expected to be hosted by a browser, and runs in an isolated sandbox so that there won’t be any security issues</p> <ol> <li>Silverlight don’t have direct access to the file system, other than the isolated storage area </li> <li>There is no direct way to open common dialog boxes like File Save in Silverlight (Though Opendialog box is supported).</li> </ol> <p>b) Silverlight can’t access local resources like a printer</p> <p>What are the ways to go beyond the sandbox, so that I can host a Silverlight application locally, to read files and save them back if required, to hand over data to a printer, and so on..</p> <p><strong>Update:</strong></p> <p>Is full WPF is not an option for me? No. I'm also interested in a cross platform solution - for instance, you could host Silverlight in Mono Web browser control, so that you can run it virtually anywhere.</p> <p>The idea is to re-use the same application that I'm building for web in my desktop as well, by providing separation of concerns at some areas - like persistence, resource access etc. Scenarios:</p> <p>1- Some kind of gadget container, with access to local resources. 2 - A desktop Silver light based media application</p> <p><strong>Update:</strong></p> <p>I just did a POC to enable me to access printer and save files locally, of course through a shell where I'm hosting my Silverlight application. If you wan't you can have a look at the post <a href="http://amazedsaint.blogspot.com/2008/12/thinking-outside-silverlight-sandbox.html" rel="nofollow noreferrer">here in my blog</a></p>
<p>Two ways I can think about is,</p> <p><strong>Create a "Shell"</strong></p> <p>Host the HTML Page with Silverlight, in a Winforms desktop application, using a web browser control, and communicate to and fro using HTML DOM. Then I can request the hosted shell to do things like printing. <a href="http://amazedsaint.blogspot.com/2008/12/thinking-outside-silverlight-sandbox.html" rel="nofollow noreferrer">See details here</a></p> <p>Mono also has a web browser control - based on FireFox XULRunner instead of IE - not yet succeeded in loading Silverlight inside that. Another option might be using Webkit.</p> <p><img src="https://3.bp.blogspot.com/__Mw4iY-4nuY/SUYUVhMcMtI/AAAAAAAAAXU/5vYVQz2EBnw/s400/image001.gif" alt="Desktop Shell"></p> <p><strong>Embed a web server</strong></p> <p>Embed a light weight web server with in the Host application, and handle requests to perform such operations. You can probably define a protocol on top of HTTP for things like saving to a local folder, sending data to print etc.</p> <p><img src="https://3.bp.blogspot.com/__Mw4iY-4nuY/SUYUW8Rf2PI/AAAAAAAAAXc/kb-6LCr17gA/s400/image002.gif" alt="Embedding A Server"></p>
<p>I am attempting to also reuse a codebase for both desktop and silverlight. There are two options that I know of in addition to the ones mentioned</p> <p>If you directly reference (instead of a project reference) a silverlight dll from a normal project, it should work. This would let you reference a silverlight dll for both projects.</p> <p>Have two project files (one wpf, one silverlight) that point to the same set of files. You might have to have to use a few compiler flags here and there, but this should let you use the same files for both.</p>
47,991
<p>What would be a very fast way to determine if your connectionstring lets you connect to a database?</p> <p>Normally a connection attempt keeps the user waiting a long time before notifying the attempt was futile anyway.</p>
<p>You haven't mentioned what database you are connecting to, however. In <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="nofollow noreferrer">SQL Server 2005</a>, from .NET, you can specify a connection timeout in your connection string like so:</p> <pre><code>server=&lt;server&gt;;database=&lt;database&gt;;uid=&lt;user&gt;;password=&lt;password&gt;;Connect Timeout=3 </code></pre> <p>This will try to connect to the server and if it doesn't do so in three seconds, it will throw a timeout error.</p>
<p>Shorten the timeout on the connection string and execute something trivial.</p> <p>The wait should be about the same as the timeout.</p> <p>You would still need a second or two though.</p>
3,199
<p>How would I reset the primary key counter on a sql table and update each row with a new primary key?</p>
<p>I would add another column to the table first, populate that with the new PK.</p> <p>Then I'd use update statements to update the new fk fields in all related tables.</p> <p>Then you can drop the old PK and old fk fields.</p> <p><strong>EDIT:</strong> Yes, as Ian says you will have to drop and then recreate all foreign key constraints.</p>
<p>If this is Microsoft's SQL Server, one thing you could do is use the <strong>[dbcc checkident](<a href="http://msdn.microsoft.com/en-us/library/ms176057(SQL.90).aspx)" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms176057(SQL.90).aspx)</a></strong></p> <p>Assume you have a single table that you want to move around data within along with renumbering the primary keys. For the example, the name of the table is <strong>ErrorCode</strong>. It has two fields, <strong>ErrorCodeID</strong> (which is the primary key) and a <strong>Description</strong>. </p> <h2>Example Code Using dbcc checkident</h2> <pre><code>-- Reset the primary key counter dbcc checkident(ErrorCode, reseed, 7000) -- Move all rows greater than 8000 to the 7000 range insert into ErrorCode select Description from ErrorCode where ErrorCodeID &gt;= 8000 -- Delete the old rows delete ErrorCode where ErrorCodeID &gt;= 8000 -- Reset the primary key counter dbcc checkident(ErrorCode, reseed, 8000) </code></pre> <p>With this example, you'll effectively be moving all rows to a different primary key and then resetting so the next insert takes on an 8000 ID.</p> <p>Hope this helps a bit!</p>
28,470
<p>I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via </p> <pre><code>$element = $dom-&gt;getElementsByTagName('foo')-&gt;item(0); foreach($element-&gt;childNodes as $node){ $data[$node-&gt;nodeName] = $node-&gt;nodeValue; } </code></pre> <p>However, what I'm trying to do, is from an XML like, </p> <pre><code>&lt;stuff&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;value/&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;/stuff&gt; </code></pre> <p>iterate over every <em>foo</em> tag, and get specific <em>bar</em> or <em>pub</em>, and get values from there. Now, how do I iterate over <em>foo</em> so that I can still access specific child nodes by name?</p>
<p>Not tested, but what about:</p> <pre><code>$elements = $dom-&gt;getElementsByTagName('foo'); $data = array(); foreach($elements as $node){ foreach($node-&gt;childNodes as $child) { $data[] = array($child-&gt;nodeName =&gt; $child-&gt;nodeValue); } } </code></pre>
<p>With <a href="https://github.com/servo-php/fluidxml" rel="nofollow"><strong>FluidXML</strong></a> you can query and iterate XML very easly.</p> <pre><code>$data = []; $store_child = function($i, $fooChild) use (&amp;$data) { $data[] = [ $fooChild-&gt;nodeName =&gt; $fooChild-&gt;nodeValue ]; }; fluidxml($dom)-&gt;query('//foo/*')-&gt;each($store_child); </code></pre> <p><a href="https://github.com/servo-php/fluidxml" rel="nofollow">https://github.com/servo-php/fluidxml</a></p>
23,314
<p>Application frameworks such as DotNetNuke, Eclipse, Websphere and so forth are available today which offer customizable frameworks that can be used as dashboard applications. Do you use these or do you and your peers keep writing amazing, modular, maintainable dashboard frameworks which you support yourselves?</p> <p>Are there any good web based, OS independent frameworks out there that you suggest using to build your own enterprise class infrastructure around?</p>
<p>The one I use is Oracle Application Development Framework. It's a complete, fully supported framework, and Oracle use it themselves to build their own enterprise applications. It comes with a lot of JSF components that are very easy to bind to the underlying data objects. I'd recommend this for all Java applications that need database data. </p> <p>You find a discussion of it on the Oracle Wiki: <a href="http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent" rel="nofollow noreferrer">http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent</a></p>
<p>At work, we try to create from scratch as little as possible. We use Frameworks a lot (maybe not always end to end frameworks). We have used Dot Net Nuke a lot. Another framework we use a lot is CSLA.</p>
10,565
<p>I have a project with several sources directories : </p> <pre><code>src/A /B /C </code></pre> <p>In each, the Makefile.am contains </p> <pre><code>AM_CXXFLAGS = -fPIC -Wall -Wextra </code></pre> <p>How can avoid repeating this in each source folder ? </p> <p>I tried to modifiy src/Makefile.am and the configure.in, but without success. I thought I could use AC_PROG_CXX to set the compilation flags globally but can't find much documentation on how to use those macro (do you have any pointer to such a documentation ?).</p> <p>Thanks in advance</p>
<p>You can do several things:</p> <p>(1) One solution is to include a common makefile fragment on all your <code>Makefile.am</code>s:</p> <pre><code>include $(top_srcdir)/common.mk ... bin_PROGRAMS = foo foo_SOURCES = ... </code></pre> <p>in that case you would write</p> <pre><code>AM_CXXFLAGS = -fpic -Wall -Wextra </code></pre> <p>to <code>common.mk</code> and in the future it will be easier to add more macros or rules to all <code>Makefile.am</code>s by just editing this file.</p> <p>(2) Another solution would be to set these variables globally in your <code>configure.ac</code> (the name <code>configure.in</code> has been deprecated long ago), as in :</p> <pre><code>... AC_SUBST([AM_CXXFLAGS], [-fpic -Wall -Wextra]) ... </code></pre> <p>Then you don't even have to say anything in your <code>Makefile.am</code>s, they automatically inherit this global definition. The drawback is that you can't opt-out easily (with the first solution it's easy to decide not to include <code>common.mk</code>) and the dependency is not really explicit to third-party people (when they read the <code>Makefile.am</code> they have no hint about where the flags may come from).</p> <p>(3) A third solution would be to do as <a href="https://stackoverflow.com/users/15622/orsogufo">orsogufo</a> suggested: overwriting the user variable CXXFLAGS in <code>configure.ac</code>. I would advise against it, because it defeats one of the features of the GNU Build System: users are allowed to override this variable at <code>make</code>-time. For instance you may want to type</p> <pre><code>make CXXFLAGS='-O0 -ggdb' </code></pre> <p>when debugging a piece of code, and this will overwrite any definition of <code>CXXFLAGS</code> (but not those in <code>AM_CXXFLAGS</code>). To be honest, most projects fails to support this correctly because they play tricks with <code>CXXFLAGS</code>.</p> <p>Finally, I should mention that <code>-fpic</code>, <code>-Wall</code>, and <code>-Werror</code> are not portable options. Depending on the scope of your project you may want to add configure check for these (<a href="http://www.gnu.org/software/gnulib/" rel="nofollow noreferrer">gnulib</a> recently acquired new macros to tests for warnings flags, and <a href="http://www.gnu.org/software/libtool/" rel="nofollow noreferrer">libtool</a> can be used to build shared libraries).</p>
<p>Use EXTRA_CFLAGS in configure.ac</p> <p>For example for your case it would be this:</p> <p><code>EXTRA_CFLAGS=-fPIC -Wall -Wextra</code></p>
41,922
<p>Is there any alternative image manipulation library for .net? I would prefer something that is managed and open source. </p> <p>I ask this because of two reasons:</p> <ol> <li>I have encountered hard to debug GDI+ errors with System.Drawing in the past</li> <li>I have read that using System.Drawing in asp.net web applications is not 100% supported.</li> </ol> <p>Thanks!</p> <p>edit: clarification, I know that System.Drawing can work asp.net web apps - I have used it in the past. I really just wonder if there are any managed image manipulation libraries for .net :)</p>
<p>I don't know of any fully-managed 2D drawing libraries that are either free or open-source (there appears to be a few commercially available, but OSS is the way to go). However, you might look into <a href="http://www.go-mono.com/docs/index.aspx?tlink=0@N:Cairo" rel="nofollow noreferrer">the Mono bindings to Cairo</a>.</p> <p>Cairo is a platform independent 2D drawing API. You can find more information about it at <a href="http://cairographics.org" rel="nofollow noreferrer">the Cairo homepage</a>. The <a href="http://en.wikipedia.org/wiki/Cairo_(graphics)" rel="nofollow noreferrer">Cairo Wikipedia page</a> also has some good info.</p> <p>Cairo is also used fairly widely in the Open Source world, which to me says something about its robustness. Mozilla, Webkit, and Mono all use it, among others. Ironically, Mono actually uses it to back their System.Drawing implementation... go figure.</p> <p>There might also be a way to use Mono's System.Drawing implementation as a drop-in replacement for the Microsoft implementation, though I'm not sure how or if that would even work. I would probably start by replacing the System.Drawing.dll reference with Mono's version, and then try to deal with any errors.</p>
<p>With respect to (1), most of the hard to debug errors are due to not closing open handles (Dispose() in managed-land). I'm curious where you heard (2).</p>
3,426
<p>I need a tool that handle both on-screen and printed reports, via my C# application. </p> <p>I'm looking for simple, standard and powerful. </p> <p>I need to be able to give the user the ability to select which columns to display, formatting, etc... with my own GUI and dynamically build the report based upon their choices. Crystal does not fit the bill here because the columns cannot be added on the fly (and the column widths can not be adjusted on the fly).</p> <p>I'm thinking of using HTML with the WebBrowser control in my app, but I will have very little control over printing and print preview.</p> <p>Another option is go to .NET 3.5 (I'm using 2.0) and use XAML with Flow Documents.</p> <p>What would you use?</p>
<p>We use SQL reporting services. HTML reports have their place but you dont get very much controlling over formatting. <BR></p> <p>SQL reporting services summary:</p> <p>Advantages:<BR> Basic version is free<BR> Included with SQL express<BR> Many exporting options pdf, html, csv etc<BR> Can use many different datasources<BR> Webservice which exposes various methods<BR> SQL standard editon includes a report builder component to allow users create and share their own reports<BR> Lots of features for querying formatting etc<BR> Scheduling options<BR> Extensibility import .net framework dlls for custom functionality<BR> Familiar microsoft environment<BR> <BR><BR> Disadvantages:<BR> An extra thing to setup<BR> Seemless authentication between application and report server can be a pain depending on your setup<BR> A little bit of a learning curve although its not too hard to pick up <BR> Report model creator needs some work and doesnt automatically a-z fields<BR> <BR><BR> I have heard good things about DevXpress so may be worth looking into. </p> <p>I used Crystal about 5 years ago and remember it being a pain to setup and was costly licence wise.</p>
<p>I'm currently considering DevXpress XtraReports as a replacement for CR. So far I like what I see.</p>
19,887
<p>What's the point in the standard pattern for event delegates in .net? I.e. the EventHandler predefined delegate? Why not just choose the most appropriate signature for the requirement?</p> <p>Edit: And furthermore, is it necessary to slavishly follow Microsoft's example in all cases?</p>
<p>It's mainly for consistency and versioning—with the <code>sender</code> paramater as always System.Object and the <code>args</code> parameter as always a System.EventArgs, or a dervied class thereof, you can change the sender argument passed to it as well as change the EventArgs type afterwards without breaking any existing code.</p> <p>The whole .NET eventing idiom was designed to support component-based development, where the calling code is not under control of the developer of the component with the events.</p>
<p>It decouples the caller from the callee.</p>
30,708
<p>I have some Ruby code which takes dates on the command line in the format:</p> <pre><code>-d 20080101,20080201..20080229,20080301 </code></pre> <p>I want to run for all dates between <code>20080201</code> and <code>20080229</code> inclusive and the other dates present in the list.</p> <p>I can get the string <code>20080201..20080229</code>, so is the best way to convert this to a Range instance? Currently, I am using <code>eval</code>, but it feels like there should be a better way.</p> <hr> <p>@Purfideas I was kind of looking for a more general answer for converting any string of type <code>int..int</code> to a Range I guess.</p>
<p>But then just do </p> <pre><code>ends = '20080201..20080229'.split('..').map{|d| Integer(d)} ends[0]..ends[1] </code></pre> <p>anyway I don't recommend eval, for security reasons</p>
<p>Combining @Purfideas answer with another answer somewhere on StackOverflow, I solved this by also surrounding the code with an input check, so the only thing used is a valid enumerable </p> <pre><code>if !value[/^[0-9]+\.\.[0-9]+$/].nil? ends = value.split('..').map{|d| Integer(d)} value = ends[0]..ends[1] end </code></pre> <p>It essentially rewrites your string value to a enumerable value. This comes in handy if you add a enumerable field in a yaml config file.</p> <p>If you need it for your application, you could extend the regex with an optional third literal dot, that could be optional.</p>
7,692
<p>I have a ARM11 based hardware board which runs a Linux kernel ver. 2.6.21.5-cfs-v19. I have my application running on this ARM-LINUX board. To do source level debugging, of my application I used to use gdb from command prompt of the linux board, that was with some earlier version of the board linux version. </p> <p>With this version 2.6.21.5-cfs-v19, I dont have a related version of gdb for the board. I tried to look around to get gdb for this version of linux and arm port of it, but without much success. Can anyone point me where I can get either an independant executable for gdb for above mentioned os and board configuration or source for the same, which I may try compiling for that target.</p> <p>-AD.</p>
<p>Sometime ago I published an <a href="http://www.linux.com/feature/121735" rel="nofollow noreferrer">article</a> about cross-target debugging with GDB and GDBServer. The target processor there is PPC7450, but it's rather detailed, so maybe you'll find it useful.</p>
<p>You might have some luck using <a href="http://wiki.openembedded.net/index.php/Main_Page" rel="nofollow noreferrer">OpenEmbedded</a>. If there's no precompiled version you can use right away, setting up an OE-cross compile environment is not that hard. </p> <p>Another option could be to install gdb-server on the board, like described in <a href="http://dominion.thruhere.net/koen/cms/using-gdbserver" rel="nofollow noreferrer">this blogpost</a>.</p>
7,457
<p>This question is directed to the non-english speaking people here.</p> <p><em>It is somewhat biased because SO is an &quot;english-speaking&quot; web forum, so... In the other hand, most developers would know english anyway...</em></p> <p>In your locale culture, are technical words translated into locale words ? For example, how &quot;Design Pattern&quot;, or &quot;Factory&quot;, or whatever are written/said in german, spanish, etc. etc. when used by IT? Are the english words prefered? The local translation? Do the two version (english/locale) are evenly used?</p> <h3>Edit</h3> <p>Could you write with your answer the locale translation of &quot;Design Pattern&quot;?</p> <p>In french, according to Wikipedia.fr, it is &quot;Patron de conception&quot;, which translates back as &quot;Model of Conceptualization&quot; (I guess).</p>
<p>Coming from Switzerland and speaking German I vote for keeping them in English. I have been at an IBM congress some time back (OS/2 0.9 developpers conference, I0m giving away my age here). At that time most people were not as familiar with the names of interface components (combobox, listbox, button) as they are today, especially not the many mainframe programmers attending.</p> <p>So everything was translated simultaniously into different languages. And i mean everything. This let to the effect that:</p> <ul> <li>A wrong standard set of names was put in place</li> <li>Programmers from different nations were not able to talk to each other</li> <li>It was really hard to follow the talks, especially if you had some previous knowledge</li> </ul> <p>The only way to go about was to have one ear covered with the headphones while listening to the English original speach and trying to put the English names of things in the right spot in the German translation. It was so tyring.</p>
<p>What I normally do is to danish-sify (I'm from denmark), or use the danish words for IT terms when talking to business people, or normal non-it people. If it is IT people i just use the english terms.</p>
13,617
<p>I was going to Ask a Question earlier today when I was presented to a surprising functionality in Stackoverflow. When I wrote my question title stackoverflow suggested me several related questions and I found out that there was already two similar questions. That was stunning! </p> <p>Then I started thinking how I would implement such function. How I would order questions by relatedness:</p> <ol> <li>Question that have higher number of words matchs with the new question</li> <li>If the number of matchs are the same, the order of words is considered</li> <li>Words that appears in the title has higher relevancy</li> </ol> <p>That would be a simple workflow or a complex score algortithm? Some stemming to increase the recall, maybe? Is there some library the implements this function? What other aspects would you consider? Maybe Jeff could answer himself! How did you implemented this in Stackoverflow? :)</p>
<p>One such way to implement such an algorithm would involve ranking the questions as per a heuristic function which assigns a 'relevance' weight factor using the following steps:</p> <ol> <li>Apply a noise filter to the 'New' question to remove words that are common across a large number of objects such as: 'the', 'and', 'or', etc.</li> <li>Get the number of words contained in the 'New' question which match the words the set of questions already posted on the website. [A]</li> <li>Get the number of tag matches between the words in the 'New' question and the available. [B]</li> <li>Compute the 'relevance weight' based on [A] and [B] as 'x[A] + y[B]', where x and y are weight multipliers (Assign a higher weight multiplier to [B] as tagging is more relevant than simple word search)</li> <li>Get the top 5 questions which have the highest 'relevance weight'.</li> </ol> <p>The heuristic might require tweaking to get optimal results, but it should work.</p>
<p>Isn't StackOverflow going to be open sourced at some point? If so, you can always find out how they did it there.</p> <p>Update: It appears that they say they <em>might</em> open source it. I hope they do.</p>
6,399
<p>I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy. </p> <p>If I use the web service, then it is possible to set proxy. </p>
<p>I'm not entirely sure if this is what you are looking for but here you go.</p> <pre><code> MyClient client = new MyClient(); client.ClientCredentials.UserName.UserName = "u"; client.ClientCredentials.UserName.Password = "p"; </code></pre>
<p>Not sure if this is what you are looking for but the below is a working code sample to authenticate using the client credentials.</p> <pre><code> Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "username" client.ClientCredentials.UserName.Password = "password" Dim ProductList As List(Of Product) = client.GetProducts() mView.Products = ProductList client.Close() </code></pre>
13,094
<p>How can I call a C++ function from C# .NET?</p>
<ol> <li><p>compile the C++ function into a dll and <a href="http://msdn.microsoft.com/en-us/magazine/cc164123.aspx" rel="nofollow noreferrer">use P/Invoke</a></p> <p>or</p> </li> <li><p>compile the C++ function into a C++/CLI assembly, wrap in a managed C++ class, and then treat like any other assembly (add a reference, use a using statement and call the class)</p> </li> </ol>
<p>Or</p> <p>Create a COM wrapper and then reference it from .NET</p>
35,998
<p>Can you use the bash "getopts" function twice in the same script?</p> <p>I have a set of options that would mean different things depending on the value of a specific option. Since I can't guarantee that getopts will evaluate that specific option first, I would like to run getopts one time, using only that specific option, then run it a second time using the other options.</p>
<p>Yes, just reset OPTIND afterwards.</p> <pre><code>#!/bin/bash set -- -1 while getopts 1 opt; do case "${opt}" in 1) echo "Worked!";; *) exit 1; esac done OPTIND=1 set -- -2 while getopts 2 opt; do case "${opt}" in 2) echo "Worked!";; *) exit 1; esac done </code></pre>
<p>getopts does not modify the original arguments, as opposed to the older getopt standalone executable. You can use the bash built-in getopts over and over without modifying your original input.</p> <p>See the bash man page for more info.</p> <p>HTH.</p> <p>cheers,</p> <p>Rob</p>
17,467