instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>How do I get a function's name as a string?</p> <pre><code>def foo(): pass &gt;&gt;&gt; name_of(foo) &quot;foo&quot; </code></pre>
<pre><code>my_function.__name__ </code></pre> <p>Using <code>__name__</code> is the preferred method as it applies uniformly. Unlike <code>func_name</code>, it works on built-in functions as well:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.time.func_name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' &gt;&gt;&gt; time.time.__name__ 'time' </code></pre> <p>Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a <code>__name__</code> attribute too, so you only have remember one special name.</p>
<p>You can get a function's name as a string by using the special <code>__name__</code> variable.</p> <pre class="lang-py prettyprint-override"><code>def my_function(): pass print(my_function.__name__) # prints &quot;my_function&quot; </code></pre>
31,319
<p>When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.</p> <p>As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:</p> <pre><code>if (condition) { do { ... } while (same condition); } </code></pre> <p>or the inverse (<code>if</code> inside the <code>while</code>), it makes me wonder if they actually wrote it that way or if they added the <code>if</code> statement when they realized the loop didn't handle the null case.</p> <p>I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?</p>
<p>I always follow the rule that if it should run zero or more times, test at the beginning, if it must run <em>once</em> or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.</p>
<p>In a typical Discrete Structures class in computer science, it's an easy proof that there is an equivalence mapping between the two.</p> <p>Stylistically, I prefer while (easy-expr) { } when easy-expr is known up front and ready to go, and the loop doesn't have a lot of repeated overhead/initialization. I prefer do { } while (somewhat-less-easy-expr); when there is more repeated overhead and the condition may not be quite so simple to set up ahead of time. If I write an infinite loop, I always use while (true) { }. I can't explain why, but I just don't like writing for (;;) { }.</p>
27,680
<p>Been thinking, what's the difference between declaring a variable with [] or * ? The way I see it:</p> <pre><code>char *str = new char[100]; char str2[] = "Hi world!"; </code></pre> <p>.. should be the main difference, though Im unsure if you can do something like</p> <pre><code>char *str = "Hi all"; </code></pre> <p>.. since the pointer should the reference to a static member, which I don't know if it can?</p> <p>Anyways, what's really bugging me is knowing the difference between:</p> <pre><code>void upperCaseString(char *_str) {}; void upperCaseString(char _str[]) {}; </code></pre> <p>So, would be much appreciated if anyone could tell me the difference? I have a hunch that both might be compiled down the same, except in some special cases?</p> <p>Ty</p>
<p>Let's look into it (for the following, note <code>char const</code> and <code>const char</code> are the same in C++):</p> <h2>String literals and char *</h2> <p><code>"hello"</code> is an array of 6 const characters: <code>char const[6]</code>. As every array, it can convert implicitly to a pointer to its first element: <code>char const * s = "hello";</code> For compatibility with C code, C++ allows one other conversion, which would be otherwise ill-formed: <code>char * s = "hello";</code> it removes the const!. This is an exception, to allow that C-ish code to compile, but it is deprecated to make a <code>char *</code> point to a string literal. So what do we have for <code>char * s = "foo";</code> ?</p> <p><code>"foo"</code> -> <code>array-to-pointer</code> -> <code>char const*</code> -> <code>qualification-conversion</code> -> <code>char *</code>. A string literal is read-only, and won't be allocated on the stack. You can freely make a pointer point to them, and return that one from a function, <em>without</em> crashing :). </p> <h3>Initialization of an array using a String literal</h3> <p>Now, what is <code>char s[] = "hello";</code> ? It's a <em>whole</em> other thing. That will create an array of characters, and fill it with the String <code>"hello"</code>. The literal isn't pointed to. Instead it is copied to the character-array. And the array is created <em>on the stack</em>. You cannot validly return a pointer to it from a function.</p> <h2>Array Parameter types.</h2> <p><p> How can you make your function accept an array as parameter? You just declare your parameter to be an array:</p> <pre><code>void accept_array(char foo[]); </code></pre> <p>but you omit the size. Actually, any size would do it, as it is just ignored: The Standard says that parameters declared in that way will be transformed to be the same as</p> <pre><code>void accept_array(char * foo); </code></pre> <h3>Excursion: Multi Dimensional Arrays</h3> <p>Substitute <code>char</code> by any type, including arrays itself:</p> <pre><code>void accept_array(char foo[][10]); </code></pre> <p>accepts a two-dimensional array, whose last dimension has size 10. <em>The first element of a multi-dimensional array is its first sub-array of the next dimension</em>! Now, let's transform it. It will be a pointer to its first element again. So, actually it will accept a pointer to an array of 10 chars: (remove the <code>[]</code> in head, and then just make a pointer to the type you see in your head then):</p> <pre><code>void accept_array(char (*foo)[10]); </code></pre> <p>As arrays implicitly convert to a pointer to their first element, you can just pass an two-dimensional array in it (whose last dimension size is 10), and it will work. Indeed, that's the case for <em>any</em> n-dimensional array, including the special-case of <code>n = 1</code>; </p> <h2>Conclusion</h2> <pre><code>void upperCaseString(char *_str) {}; </code></pre> <p>and </p> <pre><code>void upperCaseString(char _str[]) {}; </code></pre> <p>are the same, as the first is just a pointer to char. But note if you want to pass a String-literal to that (say it doesn't change its argument), then you should change the parameter to <code>char const* _str</code> so you don't do deprecated things. </p>
<p>The first option dynamically allocates 100 bytes.</p> <p>The second option statically allocates 10 bytes (9 for the string + nul character).</p> <p>Your third example shouldn't work - you're trying to statically-fill a dynamic item.</p> <p>As to the <code>upperCaseString()</code> question, once the C-string has been allocated and defined, you can iterate through it either by array indexing or by pointer notation, because an array is really just a convenient way to wrap pointer arithmetic in C.</p> <hr> <p>(That's the simple answer - I expect someone else will have the authoritative, complicated answer out of the spec :))</p>
39,704
<p>I have an enumeration of delivery status codes. And when I save delivery data to the database they are stored with a foreign key to a table containing the same data (i.e. the same delivery codes)</p> <p>What is the best strategy for keeping an enumeration in synch with data in a database?</p> <p>Do you just remember to add to the enumeration when a new code is added to the database?</p> <p>Or load the data into a dictionary when the application starts? And use the dictionary instead of an enumeration? Though this means that I don't have a strongly typed representation of the data - which I definitely want.</p> <p>Or something else?</p> <p>The data is not very volatile but new codes do get added once every blue moon</p> <p>Would appreciate any suggestions.</p> <p>thanks</p>
<p>I use T4 templates in Visual Studio 2008. This way, I can force code generation during build and it generates Enums for each table that I want. </p> <p>A good starting point would be <a href="http://dotnet.org.za/hiltong/archive/2008/08/06/generating-enums-from-database-tables.aspx" rel="nofollow noreferrer">Hilton Giesenow's sample</a>, which I believe answers exactly your question.</p> <p>A more interesting approach, from a different angle, would be to use SQL views to emulate enums in the database. This way you synchronize the database with your C# (or others) code. You can find a great post about it on Oleg Sych's blog, <a href="http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/" rel="nofollow noreferrer">here</a>.</p>
<p>When I use a enumeration in the code, I usually store the formatted name as a varchar in the database rather than keep a table of the enumeration values in the database. I realize that this is not as normalized as one might like, but I believe it is better than trying to keep the database and my enumeration synched. All that is needed is to format on insert/update and parse on select to reconstitute the value back into the enumeration.</p> <p>I only do this when I believe that the enumeration is going to be fixed -- although, I too have made infrequent updates. If I believe that it is likely that the data will be regularly updated, I won't use an enumeration and will have a separate table in the database with foreign key references.</p>
41,780
<p>I am trying to generate some code at runtime using the DynamicMethod class in the Reflection.Emit namespace but for some reason its throwing a "VerificationException". Here is the IL code I am trying to use...</p> <pre><code>ldarg.1 ldarg.0 ldfld, System.String FirstName callvirt, Void Write(System.String) ldarg.1 ldarg.0 ldfld, System.String LastName callvirt, Void Write(System.String) ldarg.1 ldarg.0 ldfld, Int32 Age callvirt, Void Write(Int32) ret </code></pre> <p>I need a way to debug the generated IL code. What options do I have? I am using VS2008 professional.</p>
<p>I have found some more help here...</p> <p><a href="http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx" rel="noreferrer">DebuggerVisualizer for DynamicMethod (Show me the IL) </a> It's is a debugger visualizer using which you will be able to see the generated IL at runtime!</p> <p>And even better is <a href="http://blogs.msdn.com/yirutang/archive/2005/05/26/422373.aspx" rel="noreferrer">Debugging LCG</a> which allows you to debug the generated code at runtime using Windbg!</p>
<p>There is no way to debug IL directly in the sense of using a debugger (not builtin at least). You really only have two options here</p> <ol> <li>Ask Rob suggested. Manually type out the IL and ilasm into a DLL/EXE. Then run peverify on the resulting DLL to see your error.</li> <li>If you are actually wanting to debug the IL then you're likely stuck with doing it raw assembly. </li> </ol>
41,567
<p>I'm using a winforms webbrowser control to display some content in a windows forms app. I'm using the DocumentText property to write the generated HTML. That part is working spectacularly. Now I want to use some images in the markup. (I also would prefer to use linked CSS and JavaScript, however, that can be worked around by just embedding it.)</p> <p>I have been googling over the course of several days and can't seem to find an answer to the title question. </p> <p>I tried using a relative reference: the app exe is in the bin\debug. The images live in the "Images" directory at the root of the project. I've set the images to be copied to the output directory on compile, so they end up in bin\debug\Images*. So I then use a reference like this "Images..." thinking it will be relative to the exe. However, when I look at the image properties in the embedded browser window, I see the image URL to be "about:blankImages/*". Everything seems to be relative to "about:blank" when HTML is written to the control. Lacking a location context, I can't figure out what to use for a relative file resource reference.</p> <p>I poked around the properties of the control to see if there is a way to set something to fix this. I created a blank html page, and pointed the browser at it using the "Navigate()" method, using the full local path to the file. This worked fine with the browser reporting the local "file:///..." path to the blank page. Then I again wrote to the browser, this time using Document.Write(). Again, the browser now reports "about:blank" as the URL.</p> <p>Short of writing the dynamic HTML results to a real file, is there no other way to reference a file resource?</p> <p>I am going to try one last thing: constructing absolute file paths to the images and writing those to the HTML. My HTML is being generated using an XSL transform of a serialized object's XML so I'll need to play with some XSL parameters which will take a little extra time as I'm not that familiar with them.</p>
<p>Here's what we do, although I should mention that we use a custom web browser to remove such things as the ability to right-click and see the good old IE context menu:</p> <pre><code>public class HtmlFormatter { /// &lt;summary&gt; /// Indicator that this is a URI referencing the local /// file path. /// &lt;/summary&gt; public static readonly string FILE_URL_PREFIX = "file://"; /// &lt;summary&gt; /// The path separator for HTML paths. /// &lt;/summary&gt; public const string PATH_SEPARATOR = "/"; } // We need to add the proper paths to each image source // designation that match where they are being placed on disk. String html = HtmlFormatter.ReplaceImagePath( myHtml, HtmlFormatter.FILE_URL_PREFIX + ApplicationPath.FullAppPath + HtmlFormatter.PATH_SEPARATOR); </code></pre> <p>Basically, you need to have an image path that has a file URI, e.g. </p> <pre><code>&lt;img src="file://ApplicationPath/images/myImage.gif"&gt; </code></pre>
<p>I ended up using something that's basically the same as what Ken suggested. However, instead of manually appending the file prefix, I used the UriBuilder class to build the complete URI with the "file" protocol.</p> <p>This also solved a subsequent problem when we tested the app in a more realistic location, Program Files. The spaces was encoded, but the OS couldn't deal with the encoded characters when the file was referenced using a standard system path (i.e. "C:\Program%20Files..."). Using the true URI value (file:///C:/Program Files/...) worked.</p>
9,767
<p><p>How to include any assembly code lines into my C program ? <p>In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?</p>
<p>One way to include assembly code is to add a wrapper function and write the assembly code in the asm block, as shown in the example below:</p> <pre><code>void wrapper_function() { asm { /* your assembly code */ } } </code></pre>
<p>You can also link in the object files. But inline assembler is much easier to maintain.</p>
28,845
<p>Is there an elegant way to have performant, natural sorting in a MySQL database?</p> <p>For example if I have this data set:</p> <ul> <li>Final Fantasy</li> <li>Final Fantasy 4</li> <li>Final Fantasy 10</li> <li>Final Fantasy 12</li> <li>Final Fantasy 12: Chains of Promathia</li> <li>Final Fantasy Adventure</li> <li>Final Fantasy Origins</li> <li>Final Fantasy Tactics</li> </ul> <p>Any other <strong>elegant</strong> solution than to split up the games' names into their components </p> <ul> <li><em>Title</em>: "Final Fantasy"</li> <li><em>Number</em>: "12"</li> <li><em>Subtitle</em>: "Chains of Promathia"</li> </ul> <p>to make sure that they come out in the right order? (10 after 4, not before 2).</p> <p>Doing so is a pain in the a** because every now and then there's another game that breaks that mechanism of parsing the game title (e.g. "Warhammer 40,000", "James Bond 007")</p>
<p>Here is a quick solution:</p> <pre><code>SELECT alphanumeric, integer FROM sorting_test ORDER BY LENGTH(alphanumeric), alphanumeric </code></pre>
<p>I know this topic is ancient but I think I've found a way to do this:</p> <pre><code>SELECT * FROM `table` ORDER BY CONCAT( GREATEST( LOCATE('1', name), LOCATE('2', name), LOCATE('3', name), LOCATE('4', name), LOCATE('5', name), LOCATE('6', name), LOCATE('7', name), LOCATE('8', name), LOCATE('9', name) ), name ) ASC </code></pre> <p>Scrap that, it sorted the following set incorrectly (It's useless lol):</p> <p>Final Fantasy 1 Final Fantasy 2 Final Fantasy 5 Final Fantasy 7 Final Fantasy 7: Advent Children Final Fantasy 12 Final Fantasy 112 FF1 FF2</p>
18,551
<p>I am looking for a redistributable component to convert HTML to PDF.</p> <p>I would - at the moment - like to avoid using a "PDF printer", as this requires a printer installation and some user "playing around" in the printers panel might break that feature.</p> <p>The HTML is available in a Browser control or as external file. The HTML is normally fairly simple, but customers can create their own templates, so a "good range" of HTML should be supported.</p> <p>Should be accessible for an automated process from C++ - DLL / COM / external executable with command line support are all fine. </p> <p>Commercial is fine, but in the thousands is not an option right now.</p> <p>So, which components do you know or can you recommend?</p>
<p><a href="http://sourceforge.net/projects/pdfcreator/" rel="nofollow noreferrer">PDFCreator</a> can function as a virtual printer but it's also usable via COM. The default setup even includes COM examples.</p> <p>You can check the COM samples in the SourceForge SVN repository right here: <a href="http://pdfcreator.svn.sourceforge.net/viewvc/pdfcreator/trunk/COM/" rel="nofollow noreferrer">http://pdfcreator.svn.sourceforge.net/viewvc/pdfcreator/trunk/COM/</a></p>
<p>You might want to have a look at <a href="http://www.realobjects.com/PDFreactor.808.0.html" rel="nofollow noreferrer"><strong>PDFReactor</strong></a></p>
41,853
<p>Are there any <strong>tools</strong> to facilitate a migration from <a href="http://www.sourcegear.com/vault/index.html" rel="noreferrer">Sourcegear's Vault</a> to <a href="http://subversion.tigris.org/" rel="noreferrer">Subversion</a>?</p> <p>I'd really prefer an existing tool or project (I'll buy!).</p> <p><strong>Requirements:</strong></p> <ol> <li>One-time migration only</li> <li>Full history with comments</li> </ol> <p><strong>Optional:</strong></p> <ol> <li>Some support for labels/branches/tags</li> <li>Relatively speedy. It can take hours but not days.</li> <li>Cost if available</li> </ol> <p>Bonus points if you can share personal experience related to this process.</p> <hr> <p>One of the reasons I'd like to do this is because we have lots of projects spread between Vault and Subversion (we're finally away from sourcesafe). It'd be helpful in some situations to be able to consolidate a particular customer's repos to SVN.</p> <p>Additionally, SVN is better supported among third party tools. For example, <a href="http://hudson.dev.java.net/" rel="noreferrer">Hudson</a> and <a href="http://www.redmine.org/" rel="noreferrer">Redmine</a>.</p> <p>Again, though: we're not abandoning vault altogether.</p>
<p>We are thinking about migrating from vault to git. I wrote vault2git converter that takes care of history and removes vault bindings from *.sln, *.csproj files.</p> <p>Once you have git repo, there is git2svn.</p> <p>I know it sounds like going rounds, but it might be faster than writing vault2svn from scratch.</p>
<p>Free. The vault user license costs have tripled since we went to it.</p>
8,181
<p>V8's documentation explains <a href="http://code.google.com/apis/v8/embed.html#dynamic" rel="noreferrer">how to create a Javascript object that wraps a C++ object</a>. The Javascript object holds on to a pointer to a C++ object instance. My question is, let's say you create the C++ object on the heap, how can you get a notification when the Javascript object is collected by the gc, so you can free the heap allocated C++ object?</p>
<p>The trick is to create a <code>Persistent</code> handle (second bullet point from the linked-to API reference: "<code>Persistent</code> handles are not held on a stack and are deleted only when you specifically remove them. ... Use a persistent handle when you need to keep a reference to an object for more than one function call, or when handle lifetimes do not correspond to C++ scopes."), and call <code>MakeWeak()</code> on it, passing a callback function that will do the necessary cleanup ("A persistent handle can be made weak, using <code>Persistent::MakeWeak</code>, to trigger a callback from the garbage collector when the only references to an object are from weak persistent handles." -- that is, when all "regular" handles have gone out of scope and when the garbage collector is about to delete the object).</p> <p>The <code>Persistent::MakeWeak</code> method signature is:</p> <pre><code>void MakeWeak(void* parameters, WeakReferenceCallback callback); </code></pre> <p>Where <code>WeakReferenceCallback</code> is defined as a pointer-to-function taking two parameters:</p> <pre><code>typedef void (*WeakReferenceCallback)(Persistent&lt;Object&gt; object, void* parameter); </code></pre> <p>These are found in the v8.h header file distributed with V8 as the public API.</p> <p>You would want the function you pass to <code>MakeWeak</code> to clean up the <code>Persistent&lt;Object&gt;</code> object parameter that will get passed to it when it's called as a callback. The <code>void* parameter</code> parameter can be ignored (or the <code>void* parameter</code> can point to a C++ structure that holds the objects that need cleaning up):</p> <pre><code>void CleanupV8Point(Persistent&lt;Object&gt; object, void*) { // do whatever cleanup on object that you're looking for object.destroyCppObjects(); } Parameter&lt;ObjectTemplate&gt; my_obj(ObjectTemplate::New()); // when the Javascript part of my_obj is about to be collected // we'll have V8 call CleanupV8Point(my_obj) my_obj.MakeWeak(NULL, &amp;CleanupV8Point); </code></pre>
<p>In general, if a garbage-collected language can hold references to resources outside of the language engine (files, sockets, or in your case C++ objects), you should provide a 'close' method to release that resource ASAP, no point waiting until the GC thinks it's worthwhile to destroy your object.</p> <p>it gets worse if your C++ object is memory-hungry and the garbage-collected object is just a reference: you might allocate thousands of objects, and the GC only sees a few KB's of tiny objects, not enough to trigger collection; while the C++ side is struggling with tens of megabytes of stale objects.</p>
20,889
<p>I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app.</p> <p>Does such an OpenID dev server exist? Is this the best way to go about it?</p>
<p>The libraries at <a href="http://openidenabled.com/" rel="noreferrer">OpenID Enabled</a> ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of <a href="http://openidenabled.com/python-openid/trunk/examples/server/" rel="noreferrer">this test provider</a>.</p>
<p>Why not run an OpenID provider from your local machine?</p> <p>If you are a .Net developer there is an OpenID provider library for .Net at <a href="http://code.google.com/p/dotnetopenid/" rel="nofollow noreferrer">Google Code</a>. This uses the standard .Net profile provider mechanism and wraps it with an OpenID layer. We are using it to add OpenID to our custom authentication engine.</p> <p>If you are working in another language/platform there are a number of OpenID implementation avalaiable from the OpenID community site <a href="http://wiki.openid.net/Libraries" rel="nofollow noreferrer">here</a>.</p>
20,736
<p>I'd like to split a string using one or more separator characters.</p> <p>E.g. "a b.c", split on " " and "." would give the list ["a", "b", "c"].</p> <p>At the moment, I can't see anything in the standard library to do this, and my own attempts are a bit clumsy. E.g.</p> <pre><code>def my_split(string, split_chars): if isinstance(string_L, basestring): string_L = [string_L] try: split_char = split_chars[0] except IndexError: return string_L res = [] for s in string_L: res.extend(s.split(split_char)) return my_split(res, split_chars[1:]) print my_split("a b.c", [' ', '.']) </code></pre> <p>Horrible! Any better suggestions?</p>
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.split('[ .]', 'a b.c') ['a', 'b', 'c'] </code></pre>
<p>Not very fast but does the job:</p> <pre><code>def my_split(text, seps): for sep in seps: text = text.replace(sep, seps[0]) return text.split(seps[0]) </code></pre>
48,844
<p>I am just learning php as I go along, and I'm completely lost here. I've never really used join before, and I think I need to here, but I don't know. I'm not expecting anyone to do it for me but if you could just point me in the right direction it would be amazing, I've tried reading up on joins but there are like 20 different methods and I'm just lost.</p> <p>Basically, I hand coded a forum, and it works fine but is not efficient. </p> <p>I have board_posts (for posts) and board_forums (for forums, the categories as well as the sections).</p> <p>The part I'm redoing is how I get the information for the last post for the index page. The way I set it up is that to avoid using joins, I have it store the info for latest post in the table for board_forums, so say there is a section called "Off Topic" there I would have a field for "forum_lastpost_username/userid/posttitle/posttime" which I woudl update when a user posts etc. But this is bad, I'm trying to grab it all dynamically and get rid of those fields.</p> <p>Right now my query is just like: </p> <pre><code>`SELECT * FROM board_forums WHERE forum_parent='$forum_id'' </code></pre> <p>And then I have the stuff where I grab the info for that forum (name, description, etc) and all the data for the last post is there:</p> <pre><code> $last_thread_title = $forumrow["forum_lastpost_title"]; $last_thread_time = $forumrow["forum_lastpost_time"]; $lastpost_username = $forumrow["forum_lastpost_username"]; $lastpost_threadid = $forumrow["forum_lastpost_threadid"]; </code></pre> <p>But I need to get rid of that, and get it from board_posts. The way it's set up in board_posts is that if it's a thread, post_parentpost is NULL, if it's a reply, then that field has the id of the thread (first post of the topic). So, I need to grab the latest post_date, see which user posted that, THEN see if parentpost is NULL (if it's null then the last post is a new thread, so I can get all the info of the title and user there, but if it's not, then I need to get the info (title, id) of the first post in that thread (which can be found by seeing what post_parentpost is, looking up that ID and getting the title from it.</p> <p>Does that make any sense? If so please help me out :(</p> <p>Any help is greatly appreciated!!!!</p>
<p>Updating board___forums whenever a post or a reply is inserted is - regarding performance - not the worst idea. For displaying the index page you only have to select data from one table board_forums - this is definitely much faster than selecting a second table to get the "last posts' information", even when using a clever join.</p>
<p>The simple solution will result in numerous queries, some optional, as you're already discovered.</p> <p>The classic approach to this is to cache the results, and only retrieve it once in a while. The cache doesn't have to live long; even two or three seconds on a busy site will make a significant difference.</p> <p>De-normalizing the data into a table you're already reading anyway will help. This approach saves you figuring out optional queries and can be a bit of a cheap win because it's just one more update when an insert is already happening. But it shifts some data integrity to the application. </p> <p>As an aside, you might be running into the recursive-query problem with your threads. Relational databases do not store heirarchical data all that well if you use a "simple" algorithim. A better way is something sometimes called 'set trees'. It's a bit hard to Google, unfortunately, so <a href="http://blog.monstuff.com/archives/000026.html" rel="nofollow noreferrer">here</a> <a href="http://www.developersdex.com/gurus/articles/112.asp" rel="nofollow noreferrer">are</a> <a href="http://weblog.openlaszlo.org/archives/2005/10/sorting-out-sql-trees/" rel="nofollow noreferrer">some</a> <a href="https://stackoverflow.com/questions/201671/how-do-you-sort-a-tree-stored-using-the-nested-set-model#457424">links</a>.</p>
49,754
<p>As stated above, I am trying to solve a problem I've had for a long time. Unfortunately, this has recently intensified to the point where it causes layer splitting/detaching from each other. I have tried various ways to fix this and, while decreasing the temperature and extrusion multiplier improved the situation, the problem is still present. </p> <p>My settings: <li>Nozzle 235&nbsp;&deg;C Bed 100&nbsp;&deg;C <li>Cooling 25&nbsp;% <li>Extrusion multiplier 0.89 <li>Speed 150&nbsp;mm/s for everything, 50&nbsp;mm/s for small perimiters <li>Acceleration 1000&nbsp;mm/s<sup>2</sup>, (default) <li>Layer height 0.15-0.3mm <li>Line width - 0.6mm for everything, but 0.45 for first layer and 0.42 for top solid infill</p> <p>Is there a different solution than lowering print speed or buying an E3D silicon sock? I have lost my spare ones and the current one wore down. Obviously, I can simply pause the print when I see plastic bulding up on the nozzle, but I am sure that there is a more efficient solution.</p> <p>UPDATE: I found that the hotend was very dirty and full of burnt/molten plastic. I am almost sure that the hotend is leaking somewhere between the heat block and the heat break. This didn't happen before I replaced the nozzle. How can I fix this? Do I have to replace the heat break or some other part?</p>
<p>I saw PETG printed at 100 mm/s, but 150! That's a lot.</p> <p>One solution to avoid blobs may be to limit the maximum speed to a value you can actually achieve with reliable results.</p> <p>Simple test to find your machine limits (each combination filament brand + nozzle + temperature has a different value): extrude filament in the air at increasing speeds, see how the flow changes, and when you see more than 5% decrease, that's it.</p> <ol> <li>M83</li> <li>mark the filament as if you were calibrating the E steps</li> <li>calculate filament speed: speed = volum/s / filament surface * 60 = mm^3/s * 25 (this factor is valid for 1.75 mm filament)</li> <li>set extrusion speed for 2 mm^3/s: G1 F50</li> <li>extrude 50 mm: G1 E50</li> <li>measure actual length extruded</li> <li>repeat 2.-6. but increase the speed by 2 mm^3/s each time: 2, 4, 6, 8, 10, 12, ...</li> <li>at a certain speed you will see that the actual filament length starts to decrease. When you see that the underextrusion reaches 5-10% (depending how much underextrusion you accept), write down that volumetric speed (mm^3/s) somewhere, it's your limit for THAT filament + THAT nozzle + THAT temperature</li> <li>Either a) calculate the max print speed = volumetric speed / layer height / line width or b) set the maximum volumetric flow rate in the slicing software so that the speed will be automatically capped taking into account layer height and line width. <a href="https://help.prusa3d.com/en/article/max-volumetric-speed_127176/" rel="nofollow noreferrer">Prusaslicer</a> allows to set that in the "Print" or in "Filament" settings, I recommend it for "Filament" settings, since it's a filament-dependent parameter.</li> </ol> <p>Example data from <a href="https://www.cnckitchen.com/blog/flow-rate-benchmarking-of-a-hotend" rel="nofollow noreferrer">CNC Kitchen</a>:</p> <p><a href="https://i.stack.imgur.com/xXRYV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xXRYV.png" alt="enter image description here"></a></p> <p>You can increase the max print speed, at the price of a little loss of quality around edges, if you calibrate the E steps at a speed corresponding to 2-3% underextrusion (alternative: to the speed of outer perimeters).</p> <p>This way you know that when you print slower than that (uncommon... typically only sharp corners and small perimeters) you'll get up to 2-3% overextrusion, and you extend by 2-3% the maximum print speed, since your max speed is the one where you get 5-10% underextrusion compared to your E steps calibration speed.</p>
<p>Even not extruding anything but just performing travel moves over PETG at 100 mm/s or higher will <em>tear it up and drag material all over the place</em>. The result is blobs stuck to the nozzle, possibly even stringing, and choppy lines that the next layer will not properly adhere to. PETG simply cannot be printed at these kind of speeds regardless of how fast your hotend can melt it.</p> <p>Turn <strong>all</strong> speeds, print and travel, down to 40-50 mm/s, then experiment to see if you can increase them at all.</p> <p>Note that if your acceleration is only 1000 mm/s², you're basically never going to reach the desired 150 mm/s anyway, so this probably won't be as much of a slowdown as you expect. Jack the acceleration up as high as your machine can handle and it might still print as fast or faster, but without the blobs.</p>
1,673
<p>We have simple HTML form with <code>&lt;input type="file"&gt;</code>, like shown below:</p> <pre><code>&lt;form&gt; &lt;label for="attachment"&gt;Attachment:&lt;/label&gt; &lt;input type="file" name="attachment" id="attachment"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>In IE7 (and probably all famous browsers, including old Firefox 2), if we submit a file like '//server1/path/to/file/filename' it works properly and gives the full path to the file and the filename.</p> <p>In Firefox 3, it returns only 'filename', because of their new 'security feature' to truncate the path, as explained in Firefox bug tracking system (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=143220" rel="noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=143220</a>)</p> <p>I have no clue how to overcome this 'new feature' because it causes all upload forms in my webapp to stop working on Firefox 3.</p> <p>Can anyone help to find a single solution to get the file path both on Firefox 3 and IE7?</p>
<p>For preview in Firefox works this - attachment is object of attachment element in first example:</p> <pre><code> if (attachment.files) previewImage.src = attachment.files.item(0).getAsDataURL(); else previewImage.src = attachment.value; </code></pre>
<p>Simply you cannot do it with FF3.</p> <p>The other option could be using applet or other controls to select and upload files.</p>
10,675
<p>I have recently run into an issue where I wanted to add a folder to the directory structure of my project that would become the new 'root' directory for the previously housed files. I've been getting help in a <a href="https://stackoverflow.com/questions/87458/can-you-specify-filenames-using-wildcards-or-regexes-in-the-subversion-mv-comma">related thread</a> but I wanted to put out a more open ended question to see what a best practice might be.</p> <p>Essentially, my situation was that I was working on development and realized that I wanted to have a resources directory that would not be part of the main development thrust but would still be versioned (to hold mockups and such). So I wanted to add a resources directory and an implementation directory, the implementation directory being the new root directory. How would you go about moving all of the previous directory structure into the implementation directory?</p>
<p>You can do it pretty easily if you use some GUI for SVN. Personally I love <a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">TortoiseSVN</a> for when I'm working in Windows. You just open up the "Repository Browser", right-click on some folder, and choose "Move...". Or, you have the option of doing it straight from within Windows Explorer, drag the files/folders you want to move with the RIGHT mouse button, when you drop them in their new location you'll get a menu, one of the options is "Move in SVN".</p>
<p>Moves in subversion are done by removing the old files and adding the new ones, so there's nothing special to do. The series of 'svn mv' commands in a loop recommended in the other question should probably work just fine.</p>
11,321
<p>I'm looking for a tool which can generate a <a href="https://en.wikipedia.org/wiki/Make_(software)#Makefile" rel="nofollow noreferrer">Makefile</a> for a C/C++ project for different compilers (<a href="https://en.wikipedia.org/wiki/GNU_Compiler_Collection" rel="nofollow noreferrer">GCC</a>, <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B" rel="nofollow noreferrer">Microsoft Visual C++</a>, <a href="https://en.wikipedia.org/wiki/C%2B%2BBuilder" rel="nofollow noreferrer">C++Builder</a>, etc.) and different platforms (Windows, Linux, and Mac).</p>
<p>Other suggestions you may want to consider:</p> <ul> <li><p><a href="http://www.scons.org/" rel="nofollow noreferrer">Scons</a> is a cross-platform, cross-compiler build library, uses Python scripting for the build systems. Used in a variety of large projects, and performs very well.</p> </li> <li><p>If you're using <a href="https://en.wikipedia.org/wiki/Qt_%28software%29" rel="nofollow noreferrer">Qt</a>, <a href="https://doc.qt.io/qt-5/qmake-manual.html" rel="nofollow noreferrer">QMake</a> is a nice build system too.</p> </li> <li><p><a href="https://cmake.org/" rel="nofollow noreferrer">CMake</a> is also pretty sweet.</p> </li> <li><p>Finally, <a href="http://www.google.co.uk/search?q=cross+platform+build+system" rel="nofollow noreferrer">if all else fails...</a></p> </li> </ul>
<p>One issue to consider is do you want a "makefile" creator or a replacement build system? The problem with replacement build systems is that you typically don't get good IDE integration for platforms whose users expect this (Visual C++). If you do want a makefile creator instead of a replacement build system, take a look at <a href="http://ociweb.com/products/mpc" rel="nofollow noreferrer">MPC</a>. It's free and open source.</p>
3,095
<p>Does anyone have a recommendation about web service security architecture in Java (preferably under JBoss)? Any recommended reading?</p> <p>I want to expose a fairly rich web service to the world but the data are sensitive and it requires authentication from the current client (Flex), accessed via RPC. I definitely do not want any server-side session state. </p> <p>What's the best way to go about implementing security through web services in Java/JBoss and where can I read about it?</p>
<p>For web services security in JBoss, I would start by reading <a href="http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide#WS-Security" rel="nofollow noreferrer">8.4 WS-Security</a> of the <a href="http://jbossws.jboss.org/mediawiki/index.php?title=User_Guide" rel="nofollow noreferrer">JBossWS User Guide</a>.</p>
<p>WSSE is simple and works well.</p> <p><a href="http://www.xml.com/pub/a/2003/12/17/dive.html" rel="nofollow noreferrer">http://www.xml.com/pub/a/2003/12/17/dive.html</a></p> <p><a href="http://www.sixapart.com/developers/atom/protocol/atom_authentication.html" rel="nofollow noreferrer">http://www.sixapart.com/developers/atom/protocol/atom_authentication.html</a></p>
32,052
<p>I have a query that is dynamically built after looking up a field list and table name. I execute this dynamic query inside a stored proc. The query is built without a where clause when the two proc parameters are zero, and built with a where clause when not.</p> <p>When I execute the proc with SET FMTONLY ON exec [cpExportRecordType_ListByExportAgentID] null, null It returns no column information. I have just now replaced building the query without a where clause to just executing the same query directly, and now I get column information. I would love to know what causes this, anyone?</p>
<p>Perhaps it is related to the fact that the passed parameters are NULL, check how your query is build perhaps it behaves in different way then expected when you pass NULL. Does you proc returns expected results when you call: SET FMTONLY OFF exec [cpExportRecordType_ListByExportAgentID] null, null ?</p> <p>Other possibility: I understand that you build your query dynamically by getting results from calling another queries to get the column names. Perhaps the query that would normally give you the column names returns no data but only column information (SET FMTONLY ON) so you do not have data to build you dynamic query.</p>
<p>Perhaps it is related to the fact that the passed parameters are NULL, check how your query is build perhaps it behaves in different way then expected when you pass NULL. Does you proc returns expected results when you call: SET FMTONLY OFF exec [cpExportRecordType_ListByExportAgentID] null, null ?</p> <p>Other possibility: I understand that you build your query dynamically by getting results from calling another queries to get the column names. Perhaps the query that would normally give you the column names returns no data but only column information (SET FMTONLY ON) so you do not have data to build you dynamic query.</p>
9,780
<p>In evaluating different systems integration strategies, I've come across some words of encouragement, but also some words of frustration over BizTalk Server. </p> <p>What are some pros and cons to using BizTalk Server (both from a developer standpoint and a business user), and should companies also consider open source alternatives? What viable alternatives are out there?</p> <p>EDIT: <a href="http://www.jitterbit.com/" rel="noreferrer">Jitterbit</a> seems like an interesting choice. Open Source and seems to be nicely engineered. Anyone on here have any experience working with it?</p>
<p>My experience with BizTalk was basically a frustrating waste of time.</p> <p>There are so many edge cases and weird little business logic tweaks you have to make when you are doing B2B data integration (which is probably the hardest part of any enterprise application) that you just need to roll your own solution.</p> <p>How hard is it to parse data files and convert them to a different format? Not that hard. Unless you're trying to inject a bloated middleware system like Biztalk into the middle of it.</p>
<p>I have no direct experience with JitterBit, but I have heard very good things from coworkers.</p>
8,666
<p>There are some good examples on how to calculate word frequencies in C#, but none of them are comprehensive and I really need one in VB.NET.</p> <p>My current approach is limited to one word per frequency count. What is the best way to change this so that I can get a completely accurate word frequency listing?</p> <pre><code>wordFreq = New Hashtable() Dim words As String() = Regex.Split(inputText, "(\W)") For i As Integer = 0 To words.Length - 1 If words(i) &lt;&gt; "" Then Dim realWord As Boolean = True For j As Integer = 0 To words(i).Length - 1 If Char.IsLetter(words(i).Chars(j)) = False Then realWord = False End If Next j If realWord = True Then If wordFreq.Contains(words(i).ToLower()) Then wordFreq(words(i).ToLower()) += 1 Else wordFreq.Add(words(i).ToLower, 1) End If End If End If Next Me.wordCount = New SortedList For Each de As DictionaryEntry In wordFreq If wordCount.ContainsKey(de.Value) = False Then wordCount.Add(de.Value, de.Key) End If Next </code></pre> <p>I'd prefer an actual code snippet, but generic 'oh yeah...use this and run that' would work as well.</p>
<pre><code>Public Class CountWords Public Function WordCount(ByVal str As String) As Dictionary(Of String, Integer) Dim ret As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer) Dim word As String = "" Dim add As Boolean = True Dim ch As Char str = str.ToLower For index As Integer = 1 To str.Length - 1 Step index + 1 ch = str(index) If Char.IsLetter(ch) Then add = True word += ch ElseIf add And word.Length Then If Not ret.ContainsKey(word) Then ret(word) = 1 Else ret(word) += 1 End If word = "" End If Next Return ret End Function End Class </code></pre> <p>Then for a quick demo application, create a winforms app with one multiline textbox called InputBox, one listview called OutputList and one button called CountBtn. In the list view create two columns - "Word" and "Freq." Select the "details" list type. Add an event handler for CountBtn. Then use this code:</p> <pre><code>Imports System.Windows.Forms.ListViewItem Public Class MainForm Private WordCounts As CountWords = New CountWords Private Sub CountBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CountBtn.Click OutputList.Items.Clear() Dim ret As Dictionary(Of String, Integer) = Me.WordCounts.WordCount(InputBox.Text) For Each item As String In ret.Keys Dim litem As ListViewItem = New ListViewItem litem.Text = item Dim csitem As ListViewSubItem = New ListViewSubItem(litem, ret.Item(item).ToString()) litem.SubItems.Add(csitem) OutputList.Items.Add(litem) Word.Width = -1 Freq.Width = -1 Next End Sub End Class </code></pre> <p>You did a terrible terrible thing to make me write this in VB and I will never forgive you.</p> <p>:p</p> <p>Good luck!</p> <p><strong>EDIT</strong></p> <p>Fixed blank string bug and case bug</p>
<p>This might be helpful:</p> <p><a href="https://stackoverflow.com/questions/90580/word-frequency-algorithm-for-natural-language-processing">Word frequency algorithm for natural language processing</a></p>
27,739
<p>How do YOU reduce compile time, and linking time for VC++ projects (native C++)?</p> <p>Please specify if each suggestion applies to debug, release, or both.</p>
<p>It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in:</p> <pre><code>// Forward declaration stuff namespace plotter { namespace logic { class Plotter; } } // Real stuff namespace plotter { namespace samples { class Window { logic::Plotter * mPlotter; // ... }; } } </code></pre> <p>It greatly reduces the time for compiling also on others compilers. Indeed it applies to all configurations :)</p>
<p><strong>Compile Time:</strong><br> If you have IncrediBuild, compile time won't be a problem. If you don't have a IncrediBuild, try the "unity build" method. It combine multiple cpp files to a single cpp file so the whole compile time is reduced. <br> <strong>Link Time:</strong><br> The "unity build" method also contribute to reduce the link time but not much. How ever, you can check if the "Whole global optimization" and "LTCG" are enabled, while these flags make the program fast, they DO make the link SLOW. <br> Try turning off the "Whole Global Optimization" and set LTCG to "Default" the link time might be reduced by 5/6. <br><em>(LTCG stands for Link Time Code Generation)</em></p>
47,553
<p>How do I iterate over the words of a string composed of words separated by whitespace?</p> <p>Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; int main() { string s = &quot;Somewhere down the road&quot;; istringstream iss(s); do { string subs; iss &gt;&gt; subs; cout &lt;&lt; &quot;Substring: &quot; &lt;&lt; subs &lt;&lt; endl; } while (iss); } </code></pre>
<p>For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; int main() { using namespace std; string sentence = "And I feel fine..."; istringstream iss(sentence); copy(istream_iterator&lt;string&gt;(iss), istream_iterator&lt;string&gt;(), ostream_iterator&lt;string&gt;(cout, "\n")); } </code></pre> <p>Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic <a href="https://en.cppreference.com/w/cpp/algorithm/copy" rel="noreferrer"><code>copy</code></a> algorithm.</p> <pre><code>vector&lt;string&gt; tokens; copy(istream_iterator&lt;string&gt;(iss), istream_iterator&lt;string&gt;(), back_inserter(tokens)); </code></pre> <p>... or create the <code>vector</code> directly:</p> <pre><code>vector&lt;string&gt; tokens{istream_iterator&lt;string&gt;{iss}, istream_iterator&lt;string&gt;{}}; </code></pre>
<p>For a ridiculously large and probably redundant version, try a lot of for loops.</p> <pre><code>string stringlist[10]; int count = 0; for (int i = 0; i &lt; sequence.length(); i++) { if (sequence[i] == ' ') { stringlist[count] = sequence.substr(0, i); sequence.erase(0, i+1); i = 0; count++; } else if (i == sequence.length()-1) // Last word { stringlist[count] = sequence.substr(0, i+1); } } </code></pre> <p>It isn't pretty, but by and large (Barring punctuation and a slew of other bugs) it works!</p>
29,219
<p>I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form_Resize event. </p> <p>This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount. </p> <p>Does anyone have any clue as to how to accomplish this? </p> <p>Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes. </p> <p>EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.</p>
<p>Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.</p> <pre><code>public static void MinimizeMemory() { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); SetProcessWorkingSetSize( Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); IntPtr heap = GetProcessHeap(); if (HeapLock(heap)) { try { if (HeapCompact(heap, 0) == 0) { // error condition ignored } } finally { HeapUnlock(heap); } } } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetProcessWorkingSetSize( IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcessHeap(); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapLock(IntPtr heap); [DllImport("kernel32.dll")] internal static extern uint HeapCompact(IntPtr heap, uint flags); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapUnlock(IntPtr heap); </code></pre>
<p>While this is in C#, look at the source code, it will solve any issues you have:</p> <p><a href="http://www.codeproject.com/KB/cs/NotifyIconExample.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/NotifyIconExample.aspx</a></p>
32,952
<p>I am trying to do this...</p> <pre><code>&lt;Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" /&gt; </code></pre> <p>But I get this error...</p> <blockquote> <p>Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'. Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.</p> </blockquote> <p>As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?</p> <p>I tried <code>Source="..Images\unlock.png"</code> which does not work in WPF.</p> <p>Any help?</p>
<p>Try slashes rather than backslashes, and use an absolute path by leading with a slash:</p> <pre><code>Source="/Images/unlock.png" </code></pre> <p>That generally works for me.</p> <p>Failing that, take a look at <a href="http://msdn.microsoft.com/en-us/library/aa970069.aspx" rel="noreferrer">Pack URIs</a>.</p>
<p>Have you tried setting the source to a <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx" rel="nofollow noreferrer">BitmapImage</a>?</p> <pre><code>&lt;Image x:Name="imgGroupImage" Margin="0,0,5,0" &gt; &lt;Image.Source&gt; &lt;BitmapImage UriSource="Images/unlock.png" /&gt; &lt;/Image.Source&gt; &lt;/Image&gt; </code></pre> <p>I believe the default type of <code>Uri</code> for <code>UriSource</code> is a relative <code>Uri</code>, which works off the application's base class. You might find you can configure the <code>BitmapSource</code> a bit easier than trying to find the exact way you have to enter the file path in the <code>Source</code> attribute.</p>
35,229
<p>I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. </p> <p>For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. </p> <p>The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools.</p> <p>So, any advice on how to blend in to Java-ME?</p>
<p>This <a href="http://crfdesign.net/programming/top-10-differences-between-java-and-c" rel="noreferrer">guy here</a> had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java:</p> <h2>Gotcha #10 - Give me my standard output!</h2> <p>To print to the standard output in Java:</p> <pre><code>System.out.println("Hello"); </code></pre> <h2>Gotcha #9 - Namespaces == Freedom</h2> <p>In Java you don't have the freedom of namespaces. The folder structure of your class must match the package name. For example, a class in the package <em>org.test</em> must be in the folder <em>org/test</em></p> <h2>Gotcha #8 - What happened to super?</h2> <p>In Java to refer to the superclass you use the reserved word <code>super</code> instead of <code>base</code></p> <h2>Gotcha #7 - Chaining constructors to a base constructor</h2> <p>You don't have this in Java. You have to call the constructor by yourself</p> <h2>Gotcha #6 - Dagnabit, how do I subclass an existing class?</h2> <p>To subclass a class in Java do this:</p> <pre><code>public class A extends B { } </code></pre> <p>That means class <code>A</code> is a subclass of class <code>B</code>. In C# would be <code>class A : B</code></p> <h2>Gotcha #5 - Why don’t constants remain constant?</h2> <p>To define a constant in Java use the keyword <code>final</code> instead of <code>const</code></p> <h2>Gotcha #4 - Where is <code>ArrayList</code>, <code>Vector</code> or <code>Hashtable</code>?</h2> <p>The most used data structures in java are <code>HashSet</code>, <code>ArrayList</code> and <code>HashMap</code>. They implement <code>Set</code>, <code>List</code> and <code>Map</code>. Of course, there is a bunch more. Read more about collections <a href="http://java.sun.com/docs/books/tutorial/collections/index.html" rel="noreferrer">here</a></p> <h2>Gotcha #3 - Of Accessors and Mutators (Getters and Setters)</h2> <p>You don't have the properties facility in Java. You have to declare the gets and sets methods for yourself. Of course, most IDEs can do that automatically.</p> <h2>Gotcha #2 - Can't I override!?</h2> <p>You don't have to declare a method <code>virtual</code> in Java. All methods - except those declared <code>final</code> - can be overridden in Java.</p> <h2>And the #1 gotcha…</h2> <p>In Java the primitive types <code>int</code>, <code>float</code>, <code>double</code>, <code>char</code> and <code>long</code> are not <code>Object</code>s like in C#. All of them have a respective object representation, like <code>Integer</code>, <code>Float</code>, <code>Double</code>, etc.</p> <p>That's it. Don't forget to see <a href="http://crfdesign.net/programming/top-10-differences-between-java-and-c" rel="noreferrer">the original link</a>, there's a more detailed discussion.</p>
<p>The short answer is - it's going to be annoying, but not difficult.</p> <p>Java and C# have all the same underlying concepts, and a lot of the libraries are very close in style, but you're going to keep bumping your head across various differences.</p> <p>If you're talking about class properties, Java has those. The syntax is </p> <pre><code>public class MyClass { public static int MY_CLASS_PROPERTY = 12; } </code></pre> <p>I would seriously suggest you get a better IDE. Any of Netbeans, Eclipse, IDEA, JBuider is going to make your transition a lot more pleasant.</p>
11,592
<p>On a web page that is to be displayed on an iPhone, is there a way to get the number pad to come up when the user taps in the field, instead of the qwerty keypad? </p> <p><a href="http://www.bennadel.com/blog/1197-Defaulting-To-The-Numeric-Keyboard-On-The-iPhone.htm" rel="nofollow noreferrer">This guy says here's how to do it</a>, but as of 2.0, this "feature" was disabled. </p> <p>I'm guessing there's some fancy javascript to employ to get around this limitation? </p>
<p>If you use the HTML5 <code>number</code> input type, the keyboard will default to showing numbers. It's not the number-only keyboard, but it's a bit better than just <code>text</code>.</p>
<p>You can make calls from JavaScript to Objective-C and then display what ever you want. If you want a framework to help you out you could check out QuickConnectiPhone. It is available at <a href="https://sourceforge.net/projects/quickconnect/" rel="nofollow noreferrer">https://sourceforge.net/projects/quickconnect/</a>.</p> <p>You could also check out <a href="http://tetontech.wordpress.com" rel="nofollow noreferrer">http://tetontech.wordpress.com</a>. This is the develpment blog for QuickConnect. It has some example code in addition to that which is included in the sourceforge download.</p>
35,320
<p>It seems like v2 of Log4j has been in development for literally years. The <a href="http://logging.apache.org/" rel="noreferrer">Apache Log4J site</a> no longer lists a roadmap, the dev mailing list seems almost entirely about 1.2 (which is appreciated!), use of v1.3 is discouraged, and the 2.0 branch is listed as "experimental". What's a believer to believe?</p>
<p>Log4j development has for all practical purposed stalled. Consider switching to logback, log4j's successor. Logback is conceptually similar to log4j and if you like log4j, you should like logback even better. It has many nice features and is well-documented.</p> <p>Disclosure: I am the founder of both log4j and logback projects. </p>
<p>Well then I guess you already answered your own question, the devs have obviously stopped focusing on 2.0 builds a long time ago and have instead decided to continue the 1.x codebase.</p> <p>And if you are on their mailing list, then ask them, the source of the issue.</p>
37,065
<p>I have a Robo 3D. However A while ago, the print bed was fractured, and now it has a long crack cutting it in half. The bed still works because it is held together, by the screws holding the bed to the tracks. So I want to continue using it, because it still is fairly good, the heating element works fine, and a replacement bed is 80$, and I am unsure if the one sold on the RoBo 3D website will be compatible with my printer as I don't have the R1, but a version before that.</p> <p><a href="https://i.stack.imgur.com/b4osS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b4osS.jpg" alt="My cracked bed, with crack running straight through the center"></a></p> <p>So my question is: How can I best align the two glass fragments, to provide as flat a print surface as possible, and two how to best hold these two pieces in place, or if it would be best to invest in a new print bed?</p> <p>EDIT: Here is a image of the heating element as well to explain the situation with how it is attached<a href="https://i.stack.imgur.com/4yr34.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4yr34.jpg" alt="The heating element attached to the underside of the glass print bed"></a></p> <p>EDIT: The RoBo 3D team have said that I just need to upgrade my y-axis with a object on thingiverse and then buy their new build plate. So I am going to experiment with a glass replacement, and if that fails to succeed then I will go along with their suggestion, and buy the upgrade. Thanks everyone for their help.</p>
<p>A little chip is fine, but I wouldn't print with that big of a crack. <strong>However</strong>, that doesn't mean you need to spend $80 on a new sheet of glass.</p> <p>Option #1- If you want borosilicate glass, you can get a sheet from either McMaster (about $40+shipping for a 10"x10" piece, less for smaller) or from a local glass maker (the price varies a lot, so you should check that also if you want to go that route). However, you won't be able to drill holes (tempered glass <em>will</em> break of you drill a hole). Borosilicate glass has the advantage of being <em>extremely</em> heat-resistant, so it won't break from thermal expansion. If you go this route, you should pick up a few binder clips also to attach the sheet to the heated bed.</p> <p>Option #2- You might be able to get picture frame glass from a hardware store. It's super cheap (mine was $3 or something from lowes) and they'll often cut it to exact size. You might be able to drill this, but you have to be extremely careful. Sometimes, the hardware store can drill holes in the sheet for you if needed. If you don't want to drill, a few binder clips will work just as well.</p> <p>Just a note for if you are using binder clips: you might need to (depending on how your hbp is set up) get a piece of glass that is slightly smaller to allow for any bed leveling screws to have room. If you're going with the picture frame glass, you should make sure that the glass will be entirely within the heated part so that there isn't any heat gradient (that's how glass cracks/shatters). </p>
<p>If your heatbed itself is aluminum/copper/other metal: Get a glass cut and replace it. The current one is probably attached to the heatbed with adhesive glue. If it the adhesive is cyanocrylate based, you can remove by rubbing with acetone. If silicone type, it will come off by some force. Don't worry, you won't damage aluminum. THe heating element is either inside the aluminum or under it. If it's not alumunum it's likely a PCB heatbed. Then I wouldn't suggest to use acetone or some "antiglue" and would just try to apply a little force and see if the glass moves a bit. If no, don't bother, PCB heatbeds can break too. Then I'd just suggest to apply some epoxy to cover the holes surrounding the cracks and keeping the glasses uniform.</p> <p>Also, about replacement glasses: picture frame glasses are very cheap. McMaster sells some high quality bearings and rods, but for glass there's no point to waste money. $5 is typical for that size borosilicate glass, if you're in USA (I'm not) I think your local Home Depot will cut it for free for you as well.</p>
178
<p>I'm starting a new job and am inheriting a asp .net web application on the 2.0 .net framework. The application works alright. It published successfully from vs 2005. I created a new virtual directory in IIS and pointed to the precompiled directory just published.</p> <p>When I load my application, I get an error that reads as follows:</p> <p>XML Parsing Error: not well-formed Location: <a href="http://localhost/Subpoena/" rel="nofollow noreferrer">http://localhost/Subpoena/</a> Line Number 1, Column 2:&lt;%@ page language="C#" autoeventwireup="true" inherits="Home, App_Web_ysxqzhr9" %> -^</p> <p>I'm not real sure what to do to fix this. The App_Web_ysxqzhr9 is a dll in the bin directory that was created by VS 2005 when I published the project. </p> <p>I admit I'm a bit rusty on my IIS skills so it might be some setting that I haven't set...or it could be something entirely different. </p> <p>Anyone have any thoughts at all?</p>
<p><em>sigh</em></p> <p>Okay found the answer. Ironically it too was on stack overflow. Here it is:</p> <p><a href="https://stackoverflow.com/questions/233478/aspnet-20-application-on-iis-5-resulting-in-error-aspnetwpexe-pid-xxxx-stopped">ASP.NET 2.0 Application on IIS 5 Resulting in Error (aspnet_wp.exe (PID: XXXX) stopped unexpectedly.)</a></p> <p>What worked for me was Mitchel Sellers response:</p> <ol> <li>Open command prompt to C:\windows\microsoft.net\framework\v2.0.50727</li> <li>run the following command: aspnet_regiis.exe -u</li> <li>run the following command: aspnet_regiis.exe -i</li> </ol> <p>Thanks anyway for all your help guys.</p>
<p>You may also need to install Microsoft WSE extensions.</p> <p>Something like this: <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=018a09fd-3a74-43c5-8ec1-8d789091255d&amp;displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=018a09fd-3a74-43c5-8ec1-8d789091255d&amp;displaylang=en</a></p> <p>EDIT: System.Web is part of the WSE but I'm not sure how it all plays together.</p>
33,301
<p>I have an app that needs to open a new window (in the same domain) so the user can view a report, but on some browsers* the new window doesn't share the non-persistent cookie of the original window, which causes the user to have to sign in again. Is there anything I can do to stop the user having to sign in again in the new window?</p> <p>*In fact, in IE7 it is sporadic - sometimes new windows share cookies, sometimes not.</p>
<p>I thought IE7 shared non-persistent cookies with tabs in the same window, as well as windows that were generated from the current window (whether or not this is the same for manual opens like File->New, or programmatic script opens, I'm not sure), but that fresh instances did not.</p> <p>Firefox shares them across all windows, regardless of how they were opened. I've always assumed that this is just the way it is, and you'd have to use persistent cookies, cookie-less sessions, or develop a single sign-on/ticketing mechanism to work around it.</p>
<p>They <em>should</em> share cookies. That has been my experience in the past. I'll edit once I've had a play.</p>
15,792
<p>How would you program a C/C++ application that could run without opening a window or console? </p>
<p>When you write a WinMain program, you automatically get the /SUBSYSTEM option to be windows in the compiler. (Assuming you use Visual Studio). For any other compiler a similar option might be present but the flag name might be different. </p> <p>This causes the compiler to create an entry in the executable file format (<a href="http://webster.cs.ucr.edu/Page_TechDocs/pe.txt" rel="noreferrer">PE format</a>) that marks the executable as a windows executable. </p> <p>Once this information is present in the executable, the system loader that starts the program will treat your binary as a windows executable and not a console program and therefore it does not cause console windows to automatically open when it runs. </p> <p>But a windows program need not create any windows if it need not want to, much like all those programs and services that you see running in the taskbar, but do not see any corresponding windows for them. This can also happen if you create a window but opt not to show it. </p> <p>All you need to do, to achieve all this is, </p> <pre><code>#include &lt;Windows.h&gt; int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int cmdShow) { /* do your stuff here. If you return from this function the program ends */ } </code></pre> <p>The reason you require a WinMain itself is that once you mark the subsystem as Windows, the linker assumes that your entry point function (which is called after the program loads and the C Run TIme library initializes) will be WinMain and not main. If you do not provide a WinMain in such a program you will get an un-resolved symbol error during the linking process.</p>
<p>If you are using <strong>MSVC</strong> or <strong>Visual Studio</strong> just use the new <strong>Project Wizard</strong> and select the <strong>Console Application</strong>.</p>
27,697
<p>Are all the additions to C# for version 4 (dynamic, code contracts etc) expected to run on the current .NET CLR, or is there a planned .NET upgrade as well?</p>
<p>C# 4 will require the .NET 4.0 CLR. </p>
<p>You don't have to wait for 4.0 to use Code Contracts as it runs on .NET 3.5, the download link for the academic preview release is <a href="http://research.microsoft.com/contracts/#downloads" rel="nofollow noreferrer">here</a>.</p>
43,608
<p>Given an aggregation of class instances which refer to each other in a complex, circular, fashion: is it possible that the garbage collector may not be able to free these objects?</p> <p>I vaguely recall this being an issue in the JVM in the past, but I <em>thought</em> this was resolved years ago. yet, some investigation in jhat has revealed a circular reference being the reason for a memory leak that I am now faced with.</p> <p><em>Note: I have always been under the impression that the JVM was capable of resolving circular references and freeing such "islands of garbage" from memory. However, I am posing this question just to see if anyone has found any exceptions.</em> </p>
<p>Only a very naive implementation would have a problem with circular references. Wikipedia has a good <a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)" rel="noreferrer">article</a> on the different GC algorithms. If you really want to learn more, try (Amazon) <a href="https://rads.stackoverflow.com/amzn/click/com/0471941484" rel="noreferrer" rel="nofollow noreferrer">Garbage Collection: Algorithms for Automatic Dynamic Memory Management </a>. Java has had a good garbage collector since 1.2 and an exceptionally good one in 1.5 and Java 6. </p> <p>The hard part for improving GC is reducing pauses and overhead, not basic things like circular reference.</p>
<p>The garbage collector is a very sophisticated piece of software -- it has been tested in a huge JCK test-suite. It is NOT perfect BUT there is a very good chance that as long as the java compiler(javac) will compile all of your classes and JVM will instantiate it, then you should be good.</p> <p>Then again, if you are holding references to the root of this object graph, the memory will NOT be freed BUT if you know what you're doing, you should be OK.</p>
21,286
<p>When I am creating a test project in Visual Studio, do I just create a C# console project type, then import Nunit?</p> <p>Does the GUI then hook into this project somehow?</p> <p>There seems to be tons of nunit related .dll's, which ones do I need?</p>
<p>Just create a class library (i.e. a DLL). You only need to import nunit.framework.dll.</p> <p>Yes, the nUnit GUI loads your assembly (which can be a DLL or a .EXE) and finds all the <strong>public</strong> classes which have been marked with the appropriate attributes.</p>
<p>I'd recommend checking out the TestDriven.Net Visual Studio plugin. It allows you to run your tests right from VS, so there's no need to fire up the NUnit GUI.</p> <p><a href="http://www.testdriven.net/" rel="nofollow noreferrer">http://www.testdriven.net/</a></p>
44,419
<p>When displaying the value of a decimal currently with <code>.ToString()</code>, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. </p> <p>Do I use a variation of <code>.ToString()</code> for this?</p>
<pre><code>decimalVar.ToString(&quot;#.##&quot;); // returns &quot;.5&quot; when decimalVar == 0.5m </code></pre> <p>or</p> <pre><code>decimalVar.ToString(&quot;0.##&quot;); // returns &quot;0.5&quot; when decimalVar == 0.5m </code></pre> <p>or</p> <pre><code>decimalVar.ToString(&quot;0.00&quot;); // returns &quot;0.50&quot; when decimalVar == 0.5m </code></pre>
<pre><code> var arr = new List&lt;int&gt;() { -4, 3, -9, 0, 4, 1 }; decimal result1 = arr.Where(p =&gt; p &gt; 0).Count(); var responseResult1 = result1 / arr.Count(); decimal result2 = arr.Where(p =&gt; p &lt; 0).Count(); var responseResult2 = result2 / arr.Count(); decimal result3 = arr.Where(p =&gt; p == 0).Count(); var responseResult3 = result3 / arr.Count(); Console.WriteLine(String.Format(&quot;{0:#,0.000}&quot;, responseResult1)); Console.WriteLine(String.Format(&quot;{0:#,0.0000}&quot;, responseResult2)); Console.WriteLine(String.Format(&quot;{0:#,0.00000}&quot;, responseResult3)); </code></pre> <p>you can put as many 0 as you want.</p>
19,934
<p>Has anyone got <a href="http://perldoc.perl.org/Sys/Syslog.html" rel="nofollow noreferrer">Sys::Syslog</a> to work on Solaris? (I'm running Sys::Syslog 0.05 on Perl v5.8.4 on SunOS 5.10 on SPARC). Here's what doesn't work for me:</p> <pre><code>openlog "myprog", "pid", "user" or die; syslog "crit", "%s", "Test from $0" or die; closelog() or warn "Can't close: $!"; system "tail /var/adm/messages"; </code></pre> <p>Whatever I do, the closelog returns an error and nothing ever gets logged anywhere.</p>
<p>By default, Sys::Syslog is going to try to connect with one of the following socket types:</p> <pre><code>[ 'tcp', 'udp', 'unix', 'stream' ] </code></pre> <p>On Solaris, though, you'll need to use an inet socket. Call:</p> <pre><code>setlogsock('inet', $hostname); </code></pre> <p>and things should start working.</p>
<p>setlogsock('inet') didn't do it for me (it looks for host "syslog") but building and installing Sys::Syslog from CPAN did. The Sys::Syslog that comes with Solaris 10 is ancient.</p>
9,331
<p>Is there anyway to automatically run <code>javascript:window.print()</code> when the page finishes loading? </p>
<p><code>&lt;body onload="window.print()"&gt;</code> or <code>window.onload = function() { window.print(); }</code></p>
<p>For me, adding <code>&lt;script&gt;window.print();&lt;/script&gt;</code> to the end of the page worked.</p> <hr> <p>I didn't need the <code>type="text/javascript"</code> attribute, or even for the page to be wrapped in a <code>&lt;body&gt;</code> tag. However, all of my previous attempts to intuitively use the answers suggested here, of just writing <code>window.onload=window.print</code> or longer versions such as <code>window.onload=()=&gt;window.print();</code> did not work, and of course calling print on the newly created window does not wait for the contents to load.</p>
29,902
<p>I'm trying to create an OS X Service. I found <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/SysServices/Tasks/providing.html#//apple_ref/doc/uid/20000853" rel="nofollow noreferrer">Providing System Services</a> in Apple's documentation, however I'm finding it less than clear on what exactly I need to do. I'm currently using an application to register my service (thinking that would be more straight forward - eventually I'd like to create a .service), however even after a logout/login my service still doesn't appear in the list of services in the menu.</p> <p>Is there some step missing from the linked document that I'm missing? I feel like there is some registration step so that the OS knows about my service (in addition to what is listed in that doc), but I'm not able to find anything.</p> <p>Thanks in advance. :)</p> <p>Edit: Here is my NSServices dictionary from my Info.plist file:</p> <pre><code> &lt;key&gt;NSServices&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;NSPortName&lt;/key&gt; &lt;string&gt;POPrlTest&lt;/string&gt; &lt;key&gt;NSMessage&lt;/key&gt; &lt;string&gt;shortenUrlService&lt;/string&gt; &lt;key&gt;NSSendTypes&lt;/key&gt; &lt;string&gt;NSStringPboardType&lt;/string&gt; &lt;key&gt;NSReturnTypes&lt;/key&gt; &lt;string&gt;NSStringPboardType&lt;/string&gt; &lt;key&gt;NSMenuItem&lt;/key&gt; &lt;dict&gt; &lt;key&gt;default&lt;/key&gt; &lt;string&gt;Shorten URL&lt;/string&gt; &lt;/dict&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre>
<p>Make sure your NSServices dictionary has everything it needs. If you're not sure, please post it so we can tell you.</p>
<p>You might want to look at some commercial products to help you with this. See this posting on <a href="http://pmougin.wordpress.com/2008/01/28/become-a-mac-os-x-services-ninja/" rel="nofollow noreferrer">Fun Script</a>.</p>
33,528
<p>I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service. When the device boots, this service typically takes some time to start. I'd like to check, from my code, if the service is running. How can I accomplish this?</p>
<p>I guess something like this would work:</p> <p>Add <code>System.ServiceProcess</code> to your project references (It's on the .NET tab).</p> <pre><code>using System.ServiceProcess; ServiceController sc = new ServiceController(SERVICENAME); switch (sc.Status) { case ServiceControllerStatus.Running: return "Running"; case ServiceControllerStatus.Stopped: return "Stopped"; case ServiceControllerStatus.Paused: return "Paused"; case ServiceControllerStatus.StopPending: return "Stopping"; case ServiceControllerStatus.StartPending: return "Starting"; default: return "Status Changing"; } </code></pre> <p>Edit: There is also a method <code>sc.WaitforStatus()</code> that takes a desired status and a timeout, never used it but it may suit your needs.</p> <p>Edit: Once you get the status, to get the status again you will need to call <code>sc.Refresh()</code> first.</p> <p>Reference: <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller(VS.80).aspx" rel="noreferrer">ServiceController</a> object in .NET.</p>
<p>Here you get all available services and their status in your local machine. </p> <pre><code>ServiceController[] services = ServiceController.GetServices(); foreach(ServiceController service in services) { Console.WriteLine(service.ServiceName+"=="+ service.Status); } </code></pre> <p>You can Compare your service with service.name property inside loop and you get status of your service. For details go with the <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx</a> also <a href="http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx</a></p>
21,464
<p>I am running GNU Emacs on Windows so entering:</p> <pre><code>M-x shell </code></pre> <p>launches the Windows command-line DOS shell. However, I would like to instead be able to run the Cygwin Bash Shell (or any other non-Windows shell) from within Emacs. How can this be easily done?</p>
<p><code>shell-file-name</code> is the variable that controls which shell Emacs uses when it wants to run a shell command.</p> <p><code>explicit-shell-file-name</code> is the variable that controls which shell <code>M-x shell</code> starts up.</p> <p><a href="https://stackoverflow.com/questions/235254/how-can-i-run-cygwin-bash-shell-from-within-emacs#235344">Ken's answer</a> changes both of those, which you may or may not want.</p> <p>You can also have a function that starts a different shell by temporarily changing <code>explicit-shell-file-name</code>:</p> <pre><code>(defun cygwin-shell () "Run cygwin bash in shell mode." (interactive) (let ((explicit-shell-file-name "C:/cygwin/bin/bash")) (call-interactively 'shell))) </code></pre> <p>You will probably also want to pass the <code>--login</code> argument to bash, because you're starting a new Cygwin session. You can do that by setting <code>explicit-bash-args</code>. (Note that <code>M-x shell</code> uses <code>explicit-</code>PROGRAM<code>-args</code>, where PROGRAM is the filename part of the shell's pathname. This is why you should not include the <code>.exe</code> when setting the shell.</p>
<p>In addition to @Chris Jones' answer about avoiding the --login argument to bash, I set the following command line arguments:</p> <pre><code> (setq explicit-bash-args '("--noediting" "-i")) </code></pre> <p>The --noediting option prevents interference with the GNU readline library and the -i option specifies that the shell is interactive. I also use the .emacs_bash file in my home directory for any emacs specific bash customizations. </p>
29,118
<p>Is there a way to know which file is being selected in windows explorer? I've been looking at the tutorial posted here <a href="https://stackoverflow.com/questions/140312/tutorial-for-windows-shell-extensions">Idiots guide to ...</a> but the actions described are:</p> <p>hover</p> <p>context </p> <p>menu properties </p> <p>drag</p> <p>drag and drop</p> <p>I wonder if is there a method that get invoked when a file is selected. For instance to create a thumbnail view of the file. </p> <p>Thanks.</p>
<p>I Found the Answer</p> <p>Ok, not sure if it is kewl answering my own question, but here we go. For some reason the enumeration needed to be marked with the [EnumMember] Attributes as below:</p> <pre><code>[DataContract] public enum Priority { [EnumMember] Low, [EnumMember] Medium, [EnumMember] High } </code></pre> <p>Once I did that my tests and services could be called without the error occurring. I'm still not sure why that specific error was displayed. The error doesn't seem to align in any correlation with the functional reason the error occurred, but this fix definitely smoothed everything out.</p>
<p>Someone on this thread posted that adding this element to the endpoint behavior fixed the issue.</p> <pre><code>&lt;dataContractSerializer maxItemsInObjectGraph="2147483647" /&gt; </code></pre> <p>This worked but it had to be added not only to the endpoint behavior but the service behavior too (which makes sense since that is where the serialization will take place).</p> <p>If it was added to the service only I got this error "Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota."</p> <p>If added to the endpoint only I still got the connection unexpectedly closed error.</p>
28,728
<p>How do I connect to the database(MYSQL) in connection bean using JSF to retrieve its contents. Also please let me know how do I configure the web.xml file?</p>
<p>To get connected to mysql: </p> <pre><code>public void open() { try { String databaseName = "custom"; String userName = "root"; String password = "welcome"; // String url = "jdbc:mysql://localhost/" + databaseName; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(url, userName, password); } catch (Exception e) { System.out.println("Not able to connect"); } } </code></pre> <p>In this case there is nothing to change in web.xml.But you to add this in pom.xml</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;groupId = mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.6&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>This was working successfully.</p>
<p>Here is an <a href="http://blog.exadel.com/?p=8" rel="nofollow noreferrer">example using Hibernate and HSQL</a> - but the basic ideas of separating the db stuff out should be valid and it includes a configured web.xml.</p>
41,376
<p>Is there an easy way to move around controls on a form exactly the same way as the tab key? This includes moving around cells on a datagridview etc.</p>
<p>using winforms you should set the Form KeyPreview property to true</p> <p>and in the keypress event for the form you should have </p> <pre><code>private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) GetNextControl(ActiveControl, true).Focus(); } </code></pre>
<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { Keys keyPressed = (Keys)msg.WParam.ToInt32(); switch (keyPressed) { case Keys.Enter: case Keys.Tab: Control ctrl = this.GetNextControl(this.ActiveControl, true); while (ctrl is TextBox == false) { ctrl = this.GetNextControl(ctrl, true); } ctrl.Focus(); return true; default: return base.ProcessCmdKey(ref msg, keyData); } } </code></pre>
45,338
<p>Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. </p> <p>Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.</p> <p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p> <p>My test library is located in say </p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p> </blockquote> <p>and I would like to get this path:</p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\</p> </blockquote> <p>The three suggestions so far fail me when I run from the MbUnit Gui:</p> <ul> <li><p><code>Environment.CurrentDirectory</code> gives <em>c:\Program Files\MbUnit</em></p></li> <li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code> gives <em>C:\Documents and Settings\george\Local Settings\Temp\ ....\DaoTests.dll</em></p></li> <li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code> gives the same as the previous.</p></li> </ul>
<p><strong>Note</strong>: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0" rel="noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0</a></p> <p><strong>Original answer:</strong></p> <p>I've defined the following property as we use this often in unit testing.</p> <pre><code>public static string AssemblyDirectory { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } </code></pre> <p>The <code>Assembly.Location</code> property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use <code>CodeBase</code> which gives you the path in URI format, then <code>UriBuild.UnescapeDataString</code> removes the <code>File://</code> at the beginning, and <code>GetDirectoryName</code> changes it to the normal windows format.</p>
<p>I use this to get the path to the Bin Directory:</p> <pre><code>var i = Environment.CurrentDirectory.LastIndexOf(@"\"); var path = Environment.CurrentDirectory.Substring(0,i); </code></pre> <p>You get this result:</p> <blockquote> <p>"c:\users\ricooley\documents\visual studio 2010\Projects\Windows_Test_Project\Windows_Test_Project\bin"</p> </blockquote>
7,611
<p>I am looking for a relatively good and well supported, and preferably open source blog application that runs on <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> and <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL&nbsp;Server</a>. It doesn’t need to be packed full of features, it just needs the basics, such as tagging, comments, etc. Extra features are a bonus.</p> <p>I would also like it to be either open source or have an extendable framework for customization of not only the look, but the functionality; preferably written in C# if it's open source, as that is my language of choice.</p> <p>Good performance, etc., the usual stuff when looking for applications.</p> <p>Even if it's a <a href="http://en.wikipedia.org/wiki/Content_management_system" rel="nofollow noreferrer">CMS</a> with a blog in it, that would be beneficial to point out as well.</p> <p>Please give the name, a link, and some of the the things you find good about it. Even if someone has posted what you were going to post, but you have other things you like about it, please add those things anyway.</p> <hr/> <p>I have garnered from the responses to check out <a href="http://www.dotnetblogengine.net/" rel="nofollow noreferrer">BlogEngine.Net</a>, <a href="http://subtextproject.com/" rel="nofollow noreferrer">subtext</a>, <a href="http://www.dasblog.info/" rel="nofollow noreferrer">dasBlog</a>, and to stay away from the blog in <a href="http://en.wikipedia.org/wiki/DotNetNuke" rel="nofollow noreferrer">DotNetNuke</a>. I will start with BlogEngine.</p>
<p>I used <a href="http://www.dotnetblogengine.net/" rel="nofollow noreferrer">BlogEngine.NET</a> for one of <a href="http://blog.atomium.be/" rel="nofollow noreferrer">my clients</a>, can definitely recommend it.</p>
<p>There are two I know of: BlogEngine.NET and DasBlog</p> <p>I'm using BlogEngine.NET. It is very easy to extend as it uses the providers for membership and such. It can be configured to run on SQL&nbsp;Server, but by default it will run using XML.</p> <p>DasBlog should also be a great blog engine, although I have never really played with it.</p> <p>Both are open source and are in C#.</p>
18,309
<p>I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?</p> <pre><code>string[] sa = {"one", "two", "three"}; sa[1].Dump(); var va = sa.Select( (a,i) =&gt; new {Line = a, Index = i}); va[1].Dump(); // Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable&lt;AnonymousType#1&gt;' </code></pre>
<p>As the comment says, you cannot apply indexing with <code>[]</code> to an expression of type <code>System.Collections.Generic.IEnumerable&lt;T&gt;</code>. The IEnumerable interface only supports the method <code>GetEnumerator()</code>. However with LINQ you can call the extension method <code>ElementAt(int)</code>.</p>
<p>You can't apply an index to a var unless it's an indexable type:</p> <pre><code>//works because under the hood the C# compiler has converted var to string[] var arrayVar = {"one", "two", "three"}; arrayVar[1].Dump(); //now let's try var selectVar = arrayVar.Select( (a,i) =&gt; new { Line = a }); //or this (I find this syntax easier, but either works) var selectVar = from s in arrayVar select new { Line = s }; </code></pre> <p>In both these cases <code>selectVar</code> is actually <code>IEnumerable&lt;'a&gt;</code> - not an indexed type. You can easily convert it to one though:</p> <pre><code>//convert it to a List&lt;'a&gt; var aList = selectVar.ToList(); //convert it to a 'a[] var anArray = selectVar.ToArray(); //or even a Dictionary&lt;string,'a&gt; var aDictionary = selectVar.ToDictionary( x =&gt; x.Line ); </code></pre>
6,678
<p>We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:</p> <pre><code>function ajaxModify(controller, parameters, div_id) { var div = $(div_id); var request = new Ajax.Request ( controller, { method: "post", parameters: parameters, onSuccess: function(data) { div.innerHTML = data.responseText; }, onFailure: function() { div.innerHTML = "Information Temporarily Unavailable"; } } ); } </code></pre> <p>However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.</p> <p>I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.</p> <p>By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.</p>
<p>The parameter is:</p> <pre><code>evalScripts:true </code></pre> <p>Note that you should be using <strong>Ajax.Updater</strong>, not <strong>Ajax.Request</strong></p> <p>See: <a href="http://www.prototypejs.org/api/ajax/updater" rel="noreferrer">http://www.prototypejs.org/api/ajax/updater</a></p> <p>Ajax.Request will only process JavaScript if the response headers are:</p> <blockquote> <p>application/ecmascript, application/javascript, application/x-ecmascript, application/x-javascript, text/ecmascript, text/javascript, text/x-ecmascript, or text/x-javascript</p> </blockquote> <p>Whereas Ajax.Updater will process JS is evalScripts:true is set. Ajax.Request is geared toward data transport, such as getting a JSON response.</p> <p>Since you are updating HTML you should be using Ajax.Updater anyways.</p>
<p>you need to use eval() function to run the javascript in Ajax repose this can be use full to separate the script and run it </p> <pre> function PaseAjaxResponse(somemixedcode) { var source = somemixedcode; var scripts = new Array(); while(source.indexOf(&quot;&lt;script&quot;) &gt; -1 || source.indexOf(&quot;&lt;/script&quot;) &gt; -1) { var s = source.indexOf(&quot;&lt;script&quot;); var s_e = source.indexOf(&quot;&gt;&quot;, s); var e = source.indexOf(&quot;&lt;/script&quot;, s); var e_e = source.indexOf(&quot;&gt;&quot;, e); scripts.push(source.substring(s_e+1, e)); source = source.substring(0, s) + source.substring(e_e+1); } for(var x=0; x&lt;scripts.length; x++) { try { eval(scripts[x]); } catch(ex) { } } return source; } </pre> <p>alliteratively for more information see this <a href="http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html" rel="nofollow">http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html</a></p>
35,115
<p>I know Windows has SMTP capabilities under IIS, but I thought a basic SMTP would be a good project for learning Windows application development. I don't want a relay. I want an actual SMTP server that will send email from localhost anonymously. Obviously, it is only to be used for routing emails sent during a development process, and I really wanted to know what I am up against.</p> <ol> <li>Would VB.net be the most common approach?</li> <li>Is it possible to route email anonymously (no username/password)?</li> <li>What are some of the fine details I need to be thinking about?</li> </ol> <p>Thanks!</p>
<p>You'll need to understand the SMTP protocol (or at least a reasonable subset of it). If you're familiar with C++, you could grab the source code for <a href="http://sourceforge.net/projects/blat" rel="nofollow noreferrer">Blat</a> to get an idea of how to create a simple mailing system.</p>
<p>You should read a book on networking protocols. If you want to do this from scratch, you need to keep an outgoing mail queue, you need to parse email addresses to find their hostnames, look up the DNS MX records of those domains, contact the server on port 25 and then talk SMTP.</p>
39,290
<p>I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality.</p> <p>I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parsers you've used?</p>
<p>I would have to say <a href="http://php.net/manual/simplexml.examples.php" rel="noreferrer">SimpleXML</a> takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like <code>$root-&gt;myElement</code>.</p>
<p>the crxml parser is a real easy to parser.</p> <p>This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.</p> <p>you can download this class at</p> <p><a href="http://freshmeat.net/projects/crxml" rel="nofollow">http://freshmeat.net/projects/crxml</a></p> <p>or from phpclasses.org</p> <p><a href="http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html" rel="nofollow">http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html</a></p>
22,844
<p>I know most of the ins and outs of Python's approach to private variables/members/functions/...</p> <p>However, I can't make my mind up on how to distinguish between methods for external use or subclassing use.</p> <p>Consider the following example:</p> <pre><code>class EventMixin(object): def subscribe(self, **kwargs): '''kwargs should be a dict of event -&gt; callable, to be specialized in the subclass''' def event(self, name, *args, **kwargs): ... def _somePrivateMethod(self): ... </code></pre> <p>In this example, I want to make it clear that subscribe is a method to be used by external users of the class/object, while event is a method that should not be called from the outside, but rather by subclass implementations.</p> <p>Right now, I consider both part of the public API, hence don't use any underscores. However, for this particular situation, it would feel cleaner to, for example, use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API. However, that would become unwieldy because then the internal API would need to be invoked as</p> <pre><code>self._EventMixin__somePrivateMethod() </code></pre> <p>So, what are your conventions, coding-wise, documentationwise, or otherwise ?</p>
<pre><code>use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API </code></pre> <p>This is a reasonable and relatively common way of doing it, yes. The double-underline-for-actually-private (as opposed to ‘protected’ in C++ terms) is in practice pretty rare. You never really know what behaviours a subclass might want to override, so assuming ‘protected’ is generally a good bet unless there's a really good reason why messing with a member might be particularly dangerous.</p> <pre><code>However, that would become unwieldy because then the internal API would need to be invoked as self._EventMixin__somePrivateMethod() </code></pre> <p>Nope, you can just use the double-underlined version and it will be munged automatically. It's ugly but it works.</p>
<pre><code>use no underscores for the external API, one underscore for the subclassable API, and two underscores for the private/internal API </code></pre> <p>This is a reasonable and relatively common way of doing it, yes. The double-underline-for-actually-private (as opposed to ‘protected’ in C++ terms) is in practice pretty rare. You never really know what behaviours a subclass might want to override, so assuming ‘protected’ is generally a good bet unless there's a really good reason why messing with a member might be particularly dangerous.</p> <pre><code>However, that would become unwieldy because then the internal API would need to be invoked as self._EventMixin__somePrivateMethod() </code></pre> <p>Nope, you can just use the double-underlined version and it will be munged automatically. It's ugly but it works.</p>
29,251
<p>I know this is possible via a simple registry change to accomplish this as long as IE/firefox is being used. However, I am wondering if there is a reliable way to do so for other browsers,</p> <p>I am specifically looking for a way to do this via an installer, so editing a preference inside a specific browser will not cut it.</p>
<p>Here is the best I can come up with:</p> <p><strong>IE</strong>: <a href="http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx</a></p> <p><strong>FireFox</strong>: <a href="http://kb.mozillazine.org/Register_protocol" rel="noreferrer">http://kb.mozillazine.org/Register_protocol</a></p> <p><strong>Chrome</strong>: Since every other browser in seems to support the same convention, I created a <a href="http://code.google.com/p/chromium/issues/detail?id=5502" rel="noreferrer">bug</a> for chrome. </p> <p><strong>Opera</strong>: I can't find any documentation, but it appears to follow the same method as IE/Firefox (see above links)</p> <p><strong>Safari</strong>: Same thing as opera, it works, but I can't find any documentation on it</p>
<p>Yes. Here is how to do it with FireFox:</p> <p><a href="http://kb.mozillazine.org/Register_protocol" rel="nofollow noreferrer">http://kb.mozillazine.org/Register_protocol</a></p> <p>and Opera:</p> <p><a href="http://www.opera.com/support/kb/view/535/" rel="nofollow noreferrer">http://www.opera.com/support/kb/view/535/</a></p>
47,631
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError</code>.</p> <p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p> <p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
<p>+1 for the <a href="http://web.archive.org/web/20110709171259/http://chardet.feedparser.org/docs/faq.html" rel="noreferrer">chardet</a> module (suggested by <a href="https://stackoverflow.com/questions/269060/is-there-a-python-library-function-which-attempts-to-guess-the-character-encoding/269105#269105"><code>@insin</code></a>).</p> <p>It is not in the standard library, but you can easily install it with the following command:</p> <pre><code>$ pip install chardet </code></pre> <p><a href="http://web.archive.org/web/20111003070626/http://chardet.feedparser.org/" rel="noreferrer">Example</a>:</p> <pre><code>&gt;&gt;&gt; import chardet &gt;&gt;&gt; import urllib &gt;&gt;&gt; detect = lambda url: chardet.detect(urllib.urlopen(url).read()) &gt;&gt;&gt; detect('http://stackoverflow.com') {'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} &gt;&gt;&gt; detect('https://stackoverflow.com/questions/269060/is-there-a-python-lib') {'confidence': 0.98999999999999999, 'encoding': 'utf-8'} </code></pre> <p>See <a href="http://guide.python-distribute.org/installation.html#installing-pip" rel="noreferrer">Installing Pip</a> if you don't have one.</p>
<p>The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.</p>
33,784
<p>I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface.</p> <p>I have an interface lets call it Account</p> <pre><code>public interface Account { public void doStuff(); } </code></pre> <p>Now I have two concrete implementors of Account OverSeasAccount and OverDrawnAccount</p> <pre><code>public class OverSeasAccount implements Account { public void doStuff() { //do overseas type stuff } } </code></pre> <p>AND</p> <pre><code>public class OverDrawnAccount implements Account { public void doStuff() { //do overDrawn type stuff } } </code></pre> <p>I have a class called Work with a List</p> <pre><code>private List&lt;Account&gt; accounts; </code></pre> <p>I am looking at discriminator fields but I seem to be only able do this for abstract classes. Is this the case? Any pointers appreciated. Can I use discriminators for interfaces? </p>
<p>I think that it is possible to to make an interface the supertype of a mapping. You may not be able to use annotations though. Annotations play well with xml config files so you might have to add a hibernate config file to your project with the mappings that you need. But you will be able to keep the annotations for the rest of your project.</p> <p><a href="http://opensource.atlassian.com/projects/hibernate/browse/ANN-9" rel="nofollow noreferrer">This</a> issue discusses it more. It seems to end with a suggestion as to how to do it with annotations so who knows. I would suggest that xml is still safer for now This <a href="http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#inheritance-tableperclass" rel="nofollow noreferrer">page</a> of the docs explains the xml mapping needed.</p>
<p>You can also introduce an abstract class without removing the interface.</p> <pre><code>// not an entity public interface Account { public void doStuff(); } @Entity public abstract class BaseAccount { public void doStuff(); } @Entity public class OverSeasAccount extends AbstractAccount { public void doStuff() { ... } } @Entity public class OverDrawnAccount extends AbstractAccount { public void doStuff() { ... } } </code></pre>
35,619
<p>Is there a USB HID pen driver in Windows Vista? If so, what are the requirements for USB descriptors, in order to make Windows Vista recognize the pen and load the pen driver?</p> <p>What I'm searching for is the pen equivalent to the HID mouse driver, HID keyboard driver and mass storage driver. The mentioned example drivers makes it possible for Windows, Linux and Mac OS to recognize mouse, keyboard and memory sticks without installing new drivers.</p> <p>Windows Vista has a lot of native support for pen, and it is possible to define a USB pen device only using standard HID usage tables (from a USB protocol point of view). So far I'm able to make USB HID descriptors that qualify as mouse and keyboard (from OS point of view), and automatically uses the standard driver supplied by the OS. </p> <p>For my Pen, however, Windows Vista just loads the generic HID driver, and does not realize that the device is a "pen". The motivation for defining a pen rather than a mouse with absolute coordinates, is that Vista supports special features like "gestures", but this is only enabled for Pen/Digitizer devices.</p>
<p>I checked out the C++ standard. In section 9.2, paragraph (or clause or whatever) 12, it says "The order of allocation of nonstatic data members separated by an access-specifier is unspecified." "Unspecified" means implementation-dependent behavior that need not be documented.</p> <p>Therefore, the standard is explicitly saying nothing about the allocation, except that i must precede j and k must precede n. Therefore, a compiler is allowed to allocate in the order i, k, j, n, and nothing about the ordering need be documented.</p>
<p>The way I interpret the standard, it sees the code example as follows: since there is no access specifier between i and j, the address of i must come before the address of j. The proposed ordering satisfies this. Idem for k and n. So in my interpretation, compilers <em>are</em> allowed to use this ordering.</p>
36,882
<ul> <li>I start up my application which uses a Jetty server, using port 9000.</li> <li>I then shut down my application with Ctrl-C</li> <li>I check with "netstat -a" and see that the port 9000 is no longer being used.</li> <li>I restart my application and get:</li> </ul> <blockquote> <pre><code>[ERROR,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] java.net.BindException: Only one usage of each socket address (protocol/network address/port) is normally permitted [TRACE,9/19 15:31:08] at java.net.PlainSocketImpl.convertSocketExceptionToIOException(PlainSocketImpl.java:75) [TRACE,9/19 15:31:08] at sun.nio.ch.Net.bind(Net.java:101) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:126) [TRACE,9/19 15:31:08] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:77) [TRACE,9/19 15:31:08] at org.mortbay.jetty.nio.BlockingChannelConnector.open(BlockingChannelConnector.java:73) [TRACE,9/19 15:31:08] at org.mortbay.jetty.AbstractConnector.doStart(AbstractConnector.java:285) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at org.mortbay.jetty.Server.doStart(Server.java:233) [TRACE,9/19 15:31:08] at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40) [TRACE,9/19 15:31:08] at ... </code></pre> </blockquote> <p>Is this a Java bug? Can I avoid it somehow before starting the Jetty server?</p> <p><strong>Edit #1</strong> Here is our code for creating our BlockingChannelConnector, note the "setReuseAddress(true)":</p> <blockquote> <pre><code> connector.setReuseAddress( true ); connector.setPort( port ); connector.setStatsOn( true ); connector.setMaxIdleTime( 30000 ); connector.setLowResourceMaxIdleTime( 30000 ); connector.setAcceptQueueSize( maxRequests ); connector.setName( "Blocking-IO Connector, bound to host " + connector.getHost() ); </code></pre> </blockquote> <p>Could it have something to do with the idle time?</p> <p><strong>Edit #2</strong> Next piece of the puzzle that may or may not help: when running the application in Debug Mode (Eclipse) the server starts up without a problem!!! But the problem described above occurs reproducibly when running the application in Run Mode or as a built jar file. Whiskey Tango Foxtrot?</p> <p><strong>Edit #3 (4 days later)</strong> - still have the issue. Any thoughts?</p>
<p>During your first invocation of your program, did it accept at least one incoming connection? If so then what you are most likely seeing is the socket linger in effect. </p> <p>For the best explanation dig up a copy of TCP/IP Illustrated by Stevens </p> <p><a href="https://i.stack.imgur.com/DNDVu.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNDVu.gif" alt="alt text"></a><br> <sub>(source: <a href="http://www.kohala.com/start/gifs/tcpipiv1.gif" rel="nofollow noreferrer">kohala.com</a>)</sub> </p> <p>But, as I understand it, because the application did not properly close the connection (that is BOTH client and server sent their FIN/ACK sequences) the socket you were listening on cannot be reused until the connection is considered dead, the so called 2MSL timeout. The value of 1 MSL can vary by operating system, but its usually a least a minute, and usually more like 5. </p> <p>The best advice I have heard to avoid this condition (apart from always closing all sockets properly on exit) is to set the SO_LINGER tcp option to 0 on your server socket during the listen() phase. As freespace pointed out, in java this is the setReuseAddress(true) method.</p>
<p>I'm not sure about Jetty, but I have noticed that sometimes Tomcat will not shut down cleanly on some of our Linux servers. In cases like that, Tomcat will restart but not be able to use the port in question because the previous instance is still bound to it. In such cases, we have to find the rogue process and explicitly kill -9 it before we restart Tomcat. I'm not sure if this is a java bug or specific to Tomcat or the JVM we're using.</p>
12,739
<p>I'm trying to programmatically restrict the memory consumption of plugins running in a .Net AppDomain, but I can't find any setup parameters for this, nor can I find a way to query an AppDomain to figure out how much memory it is consuming. Any ideas?</p>
<p>Old question, but in the meantime (since .Net framework 4.0) a new solution is available. You will have to enable ARM (Application domain Resource Monitoring). From that point on, you can request information on total consumed processor time, memory usage etc.</p> <p><a href="https://msdn.microsoft.com/en-us/library/dd997285%28v=vs.110%29.aspx" rel="noreferrer">See Microsoft documentation over here</a></p>
<p>Using the mscoree.CorRuntimeHostClass interop from C:\WINDOWS\Microsoft.NET\Framework\vXXXXXX\mscoree.tlb</p>
4,566
<p>Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to <em>assert_in_delta(expected_float, actual_float, delta)</em> from <em>test/unit</em> but returning Boolean?</p>
<pre><code>(expected_float - actual_float).abs &lt;= delta </code></pre>
<p>you may also need a relative tolerance / delta calculation</p> <p><a href="http://realtimecollisiondetection.net/blog/?p=89" rel="nofollow noreferrer">http://realtimecollisiondetection.net/blog/?p=89</a></p>
29,607
<p>I'm trying to figure out if it's worth buying a 3D printer or using an online printing service like e.g. <a href="https://treddy.it" rel="nofollow noreferrer">this one</a> in the long run. Anyone have any cost analysis?</p>
<h1>It depends</h1> <p>If it is worth to invest in a print made for you compared to getting a printer depends on the needs you have. Thee can be informed by the type of material you want to print and the requirements that has on you. Let me give you some examples when it is simply worth it to pay:</p> <ul> <li>A metal printer costs in the thousands: upper five-digit for the most baseline and <a href="https://all3dp.com/2/how-much-does-a-metal-3d-printer-cost/" rel="nofollow noreferrer">averaging in the low to mid-6-digit</a>. Ordering a single or few printed pieces will be economical, and even ordering <strong>many</strong> parts will still be well below break-even, considering that the material sets you back by up to 600 \$ per kilo!</li> <li>A nylon powder printer <a href="https://all3dp.com/1/best-sls-3d-printer-desktop-industrial/" rel="nofollow noreferrer">starts in the middle 4-digits but easily goes up to upper 5-digits and even middle 6 digits</a>. Ordering for a small-scale production this way still will be economical.</li> <li>Some specialty plastics need printers with very high-temperature chambers and hotends with extreme wear resistance. Such machinery can easily cost five digits, especially in large dimensions where it goes to six. Compared to purchasing price of the machine, ordering the part will be cheaper.</li> </ul> <p>On the other hand, getting a printer gets cheaper once you:</p> <ul> <li>use it sufficiently, for example, to iteratively modify a designed part or produce a medium variety of parts.</li> <li>have the time and money to spare to learn and tweak your machine to do what you want.</li> <li>the amount of parts you want to make would cost you more to have ordered than a new printer, or a substantial portion thereof. For an FDM machine, the first useful machines can be priced as low as 150 \$, while 300 \$ gets you a somewhat capable Ender 3 v2 - which has developed into some kind of <em>standard unit</em> for printers.</li> </ul> <p>Also note, that some printing services have limits on what they will produce. Commonly they will not provide services to manufacture tools or items that might violate local law or make it trivially to do so, for example copying keys or even manufacturing Keyblanks.</p>
<p>I would think it depends on your future needs. If you will rarely need things printed then online is more convenient than buying a printer and doing the whole learning curve, storing materials etc,.</p> <p>From what I have seen online, most people printing are not printing things they actually need.</p> <p>If you want to produce things to sell, then you're better off doing it yourself.</p>
2,131
<p>What is the cheap and good way to make a serial (RS232) programmer for AVR atMega and atTiny? There are several circuits in the Internet, but which one is better?</p> <p>I'd like to be able to program my controller from Linux and Windows using some standard tools.</p>
<p>Try the <a href="http://www.adafruit.com/index.php?main_page=product_info&amp;cPath=16&amp;products_id=26" rel="nofollow noreferrer">Serial port AVR programmer (DASA) Kit</a> from Adafruit Industries. It's only $7.50, is very popular with the <a href="http://www.arduino.cc/en/Guide/Introduction" rel="nofollow noreferrer">Arduino</a> community, and she provides step by step <a href="http://www.ladyada.net/make/spokepov/makeserialdongle.html" rel="nofollow noreferrer">instructions for assembly</a> on her personal site. </p> <p>If you don't want to build it yourself, <a href="http://www.sparkfun.com/commerce/categories.php?c=1" rel="nofollow noreferrer">Sparkfun Electronics</a> has several serial programmers available for a bit more money.</p>
<p>If usb can be used, I really don't think the original programmer (<a href="http://www.atmel.com/dyn/products/tools_card.asp?tool_id=3808" rel="nofollow noreferrer">AVR ISP mkII</a>) is that expensive, the pricing today was about 34$.</p>
15,986
<p>I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'.</p> <p>I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in. Does P4 have the equivalent of Subversion's 'ignore file' feature? </p>
<p>As of version 2012.1, Perforce supports the <code>P4IGNORE</code> environment variable. I updated my answer to <a href="https://stackoverflow.com/a/3103898/4228">this question about ignoring directories</a> with an explanation of how it works. Then I noticed this answer, which is now superfluous I guess.</p> <hr> <p>Assuming you have a client named "CLIENT", a directory named "foo" (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:</p> <pre> -//depot/foo/*.dll //CLIENT/foo/*.dll -//depot/foo/.../*.dll //CLIENT/foo/.../*.dll </pre> <p>The first line removes them from the directory "foo" and the second line removes them from all sub directories. Now, when you 'Reconcile Offline Work...', all the .dll files will be moved into "Excluded Files" folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.</p> <p>You can also do it another way, which will reduce your "Excluded Files" folder to just one, but you won't be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn't matter).</p> <pre> -//depot/foo.../*.dll //CLIENT/foo.../*.dll </pre>
<p>If you are using the Eclipse Perforce plugin, then <a href="http://perforce.com/perforce/doc.091/manuals/p4wsad/topics/adding.html" rel="nofollow noreferrer">the plugin documentation</a> lists several ways to ignore files.</p>
7,923
<p>Given the constraint of only using T-Sql in Sql Server 2005, is there a better way to remove the decimal point from a money datatype than a conversion to a varchar (here implicitly) and then a replace of the decimal point?</p> <p>Here is what I have currently.</p> <pre><code>SELECT REPLACE(1.23, '.', ''), REPLACE(19.99, '.', '') </code></pre> <p>Which returns the desired 123 and 1999, but I was wondering if there was a better way. Any thoughts?</p>
<p>Multiply by 100 and then convert to an int.</p>
<p>Could you be a little more specific about the use case? Removing the decimal point from the representation is a little unusual given that you'll lose all information about the scale. Are you assuming that there will always be two digits? If so, you could simplify multiply by 100 and then round before converting to a string.</p>
2,594
<p>I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in <pre> [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.</pre></p> <p>My class implements the BuildListener interface. Various postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...</p> <p>Can anyone shed light on what I'm doing wrong? Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.</p>
<p>I had this problem when I had two plugins providing an <code>ant.jar</code>.</p> <p>Make sure you use the <code>org.apache.ant</code> plugin and that there is no other plugin providing another <code>ant.jar</code>.</p> <p>Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).</p> <p>See <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=34466" rel="nofollow noreferrer">Eclipse Bug 34466</a>.</p>
<p>Follow the instructions as for working with contributed tasks and types found here: <a href="http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/ant_developing.htm" rel="nofollow noreferrer">Developing Ant tasks</a> and <a href="http://help.eclipse.org/ganymede/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/ant_contributing_task.htm" rel="nofollow noreferrer">Contributed Ant tasks</a></p>
22,130
<p>a question that a co-interviewer asked in interviews. I always thought it was a silly question. </p> <p>Assume single processor and not dual core.</p>
<p>Yes you can if DMA is not available. In that case you could end up using the CPU to move data around from I/O to I/O through central memory, if the I/O bandwidth on both devices is high enough you will effectively saturate the CPU. </p>
<p>I'd also look for places where IO devices are virtualized and encrypted. This is probably an unusual case, but not an impossible case.</p>
48,305
<p>My LCD rotates. The software that comes with my ATI card to rotate the desktop just crashes (<em>I've uninstalled, reinstalled and rolled them back, still crashes</em>). Is there any other way to rotate a Windows XP Desktop by 90 degree increments? I am looking for either software or code (any language is fine.) I know I have seen 3rd party support for this before, but I can't find it now.</p> <p>I realize this may not be a strictly software development related question, but it is programmer productivity related. If I can get an answer that involves how to write a program to do this, even better!</p>
<p>IRotate: <a href="http://www.entechtaiwan.net/util/irotate.shtm" rel="nofollow noreferrer">http://www.entechtaiwan.net/util/irotate.shtm</a>.<br> Have not used it but heard good things.</p> <p>Same people that make Powerstrip <a href="http://www.entechtaiwan.net/util/ps.shtm" rel="nofollow noreferrer">http://www.entechtaiwan.net/util/ps.shtm</a>.<br> Which gets rave reviews from the HTPC crowd. </p> <p>Was looking at these recently while researching stuff for an HTPC.<br> Both are try before buy shareware.</p>
<p>I hate to give you the answer you probably already know, but yeah this is a video card driver software thing and if the ATI software crashes then it's either corrupted or buggy or your Windows install has gone rotten.</p> <p>I've done this before on my NVidia-based cards without issue. I've never owned an ATI card.</p>
6,917
<p>Is it possible to create a .NET equivalent to the following code?</p> <pre><code>&lt;?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "&lt;p&gt;Hello {$_SERVER['PHP_AUTH_USER']}.&lt;/p&gt;"; echo "&lt;p&gt;You entered {$_SERVER['PHP_AUTH_PW']} as your password.&lt;/p&gt;"; } ?&gt; </code></pre> <p>I would like to be able to define a static user/password in the web.config as well. This is very easy to do in PHP, haven't seen anything explaining how to do this in MSDN.</p> <hr> <p>All I want is this:</p> <p><img src="https://i.stack.imgur.com/IJE1b.png" alt="https://i.stack.imgur.com/IJE1b.png"></p>
<p>The easiest way to achieve the same as with the PHP code would be to directly send the same headers via <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.appendheader(VS.80).aspx" rel="nofollow noreferrer">Reponse.AppendHeader()</a>.</p> <p>Still I would suggest you to read an <a href="http://www.asp.net/Learn/Security/" rel="nofollow noreferrer">ASP.NET Forms Authentication Tutorial</a>.</p>
<p>Yes, you can add to web.config and use forms authentication. I dont know php, so i cant help witjh the rest of your question</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa720092(VS.71).aspx</a>\</p>
17,999
<p>I have recently started exploring Maven, but I feel a bit overwhelmed of all xml configuration in all the pom files. Are there any good tools i can use?</p>
<p><a href="http://m2eclipse.codehaus.org/" rel="noreferrer">m2eclipse</a>, it provides a very nice form-based editor. But I only use the XML view most of the time. </p>
<p>I don't. I use <a href="http://incubator.apache.org/buildr/" rel="nofollow noreferrer">buildr</a>, which has a lot more compact ruby based syntax to describe your project.</p>
41,702
<p>I've been using various javascript frameworks including mootools, jquery, prototype and scriptaculous and have found them all good, but difficult to extend to more complex ideas.</p> <p>If I am going to knuckle down and learn one, which is the simplest to extend and use whilst staying powerful enough to use in a variety of directions?</p>
<p>I propose jQuery.</p> <p>I'll give you some of the major arguments from the presentation that my team put on yesterday for senior management to convince them of that.</p> <p>Reasons:</p> <ol> <li><p>Community acceptance. Look at <a href="http://google.com/trends?q=jquery%2C+prototype%2C+yui%2C+scriptaculous+&amp;ctab=0&amp;geo=all&amp;date=all&amp;sort=0" rel="noreferrer">this graph</a>. It shows searches for "prototype", "yui" and "scriptaculous" growing from 2004 to 2008. Then out of nowhere in 2006 searches fro "jquery" shoot up to double the number of the other libraries. The community is actually converging on a single leading product, and it's jQuery.</p></li> <li><p>jQuery is very very succinct and readable. I conducted an experiment in which I took existing code (selected at random) written in YUI, and tried re-writing it in jQuery. It was 1/4 as long in jQuery. That makes it 4 times as easy to write, and 4 times as easy to maintain.</p></li> <li><p>jQuery integrates well with the rest of the web world. The use of CSS syntax as the key for selecting items is a brilliant trick which helps to meld together the highly diseparate worlds of HTML, CSS and JavaScript.</p></li> <li><p>Documentation: jQuery has excellent documentation, with clear specifications and working examples of every method. It has excellent books (I recommend "jQuery in Action".) The only competitor which matches it is YUI.</p></li> <li><p>Active user community: the Google group which is the main community discussion forum for Prototype has nearly 1000 members. The Google group for jQuery has 10 times as many members. And my personal experience is that the community tends to be helpful.</p></li> <li><p>Easy learning curve. jQuery is easy to learn, even for people with experience as a designer, but no experience in coding.</p></li> <li><p>Performance. Check out <a href="http://mootools.net/slickspeed/" rel="noreferrer">this</a>, which is published by mootools. It compares the speed of different frameworks. jQuery is not always the VERY fastest, but it is quite good on every test.</p></li> <li><p>Plays well with others: jQuery's noConflict mode and the core library's small size help it to work well in environments that are already using other libraries.</p></li> <li><p>Designed to make JavaScript usable. Looping is a pain in JavaScript; jQuery works with set objects you almost never need to write the loop. JavaScript's greatest strength is that functions are first-class objects; jQuery makes extensive use of this feature.</p></li> <li><p>Plug-ins. jQuery is designed to make it <em>easy</em> to write plugins. And there is an enormous community of people out there writing plugins. Anything you want is probably out there. Check out things like <a href="http://ui.jquery.com/repository/real-world/effects/" rel="noreferrer">this</a> or <a href="http://interface.eyecon.ro/demos/" rel="noreferrer">this</a> for visual examples.</p></li> </ol> <p>I hope you find this convincing!</p>
<p>Another vote for jQuery. It's small, focussed, and yet very powerful. It's also reasonable well documented, by the (generally awful) standards of JS libraries.</p> <p>It's also very easy to extend, once you get your head around the syntax.</p>
16,901
<p>The question is a fairly open one. I've been using Stored Procs with MS SQLServer for some time with classic ASP and ASP.net and love them, lots.</p> <p>I have a small hobby project I'm working on and for various reasons have gone the LAMP route. Any hints/tricks/traps or good starting points to get into using stored procedures with MySQL and PHP5? My version of MySQL supports Stored Procedures.</p>
<p>Forget about <code>mysqli</code>, it's much harder to use than PDO and should have been already removed. It is true that it introduced huge improvements over mysql, but to achieve the same effect in mysqli sometimes requires enormous effort over PDO i.e. associative <code>fetchAll</code>.</p> <p>Instead, take a look at <a href="http://www.php.net/manual/en/book.pdo.php" rel="nofollow noreferrer">PDO</a>, specifically <a href="http://www.php.net/manual/en/pdo.prepared-statements.php" rel="nofollow noreferrer"> prepared statements and stored procedures</a>.</p> <pre><code>$stmt = $dbh-&gt;prepare("CALL sp_takes_string_returns_string(?)"); $value = 'hello'; $stmt-&gt;bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); // call the stored procedure $stmt-&gt;execute(); print "procedure returned $value\n"; </code></pre>
<p>I have been using ADODB, which is a great thing for abstracting actual commands to make it portable between different SQL Servers (ie mysql to mssql). However, Stored procedures do not appear to be directly supported. What this means, is that I have run a SQL query as if it is a normal one, but to "call" the SP. An example query:</p> <pre><code>$query = "Call HeatMatchInsert('$mMatch', '$mOpponent', '$mDate', $mPlayers, $mRound, '$mMap', '$mServer', '$mPassword', '$mGame', $mSeason, $mMatchType)"; </code></pre> <p>This isn't accounting for returned data,which is important. I'm guessing that this would be done by setting a @Var , that you can select yourself as the return @Variable .</p> <p>To be Abstract though, although making a first php stored procedure based web app was very difficult to work around (mssql is very well documented, this is not), It's great after its done - changes are very easy to make due to the seperation.</p>
14,424
<p>The backstory: I'm installing a pigeon net in my home. Because of the shape of the opening I'm installing the net in and the material on the sides it's difficult to anchor the net using the normal means but I can print clips that will hold the net in place.</p> <p>The clips will be outside and will be exposed to the weather and direct sunlight, the weather here is relatively hot (up to 30C) with a lot of sun most of the year and rain in the winter.</p> <p>I only have PLA, ABS and PETG available, anything else will take too long to arrive.</p> <p>I don't care about the parts changing color and mostly I don't care about them deforming a little bit - only about breaking.</p> <p>If the parts have to be replaced after a year I'm ok with it, less then that will be annoying, longer will be better.</p> <p>So, under those conditions, which of the 3 materials is more durable?</p>
<p>Ok, I tried all 3 materials.</p> <p>PLA failed after less then one day, I believe it deformed from the constant pressure and fell out (I didn't find the part but I didn't really search for it, there's some tall grass below the window)</p> <p>ABS lasted about a year, it fell strait down and I found the part, it looks ok if probably deformed by just a few mm so it doesn't pressure fit anymore.</p> <p>PETG still going strong as I write this</p>
<p>What colour was your PLA? PLA will soften around 60C and a dark colour will easily get hotter than that in direct sun on a 30C day. Clear PLA seems to have much, much better temperature resistance, but any sort of PETG will kick it's butt in that regard.</p>
565
<p>What's the best way to detect that Adobe Acrobat Reader is installed from a web browser? I'm assuming it would have to be done on the client-side (I don't think Adobe adds any user-agent strings). Preferably in JavaScript and in Internet Explorer, although it would be nice if it could also be done in FireFox, Safari, etc...</p>
<p>Also note that, even if someone does not have the Acrobat Reader plugin, he might still be able to read PDF files (for instance, by telling the browser to launch an external reader such as kpdf). So allow the user to download the PDF even if the plugin cannot be found. Not to mention the people with Javascript disabled (or NoScript users).</p>
<p><a href="http://support.adobe.com/devsup/devsup.nsf/docs/52970.htm" rel="nofollow noreferrer">This article</a> from the Adobe website should get you what you need.</p> <p><strong>EDIT</strong></p> <p>In testing this it isn't 100% though, as I have acrobat, but it doesn't detect it in IE 6.</p>
30,638
<p>The bossman wants to know how to delete a user in Sharepoint. We've got him convinced that deleting a user is too difficult because of traces of that user through the system, so now he wants to be able to change the username to all Xs or somesuch. I've poked around the DB and found a couple of UserInfo tables, one in <code>SharePoint_AdminContent_&lt;guid&gt;</code> db and another in SharedServices. Is there a better way to change usernames? Am I on the wrong track?</p> <p>Thanks. </p>
<p>Please don't access the database directly as it's not supported ; you may even destroy integrity in the process.</p> <p>If you <strong>really</strong> want to "remove" all trace of a user, I suggest looking to "<code>stsadm -o migrateuser</code>" to rename the user to a dummy XXX user created in your membership provider.</p> <p><strong>Edit</strong>: it's migrateuser and not renameuser, my mistake</p> <p><a href="http://technet.microsoft.com/en-us/library/cc262141.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/cc262141.aspx</a></p>
<p>The reason you cannot remove users from SharePoint is because users are not stored in SharePoint. Users are stored in the respective membership provider: AD, aspnetsqlmembershipprovider, etc.</p> <p>The process for removing a user from SharePoint's environment is to first go to your membership provider and delete the user there. After you have done this, you have a choice. </p> <ol> <li>You can leave the user's artifacts for legacy information. Ie, Joe Blow created a document and even though Joe Blow doesn't exist anymore (hit by bus) it's good to know that he created the document. </li> <li>Alternatively, you can run the <code>stsadm -o deleteuser</code> command Alex mentioned (once per site collection), which should disassociate that user from all their artifacts for that site collection. Any documents the user created will now be owned by the system administrator (I believe). An example of using this option is when the user account was misspelled and you want to remove all traces before creating the correct account.</li> </ol>
44,735
<p>I have 2 columns in a Grid. When I click a button, I want the first column to animate to the left from it's current position to 0. So, in effect, it collapses and I'm left with just viewing a single column.</p>
<p>Shouldn't be too hard. You'd need to create an EventTrigger that has a BeginStoryboard that targets the grid and uses a DoubleAnimation to shrink the column width. <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.animation.doubleanimation.aspx" rel="noreferrer">The example here has a similar setup.</a> The EventTrigger would go on the button and the DoubleAnimation's <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.animation.storyboard.target.aspx" rel="noreferrer">StoryBoard.Target</a> would point to the ColumnDefinition you wish to shrink. </p> <p>Okay, so that doesn't work so well. You can't shrink the column directly, but you CAN set the shrinking column to fill (width="*"), set the width of the Grid and the non-shrinking column, and then shrink the entire grid. This does work. The below example works:</p> <pre><code>&lt;Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowTitle="Opacity Animation Example" Background="White"&gt; &lt;StackPanel Margin="20"&gt; &lt;Grid Name="MyGrid" Width="200" HorizontalAlignment="Left"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="100"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="100"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Fill="Red"/&gt; &lt;Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Fill="Blue"/&gt; &lt;/Grid&gt; &lt;Button Name="hideButton"&gt; &lt;Button.Triggers&gt; &lt;EventTrigger RoutedEvent="Button.Click"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard&gt; &lt;DoubleAnimation Storyboard.TargetName="MyGrid" Storyboard.TargetProperty="(Grid.Width)" From="200" To="100" Duration="0:0:2" AutoReverse="True" /&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/Button.Triggers&gt; &lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Page&gt; </code></pre>
<p>You can also achieve this with GridLength animation , see an example here <a href="http://marlongrech.wordpress.com/2007/08/20/gridlength-animation/" rel="nofollow noreferrer">http://marlongrech.wordpress.com/2007/08/20/gridlength-animation/</a> Using this approach you can manipulate any given Grid.Column or Grid.Row size. </p> <p>For your special need just put first column with Width="Auto" and second with *, animate the with of the content inside the first column- that will do the trick.</p>
24,083
<p>When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. </p>
<p>After you commit your object into the db the object receives a value in its ID field.</p> <p>So:</p> <pre><code>myObject.Field1 = "value"; // Db is the datacontext db.MyObjects.InsertOnSubmit(myObject); db.SubmitChanges(); // You can retrieve the id from the object int id = myObject.ID; </code></pre>
<p>Try this:</p> <pre><code>MyContext Context = new MyContext(); Context.YourEntity.Add(obj); Context.SaveChanges(); int ID = obj._ID; </code></pre>
13,914
<p>Windows Forms:</p> <p>For <code>System.Drawing</code> there is a way to get the font height. </p> <pre><code>Font font = new Font("Arial", 10 , FontStyle.Regular); float fontHeight = font.GetHeight(); </code></pre> <p>But how do you get the other text metrics like average character width?</p>
<p>Use Graphics.MeasureString Method</p> <pre><code>private void MeasureStringMin(PaintEventArgs e) { // Set up string. string measureString = "Measure String"; Font stringFont = new Font("Arial", 16); // Measure string. SizeF stringSize = new SizeF(); stringSize = e.Graphics.MeasureString(measureString, stringFont); // Draw rectangle representing size of string. e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height); // Draw string to screen. e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0)); } </code></pre>
<p>I've never seen an average character width property in .NET. You can get the width of a particular string in a particular font by using Graphics.MeasureString or TextRenderer.MeasureString.</p>
39,793
<p>I have created a C# class file by using a XSD-file as an input. One of my properties look like this:</p> <pre><code> private System.DateTime timeField; [System.Xml.Serialization.XmlElementAttribute(DataType="time")] public System.DateTime Time { get { return this.timeField; } set { this.timeField = value; } } </code></pre> <p>When serialized, the contents of the file now looks like this:</p> <pre><code>&lt;Time&gt;14:04:02.1661975+02:00&lt;/Time&gt; </code></pre> <p>Is it possible, with XmlAttributes on the property, to have it render without the milliseconds and the GMT-value like this?</p> <pre><code>&lt;Time&gt;14:04:02&lt;/Time&gt; </code></pre> <p>Is this possible, or do i need to hack together some sort of xsl/xpath-replace-magic after the class has been serialized?</p> <p>It is not a solution to changing the object to String, because it is used like a DateTime in the rest of the application and allows us to create an xml-representation from an object by using the XmlSerializer.Serialize() method.</p> <p>The reason I need to remove the extra info from the field is that the receiving system does not conform to the w3c-standards for the time datatype.</p>
<p>You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.</p>
<p>You could create a string property that does the translation to/from your timeField field and put the serialization attribute on that instead the the real DateTime property that the rest of the application uses.</p>
12,700
<p>I just migrated to Windows Ultimate 64 SP1, because my system's hard drive crashed. I installed Visual Studio 2005 SP1 and all the patches that Microsoft has recommended. I finally got my source code from my SCM, but now debugging does not stop on any of my breakpoints I have set. This is just a plain Winforms app, nothing fancy.</p> <p>The first thing I did was to change the build target to x86. No dice. Then I went and downloaded Debugging Tools for x64, still no dice. I set the debugger to break on all exceptions both handled and unhandled. No dice either.</p> <p>I've been looking at Google search results, but no luck there either. I've been at this for 3 days now with no luck. Has anybody dealt with this issue before?</p> <p><strong>Update:</strong></p> <p>The projects are all set to Debug (x86).</p> <p>Breakpoints stay normal when the debugging session starts.</p> <p>I already did a re-install, and that didn't work either.</p> <p>I am running as Administrator and turned off UAC.</p> <p>I attached to the project using "Attach to Process", and I was able to step into the code that way. I'm hoping to find out why it is not auto attaching, in order to avoid having to do this manually every time.</p>
<p>This is listed as a <a href="http://msdn.microsoft.com/en-us/vstudio/aa964140.aspx#question20a" rel="nofollow noreferrer">known issue for VS2005 on Vista (Via MSDN):</a></p> <blockquote> <p><strong>Title</strong>: Just-In-Time (JIT) Debugging of an elevated process will fail</p> <p><strong>Description</strong>: Elevated processes cannot be JIT Debugged by VS 2005. This includes system processes, such as IIS, and applications started by selecting ‘Run as administrator’.</p> <p><strong>Workaround</strong>: The debugger must be attached manually before the debugger will catch unhandled exceptions or user break points (System.Diagnostics.Debugger.Break, __debugbreak, etc).</p> </blockquote>
<p>I am using Visual Studio 2005 with the same patch level on both Windows Server 2008 x64 and Vista x64 SP1 without any issues. </p> <p>Are you running it as admin? When all else fails, try uninstalling and reinstalling.</p>
30,889
<p>I have a table in a DB (Postgres based), which acts like a superclass in object-oriented programming. It has a column 'type' which determines, which additional columns should be present in the table (sub-class properties). But I don't want the table to include all possible columns (all properties of all possible types).</p> <p>So I decided to make a table, containg the 'key' and 'value' columns (i.e. 'filename' = '/file', or 'some_value' = '5'), which contain any possible property of the object, not included in the superclass table. And also made one related table to contain the available 'key' values.</p> <p>But there is a problem with such architecture - the 'value' column should be of a string data type by default, to be able to contain anything. But I don't think converting to and from strings is a good decision. What is the best way to bypass this limitation?</p>
<p>The design you're experimenting with is a variation of <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model" rel="nofollow noreferrer">Entity-Attribute-Value</a>, and it comes with a whole lot of problems and inefficiencies. It's not a good solution for what you're doing, except as a last resort.</p> <p>What could be a better solution is what fallen888 describes: create a "subtype" table for each of your subtypes. This is okay if you have a finite number of subtypes, which sounds like what you have. Then your subtype-specific attributes can have data types, and also a <code>NOT NULL</code> constraint if appropriate, which is impossible if you use the EAV design.</p> <p>One remaining weakness of the subtype-table design is that you can't enforce that a row exists in the subtype table just because the main row in the superclass table says it should. But that's a milder weakness than those introduced by the EAV design. </p> <p><strong>edit:</strong> Regarding your additional information about comments-to-any-entity, yes this is a pretty common pattern. Beware of a broken solution called "polymorphic association" which is a technique many people use in this situation.</p>
<p>The only workaround (while retaining your strucure) is to have separate tables:</p> <pre><code>create table IntProps(...); create table StringProps(...); create table CurrencyProps(...); </code></pre> <p>But I do not think that this is a good idea...</p>
45,718
<p>I would like to convert an array if IDs, into a string of comma separated values, to use in a MySQL UPDATE query. How would I do this?</p>
<p>Remember to escape values:</p> <pre><code>'"' . implode('","', array_map('mysql_real_escape_string', $data)) . '"' </code></pre>
<p>This is probably better if all ids should be numerical. Check that it consists of at least one integer with </p> <pre><code>$ids = array_filter($ids, 'is_int'); if (!$ids) { //no valid ids returned. die('or something'); } $sql .= '(' . implode(',', $ids) . ')'; </code></pre>
38,103
<p>I'm mostly familiar with Java, C and C++ in which there are ways to control that only one thread is accessing a resource at any given time. Now I'm in search for something similar but in PHP 5.x.</p> <p>To formulate my problem with one example:</p> <p>I have an ASCII-file which only stores a number, the value of a page load counter. At application deployment the file will simply hold a 0. For each access the value will be incremented by one. The goal is to keep track of page loads.</p> <p>The problem comes when many users are concurrently accessing the page containing the counter. When thread A has read the current value, let's say it is 11, another thread which we call B reads the value, still 11. Then the first thread A increments the read value and writes 12 in the file and closes it. Then the second thread B, increments the read value, which was 11, gets 12 and writes that into the file. The value 12 is stored in the file, when it really should have been 13.</p> <p>In another programming language I would have solved this using a mutex. I understand there are mutexes, shared memory and other funcionality as part of modules. But I would like a solution which works on "most servers" out there. Platform independent. Installed on most cheap web hosts. Is there a good solution to this problem? And if there isn't, which way would you take if using a <strong>database is not an option</strong>?</p>
<p>You could try php's variant of flock (<a href="http://www.php.net/flock" rel="noreferrer">http://www.php.net/flock</a>)</p> <p>I would envision something similar to (this assumes that the file /tmp/counter.txt already exists and has a counter in the file):</p> <pre><code>&lt;?php $fp = fopen("/tmp/counter.txt", "r+"); echo "Attempt to lock\n"; if (flock($fp, LOCK_EX)) { echo "Locked\n"; // Read current value of the counter and increment $cntr = fread($fp, 80); $cntr = intval($cntr) + 1; // Pause to prove that race condition doesn't exist sleep(5); // Write new value to the file ftruncate($fp, 0); fseek($fp, 0, SEEK_SET); fwrite($fp, $cntr); flock($fp, LOCK_UN); // release the lock fclose($fp); } ?&gt; </code></pre>
<p>PHP's flock() function is the route to go. However, you have to make sure that <em>all</em> accesses to the file are protected by a call to flock() first. PHP won't check if the file is locked unless you explicitly make the call to do so.</p> <p>The concept is virtually identical as with mutexes (protecting shared resources, et al), but it's important enough to bear special emphasis.</p>
22,395
<p>I've got the following two tables (in MySQL):</p> <pre><code>Phone_book +----+------+--------------+ | id | name | phone_number | +----+------+--------------+ | 1 | John | 111111111111 | +----+------+--------------+ | 2 | Jane | 222222222222 | +----+------+--------------+ Call +----+------+--------------+ | id | date | phone_number | +----+------+--------------+ | 1 | 0945 | 111111111111 | +----+------+--------------+ | 2 | 0950 | 222222222222 | +----+------+--------------+ | 3 | 1045 | 333333333333 | +----+------+--------------+ </code></pre> <p>How do I find out which calls were made by people whose <code>phone_number</code> is not in the <code>Phone_book</code>? The desired output would be:</p> <pre><code>Call +----+------+--------------+ | id | date | phone_number | +----+------+--------------+ | 3 | 1045 | 333333333333 | +----+------+--------------+ </code></pre>
<p>There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:</p> <p>This is the shortest statement, and may be quickest if your phone book is very short:</p> <pre><code>SELECT * FROM Call WHERE phone_number NOT IN (SELECT phone_number FROM Phone_book) </code></pre> <p>alternatively (thanks to <a href="https://stackoverflow.com/users/36848/alterlife">Alterlife</a>)</p> <pre><code>SELECT * FROM Call WHERE NOT EXISTS (SELECT * FROM Phone_book WHERE Phone_book.phone_number = Call.phone_number) </code></pre> <p>or (thanks to WOPR)</p> <pre><code>SELECT * FROM Call LEFT OUTER JOIN Phone_Book ON (Call.phone_number = Phone_book.phone_number) WHERE Phone_book.phone_number IS NULL </code></pre> <p>(ignoring that, as others have said, it's normally best to select just the columns you want, not '<code>*</code>')</p>
<pre><code>SELECT name, phone_number FROM Call a WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b) </code></pre>
48,017
<p>Is there a way in SWT to get a monospaced font simply, that works across various operating systems?</p> <p>For example. this works on Linux, but not Windows:</p> <pre> <code> Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE); </code> </pre> <p>or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.</p> <p>I tried getting the system font from Display, but that wasn't monospaced.</p>
<p>According to the section on <a href="http://java.sun.com/javase/6/docs/technotes/guides/intl/fontconfig.html" rel="noreferrer">Font Configuration Files</a> in the JDK documentation of <a href="http://java.sun.com/javase/6/docs/technotes/guides/intl/" rel="noreferrer">Internationalization Support</a>-related APIs, the concept of <strong>Logical Font</strong>s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:</p> <blockquote> <p>The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.</p> </blockquote> <p>So in your case, I'd try</p> <p><code>Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);</code></p> <p>to get a handle to the physical monospaced font of the current platform your code is running on.</p> <p><strong>Edit</strong>: It seems that SWT doesn't know anything about logical fonts (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=48055" rel="noreferrer">Bug 48055</a> on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...</p>
<p>If you want just a Monospaced font use "Courier" => <code>new Font(display, "Courier", 10, SWT.NORMAL)</code></p>
27,315
<p>I created a simple dialog-based application, and in the default CDialog added three buttons (by drag-and-dropping them) using the Visual Studio editor. </p> <p>The default OK and Cancel buttons are there too.</p> <p>I want to set the focus to button 1 when I click button 3.</p> <p>I set the property Flat to true in the properties for muy buttons.</p> <p>I coded this:</p> <pre><code>void CbuttonfocusDlg::OnBnClickedButton3() { // TODO: Add your control notification handler code here GetDlgItem(IDC_BUTTON1)-&gt;SetFocus(); Invalidate(); } </code></pre> <p>But the boder in button1 is never drawn. The caret (the dotted line indicating focus) is only drawn if I pressed TAB any time before clicking button 3. </p> <p>I want the button to look exactly as it looks after I click it. Showing the dotted line inside the button programatically, would be a plus.</p> <p>What I want:</p> <p><a href="https://i.stack.imgur.com/z8l0f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z8l0f.png" alt="http://i33.tinypic.com/11t8pkl.png"></a> </p> <p>What I get: </p> <p><a href="https://i.stack.imgur.com/CgqLi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CgqLi.png" alt="http://i37.tinypic.com/160q5hw.png"></a> </p>
<p>Use <code>WM_NEXTDLGCTL</code>.</p> <p>See <a href="http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx" rel="nofollow noreferrer">Reymond Chen's "How to set focus in a dialog box"</a>:</p> <pre><code>void SetDialogFocus(HWND hdlg, HWND hwndControl) { SendMessage(hdlg, WM_NEXTDLGCTL, (WPARAM)hwndControl, TRUE); } </code></pre>
<p>By calling UpdateWindow, the button is being redrawn before the focus change can take effect. The Invalidate should be sufficient by itself, the window will get repainted when everything settles down.</p>
48,299
<p>I have the handle of process 'A' on a Pocket PC 2003 device. I need to determine if that process is still running from process 'B'. Process 'B' is written in Embedded Visual C++ 4.0.</p>
<p>GetExitCodeProcess will return STILL_ACTIVE if the process was running when the function was called.</p>
<p>Process handles are waitable. They are signalled - will release any waiting thread - when the process exits. You can use them with WaitForSingleObject, WaitForMultipleObjects, etc.</p>
10,212
<p>In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object. Its toString() simply returns [Function] and I can't find any other useful accessors that give me that... Help :-/</p>
<p>I found an answer and I'll paste it below.</p> <p>@fenomas: yes, you are right of course, functions are just objects and what I'm looking for is a the name of the reference to them (if exists, i.e. the function is not anonymous). You also right that in general this doesn't look like the best way to do programming ;-) But my scenario is special: I want to implement a Checks class (similar to C CHECK) with methods such as Check.checkTrue and Checks.checkRef in which when the check fails I get a nice trace. The traces will appear only in debug version, not in release.</p> <p>I'm using MTASC and the code below only works with MTASC. It should also be used only for debugging purposes and not release. The technique is to iterate on _global and find a function that's equal to my calling function. It's a hack that does not always work (anonymous) but it serves me pretty well in most cases.</p> <pre><code>39: /** 40: * Checks that cond is true. Use this method to validate that condition 41: * cond holds. 42: * If cond is false, traces a severe message and returns false to indicate 43: * check failure. 44: * 45: * @param cond the contition expected to be true 46: * @param msg the message to emit in case the condition is false. 47: * 48: * @return false is cond is false 49: */ 50: public static function checkTrue(cond:Boolean, msg:String):Boolean { 51: if (!cond) { 52: trace("severe", "CHECK FAILED at " + 53: **getFunctionName(arguments.caller)** + ":\n" + msg); 54: } 55: return cond; 56: } 94: /** 95: * Gets the name of the function func. 96: * Warning: Use this only in debug version, not in release 98: * 99: * @return The full package path to the function. null if the function 100: * isn't found. 101: */ 102: private static function getFunctionName(func:Function):String { 103: var name:String = getFunctionNameRecursive(func, _global); 108: return name; 109: } 110: 111: /** 112: * Gets the name of the function func by recursively iterating over root. 113: * Warning: Use this only in debug version, not in release 114: */ 115: private static function getFunctionNameRecursive(func:Function, 116: root:Object):String { 117: if (!root) { 118: return null; 119: } 120: 121: // Iterate over classes in this package 122: // A class is a function with a prototype object 123: for (var i:String in root) { 124: if (root[i] instanceof Function &amp;&amp; root[i].prototype != null) { 125: // Found a class. 126: // Iterate over class static members to see if there's a match 127: for (var f:String in root[i]) { 128: if(root[i][f] == func) { 129: return i + "." + f; 130: } 131: } 132: // Loop over the class's prototype to look for instance methods 133: var instance:Object = root[i].prototype; 134: // Reveal prototype's methods. 135: // Warning: Not to be used in production code!!! 136: // The following line make all the instance attributes visible to the 137: // for-in construct. The "n" value is 8 which means "unhide" 138: // See http://osflash.org/flashcoders/undocumented/assetpropflags 139: // This operation is later undone by setting the "n" to 1 which means 140: // "hide" 141: _global.ASSetPropFlags(instance, null, 8, 1); 142: for (var f:String in instance) { 143: if(instance[f] == func) { 144: return i + "." + f; 145: } 146: } 147: // And hide instance methods again 148: // This line undoes the previous ASSetPropFlags 149: _global.ASSetPropFlags(instance, null, 1, false); 150: } 151: } 152: 153: // Iterate over sub packages. Sub packages have type "object" 154: for (var i:String in root) { 155: if (typeof(root[i]) == "object") { 156: var name:String = getFunctionNameRecursive(func, root[i]); 157: if (name) { 158: return i + "." + name; 159: } 160: } 161: } 162: return null; 163: } </code></pre>
<p>As far as I know, not in AS2 AS3 only.</p>
32,840
<p>I have an application that seems to throw exceptions only after the program has been closed. And it is very inconsistent. (We all know how fun inconsistent bugs are...)</p> <p>My guess is there is an error during the clean up process. But these memory read/write errors seem to indicate something wrong in my "unsafe" code usage (pointers?).</p> <p>What I am interested in is what is the best method to debug these situations?<br> How do you debug a program that has already closed?<br> I am looking for a starting point to break down a larger problem.</p> <p>These errors seem to present themselves in several ways (some run time, some debug):</p> <pre> 1: .NET-BroadcastEventWindow.2.0.0.0.378734a.0: Application.exe - Application Error<BR> The instruction at "0x03b4eddb" referenced memory at "0x00000004". The memory could not be "written". 2: Application.vshost.exe - Application Error<br> The instruction at "0x0450eddb" referenced memory at "0x00000004". The memory could not be "written". 3: Application.vshost.exe - Application Error<br> The instruction at "0x7c911669" referenced memory at "0x00000000". The memory could not be "read". 4: Application.vshost.exe - Application Error<br> The instruction at "0x7c910ed4" referenced memory at "0xfffffff8". The memory could not be "read". </pre>
<p>If your app is multi-threaded you could be getting errors from worker threads which aren't properly terminating and trying to access disposed objects.</p>
<p>try this to force the bug to happen while under program control</p> <pre><code> //set as many statics as you can to null; GC.Collect(); GC.WaitForPendingFinalizers(); } //exit main </code></pre>
22,071
<p>So, when playing with the development I can just set <code>settings.DEBUG</code> to <code>True</code> and if an error occures I can see it nicely formatted, with good stack trace and request information.</p> <p>But on kind of production site I'd rather use <code>DEBUG=False</code> and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)<br> At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.</p> <p>What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as <code>fcgi</code> server and I'm using apache web server as frontend (although thinking of going to lighttpd).</p>
<p>Well, when <code>DEBUG = False</code>, Django will automatically mail a full traceback of any error to each person listed in the <code>ADMINS</code> setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named <code>process_exception()</code>, which will have access to the exception that was raised:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception" rel="noreferrer">http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception</a></p> <p>Your <code>process_exception()</code> method can then perform whatever type of logging you'd like: writing to console, writing to a file, etc., etc.</p> <p>Edit: though it's a bit less useful, you can also listen for the <code>got_request_exception</code> signal, which will be sent whenever an exception is encountered during request processing:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception</a></p> <p>This does <em>not</em> give you access to the exception object, however, so the middleware method is much easier to work with.</p>
<p>You can use the logging library in Python, no need to <code>pip install</code> anything.</p> <p>Replace any <code>print()</code> with <code>logging.debug()</code> but,</p> <blockquote> <p>Django Sentry is a good way to go</p> </blockquote> <p>as EMP said.</p>
29,452
<p>I was wondering if InnoDB would be the best way to format the table? The table contains one field, primary key, and the table will get 816k rows a day (est.). This will get very large very quick! I'm working on a file storage way (would this be faster)? The table is going to store ID numbers of Twitter Ids that have already been processed?</p> <p>Also, any estimated memory usage on a <code>SELECT min('id')</code> statement? Any other ideas are greatly appreciated!</p>
<p>I'd recommend you start <a href="http://dev.mysql.com/doc/refman/5.1/en/partitioning.html" rel="nofollow noreferrer">partioning</a> your table by ID or date. Partioning splits a large table into several smaller table according to some defined logic (like splitting it by date ranges), which makes them much more managable performance and memory wise. MySQL 5.1 has this feature built-in, or you can implement it using custom solutions. </p> <p>In implement storage in a flat-file, you lose all the advantages of a database - you can no longer perform queries involving the data. </p>
<p>If you have an index on your id column, select min(id) should be O(1), there shouldn't be much of a memory requirement for this.</p> <p>If your primary key is on the twitter id then you have an index on it.</p>
47,704
<pre><code>public static void main(String[] args) { List&lt;? extends Object&gt; mylist = new ArrayList&lt;Object&gt;(); mylist.add("Java"); // compile error } </code></pre> <p>The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing. In this case what purpose does the above fulfil ??</p>
<p>Let's say you have an interface and two classes:</p> <pre><code>interface IResult {} class AResult implements IResult {} class BResult implements IResult {} </code></pre> <p>Then you have classes that return a list as a result:</p> <pre><code>interface ITest&lt;T extends IResult&gt; { List&lt;T&gt; getResult(); } class ATest implements ITest&lt;AResult&gt; { // look, overridden! List&lt;AResult&gt; getResult(); } class BTest implements ITest&lt;BResult&gt; { // overridden again! List&lt;BResult&gt; getResult(); } </code></pre> <p>It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List&lt;AResult&gt; (returned as List&lt;? extends T&gt;), which doesn't make any sense.</p> <p>So you have to remember this: List&lt;? extends X&gt; defines a list that could be easily overridden, but which is read-only.</p>
<p>This works:</p> <pre><code>List&lt;? super Object&gt; mylist = new ArrayList&lt;Object&gt;(); mylist.add("Java"); // no compile error </code></pre> <p>From O'Reilly's <a href="http://oreilly.com/catalog/9780596527754/" rel="nofollow noreferrer">Java Generics</a>:</p> <blockquote> <p>The Get and Put Principle: use an extends wildcard when you only get values our of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard you both get and put.</p> </blockquote>
9,506
<p>I didn't see the option to point the workspace (or it's VS equivalent, I'm still learning the terminology for Visual Studio, but it is called a workspace in Eclipse) to My Documents/Programming instead of -- well -- wherever it is now.</p>
<p>What Craig said, plus if you do want to change the default it's in Tools -> Options -> Projects And Solutions.</p> <p>I've never changed the default and never created a solution/project in the default location, which might tell you something about how relevant it is...</p>
<p>When you create the project you can specify whatever directory you want, you are not limited to the default.</p>
5,592
<p>Wondering if anyone knows how to see what parts of the .NET framework need to be installed to get cerftain functions working on older machines. Is there a way I can install them with my application without installing the entire .NET framework?</p>
<p>You could use <a href="http://mono-project.com" rel="nofollow noreferrer">Mono</a>, the open source implementation of the .NET framework. The Mono installer is smaller than the .NET installer. Also, Mono works with Windows versions older than XP. </p> <p>With Mono you can use the <a href="http://www.mono-project.com/Linker" rel="nofollow noreferrer">Linker</a> to bundle only a small subset of the .NET framework, the one you need, with your application.</p> <p>The downside is that Mono doesn't implement the entire .NET framework, at the moment is only compatible with the version 2.0 and parts of the 3.0. Anyway, there is a tool called <a href="http://www.mono-project.com/MoMA" rel="nofollow noreferrer">MoMa</a> which tell you how compatible with Mono is your application.</p>
<p>As far as I know this is not possible, you must have the .NET framework runtimes fully installed for them to work. Trying to piece it together just doesn't sound like a good idea at all anyway, in my opinion.</p>
43,507
<p>Where should I start learning about version control systems? I've used SVN, Team Foundation, and Sourcesafe in the past but I don't really feel like I grasp it completely, and my team doesn't seem to grasp it either.</p> <p>Which points are the most important to master? I realise this differs from VCS to VCS, but for the sake of this question we can assume that Subversion is the VCS I'm the most interested in learning about.</p> <p>Also, if you could, please recommend any books on the subject that you find useful.</p>
<p>The wikipedia article on Revision Control is a great place to start </p> <p><a href="http://en.wikipedia.org/wiki/Revision_control" rel="nofollow noreferrer">Revision control</a></p> <p>When trying to teach my colleagues, I found getting him to understand the vocabulary at the end was a great way to start to introduce him to source code control techniques.</p> <p>Don't know what a branch is? Go find out and how they work :)</p> <p>There's a free online subversion book at <a href="http://svnbook.red-bean.com" rel="nofollow noreferrer">Version Control with Subversion</a> which provides an invaluable reference.</p>
<p><a href="http://ericsink.com/vcbe/" rel="nofollow">Version control by example by Eric Sink</a> is good and easy to follow</p>
3,024
<p>Greetings – To automate testing of our database SPROCs, we’ve been using dynamically created databases inside of a User Instance. This has been working very well – the build server and, until very recently, all the developers could all run the tests. However, one of our developer machines is now returning the following error when we try to connect to the user instance:</p> <blockquote> <p>Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.</p> </blockquote> <p>Here is what the log file says:</p> <blockquote> <p>2008-12-04 10:46:29.77 Logon<br> Error: 15372, Severity: 16, State: 1. 2008-12-04 10:46:29.77 Logon<br> Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed. [CLIENT: ]</p> </blockquote> <p><strong>What I’ve done to fix it so far</strong></p> <ul> <li>Deleted C:\Documents and Settings[username]\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data</li> <li>Changed SQL Service to run as “Local System” instead of “Network Service”</li> <li>Uninstalled SQL Express, deleted ALL data directories (e.g. “MSSQL.1”), and reinstalled SQL Express</li> </ul> <p>None of these “fixes” have fixed the problem. It used to work on the machine in question, and we would like not to have to repave it.</p> <p>Please help!!!</p> <p>Thanks - Jordan</p>
<p>Okay, I tried all of the above fixes again, and then I restarted the entire system and it appears to work. Strange! I had restarted my system in the past, but it looks like you have to apply these fixes first and then restart. I think I'll try switching the service back to logging in as Network Service.</p> <p>Thanks - Jordan</p>
<p>I found the same issue on my azure VM. Then I opened the SQL Server Configuration Manager, opened SQL Server Network Configuration, -Protocols for and found that "Named Pipes" and "TCP/IP" were disabled. I enabled them, and the error went away.</p>
44,360
<p>I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:</p> <pre><code>F:\Cygnus&gt;sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <hr> <p>a test</p> <p>(1 rows affected)</p> <pre><code>F:\Cygnus&gt; </code></pre> <p>====================================================</p> <p>From Cygwin:</p> <pre><code>$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <blockquote> <p>HResult 0x35, Level 16, State 1<br> Named Pipes Provider: Could not open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired.</p> </blockquote>
<p>The backslash is being eaten by cygwin's bash shell. Try doubling it:</p> <pre><code>sqlcmd -Q "select 'a test'" -S .\\SQLEXPRESS </code></pre>
<p>You may have to allow remote connections for this, and give the full server name i.e SERVER\SQLEXPRESS</p>
13,771
<p>When running a vim instance in gnu screen hitting shift enter in insert mode adds an 'M' and then a newline, rather than just a newline.</p> <p>Does anybody know what the problem might be, or where to look?</p> <p>Relevant system info:</p> <blockquote> <p>Ubuntu 8.04.1</p> <p>Screen version 4.00.03 (FAU) 23-Oct-06</p> <p>VIM - Vi IMproved 7.1 (2007 May 12, compiled Jan 31 2008 12:20:21) Included patches: 1-138</p> <p>Konsole 1.6.6 (Using KDE 3.5.10)</p> </blockquote> <p>Thanks to the comments. When checking the value of <code>$TERM</code> I noticed that it was <code>xterm</code> (as expected), but within screen <code>$TERM</code> was set to <code>screen-bce</code>. Setting <code>TERM=xterm</code> after launching screen resolves this issue.</p> <p>Adding the following to <code>~/.screenrc</code> solved the problem without having to do anything manually:</p> <blockquote> <p>term xterm</p> </blockquote>
<p>Missing info from your question:</p> <ol> <li>Where do you run screen and see this issue? Some terminal app (KTerminal, Gnome terminal, virtual console etc) or remote session (eg putty, ssh from another computer)</li> <li>do a “echo $TERM” and tell us its output</li> <li>do a “cat -v”, press Shift-Enter, then Enter, then <kbd>Ctrl</kbd>-<kbd>D</kbd> and then tell us what is output.</li> </ol>
<p>First, you could fix your $TERM for within konsole. Install "ncurses-term" and configure konsole to set $TERM=konsole-256color. Then configure screen with "term screen-256color". Or 'konsole' and 'screen', respectively, if that's your preference. Konsole and screen are <em>not</em> xterm and doesn't support everything xterm does, so using incorrect $TERM can lead to bad things.</p>
8,884
<p>I have a table of music albums. I have a second table of album art. Unfortunately, not every album has some album art data. As such, i will need to do an OUTER JOIN between music and album art.</p> <p>Assumption: both tables just contain ints and varchars .. no blobs, etc.</p> <p><em>Question</em></p> <ul> <li>Is it better to merge both tables into one to reduce the outer join requirement?</li> </ul>
<p>The only reason I can see to keep them in separate tables is if one album can contain multiple pieces of artwork. If each table only contains, and will only ever contain, 1 piece of artwork, then sticking them in the same table should be fine. If you are joining these two tables in a lot of different instances, you may want to create a view in order to simplify your SQL statements.</p>
<p>Just use one table, with nulls for albums with no art. I don't see any advantage to having a second table...unless you have a lot of albums that share the same art.</p>
41,333
<p>I'm creating a bunch of migrations, some of which are standard "create table" or "modify table" migrations, and some of which modify data. I'm using my actual ActiveRecord models to modify the data, a la:</p> <pre><code>Blog.all.each do |blog| update_some_blog_attributes_to_match_new_schema end </code></pre> <p>The problem is that if I load the Blog class, then modify the table, then use the Blog class again, the models have the old table definitions, and cannot save to the new table. Is there a way to reload the classes and their attribute definitions so I can reuse them?</p>
<p>The answer is yes!</p> <pre><code>Blog.reset_column_information </code></pre>
<p>Create new instances:</p> <hr> <pre><code>Old_blogs = Blog.all </code></pre> <blockquote> <p># change/modify db table in here</p> </blockquote> <pre><code>New_blogs = Blog.all # this should be reloaded or you could use the .reload on this </code></pre> <blockquote> <p># change information, load old into new</p> </blockquote> <h1>ex.</h1> <pre><code>Old_blogs.each do |blog| New_blogs.find(blog.id).title = blog.title end </code></pre>
24,508
<p>The following code</p> <pre><code>public class GenericsTest2 { public static void main(String[] args) throws Exception { Integer i = readObject(args[0]); System.out.println(i); } public static &lt;T&gt; T readObject(String file) throws Exception { return readObject(new ObjectInputStream(new FileInputStream(file))); // closing the stream in finally removed to get a small example } @SuppressWarnings("unchecked") public static &lt;T&gt; T readObject(ObjectInputStream stream) throws Exception { return (T)stream.readObject(); } } </code></pre> <p>compiles in eclipse, but not with javac (type parameters of T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object). </p> <p>When I change readObject(String file) to </p> <pre><code> @SuppressWarnings("unchecked") public static &lt;T&gt; T readObject(String file) throws Exception { return (T)readObject(new ObjectInputStream(new FileInputStream(file))); } </code></pre> <p>it compiles in eclipse and with javac. Who is correct, the eclipse compiler or javac?</p>
<p>I'd say it's the bug in the Sun compiler reported <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954" rel="noreferrer">here</a> and <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379" rel="noreferrer">here</a>, because if you change your line to the one below it works with both, which seems to be exactly what is described in the bug reports.</p> <pre><code>return GenericsTest2.&lt;T&gt;readObject(new ObjectInputStream(new FileInputStream(file))); </code></pre>
<p>If you can modify your method readObject to work transparently when called, you may also use following:</p> <pre><code>public static &lt;T&gt; T readObject(String file, Class&lt;T&gt; type) throws Exception { return type.cast(readObject(new ObjectInputStream(new FileInputStream(file)))); } </code></pre> <p>This way, caller is forced to specify the type of the result and compiler knows how to cast the result.</p>
40,593
<p>I have a many-to-one relationship where the child table can have hundreds of thousands of records. In this case, calling Parent.ChildCollection.Count forces a lazy initialization of the child collection which is extremely expensive.</p> <p>In Hibernate 3.0 there is a feature lazy="extra" which allows you to check a subset of collection properties without lazy loading the whole thing.</p> <p>Unfortunately this will not be available until NHibernate 2.1, which is still in Alpha. <a href="http://jira.nhibernate.org/browse/NH-855" rel="noreferrer">http://jira.nhibernate.org/browse/NH-855</a></p> <p>How can I accomplish this with NHibernate 2.0.1?</p> <p>I used to have special properties such as this</p> <pre><code>&lt;property name="ChildCollectionCount" type="int" formula="(select count(*) from ChildTable child where child.parentID = parentID "/&gt; </code></pre> <p>but I can't use these anymore because I am now sharing this library and its a performance problem for other users.</p>
<p>Depends on your network configuration of vmware product you are using (player, server, workstation). If it is set for a bridged mode, then you can do it as any other machine - by host machine's IP. If it is a "host only" or NAT mode - check what is the gateway IP for the guest (/sbin/route), and try using it:</p> <pre><code># /sbin/route Destination Gateway Genmask Flags Metric Ref Use Iface default 10.x.y.z 0.0.0.0 UG 0 0 0 eth0 </code></pre> <p>In this case, 10.x.y.z is the ip of the host machine.</p>
<p>Depends on your network configuration of vmware product you are using (player, server, workstation). If it is set for a bridged mode, then you can do it as any other machine - by host machine's IP. If it is a "host only" or NAT mode - check what is the gateway IP for the guest (/sbin/route), and try using it:</p> <pre><code># /sbin/route Destination Gateway Genmask Flags Metric Ref Use Iface default 10.x.y.z 0.0.0.0 UG 0 0 0 eth0 </code></pre> <p>In this case, 10.x.y.z is the ip of the host machine.</p>
43,532