instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm embedding the Google Maps Flash API in Flex and it runs fine locally with the watermark on it, etc. When I upload it to the server (flex.mydomain.com) I get a sandbox security error listed below: </p> <pre><code>SecurityError: Error #2121: Security sandbox violation: Loader.content: http://mydomain.com/main.swf?Fri, 12 Sep 2008 21:46:03 UTC cannot access http://maps.googleapis.com/maps/lib/map_1_6.swf. This may be worked around by calling Security.allowDomain. at flash.display::Loader/get content() at com.google.maps::ClientBootstrap/createFactory() at com.google.maps::ClientBootstrap/executeNextFrameCalls() </code></pre> <p>Does anyone have any experience with embedding the Google Maps Flash API into Flex components and specifically settings security settings to make this work? I did get a new API key that is registered to my domain and am using that when it's published.</p> <p>I've tried doing the following in the main application as well as the component:</p> <pre><code>Security.allowDomain('*') Security.allowDomain('maps.googleapis.com') Security.allowDomain('mydomain.com') </code></pre>
<p>This sounds like a <code>crossdomain.xml</code> related problem. I did a quick search and there seems to be many people with the same issue. Some proxy requests through XMLHttpRequest etc..</p> <p><a href="http://code.google.com/p/gdata-issues/issues/detail?id=406" rel="nofollow noreferrer">Issue 406: Add crossdomain.xml for Google Accounts</a></p>
<p>Thanks for the help. Apparently this has something to do with including the Flex app on an ASP.NET page. When I moved it over to a flat HTML file, it worked fine. I don't have time to fully investigate right now, but that seems to have fixed it.</p>
8,485
<p>I'm trying to write a log file from an ASP.NET application under IIS7, but keep getting the following exception:</p> <blockquote> <p>UnauthorizedAccessException "Access to the path 'C:\Users\Brady\Exports' is denied."</p> </blockquote> <p>I have given write access to the iis_iusrs, iis_wpg, and aspnet users, based on various advices found by Google, but still get the error. Can someone please explain how I can create a log file in that directory, or, will creating a log directory under the web application itself automatically allow writing the file, and is this not perhaps a better solution?</p>
<p>You need to grant permission to one of the following accounts</p> <pre><code>ASPNET - Win XP and Win 2000 NETWORK SERVICE - Win Vista and 2003 </code></pre> <p>These are the defaults, if the application pool has been configured for a different process account then you would need to work with that specific account.</p>
<p>I think Mitchel's got it, but I'll add that troubleshooting these kinds of things is infinitely easier using SysInternals' <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">Process Monitor</a> (<a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">FileMon</a> for legacy systems) to take away the guesswork/trial and error.</p>
22,796
<p>At work we use Sandcastle for creation of help files. I have been using SandCastleGUI for some time and I'm looking for a way to create additional pages in the help file. These pages are written in XML format called MAML. The only problem is that I couldn't find any decent editor for these file format.</p> <p>I'm looking for a WYSIWYG editor to create &amp; edit additional documentation pages.</p>
<p>Finally I found a solution the good people of <a href="http://shfb.codeplex.com/" rel="nofollow">SandCastle Help File Builder</a> have included an HTML to MAML converter.<br> There are many good HTML editorsout there - and now I can use one of them and then convert the result to MAML</p>
<p>Don't know if you are still looking for a solution to this, but I've been looking at help editors and ran across a codeproject article that might be useful. The article can be found at <a href="http://www.codeproject.com/KB/dotnet/DocMounter_2_Sandcastle.aspx" rel="nofollow">http://www.codeproject.com/KB/dotnet/DocMounter_2_Sandcastle.aspx</a>. It features an editor that might be just what you need.</p>
13,379
<p>I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.</p> <p>Is there a simple way to do this without re-writing the function myself? I searched around for a simple library, but couldn't find anything. Surely this is a common problem.</p>
<p>A simpler approach is to replace everything which is not a character or a number with an underscore.</p> <p>EDIT: Here's a naive implementation in C:</p> <pre><code>#include &lt;cctype&gt; char *safe_url(const char *str) { char *safe = strdup(str); for (int i = 0; i &lt; strlen(str); i++) { if (isalpha(str[i])) safe[i] = str[i]; else safe[i] = '_'; } } </code></pre>
<p>What about <a href="http://www.boost.org/doc/libs/1_37_0/doc/html/hash.html" rel="nofollow noreferrer"><code>boost::hash</code></a>?</p>
32,526
<p>I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.</p>
<p>Try this function</p> <pre><code>CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float) RETURNS datetime AS BEGIN DECLARE @RoundedTime smalldatetime DECLARE @Multiplier float SET @Multiplier= 24.0/@RoundTo SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier RETURN @RoundedTime END select dbo.roundtime('13:15',0.5) </code></pre> <p>The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)</p>
<p>Very nice thanks. I used it in-line to round to 15 minutes</p> <pre><code>convert(smalldatetime,ROUND(cast(TDatalog.Time as float) * (24/.25),0)/(24/.25)) AS RoundedTime </code></pre>
31,068
<p>I want my validation.xml to only check for a null if certain options are selected from a dropdown. So far I have</p> <pre><code>&lt;field property="empFDServiceStartDate" depends="requiredif, date"&gt; &lt;arg0 key="Service Start date" resource="false"/&gt; &lt;var&gt; &lt;var-name&gt;field[0]&lt;/var-name&gt; &lt;var-value&gt;moverChangeType&lt;/var-value&gt; &lt;/var&gt; &lt;var&gt; &lt;var-name&gt;fieldTest[0]&lt;/var-name&gt; &lt;var-value&gt;EQUALS&lt;/var-value&gt; &lt;/var&gt; &lt;var&gt; &lt;var-name&gt;fieldValue[0]&lt;/var-name&gt; &lt;var-value&gt;Conversion&lt;/var-value&gt; &lt;/var&gt; &lt;/field&gt; </code></pre> <p>When the value "Conversion" is selected from the moverChangeType dropdown, I was hoping that the empFDServiceStartDate field would be checked for nulls before being saved. At the moment this doesn't work and it allows me to save nulls.</p> <p>Any idea?</p> <p>I am tied to struts 1.1 and therefore can't use newer commands.</p> <p>M</p>
<p>You can do this multiple test in the same test, like this:</p> <pre><code>&lt;field property="empFDServiceStartDate" depends="requiredif, date"&gt; &lt;arg0 key="Service Start date" resource="false"/&gt; &lt;var&gt; &lt;var-name&gt;test&lt;/var-name&gt; &lt;var-value&gt;((moverChangeType == "Conversion") or (moverChangeType == "SomethingElse"))&lt;/var-value&gt; &lt;/var&gt; &lt;/field&gt; </code></pre>
<p>If you want to check the field if moverChangeType equals "Conversion" try this...</p> <pre><code>&lt;field property="empFDServiceStartDate" depends="requiredif, date"&gt; &lt;arg0 key="Service Start date" resource="false"/&gt; &lt;var&gt; &lt;var-name&gt;test&lt;/var-name&gt; &lt;var-value&gt;(moverChangeType == "Conversion")&lt;/var-value&gt; &lt;/var&gt; &lt;/field&gt; </code></pre>
34,289
<p>Have you used the Perl 5.10 backtracking control verbs in your regexes yet? And what problems did they help you accomplish? </p> <hr> <p>Just as background: I have done some fiddling, but I can't get any really useful results.</p> <p>As a comparison, when I started getting what the <code>(?&gt;</code> grouping did, it started showing up more in my regexes. I liked the idea of tuning the world of Perl regex to a particular set of assumptions. As RE languages get more featured, the backtracking has made the performance of REs wildly divergent from the lean and mean FSA that they were based upon. </p> <hr> <p>When someone can tell me what <em>other</em> implementation of REs has backtracking control verbs--and PCRE <em>does not</em>, I can concede that it belongs in the general area of expertise of people knowledgeable about regexes. This is a <em>Perl</em> regex question, and guys helping people out with Ruby, Python, C#, Javascript--or any PCRE client implementations-- probably can't help or see it as a waste of space for the tags they normally read.</p>
<p>Yes, I have, although not too much. I use them to control backtracking, usually to force it to make more permutations. Here’s an <a href="https://stackoverflow.com/questions/4092348/how-to-generate-an-array-with-random-values-without-using-a-loop/4092746#4092746">amusing solution</a> and here’s a <a href="https://stackoverflow.com/questions/4168670/regex-that-matches-xabc-but-not-x-alone/4169358#4169358">practical one</a>.</p>
<p>Honestly, I haven't even used 5.10 much yet. As great as some of the new features are I only use them in personal scripts. For production I target compatibility with 5.8. For CPAN I target 5.6. This has stopped me from playing with most of the new toys.</p> <p>The backtracking control features are interesting but I can't see many applications outside of parsers. I can't imagine stuffing an entire parser into a single regex. (Even if they do support recursion now!) I'm much more excited about Perl6 grammars.</p>
31,637
<p>From what I understand, the crystals on PC's are notorious for clock skew. If clocks are always skewing, what is the best way to synchronize clocks between machines with millisecond accuracy and precision? From what I've found, NTP and PTP are possible solutions, but I was wondering if anybody had any experience on stackoverflow.com!</p> <p>I understand NTP is the popular choice, but am wondering if anybody has had any experience with PTP (IEEE1588)</p>
<p>Just run the standard NTP daemon.</p> <p>It does have options to take input from several GPS devices as well as talking to network servers.</p> <p>Edit: I was referring to <a href="http://www.ntp.org/" rel="noreferrer">http://www.ntp.org/</a>, not the one that comes with Windows.</p> <p>I don't have any suggestion as to what NTP clients are best for windows, but for Unix machines there's no real reason to not run NTP.</p>
<p>NTP is definitely the way to go. Basically fire-and-forget, as long as you let it out the firewall on your local master (which is typically the firewall or router machine.)</p>
12,332
<p>I have a library A, that I develop. When I deploy it on a machine, the corresponding <em>libA.so</em> and <em>libA-X.Y.Z.so</em> are put in /usr/lib (X.Y.Z being the version number). </p> <p>Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "<em>ldd libB.so</em>" gives me : </p> <pre><code>(...) libA-X.Y.Z.so =&gt; /usr/lib/libA-X.Y.Z.so (...) </code></pre> <p>My problem is that when I release a new version of A (X.Y.ZZ), I also have to release a new version of B. Otherwise, someone installing the latest A won't be able to install B which will be looking for the version X.Y.Z which doesn't exist.</p> <p>How do I solve this problem ? How can I tell B to look for libA.so and not libA-X.Y.Z.so ? Or is it wrong to do so ? even unsafe ? </p> <p><strong>Update 1</strong> : library A (that I inherited from someone else) uses autotools. </p> <p><strong>Update 2</strong> : when I build library A, I can see : <em>"-Wl,-soname -Wl,libA-0.6.1.so"</em>. If I understand properly that means that we are forcing the soname to be <em>libA-0.6.1.so</em>. Is that right ? Now my problem is that I have no clue how to modify this behaviour in a project which uses autotools. I googled for a while but can't find any useful information. Should I modify configure.in or a Makefile.am ? </p>
<p>When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See</p> <p><a href="http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html" rel="noreferrer">http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html</a></p>
<p>This also works in Windows as "DLL hell" :).</p> <p>If B needs a specific version of A and you would link to libA not libA-X.Y.Z then only substituting libA with newer version might cause B not to load or crash.</p> <p>But of course you can do a symlink from libA-X.Y.Z to libA-X1.Y1.Z1. If no APIs changed and only implementations than you should be safe.</p>
31,499
<p>I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event. </p> <p>I created a vector so that multiple listeners can be attached to this event, i.e.:</p> <pre><code>vector&lt; function&lt;void (int)&gt; &gt; listenerList; </code></pre> <p>I'd like to be able to remove a handler from the list to stop a listener receiving events.</p> <p>So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function?</p> <p>Thanks!</p> <p>EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/signals/tutorial.html" rel="nofollow noreferrer">Here's some info on this</a>. An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :) </p>
<p>I don't know if you're locked into std C++ and tr1, but if you aren't, it seems like your problem could be completely avoided if you just used something like boost::signal and boost::bind to solve your original problem - creating an event system - instead of trying to roll your own.</p>
<p>If you are storing function pointers only (and not other functors that match the signature required), this is easy (see code below). But in general, the answer, like other posters have said, is no. In that case, you probably want to store your functors in a hash, as values, with keys being something the user supplies on adding and removing.</p> <p>The code below demonstrates how to get the functor/pointer object that is to be called. To use it, you must know the exact type of the object to extract (i.e., the <code>typeid</code> of the type you specify must match the <code>typeid</code> of the contained functor/pointer).</p> <pre><code>#include &lt;cstdio&gt; #include &lt;functional&gt; using std::printf; using std::tr1::function; int main(int, char**); static function&lt;int (int, char**)&gt; main_func(&amp;main); int main(int argc, char** argv) { printf("%p == %p\n", *main_func.target&lt;int (*)(int, char**)&gt;(), &amp;main); return 0; } </code></pre>
11,500
<p>I am getting a web host and i have projects with teammats. I thought it be a nice idea to have my own paste site that has no expiry date on paste (i know <a href="http://pastie.org/" rel="nofollow noreferrer">http://pastie.org/</a> exist) and other things. i wanted to know. Whats a simple highlight lib i can use on code? i would be only using C/C++.</p>
<p>The question is tagged "php" but you "would be only using C/C++"?</p> <p>A PHP solution is <a href="http://qbnz.com/highlighter/" rel="nofollow noreferrer">GeSHi</a>.</p>
<p>Building a highlighter for only one language (context free, with regular lexemes such as C++) is actually pretty easy because you basically can wrap all your lexemes into one big regular expression:</p> <pre><code>$cpplex = '/ (?&lt;string&gt;"(?:\\\\"|.)*?")| (?&lt;char&gt;\'(?:\\\\\'|.)*?\')| (?&lt;comment&gt;\\/\\/.*?\n|\\/\*.*?\*\\/)| (?&lt;preprocessor&gt;#\w+(?:\\\\\n|[^\\\\])*?\n)| # This one is not perfect! (?&lt;number&gt; (?: # Integer followed by optional fractional part. (?:0(?: x[0-9a-f]+|[0-7]*)|\d+) (?:\.\d*)?(?:e[+-]\d+)?) |(?: # Just the fractional part. (?:\.\d*)(?:e[+-]\d+)?))| (?&lt;keyword&gt;asm|auto|break|case…)| # TODO Complete. Include ciso646! (?&lt;identifier&gt;\\w(?:\\w|\\d)*) /xs'; $matches = preg_match_all($cpplex, $input, $matches, PREG_OFFSET_CAPTURE); foreach ($matches as $match) { // TODO: determine which group was matched. // Don't forget lexemes that are *not* part of the expression: // i.e. whitespaces and operators. These are between the matches. echo "&lt;span class=\"$keyword\"&gt;$token&lt;/span&gt;"; } </code></pre>
38,636
<p>I'd like to yank a line in a register: <code>"{register}y</code> but without overwriting what was previously in the register. I often need to copy non-contiguous lines in a register, and I'd like to use sometimes the registers like a stack.</p> <p>Example:</p> <pre><code>line1 line2 line3 </code></pre> <p>I want to copy <code>line1</code>, by putting the cursor on it and entering <code>"ay</code>, then going on <code>line3</code> and do <code>"ay</code>. Then, when I will do <code>"ap</code>, BOTH <code>line1</code> AND <code>line3</code> will be pasted.</p> <p>Is this possible without plugins ? with plugins?</p>
<p>If you want to append to a named register use it's corresponding upper case character. i.e. In your example:</p> <pre> "ayy "Ayy "ap </pre>
<p>Just to expand on MarkB's response, did you know you can also use markers to select a block of text for your yank?</p> <p>Go to the first line of the block you want to yank and enter the mark command after selecting a letter as the marker, e.g.</p> <pre><code>ma (entered in command mode, i.e. no colon) </code></pre> <p>then go to the bottom of the block you want to yank and enter the command:</p> <pre><code>:'a,.ya A </code></pre> <p>this command means take the block of text from the line containing my marker called a up to the current line and yank it into buffer a. Same rules as MarkB mentioned apply, use lowercase buffer name to overwrite the buffer. Use uppercase buffer name to append to the buffer. So in this case this will append to the contents of buffer a.</p> <p>N.B. The 'a' used for your marker has nothing to do with the 'a' used to select your register. (AFAIK but YMMV)</p> <p>BTW 'a (apostrophe a) refers to the line containing the marker a. `a (backquote a) refers to the character under the cursor when you entered ma.</p> <pre><code>d`a (also entered in command mode) </code></pre> <p>is useful because it will delete the text between the character marked with marker a up to the character <strong>just before</strong> the character where you cursor is currently located.</p>
49,844
<p>Plone is very complex. <a href="http://en.wikipedia.org/wiki/Zope" rel="nofollow noreferrer">Zope</a>2, <a href="http://en.wikipedia.org/wiki/Zope_3" rel="nofollow noreferrer">Zope3</a>, <a href="http://codespeak.net/z3/five/" rel="nofollow noreferrer">Five</a>, <a href="http://wiki.zope.org/zope3/ZCML" rel="nofollow noreferrer">ZCML</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database" rel="nofollow noreferrer">ZODB</a>, <a href="http://en.wikipedia.org/wiki/Zope_Object_Database#ZEO" rel="nofollow noreferrer">ZEO</a>, a whole bunch of acronyms and abbreviations.</p> <p>It's hard to begin and the current state seems to be undecided. It is mainly based on Zope2, but incorporates Zope3 via Five. And there are XML config files everywhere.</p> <p>Does the steep learning curve pay of? Is this complexity still justified today?</p> <p>Background: I need a platform. Customers often need a CMS. I'm currently reading "<a href="http://plone.org/news/book-professional-plone-development-now-shipping" rel="nofollow noreferrer">Professional Plone Development</a>", without prior knowledge of Plone.</p> <p>The problem: Customers don't always want the same and you can't know beforehand. One thing is sure: They don't want the default theme of Plone. But any additional feature is a risk. You can't just start and say "<a href="https://stackoverflow.com/questions/348044/what-could-justify-the-complexity-of-plone/351692#351692">If you want to see the complexity of Plone, you have to ask for it.</a>" when you don't know the system good enough to plan.</p>
<p>If you want to see the complexity of Plone, you have to ask for it. For most people, it's just not there. It installs in a couple of minutes through a one-click installer. Then it's one click to log in, one click to create a page, use a WYSYWIG editor, and one click to save. Everything is through an intuitive web GUI. Plone is a product.</p> <p>If you want to use it as a "platform," then the platform is a stack of over one million lines of code which implements a complete content management suite. No one knows it all. However, all those "acronyms" and "files" are evidence of a software which is factored in components so that no one need know it all. You can get as deep or shallow in it as you need. If there's something you need for some aspect of content management, it's already there, you don't have to create it from scratch, and you can do it in a way that's consistent with a wide practice and review.</p>
<p>Accretion.</p>
45,290
<p>We are planning to use the jQuery library to augment our client side JavaScript needs. </p> <p>Are there any major issues in trying to use both ASP.Net AJAX and jQuery? Both libraries seem to use $ for special purposes. Are there any conflicts that we need to be aware of? </p> <p>We also use Telerik controls that use ASP.Net AJAX.</p> <p>TIA</p>
<p>We have used ASP.NET Ajax, jQuery and Telerik components on a large project for quite a while and haven't had any issues</p> <p>I would definitely recommend using jQuery</p>
<p>I have been using ext which is another javascript framework with .net. It is far easier to use than old fashioned HTML form controls</p> <pre><code>&lt;input type="text" id="whatever" /&gt; </code></pre> <p>Than using ASP.net form controls. You probably want to use the cool javascript framework form validation as opposed to the not so great built in .net validators too, but I guess that's down to your preference</p> <p>If you do want to carry on using .net controls, remember that the ID generated in markup is different to what you define, so if you want to reference a control by id in JS use:</p> <pre><code>&lt;%=MyControlId.ClientID%&gt; </code></pre>
9,089
<p>Here's the Question: What is the best way to make sure that your requirement for Flash Version "x" on a site will properly detect presence of later-version Adobe Flash Player Version "10" (or "1y" for that matter)?</p> <p>Now here's the mystery: Why are so many sites that require Flash Player versions 8 and 9 or better failing to detect Flash Player version 10?</p> <p>And here's the juicy background, in technicolor screen captures in my post, "<a href="http://orcmid.com/blog/2008/12/wtf-adobe-flash-version-1x-crisis.asp" rel="nofollow noreferrer">WTF: The Adobe Flash Version 1x Crisis</a>."</p> <p><strong>UPDATE 2:</strong> I have since confirmed that the problem I am seeing is not about improper comparison for the same-or-more-recent version. It appears that some client-side detection is unable to determine whether there is any Flash Player installed at all, much less what version it is. I have also discovered that if I am running as admin I don't have the problem: detection of Flash 10 works just fine. That makes this a bigger can of snakes than I first thought. I'm not ready to change this question's title just yet, and I am continuing to dissect client-side code to see what wondrous logic unfolds. <a href="http://orcmid.com/blog/2008/12/wtf-umm-flash-10-detection-not-so.asp" rel="nofollow noreferrer">Details on these latest revelations</a> are on my blog.</p> <p><strong>UPDATE:</strong> Although I did a search, I missed the related question "<a href="https://stackoverflow.com/questions/214424/why-dont-flash-videos-play-after-upgrading-to-flash-10">Why don't flash videos play after upgrading to Flash 10?</a>" The speculations there are interesting but they don't get to the bottom of it. Also, it's not clear how Levi's problem was resolved. Interesting ... Maybe we can get to the bottom of things here.</p> <hr> <p><strong>Some Background</strong></p> <p>I managed to install the new Adobe Flash Player version 10.0.12.36 as a clean install (with previous versions removed using the Adobe-provided uninstaller).</p> <p>The first disappointment was noticed when I couldn't play the latest NCIS program from the CBS Television site, not in HD, not in plain-old standard. But I could play videos of my favorite programs on Hulu. The more I nosed around, the more times I found those obnoxious you-don't-have-Flash, you-need-a-later-version-of-Flash, your-version-of-Flash-old messages that offered a button for downloading.</p> <p>Every time I clicked the download/update button, and told the Adobe site to do the install (which should fail if attempted, because I am not running as admin), my already having version 10.0.12.36 was confirmed instantly and no update was attempted.</p> <p>Curious, huh?</p> <hr> <p><strong>The Challenge</strong></p> <p>I think I know exactly what the most-likely bug is in the Flash-detection script that people are using. It is just too juicy to not be the bug.</p> <p>Now, that does not mean all sites that fail to detect version 10 suffer from the same bug. I just think the one I have in mind is really likely. I should probably seal my theory in an envelope somewhere. Meanwhile, let's see what the StackOverflow community has to offer and what we conclude the lesson is.</p> <p>I say the bug is really simple and very funny. What do you say?</p>
<p>My guess is the javascript is doing string comparison, and in string land, "10" &lt; "9".</p> <p>Also, Flash10 changed their security model somewhat (breaking a tool I use called SWFUpload) so it may be related to that (see: <a href="http://benr75.com/articles/2008/11/25/swfupload-with-flash-10-fix" rel="nofollow noreferrer">http://benr75.com/articles/2008/11/25/swfupload-with-flash-10-fix</a> )</p>
<p>My guess would be detection from string which is something like "Flash Player version X.Y" by doing something like "get the character before '.' and convert it to number." I've done this a few times myself, it's just stupid.</p>
45,124
<p>We have some COBOL programs in our financial applications which need to interact with some of our backend systems. One of the available interfaces is through a web service. Can a program written in Cobol make requests to a web service?</p>
<p><a href="http://www.microfocus.com/" rel="nofollow noreferrer">Microfocus</a> provide a tool called Enterprise Server which allows COBOL to interact with web services.</p> <p>If you have a COBOL program A and another COBOL program B and A calls B via the interface section, the tool allows you to expose B's interface section as a web service.</p> <p>For program A, you then generate a client proxy and A can now call B via a web service.</p> <p>Of course, because B now has a web service any other type of program (command line, Windows application, Java, ASP etc.) can now also call it.</p>
<p>ibm is now trying to implement a technology called embedded websphere with java. ibm belives this is the only way to give the life to mainframes.</p>
19,704
<p><a href="http://en.wikipedia.org/wiki/ICalendar" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/ICalendar</a></p> <p>I'm working to implement an export feature for events. The link above lists tons of clients that support the ICalendar standard, but the "three big ones" I can see are Apple's iCal, Microsoft's Outlook, and Google's Gmail.</p> <p>I'm starting to get the feeling that each of these client implement different parts of the "standard", and I'm unsure of what pieces of information we should be trying to export from the application so that someone can put it on their calendar (especially around recurrence).</p> <p>For example, from what I understand Outlook doesn't support hourly recurrence.</p> <p>Could any of you provide guidance of the "happy medium" here from a features implementation standpoint?</p> <p>Secondary question, if we decide to cut features from the export (such as hourly recurrence) because it isn't supported in Outlook, should we support it in the application as well? (it is a general purpose event scheduling application, with no business specific use in mind...so we really are looking for the happy medium).</p>
<p>I have to say that I don't use the hourly recurrence feature as really how many people have events that repeat in the same day? I could see if someone however was to schedule when they needed to take a particular medicine at recurring times throughout the day.</p> <p>I would say support full features in the application itself, but provide a warning when they go to export the calendar that all event details may not work as expected or find a way to export in a different manner for Outlook alone that does provide the hourly recurrence feature.</p>
<p>I use iCal in <a href="http://www.mozilla.org/projects/calendar/" rel="nofollow noreferrer">Lightning</a> (Thunderbird) and <a href="http://www.rainlendar.net/cms/index.php" rel="nofollow noreferrer">Rainlendar</a>.</p> <p>I have used Calendaring software for years (decades) and have never had a need for repeating events within the same day. It is simple to add additional daily repeating events in the same day if it is really needed.</p>
2,813
<p>When and how should table stats gathering be performed for Oracle, version 9 and up? How would you go about gathering stats for a large database, where stats gathering would collide with "business hours".</p>
<p>I don't agree that you should always rebuild your statistics after there have been lots of deletes or inserts. As ever, it depends. In a data warehouse situation, when re-building your materialized views you will be doing lots of deletes and inserts but the base structure of the data will not change.</p> <p>You only need to re-calculate statistics on a table if there has been a <em>significant</em> change in its content. This does <em>not</em> necessarily mean after lots of deletes or inserts, but rather when deletes, inserts, or updates materially change the content with respect to possible execution plans.</p> <p>If you are truncating tables and rebuilding (which will reset your statistics), instead of an expensive statistics calculation, you're often better off storing the statistics before truncating and restoring them once you've rebuilt the table.</p> <p>For saving the current views of statistics you use:</p> <pre><code>dbms_stats.export_table_stats </code></pre> <p>and to restore them afterwards you use:</p> <pre><code>dbms_stats.import_table_stats </code></pre> <p>(There are corresponding procedures for <code>schema</code> and <code>database</code>.)</p>
<p>Make sure when using the estimate (sample_percent) that you gather at least 10 percent. Below that can yield very questionable results.</p>
5,741
<p>I am building the diagram component in JavaScript. It has two layers rendered separately: foreground and background.</p> <p>To determine the required size of the background:</p> <ol> <li>render the foreground </li> <li>measure the height of the result</li> <li>render the foreground and the background together</li> </ol> <p>In code it looks like this:</p> <pre><code>var foreground = renderForegroundIntoString(); parentDiv.innerHTML = foreground; var height = parentDiv.children[0].clientHeight; var background = renderBackgroundIntoString(height); parentDiv.innerHTML = foreground + background; </code></pre> <p>Using IE7, this is a piece of cake. However, Firefox2 is not really willing to render the <code>parentDiv.innerHTML</code> right away, therefore I cannot read out the foreground height.</p> <p>When does Firefox execute the rendering and how can I delay my background generation till foreground rendering is completed, or is there any alternative way to determine the height of my foreground elements?</p> <p>[Appended after testing Dan's answer (thanx Dan)]</p> <p>Within the body of the callback method (called back by <code>setTimeout(...))</code> I can see, the rendering of the <code>innerHTML</code> is still not complete. </p>
<p>You should never, ever rely on something you just inserted into the DOM being rendered by the next line of code. All browsers will group these changes together to some degree, and it can be tricky to work out when and why.</p> <p>The best way to deal with it is to execute the second part in response to some kind of event. Though it doesn't look like there's a good one you can use in that situation, so failing that, you can trigger the second part with:</p> <pre><code>setTimeout(renderBackground, 0) </code></pre> <p>That will ensure the current thread is completed before the second part of the code is executed.</p>
<p>I don't think you want parentDiv.children[0] (children is not a valid property in FF3 anyway), instead you want parentDiv.childNodes[0], but note that this includes text nodes that may have no height. You could try looping waiting for parentDiv's descendants to be rendered like so:</p> <pre> function getRenderedHeight(parentDiv) { if (parentDiv.childNodes) { var i = 0; while (parentDiv.childNodes[i].nodeType == 3) { i++; } //Now parentDiv.childNodes[i] is your first non-text child return parentDiv.childNodes[i].clientHeight; //your other code here ... } else { setTimeout("isRendered("+parentDiv+")",200); } } </pre> <p>and then invoke by: getRenderedHeight(parentDiv) after setting the innerHTML.</p> <p>Hope that gives some ideas, anyway.</p>
20,374
<p>The following code fails at runtime&hellip;</p> <pre> Dim Id As Guid = CType(e.CommandArgument, Guid) </pre> <p>It throws this exception&hellip;</p> <pre> System.InvalidCastException was unhandled by user code Specified cast is not valid </pre> <p>Why can't I cast <strong><em>e.CommandArgument</em></strong> as a Guid?</p>
<p>Try:</p> <pre><code>Dim DeleteId As Guid = New Guid(Convert.ToString(e.CommandArgument)) </code></pre> <p>This works...</p> <pre> Dim DeleteId As Guid = New Guid(DirectCast(e.CommandArgument, String)) </pre>
<p>The message "cast is not valid" suggests that the datatype for one of the values does not match what's in the database. Can you put a breakpoint on the line where the value of DeleteId is set and see what the Guid looks like? Then, you can compare it with what you see in the database for DogId. I suspect that you will find your datatype problem there.</p>
31,788
<p>In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:</p> <pre><code>For Each item As Host In hostCollection1 hostCollection2.Add(item) Next </code></pre> <p>My collections are generic collections, inherited from the base class -- Collection(Of )</p>
<p>You can use AddRange: <code>hostCollection2.AddRange(hostCollection1)</code>.</p>
<p><code>Array.Copy</code> may solve your problem.</p>
17,746
<p>I have not had to mess with mailto links much. However I now need to add a link in the body of a mailto if it is possible. </p> <p>Is there a way to add a link or to change the email opened to an html email vs a text email?</p> <p>Something like:</p> <pre><code>&lt;a href="mailto:test@test.test?body=The message's first paragraph.%0A%0aSecond paragraph.%0A%0AThird Paragraph.%0A%0ALink goes here"&gt;Link text goes here&lt;/a&gt; </code></pre>
<p>Section 2 of <a href="https://www.rfc-editor.org/rfc/rfc2368" rel="noreferrer" title="RFC 2368">RFC 2368</a> says that the <code>body</code> field is supposed to be in <code>text/plain</code> format, so you can't do HTML.</p> <p>However even if you use plain text it's possible that some modern mail clients would render a URL as a clickable link anyway, though.</p>
<p>Here's what I put together. It works on the select mobile device I needed it for, but I'm not sure how universal the solution is </p> <pre><code>&lt;a href="mailto:me@me.com?subject=Me&amp;body=%3Chtml%20xmlns%3D%22http:%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%3C%2Fhead%3E%3Cbody%3EPlease%20%3Ca%20href%3D%22http:%2F%2Fwww.w3.org%22%3Eclick%3C%2Fa%3E%20me%3C%2Fbody%3E%3C%2Fhtml%3E"&gt; </code></pre>
30,709
<p>I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?</p>
<p>This registry key should tell you:</p> <pre><code>HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System </code></pre> <p>Value <code>EnableLUA (DWORD)</code></p> <p><code>1</code> enabled / <code>0</code> or missing disabled</p> <p>But that assumes you have the rights to read it. </p> <p>Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see <a href="http://blogs.msdn.com/cjacks/archive/2006/10/09/How-to-Determine-if-a-User-is-a-Member-of-the-Administrators-Group-with-UAC-Enabled-on-Windows-Vista.aspx" rel="nofollow noreferrer">here</a>). Not foolproof, but it may work.</p> <p>The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem. </p>
<p>AFAIK, UAC is apolicy setting on the local user or group. So you can read this property from within .Net. Sorry for not having more details but I hope this helps</p>
12,107
<p>I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall?</p>
<p><strong>Step 1</strong></p> <p>Stop database:</p> <pre><code>shell&gt; /etc/init.d/mysql stop </code></pre> <p><strong>Step 2</strong></p> <p>Restart database</p> <ul> <li>without password autentification</li> <li>without connection to the network</li> </ul> <p>Access to database is only possible through it's sock file '/var/lib/mysql/mysql.sock'.</p> <pre><code>shell&gt; mysqld --user=mysql --pid-file=/var/lib/mysql/mysqld.pid \ --socket=/var/lib/mysql/mysql.sock --datadir=/var/lib/mysql \ --skip-grant-tables --skip-networking &amp; </code></pre> <p><strong>Step 3</strong></p> <p>Connect to the database and change password:</p> <pre><code>shell&gt; mysql --database mysql --socket=/var/lib/mysql/mysql.sock </code></pre> <p>If you want to, show all users:</p> <pre><code>mysql&gt; select User, password from user; </code></pre> <p>Set new password:</p> <pre><code>mysql&gt; update user set password=password('NEW PASS') WHERE User='USERNAME'; </code></pre> <p>Leave database connection:</p> <pre><code>mysql&gt; exit </code></pre> <p><strong>Step 4</strong></p> <p>Restart database server "normally".</p> <pre><code>shell&gt; kill `cat /var/lib/mysql/mysqld.pid` shell&gt; /etc/init.d/mysql start </code></pre>
<p>If you are running an Ubuntu server (possibly also Debian?) you can easily reset. </p> <p>If you are on 12.04:</p> <pre><code>sudo dpkg-reconfigure mysql-server-5.5 </code></pre> <p>If you are on 10.04:</p> <pre><code>sudo dpkg-reconfigure mysql-server-5.1 </code></pre> <p>If you are not sure which mysql-server version is installed you can try: </p> <pre><code>dpkg --get-selections | grep mysql-server </code></pre> <p>See for more info:</p> <p><a href="https://help.ubuntu.com/12.04/serverguide/mysql.html" rel="nofollow">https://help.ubuntu.com/12.04/serverguide/mysql.html</a> <a href="https://help.ubuntu.com/10.04/serverguide/mysql.html" rel="nofollow">https://help.ubuntu.com/10.04/serverguide/mysql.html</a></p>
7,696
<p>I'm using a PropertyGrid in a tool app to show a window to monitor an object in a remote app. Every second or so I get an update from the app with the state of any members that have changed, and I update the grid. I call Refresh() to make the changes take. This all works pretty well except one thing.</p> <p>Say the object is too tall to fit in the grid so there's a scrollbar. The user has selected a grid item but has also scrolled up above it so that the selected item is below the bottom of the control.</p> <p>The problem is that on Refresh() the control automatically scrolls the grid item into view (strangely it doesn't do this when the item is above the top of the control).</p> <p>I'm looking for a way to either prevent this, or to save state, do the Refresh(), and then set it back. I tried getting the underlying VScrollBar in the PropertyGridView inside the PropertyGrid, and messing with "Value", but it doesn't stay permanently set. Always pops back so the item is in view.</p> <p>Deselecting the item during scrolling is my fallback (the auto scroll-into-view doesn't happen with no selected grid item) but it hurts the usability a little so I'm looking for another way.</p> <p>Anyone run into something similar?</p>
<p>This is not possible in the MS PropertyGrid. This component has too many unaccessible internals to give you the flexibility you are requesting and as you realized yourself it is not consistent (you have the issue for a property below the grid but not when it is above). That's why I created <a href="http://www.visualhint.com" rel="nofollow noreferrer">Smart PropertyGrid.Net</a>. If a commercial product is an option for you, this grid has the option to store property states and restore them after you made an action on the grid (like Refresh()) without any flicker.</p>
<p>For me the following made the difference:</p> <p>dont assign a new object.</p> <p>Simply update the fields of the old object with the new data.</p> <p>Now, on refresh, my PropertyGrid does not scroll any more, and also shows updated content.</p>
36,781
<p>I have a CIFS share mounted on a Linux machine. The CIFS server is down, or the internet connection is down, and anything that touches the CIFS mount now takes several minutes to timeout, and is unkillable while you wait. I can't even run ls in my home directory because there is a symlink pointing inside the CIFS mount and ls tries to follow it to decide what color it should be. If I try to umount it (even with -fl), the umount process hangs just like ls does. Not even sudo kill -9 can kill it. How can I force the kernel to unmount?</p>
<p>I use lazy unmount: <code>umount -l</code> (that's a lowercase <code>L</code>)</p> <blockquote> <p>Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)</p> </blockquote>
<p>On RHEL 6 this worked for me also:</p> <p>umount -f -a -t cifs -l FOLDER_NAME</p>
10,029
<p>How can we print using print document so that we can control the printer paper size?</p> <ul> <li>It must be controlled after web hosting is done without the print dialog popup or javascript popup. </li> <li>It should print on the client's printer after webhosting without the print dialog option and setting the paper size.</li> <li>It should be done in C# .net</li> </ul>
<p>As a user I don't want that when I enter a site someone to change my printer's settings or to take control over my printer.</p> <p>For security reasons I hope this is not possible.</p>
<p>I have looked into this before, and the only way to force things like portrait/landscape etc, is to get the user to install an ActiveX control (or similar).</p> <p>Javascript or CSS alone cannot do it.</p>
40,974
<p>I'm writing an application that will need to open up browser windows (probably can stick to IE) to websites that use Forms Authentication. The trick is that they need to be authenticated already, in order to save time due to the sheer number of sites we need to get into. (Eventually I'll be screen scraping them and processing the data... but I'll still need to get the authentication piece working so they can click through to the real site when needed.)</p> <p>I've got the Forms Authentication piece working, in that I can use an HttpWebRequest to get the html and just pass it through to the browser. However I can't get it to transfer the cookies to the client browser so that it can go to the actual website.</p> <p>I'm getting the System.Net.Cookies for the authentication, and I've tried copying them into System.Web.HttpCookies and adding those to the Response object. If I put a link on the page or use Response.Redirect to go to the website it doesn't work, it acts as if the user is not authenticated.</p> <p>Anyone have any idea how I would pull this off?</p> <p>Here's the current code, in case that makes this more clear:</p> <pre><code>Dictionary&lt;string, string&gt; formValues = new Dictionary&lt;string, string&gt;(4); formValues.Add("txbUserName", "USERNAME"); formValues.Add("txbPassword", "PASSWORD"); formValues.Add("SubmitB", "Log In"); HttpWebRequest webRequest; StreamReader responseReader; string responseData; //This authenticates an HttpWebRequest and returns it webRequest = FormsAuthHttpWebRequest.Create("REQUESTURI", "LOGINURI", formValues) as HttpWebRequest; responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); responseReader.Close(); foreach (Cookie cookie in webRequest.CookieContainer.GetCookies(new Uri("SITEURI"))) { HttpCookie httpCookie = new HttpCookie(cookie.Name, cookie.Value) { Domain = cookie.Domain, Expires = cookie.Expires, Path = cookie.Path, HttpOnly = cookie.HttpOnly, Secure = cookie.Secure }; Response.Cookies.Add(httpCookie); } Response.Redirect("REQUESTURI"); </code></pre>
<p>I don't think you're going to be able to do this. The browser is going to ignore any "Add-Cookie" headers from a web server that does not belong to the domain associated with the cookies. This is part of the built-in security for cookies - it would be catastrophic (from a security and privacy perspective) if other websites could read or write cookies for another domain.</p>
<p>I think the browser may be ignoring the cookies in the response header because of the impending Response.Redirect. We ran into that issue recently, and discovered that FF accepted the cookies, but IE6&amp;7 did not.</p> <p>I'm not sure I understand exactly what you're trying to do, though. Are you attempting to send cookies from Site A to the browser that are actually meant for Site B? </p>
43,557
<p>When I hit /// in Visual Studio, is it possible to change the resulting snippet from this:</p> <pre><code>/// &lt;summary&gt; /// /// &lt;/summary&gt; </code></pre> <p>to this?:</p> <pre><code>/// &lt;summary&gt;&lt;/summary&gt; </code></pre>
<p>Here is the solution working in at least VS2010.</p> <p>Save the bottom code as a file summ.snippet.<br> Visual Studio 2010 / Tools / Code Snippet Manager<br> Click import, browse to file. Save with default options.</p> <p>Now goto your code window and type summ + tab + tab</p> <p>Result</p> <pre><code>/// &lt;summary&gt; &lt;/summary&gt; </code></pre> <p>with the cursor in the middle of the tag, ready to type.</p> <p>Here is the contents of the summ.snippet</p> <pre><code>&lt;CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt; &lt;CodeSnippet Format="1.0.0"&gt; &lt;Header&gt; &lt;Title&gt;Summary - inline&lt;/Title&gt; &lt;Description&gt;Created inline summary comment tag&lt;/Description&gt; &lt;Author&gt;Mike Vanderkley&lt;/Author&gt; &lt;Shortcut&gt;summ&lt;/Shortcut&gt; &lt;SnippetTypes&gt; &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt; &lt;/SnippetTypes&gt; &lt;/Header&gt; &lt;Snippet&gt; &lt;Code Language="csharp"&gt; &lt;![CDATA[/// &lt;summary&gt; $end$ &lt;/summary&gt;]]&gt; &lt;/Code&gt; &lt;/Snippet&gt; &lt;/CodeSnippet&gt; &lt;/CodeSnippets&gt; </code></pre>
<p>I know that it was possible for VB in VS 2005 and VS 2008. Last I had checked, though, there was not a way to do it for C#, sadly. That has been a pet peeve of mine for some time, now.</p>
48,202
<p>The title pretty much says it all. I want to create a SqlConnection and then check that connection without opening a database, cause at that point I don't know yet where will I connect to. Is it possible to do that? The SqlConnection class has a 'Open' member which tries to open the database you'd set in the Database property, and if you didn't set one, SqlServer tries with the master db. The thing is the user I'm trying to connect with (MACHINE\ASPNET) has access to some databases (which I don't know yet) and not the master db.</p> <p>Regards, Seba</p>
<p>Connect to temp db. Everybody has accecss to tempdb so you will be able to authenticate yourself for access. Later when you know the actual database , you can change this property to connect to the db you want.</p>
<p>I don't know whether you got your answers but as we all look here for answers I hope this is what you were looking for</p> <pre><code>dim con as new sqlconnection con.connectionstring="&lt;&lt;put your conn string here&gt;&gt;" 'try...catch block fires exception if the con is not successfully opened try con.open() catch ex as exception msgbox ex.message end try </code></pre>
18,671
<p>Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.</p> <p>My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?</p> <p>The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own?</p>
<p>LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.</p> <p>LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.</p> <p>This is a good introductory article on MSDN: <a href="http://msdn.microsoft.com/en-us/library/cc161164.aspx" rel="noreferrer">Introducing LINQ to Relational Data</a></p>
<blockquote> <p>Linq-to-SQL</p> </blockquote> <p><em>It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper.</em></p> <blockquote> <p>Linq-to-Entities</p> </blockquote> <p><em>Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases</em></p> <blockquote> <p>According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda.</p> </blockquote>
3,013
<p>Is Software Testing really given its importance at the academic level?</p> <p>I believe there is a need in universities offering Software Engineering (and probably even Computer Science) to treat <strong>Software Testing</strong> as a separate course and topic in itself, rather than as part of a general topic of Software Engineering. Irrespective of the testing methodology and techninque used, this is something that is as much a part of a software professional's life as writing code. </p> <p>I am not sure this is happening in most of universities - it is still being given secondary importance. When a fresh graduate comes out of university, he is all about programming and creating things, not on how to test them. </p> <p>Should Software Testing really become a first-class concept at the academic level (or at-least treated like one)?</p>
<p>Yes, it probably should be given more consideration, and at some places it is. As a part of the new curriculum at the university I attended all programming projects are required to include test cases. There's no way to enforce a particular methodology, like TDD, but I think this is a step in the right direction.</p> <p>There are even tools available, like <a href="http://portal.acm.org/citation.cfm?id=1384371" rel="nofollow noreferrer">Web-CAT</a>, that allow for automated evaluation of test coverage. The students submit their code and their tests, and the system tells them how they scored against a set of instructor-accepted tests.</p>
<p>Yes, absolutely.</p>
32,418
<p>Is there any reason to use a varchar field instead of a date field in MySQL? I'm looking at an existing site and I see the developer has done this. Is there any reason to?</p>
<p>Unless it really <em>is</em> acting primarily as a string — say, it wants to preserve date formatting style, locale-named months, named timezones etc. and doesn't care about being computable — no, varchar would not be a good choice.</p> <p>Handling real date datatypes can be problematic/non-portable across different DBMSs/data access layers, but the usual solution to that is just to use an integer (Unix-style) timestamp instead.</p>
<p>I've seen lots of "Developer turned DBA" type people completely misuse database types, just chock it up to inexperience.</p>
35,805
<p>Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):</p> <pre><code>CREATE PROCEDURE incrementCounter AS DECLARE @current int SET @current = (select CounterColumn from MyTable) + 1 UPDATE MyTable SET CounterColumn = current GO </code></pre> <p>We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.</p> <p>Can this stored procedure be executed multiple times, at the same time? </p> <p>i.e. is this possible:</p> <p>I call 'incrementCounter' twice. Call A gets to the point where it sets the 'current' variable (let's say it is 5). Call B gets to the point where it sets the 'current' variable (which would also be 5). Call A finishes executing, then Call B finishes. In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution</p>
<p>This is for SQL Server.</p> <p>Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with </p> <p>BEGIN TRANSACTION<br> Statement ...<br> Statement ...<br> COMMIT TRANSACTION</p> <p>(It's common to use BEGIN TRAN and END TRAN for short.)</p> <p>Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.</p> <p>Contrary to a popular misconception, this will work in your case with default transaction level settings.</p>
<p>Maybe I'm reading too much into your example (and your real situation may be significantly more complicated), but why wouldn't you just do this in a single statement?</p> <pre><code>CREATE PROCEDURE incrementCounter AS UPDATE MyTable SET CounterColumn = CounterColumn + 1 GO </code></pre> <p>That way, it's automatically atomic and if two updates are executued at the same time, they'll always be ordered by SQL Server so as to avoid the conflict you describe. If, however, your real situation is much more complicated, then wrapping it in a transaction is the best way to do this.</p> <p>However, if another process has enabled a "less safe" isolation level (like one that allows dirty reads or non-repeatable reads), then I don't think a transaction will protect against this, as another process can see into the partially updated data if it's elected to allow unsafe reads.</p>
32,465
<p>We're in the process of replacing a legacy system. There is going to be a period of time with both the applications running in tandem. Users will be able to use either system and the challenge is to be able to keep their databases in sync with each other.</p> <p>The new system is ASP.NET and the legacy is VB6. Both are running on a SQL Server database. It is unclear at this time if the databases will be in the same server room, let alone the same country.</p> <p>The two solutions on the table so far are:</p> <ol> <li>Web services that sit on each machine and is called by the other application. <ul> <li>Need to modify the Save method on the base class(es?) for the native objects. This is invasive and could be a problem when it comes to switching it off.</li> </ul></li> <li><p>A single windows service that polls each database and works out what's changed and forwards adapted updates as appropriate.</p> <ul> <li>Need to change the schemas in both applications to ensure that they have a LastModified (DateTime) on all tables so we can do a periodic SELECT at any given interval. </li> </ul></li> </ol> <p>Both solutions seem reasonable. Both solutions have pros and cons. The business has asked for no more than a 2 second delay(!) between updating one system and seeing it in the other. That's possibly a stretch target but it's something to aim for.</p> <p>Others that have been suggested but rejected (I'm willing to reconsider) are:</p> <ul> <li>Database triggers (blugrh)</li> <li>BizTalk or other bus (seems like a sledge hammer and is too complex for a switchover solution)</li> <li>Modifying all the stored procedures (noooo.)</li> <li>SSIS (don't know enough about this yet)</li> </ul> <p>Appreciate any thoughts you may have.</p> <p>EDIT: N.B. The schemas are completely different.</p>
<p>2 seconds, that is a really tight timeline, and I'm guessing that your windows app solution just might not cut it, not if there are hundreds of changes or anything at one time, and the poll time has to be almost every second to hope to make it within 2.</p> <p>Are the databases using the same structure? If so, I'd look at implementing replication.</p> <p><strong>Edit</strong></p> <p>After the comment and addition that the schemas are entirely different, I have to say that really I see two sets of operations.</p> <ol> <li><p>Modify the data storage options IN the app to make inserts/updates/deletes in both tables. Advantage: Immediate, no external process to share. Disadvantage: have to modify all code, hard to disable etc.</p></li> <li><p>Create a sync application as you mentioned, to sync changed data. Advantage: can simply disable after transfer done. Disadvantage: very complex to write especially if there are a large number of tables. Also, not as fast, 2 seconds is going to be VERY hard to accomplish</p></li> </ol>
<p>Personally I would reject the idea of users using either system simulataneously. How are you going to resolve the issue if user 1 changed record 1 on system 1 and user 2 changed record 1 in a different way on system 2?</p> <p>Further, if you don't require people to use the new system, they won't. Resistance to change is very very strong in most organizations.</p> <p>I would suggest instead that you rollout the new system and require all to use it and hourly send data to the old system in case you need to revert for any reason.</p> <p>I see no reasonable way to get a 2 second synch. That is a ridiculous requirement and the business side should be told so in no uncertain terms. </p> <p>Sometimes you just have to fight back when busines users want something unreasonable.</p>
34,304
<p>I have a Publishing Portal site and I need to add some announcements to some of the pages. I've read an article which says that i have to create an announcement list to be able add an announcement web part but i can't seem to find any resources on how i can add an announcement list.</p> <p>Any help will be greatly appreciated.</p> <p>TIA!</p>
<p>From the home page of your site (or from any page really) you should see a "View All Site Content" link on the top of the navigation menu.</p> <p><a href="http://friendfeed.s3.amazonaws.com/86fed07f0809beefaeeaee0013ee2b952079bc09" rel="nofollow noreferrer">View All Site Content http://friendfeed.s3.amazonaws.com/86fed07f0809beefaeeaee0013ee2b952079bc09</a></p> <p>Click on that link and it will show you a dashboard listing all of the SharePoint lists that have been provisioned for the current site. Click on the Create button to create a new SharePoint list.</p> <p><a href="http://friendfeed.s3.amazonaws.com/6c0b244801826f8b3ee01811211b88668ba8f713" rel="nofollow noreferrer">Create new SharePoint List http://friendfeed.s3.amazonaws.com/6c0b244801826f8b3ee01811211b88668ba8f713</a></p> <p>From there you will see the option to create an Announcments list (under the Communications header). Complete the wizard to complete the list.</p> <p>Once the list is created you can select Edit Page from the Site Actions menu on any SharePoint page in the site and then select a "Add a Web Part" on the web part zone you want to put your Announcements web part into. You should now see a web part listed with the same name as your Announcements list that you just created.</p> <p>Select that web part to add it to the page and display.</p> <p>Hope that helps. If this isn't the answer to your problem leave a comment or update your question with clarification and I will try to help.</p>
<p>Giving you direct instructions on how to create the list would most likely leave you more lost than ever. If this is a publishing portal, there's a lot more to learn beyond just creating a list. Content must be approved, and is versioned. I'd strongy advise you not to start poking around in there as you run a large risk of messing up the portal. Don't get stressed by people demanding you perform such things without having received any training. Grab yourself a coffee, flip your boss the finger and watch some pertinant webcasts on <a href="http://office.microsoft.com/en-us/sharepointserver/FX101211721033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/sharepointserver/FX101211721033.aspx</a></p> <p>Hope this helps,</p> <p>Oisin</p>
15,563
<p>If a customer sends me a non-commercial 3D model to print, am I allowed to charge money for the 3D printing process? I understand I cannot charge anything for the model nor offer it as a part of my business.</p> <p>I cannot download the model myself, print and sell it, but if the customer downloads it and sends it to me for me to print it, is it a violation of the license or not?</p>
<p><em>I would have liked to answer linking to credible official sources, but I cannot add references either on direct B-spline printing. So I'm writing down my thoughts. I've familiarized myself in B-splines to understand what they are and read into the 2 references given by the OP.</em></p> <hr /> <p>Basically, the printer software only allows printing of straight lines. Yes I know we can give orders to the printer to print a curve (using <code>G2</code> or <code>G3</code>), but these eventually will be converted to printing straight lines. There is no ready made printer firmware available to print cubic curves directly to my knowledge. If it would be possible, these curves should eventually be translated into smaller straight lines by the firmware of timed stepper rotational output. These extra calculations would demand a considerable effort of the printer board processor, most probably far more an 8-bit processor would be able to handle.</p> <p>Comparing the <a href="https://m.box.com/shared_item/https%3A%2F%2Fumich.box.com%2Fs%2Fn9cvs27ckehdr64gzv5igtmboykymgk6" rel="nofollow noreferrer">paper released in 2017</a> to the <a href="https://hackaday.io/project/7045-splinetravel" rel="nofollow noreferrer">G-code pre-processing software</a> reveals that although both seem to refer to B-spline techniques, they are implemented differently. For example, the pre-processing software aims to reduce the linear travel moves by replacing these with B-spline curves (and not affect the actual print object), while the paper focuses on the optimization of the actual printing curves being optimized by B-spline curves (also using a pre-processor). Both eventually would need to create a multitude of small straight lines to have the printer be able to actually print the object as there is no 3D printing firmware solution to print curves. Do note that the method in the paper has been <a href="https://3dprint.com/195734/um-update-algorithm/" rel="nofollow noreferrer">questioned by the RepRap community</a>, which demonstrated that they could print the same object way faster than the B-spline optimized example. Furthermore, do note that the Marlin community is probably moving in that direction as can be seen from e.g. <a href="https://github.com/MarlinFirmware/Marlin/issues/8308" rel="nofollow noreferrer">this feature request</a> and <a href="http://marlinfw.org/meta/gcode/" rel="nofollow noreferrer">this G-code meta overview</a>; G-code instruction <code>G5</code>.</p> <p>So, both methods rely on pre-processing G-codes by identification of sliced coordinate (print) moves, translation into Bézier/B-spline curves for (print) moves, which eventually are translated into normal <code>G0/G1</code> (print) moves. It does not appear that the Marlin community/developers are aiming to implement Bézier or B-spline curves soon. This implies that if you want to pursuit printing B-splines, you need to make your own pre-processor, or dive into Marlin C++ development; an 8-bit based printer board would not be sufficient indeed like the OP mentioned, up-scaling to 32-bit or interfacing with USB might be the only solution.</p>
<p>In more practical terms, you could design the part so that the corners are rounded (also known as fillets). This will help keep the print head moving and would prevent the sudden stop and start effect that causes "jerking". Further 8 bit controllers tend to get saturated when reading large amounts of g-code from the sd card or the serial port. Upgrading to a 32 bit controller will prevent that kind of jerking.</p> <p>Both of these methods pale in comparison to just speeding up the print. Upgrading the hardware to be faster (various methods exist) would yield more of a reduced time than trying to optimize the g-code (in my humble opinion). Delta printers have the potential to be the fastest type of FDM printer, assuming that you could get the filament to melt fast enough.</p>
1,402
<p>I want to be able to figure out what port a particular program is using. Are there any programs available online or that come with windows that will tell me which processes are using which ports on my computer?</p> <p>PS - before you downmod this for not being a programming question, I'm looking for the program to test some networking code.</p>
<p><code>netstat -b -a</code> lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista.</p> <p>I usually add <code>-n</code> as well to make it a little faster, but adding <code>-b</code> can make it quite slow.</p> <p><em>Edit</em>: If you need more functionality than netstat provides, <a href="https://stackoverflow.com/questions/105418/what-port-is-a-given-program-using#105487">vasac suggests</a> that you try <a href="http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx" rel="noreferrer">TCPView</a>.</p>
<p>most decent firewall programs should allow you to access this information. I know that Agnitum OutpostPro Firewall does.</p>
13,091
<p>I just figured out that I can actually <strong>store objects in the $_SESSION</strong> and I find it quite cool because when I jump to another page I still have my object. Now before I start using this approach I would like to find out if it is really such a good idea or if there are <strong>potential pitfalls</strong> involved. </p> <p>I know that if I had a single point of entry I wouldn't need to do that but I'm not there yet so I don't have a single point of entry and I would really like to keep my object because I don't lose my state like that. (Now I've also read that I should program stateless sites but I don't understand that concept yet.)</p> <p>So <strong>in short</strong>: Is it ok to store objects in the session, are there any problems with it?</p> <hr> <p>Edit:</p> <p><em>Temporary summary</em>: By now I understand that it is probably <strong>better to recreate</strong> the object even if it involves querying the database again. </p> <p>Further answers could maybe <strong>elaborate on that aspect</strong> a bit more!</p>
<p>I know this topic is old, but this issue keeps coming up and has not been addressed to my satisfaction:</p> <p>Whether you save objects in $_SESSION, or reconstruct them whole cloth based on data stashed in hidden form fields, or re-query them from the DB each time, you are using state. HTTP is stateless (more or less; but see GET vs. PUT) but almost everything anybody cares to do with a web app requires state to be maintained somewhere. Acting as if pushing the state into nooks and crannies amounts to some kind of theoretical win is just wrong. State is state. If you use state, you lose the various technical advantages gained by being stateless. This is not something to lose sleep over unless you know in advance that you ought to be losing sleep over it.</p> <p>I am especially flummoxed by the blessing received by the "double whammy" arguments put forth by Hank Gay. Is the OP building a distributed and load-balanced e-commerce system? My guess is no; and I will further posit that serializing his $User class, or whatever, will not cripple his server beyond repair. My advice: use techniques that are sensible to your application. Objects in $_SESSION are fine, subject to common sense precautions. If your app suddenly turns into something rivaling Amazon in traffic served, you will need to re-adapt. That's life. </p>
<p>I would also bring up when upgrading software libraries - we upgraded our software and the old version had objects in session with the V1 software's class names, the new software was crashing when it tried to build the objects that were in the session - as the V2 software didn't use those same classes anymore, it couldn't find them. We had to put in some fix code to detect session objects, delete the session if found, reload the page. The biggest pain initially mind you was recreating this bug when it was first reported (all too familiar, "well, it works for me" :) as it only affected people who where in and out the old and new systems recently - however, good job we did find it before launch as all of our users would surely have had the old session variables in their sessions and would have potentially crashed for all, would have been a terrible launch :)</p> <p>Anyway, as you suggest in your amendment, I also think it's better to re-create the object. So maybe just storing id and then on each request pulling the object from the database, is better/safer.</p>
16,027
<p>When using JDBC, I often come across constructs like </p> <pre><code>ResultSet rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt(1); // Some other actions } </code></pre> <p>I asked myself (and authors of code too) why not to use labels for retrieving column values: </p> <pre><code>int id = rs.getInt("CUSTOMER_ID"); </code></pre> <p>The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.<br> So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)? </p>
<p>You should use <strong>string labels by default.</strong></p> <p><strong>Pros:</strong></p> <ul> <li>Independence of column order</li> <li>Better readability/maintainability</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>You have no control over the column names (access via stored procedures)</li> </ul> <p><strong>Which would you prefer?</strong></p> <p>ints?</p> <pre><code>int i = 1; customerId = resultSet.getInt(i++); customerName = resultSet.getString(i++); customerAddress = resultSet.getString(i++); </code></pre> <p>or Strings?</p> <pre><code>customerId = resultSet.getInt("customer_id"); customerName = resultSet.getString("customer_name"); customerAddress = resultSet.getString("customer_address"); </code></pre> <p>And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all?</p> <p>That's why you should use <strong>string labels by default.</strong></p>
<p>I agree with previous answers that performance is not something that can force us to select either of the approaches. It would be good to consider the following things instead:</p> <ul> <li>Code readability: for every developer reading your code labels have much more sense than indexes.</li> <li>Maintenance: think of the SQL query and the way it is maintained. What is more likely to happen in your case after fixing/improving/refactoring SQL query: changing the order of the columns extracted or changing result column names. It seems for me that changing the order of the columns extracted (as the results of adding/deleting new columns in result set) has greater probability to happen.</li> <li>Encapsulation: in spite of the way you choose try to isolate the code where you run SQL query and parse result set in the same component and make only this component aware about the column names and their mapping to the indexes (if you decided to use them).</li> </ul>
22,608
<p>I am using the jQuery Datepicker widget with two input boxes, one for the <strong>"From"</strong> date and the second with the <strong>"To"</strong> date. I am using the <a href="http://jqueryui.com/datepicker/" rel="noreferrer">jQuery Datepicker functional demo</a> as a basis for getting the two input boxes to work with each other, but I need to be able to add these additional restrictions:</p> <ol> <li><p>Date range can be no earlier than 01 December 2008 </p></li> <li><p><strong>"To"</strong> date can be no later than today</p></li> <li><p>Once a <strong>"From"</strong> date is selected, the <strong>"To"</strong> date can only be within a range of 7 days after the <strong>"From"</strong> date</p></li> <li><p>If a <strong>"To"</strong> date is selected first, then the <strong>"From"</strong> date can only be within the range of 7 days before the <strong>"To"</strong> date (with the limit of 01 December being the first selectable date)</p></li> </ol> <p>I can't seem to get all of the above working together.</p> <p>In summary, I would like to be able to select a range of up to 7 days between 01 December and today (I realise I am posting this on 1st December so will only get today for the moment).</p> <p>My code so far</p> <pre><code>$(function () { $('#txtStartDate, #txtEndDate').datepicker( { showOn: "both", beforeShow: customRange, dateFormat: "dd M yy", firstDay: 1, changeFirstDay: false }); }); function customRange(input) { return { minDate: (input.id == "txtStartDate" ? new Date(2008, 12 - 1, 1) : null), minDate: (input.id == "txtEndDate" ? $("#txtStartDate").datepicker("getDate") : null), maxDate: (input.id == "txtStartDate" ? $("#txtEndDate").datepicker("getDate") : null) }; } </code></pre> <p>I'm missing the 7 day range restriction and also preventing a <strong>"To"</strong> date selection before 01 December 2008 or after today. Any help would be much appreciated, Thanks.</p>
<p>Many thanks for your help Ben, I have built upon your posts and have come up with this. It is now complete and works brilliantly!</p> <p>Here's a <strong><a href="http://jsbin.com/evudo" rel="noreferrer">Working Demo</a></strong>. Add <strong>/edit</strong> to the URL to see the code</p> <p>Complete Code below-</p> <pre><code>$(function () { $('#txtStartDate, #txtEndDate').datepicker({ showOn: "both", beforeShow: customRange, dateFormat: "dd M yy", firstDay: 1, changeFirstDay: false }); }); function customRange(input) { var min = new Date(2008, 11 - 1, 1), //Set this to your absolute minimum date dateMin = min, dateMax = null, dayRange = 6; // Set this to the range of days you want to restrict to if (input.id === "txtStartDate") { if ($("#txtEndDate").datepicker("getDate") != null) { dateMax = $("#txtEndDate").datepicker("getDate"); dateMin = $("#txtEndDate").datepicker("getDate"); dateMin.setDate(dateMin.getDate() - dayRange); if (dateMin &lt; min) { dateMin = min; } } else { dateMax = new Date; //Set this to your absolute maximum date } } else if (input.id === "txtEndDate") { dateMax = new Date; //Set this to your absolute maximum date if ($("#txtStartDate").datepicker("getDate") != null) { dateMin = $("#txtStartDate").datepicker("getDate"); var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(),dateMin.getDate() + dayRange); if(rangeMax &lt; dateMax) { dateMax = rangeMax; } } } return { minDate: dateMin, maxDate: dateMax }; } </code></pre>
<p>This is how I have done it. I have taken the source from the Jquery UI website and modified it to add your constraints.</p> <pre><code>$(document).ready(function () { var dates = $('#StartDate, #EndDate').datepicker({ minDate: new Date(2008, 11, 1), maxDate: "+0D", dateFormat: "dd M yy", changeMonth: true, changeYear: true, onSelect: function (selectedDate) { var option = this.id == "StartDate" ? "minDate" : "maxDate", instance = $(this).data("datepicker"), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); var edate; var otherOption; var d; if (option == "minDate") { otherOption = "maxDate"; d = date.getDate() + 7; } else if (option == "maxDate") { otherOption = "minDate"; d = date.getDate() - 7; } var m = date.getMonth(); var y = date.getFullYear(); edate = new Date(y, m, d); dates.not(this).datepicker("option", option, date); dates.not(this).datepicker("option", otherOption, edate); } }); }); </code></pre> <p>Initial Idea from: <a href="http://jqueryui.com/demos/datepicker/#date-range" rel="nofollow">http://jqueryui.com/demos/datepicker/#date-range</a></p> <p><strong>Note:</strong> You would also need an option to reset/clear the dates (i.e. if a user chooses a 'From date', the 'To date' becomes limited. After choosing a 'From date' if the user now chooses a 'To date', the From date also gets limited. You need to have a clear option to allow the user to choose a different "From" date now.)</p>
42,846
<p>A program that I work on assumes that the UUID generated by the Windows RPC API call UuidCreateSequential() contains the MAC address of the primary ethernet adapter. Is this assumption correct or should I use a different method to get the MAC address?</p>
<p>I wouldn't rely on this - the only reason that UuidCreateSequential has the MAC address is it's trying to guarantee that the UUID is unique across the network. Plus, why would you use such a weird way to get a MAC address? Use WMI and <em>actually</em> ask for the MAC address instead of a side-effect of a UUID creation function. </p>
<p>Only a version 1 UUID contains a MAC address, and only if the original generator had access to the MAC address to begin with. If the original generator didn't have access to a MAC address, it would have used 6 random bytes sourced from a cryptographically secure random number generator, as per section 4.5 of RFC 4122. Because of this, there is no guarantee that the MAC address given in a UUID is actually a MAC address.</p> <p>In most cases, the only reason anyone would ever need to parse out the MAC address from a UUID is for forensic purposes. See for example the UUIDs embedded in the Word document payload for the Melissa virus. Investigators extracted the MAC address from these IDs and matched it to the MAC address of the suspect's primary network adapter.</p> <p>If you are trying to obtain the MAC address of your own computer, there are far better ways of going about this.</p>
42,740
<p>We recently switched some of our sites from deflate to gzip and noticed a significant increase in cpu load on our servers.</p>
<p>Is it possible that you are experiencing cache miss? That is, compressed content is sometimes cached compressed but switching compression schemes would (or at least should) invalidate that cache causing dramatically increased cpu utilization. Did you try switching it back?</p>
<p>gzip is, basically, deflate with some additional headers. So there should not be a significant performance hit. Now, maybe your deflate tool is just more efficient than your gzip tool. Are you using the same tool for both compressions or two different ones?</p>
25,956
<p>How can I drop all tables whose names begin with a given string? </p> <p>I think this can be done with some dynamic SQL and the <code>INFORMATION_SCHEMA</code> tables.</p>
<p>You may need to modify the query to include the owner if there's more than one in the database.</p> <pre class="lang-sql prettyprint-override"><code>DECLARE @cmd varchar(4000) DECLARE cmds CURSOR FOR SELECT 'drop table [' + Table_Name + ']' FROM INFORMATION_SCHEMA.TABLES WHERE Table_Name LIKE 'prefix%' OPEN cmds WHILE 1 = 1 BEGIN FETCH cmds INTO @cmd IF @@fetch_status != 0 BREAK EXEC(@cmd) END CLOSE cmds; DEALLOCATE cmds </code></pre> <p>This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run.</p> <p>I know that if I were going to do this against a production database, I'd be as careful as possible.</p> <p><strong>Edit</strong> Code sample fixed.</p>
<p>Try following code:</p> <pre><code>declare @TableLst table(TblNames nvarchar(500)) insert into @TableLst (TblNames) SELECT 'DROP TABLE [' + Table_Name + ']' FROM INFORMATION_SCHEMA.TABLES WHERE Table_Name LIKE 'yourFilter%' WHILE ((select COUNT(*) as CntTables from @TableLst) &gt; 0) BEGIN declare @ForExecCms nvarchar(500) = (select top(1) TblNames from @TableLst) EXEC(@ForExecCms) delete from @TableLst where TblNames = @ForExecCms END </code></pre> <p>This SQL script is executed without using a <strong>cursor</strong>.</p>
2,640
<p>The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). </p> <p>Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a &lt;textarea&gt; control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. </p> <p>For more information on the bug, <a href="http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html" rel="noreferrer">read it here</a>.</p> <p>This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. </p> <p>Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.</p>
<p>I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]</p> <p><a href="http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html" rel="nofollow noreferrer">http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html</a>.</p> <p>You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.</p> <pre> &lt;div onkeypress="return FireDefaultButton(event, '&lt;%= aspButtonID.ClientID %&gt;')"&gt; (your form goes here) &lt;/div&gt; </pre> <p>Here's the function.</p> <pre> function FireDefaultButton(event, target) { // srcElement is for IE var element = event.target || event.srcElement; if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase())) { var defaultButton; defaultButton = document.getElementById(target); if (defaultButton && "undefined" != typeof defaultButton.click) { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } return true; } </pre>
<p>For this particular issue, the reason is because javascript generated by ASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in FireFox (use event.target instead):</p> <pre><code>function WebForm_FireDefaultButton(event, target) { if (!__defaultFired &amp;&amp; event.keyCode == 13 &amp;&amp; !(event.srcElement &amp;&amp; (event.srcElement.tagName.toLowerCase() == "textarea"))) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton &amp;&amp; typeof(defaultButton.click) != "undefined") { __defaultFired = true; defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } } return true; } </code></pre> <p>If we change the first 2 lines into:</p> <pre><code>function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (!__defaultFired &amp;&amp; event.keyCode == 13 &amp;&amp; !(element &amp;&amp; (element.tagName.toLowerCase() == "textarea"))) { </code></pre> <p>Put the changed code in a file and then do</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { ClientScript.RegisterClientScriptInclude("js1", "JScript.js"); } </code></pre> <p>Then it will work for both IE and FireFox.</p> <p>Source:</p> <p><a href="http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html" rel="nofollow noreferrer">http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html</a></p>
7,264
<p>The error I'm getting:</p> <pre><code>in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable </code></pre> <p>Cliff notes:</p> <ul> <li>trying to include framework</li> <li>doesn't want to link</li> </ul> <p>More detail: I'm developing for a <em>mobile device... hint, hint</em> using Xcode and I'm trying to make my own custom framework which I can include from another application. So far, I've done the following:</p> <ol> <li>Create a new project; an iPhone OS window based app.</li> <li>Go to target info-> under packaging, change the wrapper extension from app to framework</li> <li>Go to Action->new build phase -> copy headers. Change roles of headers to 'public'</li> <li>From my application, I add the framework to the frameworks group.</li> </ol>
<p>Apple clearly said that you can <strong>not</strong> use dynamic libraries on their mobiles. And a private framework is just this.</p> <p>You can, however, use static libraries.</p>
<p>I haven't tried it for so called <em>mobile device</em>, but I would guess its very similar to the method for a regular Cocoa application. Check out this tutorial:</p> <p><a href="http://rentzsch.com/cocoa/embeddedFrameworks" rel="nofollow noreferrer">Embedded Cocoa Frameworks</a></p>
10,385
<p>Any one has any idea how to map an infopath field to a sharepoint column of type choice? The infopath field is a repeating field, so the user can select multiple options, I want to be able to map those to the choice field in sharepoint. Any ideas?</p> <p>update: What I'm trying to do is the following. I have a choice column in sharepoint which allows user entered values. In infopath, I have a repeating field. I'm binding the field to a dropdownlist. The dropdownlist gets filled by a webservice. This dropdownlist is in a repeating section, so the user can choose to select from multiple dropdownlists. So lets say the user adds 2 dropdownlists, and selects an option from each dropdownlist. I want to be able to add those selections as choices in the sharepoint choice column.</p>
<p>SharePoint list is a flat structure, and because of that Infopath does not allow you map repeating sections to list columns. </p> <p>You might wanna consider the following workaround:</p> <ul> <li>Store Infopath form to one library (along with non-repeating fields)</li> <li>Use one of <a href="http://www.codeplex.com/SPDActivities" rel="nofollow noreferrer">these</a> custom activities to extract data from repeating table and copy it to another list</li> <li>Create a custom data view or a web part to display these items (if necessary)</li> </ul> <p>This approach can be useful if you need to do some additional tasks with the repeating data.</p>
<p>Is it not similar to Create a Repeating Cascading List from:</p> <ul> <li><a href="http://www.infopathdev.com/blogs/greg/archive/2005/07/14/Create-a-Repeating-Cascading-List-from-a-Flat-Data-Source.aspx" rel="nofollow noreferrer">a Flat Data Source</a> or</li> <li><a href="http://www.infopathdev.com/blogs/greg/archive/2005/07/14/Create-a-Repeating-Cascading-List-from-a-Hierarchical-Data-Source.aspx" rel="nofollow noreferrer">a Hierarchical Data Source</a> ?</li> </ul> <p>If it is, may be those two articles may give you some pointers.</p>
46,765
<p>I want to assign the decimal variable &quot;trans&quot; to the double variable &quot;this.Opacity&quot;.</p> <pre class="lang-cs prettyprint-override"><code>decimal trans = trackBar1.Value / 5000; this.Opacity = trans; </code></pre> <p>When I build the app it gives the following error:</p> <blockquote> <p>Cannot implicitly convert type decimal to double</p> </blockquote>
<p>An explicit cast to <code>double</code> like this isn't necessary:</p> <pre><code>double trans = (double) trackBar1.Value / 5000.0; </code></pre> <p>Identifying the constant as <code>5000.0</code> (or as <code>5000d</code>) is sufficient:</p> <pre><code>double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; </code></pre>
<p><strong>Try the following code:</strong></p> <h3>Decimal values</h3> <pre><code>decimal d1 = 3234.3434m; </code></pre> <h3>Convert to double</h3> <pre><code>double r1 = Decimal.ToDouble(d1); </code></pre>
2,230
<p>How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this <em>almost</em> works for me:</p> <pre><code>proc1 = subprocess.Popen(['python','mytest.py']) proc2 = subprocess.Popen(['python','mytest.py']) proc1.wait() print "1 finished" proc2.wait() print "2 finished" </code></pre> <p>The problem is that when <code>proc2</code> finishes before <code>proc1</code>, the parent process will still wait for <code>proc1</code>. On Unix one would use <code>waitpid(0)</code> in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?</p>
<p>It might seem overkill, but, here it goes:</p> <pre><code>import Queue, thread, subprocess results= Queue.Queue() def process_waiter(popen, description, que): try: popen.wait() finally: que.put( (description, popen.returncode) ) process_count= 0 proc1= subprocess.Popen( ['python', 'mytest.py'] ) thread.start_new_thread(process_waiter, (proc1, "1 finished", results)) process_count+= 1 proc2= subprocess.Popen( ['python', 'mytest.py'] ) thread.start_new_thread(process_waiter, (proc2, "2 finished", results)) process_count+= 1 # etc while process_count &gt; 0: description, rc= results.get() print "job", description, "ended with rc =", rc process_count-= 1 </code></pre>
<p>you can use <a href="https://psutil.readthedocs.io/en/latest/" rel="nofollow noreferrer">psutil</a></p> <pre><code>import psutil with psutil.Popen([&quot;python&quot;, &quot;mytest.py&quot;]) as proc1, psutil.Popen( [&quot;python&quot;, &quot;mytest.py&quot;] ) as proc2: gone, alive = psutil.wait_procs([proc1, proc2], timeout=3) </code></pre> <p>'gone' and 'alive' are lists indicating which processes are gone and which ones are still alive.</p> <p>Optionally you can specify a callback which gets invoked every time one of the watched processes terminates:</p> <pre><code>def on_terminate(proc): print &quot;%s terminated&quot; % proc gone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate) </code></pre>
12,589
<p>We're building a text templating engine out of a custom HttpModule that replaces tags in our HTML with whole sections of text from an XML file.</p> <p>Currently the XML file is loaded into memory as a string/string Dictionary so that the lookup/replace done by the HttpModule can be performed very quickly using a regex.</p> <p>We're looking to expand the use of this though to incorperate larger and larger sections of replaced text and I'm concerned over keeping more verbose text in memory at one time as part of the Dictionary, especially as we use ASP.NET caching for many uses as well.</p> <p>Does anyone have a suggestion for a more efficient and scalable data structure/management strategy that we could use?</p> <p><b>UPDATE:</b> In response to Corbin March's great suggestion below, I don't think this is a case of us going down a 'dark road' (although I appreciate the concern). Our application is designed to be reskinned completely for different clients, right down to text anywhere on the page - including the ability to have multiple languages. The technique I've described has proven to be the most flexible way to handle this.</p>
<p>The amount of memory you are using is going to be roughly the same as the size of the file. The XML will have some overhead in the tags that the Dictionary will not, so it's a safe estimate of the memory requirements. So are you talking about 10-50 MB or 100-500 MB? I wouldn't necessarily worry about 10 to 50 MB.</p> <p>If you are concerned, then you need to think about if you really need to do the replacements everytime the page is loaded. Can you take the hit of going to a database or the XML file once per page and then caching the output of the ASP.NET page and hold it for an hour? If so, consider using <a href="http://msdn.microsoft.com/en-us/library/06bh14hk.aspx" rel="nofollow noreferrer">Page Caching</a>.</p>
<p>A couple ideas:</p> <p>Compress your dictionary values. Check out Scott Hanselman's <a href="http://www.hanselman.com/blog/TheWeeklySourceCode35ZipCompressingASPNETSessionAndCacheState.aspx" rel="nofollow noreferrer">cache compressing article</a> to get the spirit of the exercise. If your dictionary keys are large, consider compressing those as well. </p> <p>Only load items from your XML file into memory when they're requested and attach an item expiration. If the expiration occurs without another request, unload the item. The idea is that some dictionary items are used less frequently so an IO hit for the infrequent items is acceptable. Obviously, the ASP.NET Cache does this for you - I'm assuming Cache is out-of-context by the time you're crunching your output.</p> <p>Just an opinion... but my spidersense warns me you may be going down a dark road. A huge part of ASP.NET is its templating features - master pages, page templates, user controls, custom controls, templated controls, resource schemes for internationalization. If at all possible, I'd try to solve your problem with these tools versus a text-crunching HttpModule.</p>
35,067
<p>I'm developing an MFC application and I've recently been searching for a good method to remove the icon from a Windows title bar, but retain the close button. The two obvious candidate solutions are turning off the system menu style or using the tool window style, but I would prefer not to disable the system menu or use the shrunken tool window title bar. Many MFC applications have this functionality, so I wonder: am I missing some standard way of doing this?</p>
<p>You can use <code>WM_NCRBUTTONDOWN</code> to detect if the user has right-clicked on your caption and then bring up the system menu.</p>
<p>what about getting rid of the system menu and then putting it back in another place yourseld (say next to the close button etc.)?</p>
3,132
<p>I have spent ages debugging this problem but I can't figure out what I am doing wrong.</p> <p>I have a Wanhao duplicator i3 (Prusa i3 clone) and until recently I used Wanhao's adapted version of the Cura slicer. But it's quite an old Cura version and I wanted to make use of the improved supports in the new Cura.</p> <p>Unfortunately it seems like I just can't get the infill in the newest Cura to work. I copied all the settings from my Wanhao branded Cura version and printed the same file.</p> <p><strong>This is the result:</strong></p> <p><a href="https://i.stack.imgur.com/RJPkN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJPkN.jpg" alt="Infill of tiny pillars"></a></p> <p>The infill is shaped like many tiny pillars. They are super fragile and while they do support material to be printed on top, they hardly withstand any pressure.</p> <p>I have gone through quite a few testing cubes each with some setting altered, but nothing seemed to help.</p> <p>It can't be the printers fault as I have successfully printed test cubes sliced with the old Cura in between (and not only once). Increasing temperature or slowing down the infill didn't help either. Neither did increasing flow rate or switching to triangular infill pattern. Also I have tried printing with all speeds set to 50mm/s and it still failed.</p> <p><strong>My standard settings</strong> <em>(from which I have created many test cubes with each cube having some settings tweaked)<strong></em>:</strong></p> <pre><code>Layer Height: 0.12 mm Init. Layer Height: 0.10 mm Wall Line Count: 2 Top Layers: 6 Bottom Layers: 4 Infill Line distance: 5 mm (used to be 20 % in old Cura, but this is very dense in the new Cura) Infill Pattern: Lines Infill Overlap Percentage: 20 % Printing Temperature: 200 °C Build Plate Temperature: 60 °C Retraction: Enabled, Distance: 2 mm, Speed: 60 mm/s Speeds: Print:60 mm/s, Infill: 60 mm/s, Outer Wall: 30 mm/s, Inner Wall: 60 mm/s, Top/Bottom: 40 mm/s, Travel: 100 mm/s, Initial Layer: 20 mm/s Combing Mode: All </code></pre>
<p>This problem is most commonly caused by infill speeds which are too high.</p> <p>Instead of printing lines, the filament is caught on one of the lines of the previous layer, leaves a blob there and only restarts extrusion when it hits the next line. Instead of extruding continuously the filament comes out in blobs at the locations where there's filament on the previous layer.</p> <p>You can have good infill up to some layer and suddenly start getting this problem as of some layer. When the problem occurs the next layer is more likely to show the problem. It's snowballing.</p>
<p>I am using the same printer (v1.2) with some upgrades and have been using the latest Ultimaker Cura (4.1) ever since they came out. For the first few prints I used an imported Ultimaker Cura profile, but after 3-4 bad prints I created a new profile from scratch, using a percentage for infill, with no problems at all.</p>
637
<p>I have come across a lot of optimization tips which say that you should mark your classes as sealed to get extra performance benefits.</p> <p>I ran some tests to check the performance differential and found none. Am I doing something wrong? Am I missing the case where sealed classes will give better results?</p> <p>Has anyone run tests and seen a difference?</p> <p>Help me learn :)</p>
<p>The JITter will sometimes use non-virtual calls to methods in sealed classes since there is no way they can be extended further.</p> <p>There are complex rules regarding calling type, virtual/nonvirtual, and I don't know them all so I can't really outline them for you, but if you google for sealed classes and virtual methods you might find some articles on the topic.</p> <p>Note that any kind of performance benefit you would obtain from this level of optimization should be regarded as last-resort, always optimize on the algorithmic level before you optimize on the code-level.</p> <p>Here's one link mentioning this: <a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx" rel="noreferrer">Rambling on the sealed keyword</a></p>
<p>Run this code and you'll see that sealed classes are 2 times faster:</p> <pre><code>class Program { static void Main(string[] args) { Console.ReadLine(); var watch = new Stopwatch(); watch.Start(); for (int i = 0; i &lt; 10000000; i++) { new SealedClass().GetName(); } watch.Stop(); Console.WriteLine("Sealed class : {0}", watch.Elapsed.ToString()); watch.Start(); for (int i = 0; i &lt; 10000000; i++) { new NonSealedClass().GetName(); } watch.Stop(); Console.WriteLine("NonSealed class : {0}", watch.Elapsed.ToString()); Console.ReadKey(); } } sealed class SealedClass { public string GetName() { return "SealedClass"; } } class NonSealedClass { public string GetName() { return "NonSealedClass"; } } </code></pre> <p>output: Sealed class : 00:00:00.1897568 NonSealed class : 00:00:00.3826678</p>
2,432
<p>What are the advantages and disadvantages of the Session Façade Core J2EE Pattern? </p> <p>What are the assumptions behind it? </p> <p>Are these assumptions valid in a particular environment? </p>
<p>Session Facade is a fantastic pattern - it is really a specific version of the Business Facade pattern. The idea is to tie up business functionality into discrete bundles - such as TransferMoney(), Withdraw(), Deposit()... So that your UI code is accessing things in terms of business operations instead of low level data access or other details that it shouldn't have to be concerned with.</p> <p>Specifically with the Session Facade - you use a Session EJB to act as the business facade - which is nice cause then you can take advantage of all the J2EE services (authentication/authorization, transactions, etc)...</p> <p>Hope that helps...</p>
<p>The main advantage of the Session Facade pattern is that you can divide up a J2EE application into logical groups by business functionality. A Session Facade will be called by a POJO from the UI (i.e. a Business Delegate), and have references to appropriate Data Access Objects. E.g. a PersonSessionFacade would be called by the PersonBusinessDelegate and then it could call the PersonDAO. The methods on the PersonSessionFacade will, at the very least, follow the CRUD pattern (Create, Retrieve, Update and Delete). </p> <p>Typically, most Session Facades are implemented as stateless session EJBs. Or if you're in Spring land using AOP for transactions, you can create a service POJO that which can be all the join points for your transaction manager. </p> <p>Another advantage of the SessionFacade pattern is that any J2EE developer with a modicum of experience will immediately understand you. </p> <p>Disadvantages of the SessionFacade pattern: it assumes a specific enterprise architecture that is constrained by the limits of the J2EE 1.4 specification (see Rod Johnson's books for these criticisms). The most damaging disadvantage is that it is more complicated than necessary. In most enterprise <em>web</em> applications, you'll need a servlet container, and most of the stress in a web application will be at the tier that handles HttpRequests or database access. Consequently, it doesn't seem worthwhile to deploy the servlet container in a separate process space from the EJB container. I.e. remote calls to EJBs create more pain than gain. </p>
11,449
<p>I use Netbeans IDE (6.5) and I have a SQLite 2.x database. I installed a JDBC SQLite driver from <a href="http://www.zentus.com/sqlitejdbc/" rel="nofollow noreferrer">zentus.com</a> and added a new driver in Nebeans services panel. Then tried to connect to my database file from Services > Databases using this URL for my database: </p> <p>jdbc:sqlite:/home/farzad/netbeans/myproject/mydb.sqlite</p> <p>but it fails to connect. I get this exception:</p> <pre><code>org.netbeans.modules.db.dataview.meta.DBException: Unable to Connect to database : DatabaseConnection[name='jdbc:sqlite://home/farzad/netbeans/myproject/mydb.sqlite [ on session]'] at org.netbeans.modules.db.dataview.output.SQLExecutionHelper.initialDataLoad(SQLExecutionHelper.java:103) at org.netbeans.modules.db.dataview.output.DataView.create(DataView.java:101) at org.netbeans.modules.db.dataview.api.DataView.create(DataView.java:71) at org.netbeans.modules.db.sql.execute.SQLExecuteHelper.execute(SQLExecuteHelper.java:105) at org.netbeans.modules.db.sql.loader.SQLEditorSupport$SQLExecutor.run(SQLEditorSupport.java:480) at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:572) [catch] at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:997) </code></pre> <p>What should I do? :(</p>
<p>The current version of Zentus SQLiteJDBC is v053, based on SQLite 3.6.1. It will not open a 2.x SQLite database. Perhaps you can use SQLite 2.x command line tool to .dump your database, and the Sqlite3 command line tool to .load it. The use Zentus SQLiteJDBC to access the new SQLite 3.x database.</p> <p>Alternatively, use a JDBC driver that supports SQLite 2 such as <a href="http://www.ch-werner.de/javasqlite/" rel="nofollow noreferrer">this one</a>.</p>
<p>It's againg me...</p> <p>I have made two mistakes during my first attempt. After setting <code>CLASSPATH</code> as a system variable (hope I didn’t broke smth else :)), putting <code>sqlite_jni.dll</code> to the <code>system32</code> folder and correcting <code>JDBC url</code> I have got a success :)</p> <p>I also have downloaded their <code>SQLite ODBC wrapper</code>. Installed it and made a connection to my <code>SQLite2</code> database via ordinary and <code>UTF8</code> based <code>ODBC</code> driver. I also used built in <code>NetBeans JDBC-ODBC</code> Bridge driver to be able to set up this connection.</p> <p>All three connections have been created but:</p> <ul> <li><p><code>ordinary ODBC driver</code>: I see text data in a wrong encoding. All other columns are displayed correctly</p></li> <li><p><code>UTF8 ODBC driver</code>: I don’t see text data at all. All other columns are displayed correctly</p></li> <li><p><code>JDBC driver</code>: I don’t see any column at all. <code>"Select * from my_any_table"</code> always returns an empty <em>single</em> column</p></li> </ul> <p>I have Russian based data in my database.</p> <p>So...currently I have returned to sqlite command line interface :))</p>
42,587
<p>I am wondering if it would it be feasible (at an affordable price) to 3D print a boat hull (small dimensions, maybe something like 60x40x20 cm). </p> <p>I am mostly concerned about: </p> <ul> <li><strong>durability</strong> (against salty water, UV rays, extreme temperatures (under the sun or in a cold ocean)</li> <li><strong>strength</strong> (the material should be able to resist some chocs and maybe a little bit of pressure if a wave was to smash on it).</li> <li><strong>waterproofness</strong></li> </ul> <p>Those characteristics should <em>last</em> during extended periods of time in water (at least several months, maybe more, about a year or two). </p> <p><strong>Is there any easily accessible 3D printing material that would match those characteristics?</strong> </p>
<p>You will really need to specify your constraints better because the short answer is <strong>yes, what you describe <em>is</em> entirely possible</strong>, but without knowing whether you are limited to a particular budget, process, or aesthetic, it's not a particularly useful answer.</p> <p>Some machines (ex. Stratasys Connex 1000) will print models up to 1m in length, so sure, you could print an entire hull with the dimensions you specify.</p> <p><strong>Pros</strong>:</p> <ul> <li>Monohull construction</li> <li>Excellent surface finish</li> <li>Many resin options are UV and salt water resistant with decent enough durability</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>Ridiculously expensive machine with decently expensive resins</li> <li>It will waste plenty of support material in printing (which means added cost too)</li> <li>Not really <em>easily</em> accessible, but some design studios will have them and will print things for you, for a cost</li> </ul> <p>Other machines (ex. Ultimaker 2 Extended) will print models up to 30cm along the vertical axis. It would require some assembly in the end, but you could segment your build and get a boat hull in the end.</p> <p><strong>Pros:</strong></p> <ul> <li>Easily accessible</li> <li>Fairly low cost (Maybe under \$1000 for the machine vs nearly \$1M and many filaments cost 1/10th that of polyjet resins or sintering powders)</li> <li>The materials themselves can be UV resistant and salt water resistant</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>Joinery and seams create passageways for water ingress, so you'd need secondary sealant</li> <li>The FDM process itself isn't always watertight, so you'd need sealant anyway</li> <li>Low interlayer adhesion limits the tensile strength along one axis and the shear strength in one plane, so you'd either need composite hull panels with varying print orientations (in which case, just do a composite layup instead) or a fairly careful analysis of principle hydrodynamic stresses</li> </ul> <p>There's significantly more to the discussion as well, but without really understanding your design constraints, it's difficult to give any concrete advice.</p>
<p>Probably feasible, Affordable or simple probably not. To start from an affordability perspective, kayaks normally weigh around 20 kg, they <a href="http://www.grassrootsengineering.com/blog/2014/03/" rel="nofollow noreferrer">kayak in the video mentioned in the other answer</a> weighs in at 30kgs. Assuming you print all your parts perfectly, your using \$15 a kg filament, and you use 25 kg of abs you are looking at a minimum of \$375 in material just to print the kayak. After this the cost would only go up because now you need the parts to fasten it all together, the seat ect... In other words, it will probably be no cheaper and a whole lot more time intensive then buying one.</p>
508
<p>I'm looking for a basic software for statistical analysis. Most important is simple and intuitive use, getting started "right out of the box". At least basic operations should be interactive. Free would be a bonus :) </p> <p>The purpose is analysis of data dumps and logs of various processes. </p> <ul> <li>Importing a comma/tab separated file</li> <li>sorting and filtering rows on conditions</li> <li>basic aggregates: count, average, deviation, regression, trend</li> <li>visualization - plotting the data,bin distribution etc.</li> </ul> <p>Excel fails (at least for me) for the filtering and re-combining data, I guess something like "Excel with SQL" would be nice. I've been using MS Access + Excel and copying around data before, but that's a pain.</p> <p>Do you have any recommendation?</p> <p><strong>Clarification</strong> I am not looking for a specific tool for IIS/web server logs, but various data end event logs (mostly from custom applications) with tab-separated values.</p>
<p>Specifically for Log file analysis I would recommend <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&amp;displaylang=en" rel="nofollow noreferrer">Microsoft's Log Parser</a>(free), which will allow you to run queries with basic aggregation against all types of text based files (and across sets of files), XML, CSV, Event Log, the Registry, file system, Active Directory, etc..</p> <p>There is also a free GUI build on top of it called <a href="http://www.lizardl.com/PageHtml.aspx?lng=2&amp;PageId=18&amp;PageListItemId=17" rel="nofollow noreferrer">Log Parser Lizard GUI</a> which makes it more user friendly and can do basic graphing etc.</p>
<p>I used <a href="http://www.tableausoftware.com/" rel="nofollow noreferrer">Tableau Software</a> at a previous gig, and it's pretty amazing - extremely intuitive and easy to use.</p> <p>Unfortunately it's also pricey.</p>
36,939
<p>When I run <code>get-user|get-member</code> in powershell with the exchange add-in I noticed there is no description property.</p> <p>Does anyone know if it has been renamed to something else or another way of accessing it? </p>
<p>If you aren't looking to change the description this should work:</p> <pre><code>[PS] C:\&gt;$ANR = "testuser@example.com" [PS] C:\&gt;$foo = [adsi]("LDAP://" + (get-user $ANR).DistinguishedName) [PS] C:\&gt;$foo.description My Description </code></pre> <p>If you are wanting to edit, you will need to get further into System.DirectoryServices &amp; look at how to write objects back to AD. It would likely be simpler to use quest of another package that does some wrapping. If you want to roll your own there are gobs of blogs on AD programming in Powershell.</p>
<p>get-user? do you mean get-qaduser from the quest cmdlet suite?</p> <p>if so, I believe not all properties are retrieved by default. There's an -Include parameter that lets you specify additional properties to retrieve from AD, IIRC.</p>
43,360
<p>I would like to provide the raw text referring to an environment variable to a command instead of evaluating the environment variable.</p> <p>I need this to configure BizTalk from the command line, for example:</p> <p>BTSTask.exe AddResource -ApplicationName:App1 -Type:System.BizTalk:BizTalkAssembly -Overwrite -Source:..\Schemas\bin\development\App1.Schemas.dll -Destination:%BTAD_InstallDir%\App1.Schemas.dll</p> <p>This command adds a resource to a BizTalk application. I want the destination to be %BTAD_InstallDir%\App1.Schemas.dll, however at present it is evaluating the environment variable (to nothing) and using \App1.Schemas.dll.</p> <p>Is it possible to escape or disable the evaluation of this environment variable while parsing\executing this command?</p> <p>I have tried escaping the first and both percentage characters with a carrot (^), however this did not stop the evaluation.</p> <p><b>[EDIT]</b> When I execute this at the command prompt it doesn't replace the environment variable, however it does when I run it as a script, any thoughts as to why this is different?</p>
<p>Did you try:</p> <pre><code>%%BTAD_InstallDir%% </code></pre> <p>in your script ?</p> <p>That should prevent the script to interpret the variable, and it would pass <code>%BTAD_InstallDir%</code> to the program.</p>
<p>Not sure if it's the same as my case, but i was troubling to use a batch file to create a script which has %temp% variable inside. The workaround i found: set test=%temp; echo {command} %test%%>>path_to_my_batch_file; Hope this helps someone:)</p>
41,867
<p>I'm looking for a groovy equivalent on .NET <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">http://boo.codehaus.org/</a></p> <p>So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.</p> <p>Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version? </p> <p><em>Edit</em>: Changed BOO to Boo</p>
<p>Information on this topic is now available on Wikipedia at: <a href="http://en.wikipedia.org/wiki/Search_data_structure" rel="noreferrer">Search data structure</a></p> <pre><code>+----------------------+----------+------------+----------+--------------+ | | Insert | Delete | Search | Space Usage | +----------------------+----------+------------+----------+--------------+ | Unsorted array | O(1) | O(1) | O(n) | O(n) | | Value-indexed array | O(1) | O(1) | O(1) | O(n) | | Sorted array | O(n) | O(n) | O(log n) | O(n) | | Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) | | Sorted linked list | O(n)* | O(1)* | O(n) | O(n) | | Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) | | Heap | O(log n) | O(log n)** | O(n) | O(n) | | Hash table | O(1) | O(1) | O(1) | O(n) | +----------------------+----------+------------+----------+--------------+ * The cost to add or delete an element into a known location in the list (i.e. if you have an iterator to the location) is O(1). If you don't know the location, then you need to traverse the list to the location of deletion/insertion, which takes O(n) time. ** The deletion cost is O(log n) for the minimum or maximum, O(n) for an arbitrary element. </code></pre>
<p>Amortized Big-O for hashtables:</p> <ul> <li>Insert - O(1)</li> <li>Retrieve - O(1)</li> <li>Delete - O(1)</li> </ul> <p>Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.</p>
14,942
<p>I've been thinking about alternatives to support materials for FDM printers, such as multi axis printers, dual head with soluble support material or printing in a gel/liquid which traps the material in place. Then it occurred to me that it might be possible to use the surface tension of a liquid to act as support material, same way small objects an insect can float on water even though they are heavier than water. This would also work great for cooling the extruded material. NOTE, we are still using a base plate like any other FDM printer, the only difference is that we have a water surface on the build plate which act as support material for large overhangs/steep angles. Everything is still attached to the build plate itself. We are not just printing stand alone parts on the surface of the water.</p> <p>After some highly scientific testing (Dropping an extruded string of PLA and placing a thin printed PLA part on the top of water) I've concluded that it is very feasible to float PLA on the surface tension of water. See picture for refence: <a href="https://i.stack.imgur.com/hikJO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hikJO.jpg" alt="PLA floating on surface tension"></a></p> <p>As you can see the floating structure is not at all trivial, it has both smooth round shapes and many sharp corners and holes in it, it was still extremely simple to get floating (I could drop it in from a height of 5 cm and it would still not break the surface tension). I also tried my best to investigate the effects of having structures underneath which might mess up the surface tension by placing larger PLA parts under the floating ring and trying to sink the ring by touching the underside and corners without any success at sinking the floating part. The only way I could get this part to sink was to push it down under water. Even if the surface tension was only broken half way along the ring the ring would still float. If you are thinking that the ring acted as a boat, that is not the case. I made sure to fill the small indents with water so that there were no pockets of air keeping it afloat.</p> <p>An even more encouraging result was another ring which was much thicker than it was wide. It still managed to float from the surface tension on the top side of the structure while the rest of it was submerged, accurately mimicking how the structure would actually be in the water during printing. See picture: <a href="https://i.stack.imgur.com/CPQSH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CPQSH.jpg" alt="Floating PLA ring thick "></a></p> <p>While this ring much easier to sink it was very resistant to being moved around. Again, basically the only way to sink it was to push it down under water, though as soon as the surface tension was broken on one side the whole ring quickly sank.</p> <p>All this leads me to my question: Does anyone know of a 3D printer which uses the surface tension of water as support material?</p> <p>I've searched around some on the web and I have not really found anything at all on the matter. I can foresee many potential problems (such as the extruder moving unsupported lines to the side when changing direction, layer adhesion, enclosed areas not filling with water etc) but the potential to print without support and only have to worry about keeping the newly extruded material in place could open up a lot of potential.</p> <p>UPDATE: I also tried 60 degree Celsius water (In case you need hot water to help with layer adhesion) and the surface tension still was able to float the thicker ring piece, though it felt like the surface tension was weaker.</p>
<h1>It's not feasible as described with normal FDM technology.</h1> <p>FDM bases on depositing material in a single path. This needs the deposited material to stay at the same XY coordinates for subsequent paths. And exactly here is where a floating piece fails: a free-floating piece is by its very definition unrestricted in XY, and would move to follow the nozzle.</p> <p>There are is also a whole plethora of factors that make this idea not feasible with the standard technology, meaning you'll have to develop the whole process, not just recombine two ideas. This means, you need to solve the following issues:</p> <h2>Heatsink Water</h2> <p>The extruded plastic needs to stay close to the melting point for some time, so it can fuse and bond with the lines next to them. However, water is known to be a very good method to get the heat away from items, as each liter of water can take about 4.1 MJ and only heat by one Kelvin. PLA on the other hand only stores about <a href="https://www.makeitfrom.com/material-properties/Polylactic-Acid-PLA-Polylactide" rel="nofollow noreferrer">1.8 MJ per Kilogram and Kelvin</a>.</p> <p>As a back of the envelope calculation, the temperature differential between room temperature and printing temperature PLA is about 180 Kelvin. Each gram of PLA is equivalent to 319.8 mm of filament (assuming a density of 1.3 g/cm³) or an extruded line of 9.6 kilometer length of 0.4 mm width and 0.2 mm height! That one gram contains about 324 Joules of energy that will be dispersed to the room temperature as it cools down. The water vat would not even get measurably warmer from sucking those few joules from a whole print!</p> <p>While this could be, in the right setup, be used to rapidly cool the print and <em>solidify</em> it in shape, the result of the rapid healing will most likely also impact print quality negatively, as cross-layer bonding is reduced.</p> <h2>Separator water</h2> <p>It is a well-known trick in creating polymer fibers to extrude underwater, as the water not only cools (see above) but also acts as a separator between the fibers, for the very short timeframe they are still malleable. This would also strike when printing into the water - there'll be a water layer in between the deposited filament, which would need to either get pressed out or cooked out before any cross-extrusion bonding can occur. As a result, just extruding into the water should result in a print that has almost no sturdiness, and might fall apart on touch.</p> <h2>Floating</h2> <p>Water has a density of 1 g/cm³. PLA has a density of 1.3 g/cm³. So a solid chunk of PLA sinks. But we don't print solid, we include air. Not just a few percent but infill is usually below 20 %. I have just printed a cube. After smoothing the surface by sanding, the cube is 29,7x29.9x29.9 mm. It has 3 parameters, 20% infill, 5 top and bottom layers with 0.2 mm layer height and comes to 11 grams. 11 g/26.55 cm³=0.41 g/cm³. Or in other words: the cube would float, about 40 % under the water surface, 60 % above the surface. The print would be, as a result, quickly break the water surface and get no support from the water at all.</p> <h2>Submerging the bed?</h2> <p>The main issue of a free-floating object (position) might be mitigated if there was a bed that would be submerged, but one would open a new can of worms, that might be even worse: the volume of the print and the accuracy of pumps.</p> <p>As the print goes on - quality be dammed - the print grows in volume. However, it doesn't grow entirely linear, depending on two factors:</p> <ul> <li>Is the print happening on/below the water surface? Then we will include water in the print. The volumetric growth of the print is in this case just the deposited filament. You'll need an overflow to compensate for the print growing and keep the water level in position.</li> <li>Is the print happening <em>just above</em> the surface of the water? then the displaced volume grows according to the depth of the print in the water. This would mitigate most of the problems from water preventing cross-bonding and causing floating, and even use the heatsink properties more beneficial, as any filament starting to sag will be stopped. It also would prevent water from being encased in the print. However, it does not use surface tension. Also, you'll need an overflow system to keep the water level steady.</li> </ul>
<p>I just had the same idea and googled it. My idea was to submerge the whole print platform in the water and lower it down so that the water level and the current layer line are always at the same height. Maybe a pump would be required to counteract the plastic displacing water. Completely floating parts of the print could have a tower with three contact points underneath to keep them in place without having to lift the whole structure.</p>
1,536
<p>Here are the errors:</p> <pre> $ perl ftper.pl Use of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5.1 /i686-cygwin/Tk/After.pm line 39. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. se of uninitialized value $id in delete at /usr/lib/perl5/vendor_perl/5.10/i686 cygwin/Tk/After.pm line 87. </pre> <p>Here is the Perl/Tk code:</p> <pre><code>#! /usr/bin/perl -w use strict; use Tk; use Tk::Scale; use File::DosGlob 'glob'; ##################################################################### # Define variables # ##################################################################### my $UserID; my $Password; my $BnsNode; my $Status_msg = "BUILD SCRIPT!"; ##################################################################### # Window variables # ##################################################################### my $mw; my $frmUserID; my $lblUserID; my $frmPassword; my $lblPassword; my $edtUserID; my $edtPassword; my $frmTop; my $frmBig; my $frmButtonLine; my $btnExit; my $btnSubmit; my $lblStatus; my $lblUnixNode; my $frmUnixNode; my $edtUnixNode; ################################################################# # Main Logic # ################################################################# init_mainwindow(); MainLoop; ################################################################# # init_mainwindow # ################################################################# sub init_mainwindow { $mw = MainWindow-&gt;new; $mw-&gt;title("BUILD"); $mw-&gt;resizable(100, 100); $mw-&gt;geometry("+175+100"); # Top Level frame for top section of form. $frmTop = $mw-&gt;Frame(-bd =&gt; 2, -relief =&gt; 'ridge') -&gt;pack(-side =&gt; 'top', -fill =&gt; 'x', -pady =&gt; 3); $frmUserID = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblUserID = $frmUserID-&gt;Label(-text =&gt; "Unix User ID:") -&gt;pack(-side =&gt; 'left'); $edtUserID = $frmUserID-&gt;Entry(-textvariable =&gt; \$UserID, -background =&gt; 'white')-&gt;pack(-side =&gt; 'left'); $frmUnixNode = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblUnixNode = $frmUserID-&gt;Label(-text =&gt; "BNS Number") -&gt;pack(-side =&gt; 'left'); $edtUnixNode = $frmUserID-&gt;Entry(-textvariable =&gt; \$BnsNode, -background =&gt; 'white')-&gt;pack(-side =&gt; 'left'); $frmPassword = $frmTop-&gt;Frame(-bd =&gt; 2)-&gt;pack( -side =&gt; 'top', -fill =&gt; 'x'); $lblPassword = $frmPassword-&gt;Label( -text =&gt; "Password: ")-&gt;pack(-side =&gt; 'left'); $edtPassword = $frmPassword-&gt;Entry(-textvariable =&gt; \$Password, -background =&gt; 'white', -show =&gt; "*") -&gt;pack(-side =&gt; 'left'); # Top Level frame for bottom section of form. $frmButtonLine = $mw-&gt;Frame(-bd =&gt; 2, -relief =&gt; 'ridge') -&gt;pack(-side =&gt; 'top', -fill =&gt; 'x', -pady =&gt; 3); $btnExit = $frmButtonLine-&gt;Button(-text =&gt; "Exit", -command =&gt; \&amp;close_mw, -width =&gt; 6)-&gt;pack( -side =&gt; 'right', -padx =&gt; 1); $btnSubmit = $frmButtonLine-&gt;Button(-text =&gt; "Run Script", -command =&gt; \&amp;execute_script, -width =&gt; 6)-&gt;pack( -side =&gt; 'right', -padx =&gt; 1); $lblStatus = $mw-&gt;Label(-textvariable =&gt; \$Status_msg, -borderwidth =&gt; 2, -relief =&gt; 'groove') -&gt;pack(-fill =&gt; 'x', -side =&gt; 'bottom'); $edtUserID-&gt;focus; } ##################################################################### # excute_script # ##################################################################### sub execute_script { unless (defined($UserID)) { update_status("Must enter a user id!"); $edtUserID-&gt;focus; return 0; } unless (defined($Password)) { update_status("Must enter a password!"); $edtPassword-&gt;focus; return 0; } update_status("$BnsNode ,$UserID "); } ##################################################################### # close_mw # ##################################################################### sub close_mw { $mw-&gt;destroy; } ##################################################################### # update_status # ##################################################################### sub update_status { my ($msg) = @_; $Status_msg = $msg; $lblStatus -&gt; update; } </code></pre>
<p>The error messages themselves are straightforward enough:</p> <blockquote> <p>Use of uninitialized value $id in hash element at ...Tk/After.pm line 39.</p> <p>Use of uninitialized value $id in delete at ...Tk/After.pm line 87.</p> </blockquote> <ul> <li>&quot;Use of uninitialized value&quot; means that you used a value with a value of <code>undef</code> (undefined).</li> <li><code>$id</code> is the name of the uninitialized variable.</li> <li>&quot;in hash element&quot; means that you used the value as hash key, e.g. <code>$h{$id}</code></li> <li>&quot;in delete&quot; means that you used the value as a hash key to be deleted. e.g. <code>delete $h{$id}</code></li> <li>&quot;...Tx/After.pm&quot; is the module where the error occurred.</li> <li>&quot;line 39&quot; and &quot;line 87&quot; are the line numbers (in the module) where the error occurred.</li> </ul> <p>Tk::After provides callback scheduling to Perl/Tk applications. Things like &quot;run this function after (or every) 500 ms.&quot; <code>$id</code> is the identifier for a specific callback on a widget.</p> <p>What do do about the warnings is harder. I don't see any explicit calls to Tk::After in the code you provided. It's possible that there's a bug in your Tk installation that's triggering the warning. I don't get any warnings when running it under Perl 5.10 with Tk 804.028.</p>
<p>I'm seeing the same issue with v5.10.0 and 804.028-1 on x86 Cygwin. Interestingly, the problem does not appear if the code is executed in the debugger, suggesting a difference in the way code is compiled/executed/??? inside and outside of the debugger.</p> <p>I suspect the underlying PerlTk code to be correct and that the problem lies in the Perl source/executable itself - who should this sort of thing be reported to?</p> <p>MikeP</p>
41,211
<p>I've been looking around for a good MVC framework for Python using PyGTK. I've looked at <a href="http://www.async.com.br/projects/kiwi/" rel="nofollow noreferrer">Kiwi</a> but found it a bit lacking, especially with using the Gazpacho Glade-replacement.</p> <p>Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.</p>
<p>In defense of Kiwi:</p> <ul> <li>Kiwi works fine with Glade3 instead of Gazpacho. (who forced you to use Gazpacho?)</li> <li>Kiwi is my first dependency for <em>any</em> PyGTK application commercial or open source.</li> <li>Kiwi is very actively maintained.</li> </ul> <p>I have generally got to a stage where I think its irresponsible to not use Kiwi in a PyGTK application. Perhaps you can tell us what you found "lacking" so we can improve the framework. #kiwi on irc.gimp.net (or the Kiwi mailing list).</p>
<p>PureMVC</p> <p><a href="http://trac.puremvc.org/PureMVC_Python" rel="nofollow noreferrer">http://trac.puremvc.org/PureMVC_Python</a></p>
40,060
<p>So I've got a <code>JPanel</code> implementing <code>MouseListener</code> and <code>MouseMotionListener</code>:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { public DisplayArea(Rectangle bounds, Display display) { setLayout(null); setBounds(bounds); setOpaque(false); setPreferredSize(new Dimension(bounds.width, bounds.height)); this.display = display; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; if (display.getControlPanel().Antialiasing()) { g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); } public void mousePressed(MouseEvent event) { System.out.println("mousePressed()"); mx1 = event.getX(); my1 = event.getY(); } public void mouseReleased(MouseEvent event) { System.out.println("mouseReleased()"); mx2 = event.getX(); my2 = event.getY(); int mode = display.getControlPanel().Mode(); switch (mode) { case ControlPanel.LINE: System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); } } public void mouseEntered(MouseEvent event) { System.out.println("mouseEntered()"); } public void mouseExited(MouseEvent event) { System.out.println("mouseExited()"); } public void mouseClicked(MouseEvent event) { System.out.println("mouseClicked()"); } public void mouseMoved(MouseEvent event) { System.out.println("mouseMoved()"); } public void mouseDragged(MouseEvent event) { System.out.println("mouseDragged()"); } private Display display = null; private int mx1 = -1; private int my1 = -1; private int mx2 = -1; private int my2 = -1; } </code></pre> <p>The trouble is, none of these mouse functions are ever called. <code>DisplayArea</code> is created like this:</p> <pre><code>da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); </code></pre> <p>I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything?</p>
<p>The <em>implements mouselistener, mousemotionlistener</em> just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor:</p> <pre><code>this.addMouseListener(this); this.addMouseMotionListener(this); </code></pre>
<p>I don't see anywhere in the code where you call addMouseListener(this) or addMouseMotionListener(this) for the DisplayArea in order for it to subscribe to those events. </p>
5,377
<p>I want to get other process' argv like ps.</p> <p>I'm using Mac OS X 10.4.11 running on Intel or PowerPC.</p> <p>First, I read code of ps and man kvm, then I wrote some C code.</p> <pre><code>#include &lt;kvm.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/sysctl.h&gt; #include &lt;paths.h&gt; int main(void) { char errbuf[1024]; kvm_t *kd = kvm_openfiles(_PATH_DEVNULL, NULL, _PATH_DEVNULL, O_RDONLY, errbuf); int num_procs; if (!kd) { fprintf(stderr, "kvm_openfiles failed : %s\n", errbuf); return 0; } struct kinfo_proc *proc_table = kvm_getprocs(kd, KERN_PROC_ALL, 0, &amp;num_procs); for (int i = 0; i &lt; num_procs; i++) { struct kinfo_proc *pproc = &amp;proc_table[i]; char **proc_argv = kvm_getargv(kd, pproc, 0); printf("%p\n", proc_argv); } kvm_close(kd); return 0; } </code></pre> <p>When ran on PowerPC, <code>kvm_getargv()</code> always returned NULL. When ran on Intel, <code>kvm_openfiles()</code> failed with error <code>/dev/mem: No such file or directory</code>.</p> <p>Of cource, I know about permission.</p> <p>Second, I tried sysctl.</p> <pre><code>#include &lt;sys/sysctl.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define pid_of(pproc) pproc-&gt;kp_proc.p_pid int main(void) { int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 }; int buffer_size; sysctl(mib, 4, NULL, &amp;buffer_size, NULL, 0); struct kinfo_proc *result = malloc(buffer_size); sysctl(mib, 4, result, &amp;buffer_size, NULL, 0); int num_procs = buffer_size / sizeof(struct kinfo_proc); for (int i = 0; i &lt; num_procs; i++) { struct kinfo_proc *pproc = result + i; int mib[3] = { CTL_KERN, KERN_PROCARGS, pid_of(pproc) }; // KERN_PROC_ARGS is not defined char *proc_argv; int argv_len; sysctl(mib, 3, NULL, &amp;argv_len, NULL, 0); proc_argv = malloc(sizeof(char) * argv_len); sysctl(mib, 3, proc_argv, &amp;argv_len, NULL, 0); fwrite(proc_argv, sizeof(char), argv_len, stdout); printf("\n"); free(proc_argv); } return 0; } </code></pre> <p>By fwrite, I got argv[0] but argv[1..] are not (environment variables are printed out.)</p> <p>There is no more way to do it?</p>
<p>Have you <a href="http://hubpages.com/hub/Interop_Forms_Toolkit_10" rel="nofollow noreferrer">looked at this?</a> Direct Link to <a href="http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx" rel="nofollow noreferrer">Product here</a></p>
<p>You do not need any third party tools out anything outside of what comes with Visual Studio if you mainly just want your VB6 program to cause a .NET Winform to be displayed.</p> <p>The approach we have taken here is to expose a C# wrapper class to VB6 by giving it a COM interface. This class has a few methods which can be called from VB6. They, in turn, instantiate and then show the Winform. It works well.</p>
25,824
<p>In a nutshell: I want to do the same thing "Dependency Walker" does.</p> <p>Is there any Win32 API function which can enumerate the dependencies of a EXE and/or DLL file?</p> <p>And is there any safe way to detect dependencies on ActiveX classes? (I doubt it is possible, but who knows ...)</p> <p><strong>EDIT:</strong> I'm aware of available tools which provide the same core functionality (Dependency Walker, ProcessExplorer, AQTime, ...) but I want to create my own program which dumps a text file containing the required modules. </p>
<p>It seems that Dependency Walker source code itself was given by Microsoft via MSJ. Please look at <em><a href="http://www.mail-archive.com/delphi@delphi.org.nz/msg11397.html" rel="nofollow noreferrer">Re: [DUG]: Dependency Walker</a></em>.</p> <p>You need to refer some other site to download since the link given in this mail trail is not working.</p> <p>Please check <em><a href="http://www.microsoft.com/msj/codeupdates.aspx" rel="nofollow noreferrer">MSJ Source Code Updates</a></em>: Since I don't have time, I have not checked whether it contains source code or only EXE foæes.</p>
<p>You can write a console app to wrap this up, create a PowerShell script with it or, like I usually end up doing since I only have to do it once in a blue moon, add the following to your code for a quick check:</p> <pre><code> private static HashSet&lt;string&gt; ReferencedAssemblies = new HashSet&lt;string&gt;(); ... OutputDependencies(Assembly.GetAssembly(typeof(Program)), 0); ... static void OutputDependencies(Assembly assembly, int indent) { if (assembly == null) return; Console.WriteLine(new String(' ', indent * 4) + assembly.FullName); if (!ReferencedAssemblies.Contains(assembly.FullName)) { ReferencedAssemblies.Add(assembly.FullName); foreach (var childAssembly in assembly.GetReferencedAssemblies()) { OutputDependencies(Assembly.Load(childAssembly.FullName), indent + 1); } } } </code></pre>
47,325
<p>I have an actionscript 2 application that I'd like to write automated UI testing for. For example I'd like to simulate a mouse click on a button and validate that a movie-clip is displayed at the right position and in the right color... Basically, UI testing. What are the best tools available or what is the desired approach? In JavaScript there is the selenium framework which does a nice job. Any similar tool for flash?</p>
<p>I know this is an old question, but this could be useful for future reference. There is a relatively new project</p> <p><a href="https://sourceforge.net/adobe/genie/wiki/Home/" rel="nofollow">Automated UI tester for ActionScript</a></p> <p>Its installation is pretty simple, and is described in the user guide step by step.</p>
<p>This may be of use</p> <p><a href="http://osflash.org/autotestflash" rel="nofollow noreferrer">Flash UI testing</a></p>
15,396
<p>It seems that nginx is used with php, ruby and python. </p> <p>Anyone has an example of how to setup nginx to work with jetty/tomcat in backend? </p> <p>Thanks.</p>
<p>nginx can forward via HTTP protocol, so just point it to the correct port and you're set:</p> <pre><code>server { location /anything { proxy_pass http://localhost:8080/whatever; } } </code></pre>
<p>nginx can forward via HTTP protocol, so just point it to the correct port and you're set:</p> <pre><code>server { location /anything { proxy_pass http://localhost:8080/whatever; } } </code></pre>
33,472
<p>I'm trying to run a c++ 2d array (pretty simple file) and it works but an error (at least I think it's an error) appears on the end.</p> <p>The code for the array is;</p> <pre><code>int myArray[10][10]; for (int i = 0; i &lt;= 9; ++i){ for (int t = 0; t &lt;=9; ++t){ myArray[i][t] = i+t; //This will give each element a value } } for (int i = 0; i &lt;= 9; ++i){ for (int t = 0; t &lt;=9; ++t){ cout &lt;&lt; myArray[i][t] &lt;&lt; "\n"; } </code></pre> <p>this prints the array properly but adds</p> <p>"0x22fbb0"</p> <p>on the end. What is this and why does it happen?</p>
<p>The error is not in the code you posted. do you have another cout afterwards?</p> <p>the 0x22.... looks like a memory address, so specifically you might have a line that reads</p> <p>cout &lt;&lt; myArray;</p> <p>somewhere.</p>
<p>The code you showed is fine so far. The address printed does not seem to be printed from that part of your code. I can imagine two situations for that.</p> <ul> <li>You accidentally print myArray[i] or myArray and forgot to apply the other index. As an array value converts to the address of its first element, it causes an address being printed.</li> <li>You accidentally print cout itself like cout &lt;&lt; cout. cout has an implicit conversion to a pointer type (it is used to check for sane state like in <code>if(cout) { ... }</code>) and this will cause an address being printed too.</li> </ul> <p>It could be a totally other situation. Can you paste the code that appears after the two loops?</p>
47,006
<p>Even though <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-May/007896.html" rel="noreferrer">Python</a> and <a href="http://www.reddit.com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/" rel="noreferrer">Ruby</a> have one kernel thread per interpreter thread, they have a global interpreter lock (GIL) that is used to protect potentially shared data structures, so this inhibits multi-processor execution. Even though the portions in those languajes that are written in C or C++ can be free-threaded, that's not possible with pure interpreted code unless you use multiple processes. What's the best way to achieve this? <a href="http://blogs.codehaus.org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads.html" rel="noreferrer">Using FastCGI</a>? Creating a <a href="http://blog.innerewut.de/files/images/stage_2.png" rel="noreferrer">cluster or a farm</a> of virtualized servers? Using their Java equivalents, JRuby and Jython?</p>
<p>I'm not totally sure which problem you want so solve, but if you deploy your python/django application via an apache prefork MPM using mod_python apache will start several worker processes for handling different requests.</p> <p>If one request needs so much resources, that you want to use multiple cores have a look at <a href="http://pyprocessing.berlios.de/" rel="nofollow noreferrer">pyprocessing</a>. But I don't think that would be wise.</p>
<p>For Python, the <a href="http://pyprocessing.berlios.de/" rel="nofollow noreferrer">PyProcessing</a> project allows you to program with processes much like you would use threads. It is included in the standard library of the recently released 2.6 version as <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow noreferrer"><code>multiprocessing</code></a>. The module has many features for establishing and controlling access to shared data structures (queues, pipes, etc.) and support for common idioms (i.e. managers and worker pools).</p>
5,783
<p>I use VS6 and ATL with CServiceModule to implement a custom windows service. In case of a fatal error service should shut itself down. Since CServiceModule is available via _Module variable in all files I thought of something like this to cause CServiceModule::Run to stop pumping messages and shut itself down</p> <pre><code>PostThreadMessage(_Module.dwThreadID, WM_QUIT, 0, 0); </code></pre> <p>Is this correct or you have better idea ?</p>
<p>What you describe is called writing a COM addin. You need to create an automation DLL and implement the <a href="http://msdn.microsoft.com/en-us/library/aa155640(office.10).aspx#comaddins_idtextens2" rel="noreferrer"><code>IDTExtensibility2</code></a> interface. You will then receive the Excel <code>Application</code> interface as a parameter to the <code>OnConnection</code> method.</p> <p>You will also need to <a href="http://msdn.microsoft.com/en-us/library/aa155640(office.10).aspx#comaddins_registration" rel="noreferrer">register</a> your DLL as an addin so Excel will automatically load it.</p> <p><strong>EDIT:</strong> Forgot to mention: You might want to take a look at <a href="http://www.add-in-express.com/add-in-delphi/" rel="noreferrer">Add-in Express</a>. Their framework and components make getting started with the creation of Office addins ridiculuously easy. You definitely won't have to bother with the details of <code>IDTExtensibility2</code>. All that comes with a (well-justified) price tag, though.</p>
<p>I do not know much about Office, but I guess you should use COM/ActiveX. Then you also get your IDispatch. See <a href="http://delphi.about.com/od/comoleactivex/OLE_COM_DCOM_Automation_ActiveX_Delphi_knowledge_base.htm" rel="nofollow noreferrer">http://delphi.about.com/od/comoleactivex/OLE_COM_DCOM_Automation_ActiveX_Delphi_knowledge_base.htm</a></p>
44,737
<p>I have a connection to a Microsoft SQL Server and want the change the connection authenticated user. Is it possible to do it without closing and reopening the connection?</p> <p>The ideal is something like Oracle <a href="http://www.techonthenet.com/oracle/roles.php" rel="nofollow noreferrer">set role</a> feature. </p> <p>I'd love if the solution also works for SQL Server 2000. </p>
<p>You might want to take a look at app roles (sp_setapprole), but you must be aware of consequences being that once the context is changed (e.g. the role is set), it can't be reverted with SQL Server 2000 (it's possible with 2005). The result of this is that the connection is effectively useless when closed in your code, e.g. it can't be returned to the pool and reused, which leads to scalability issues.</p> <p>Otherwise it is not possible to change the security context once it has been established.</p>
<p>Depending on what you are doing, EXECUTE AS may help you out here. This allows you to execute SQL in the context of another user in a similar fashion to the RUN AS available from the Windows shell. The profiler and audit tracing in SQL Server allows you to see both the original user and which context a statement is run under.</p> <p>EXECUTE AS USER = 'newuser'; SELECT ... &lt;-- SQL code from under the context of newuser REVERT;</p> <p>Note: This is not available under SQL Server 2000 and was added because of requests like yours. </p>
44,847
<p>I'm using the Lengauer and Tarjan algorithm with path compression to calculate the dominator tree for a graph where there are millions of nodes. The algorithm is quite complex and I have to admit I haven't taken the time to fully understand it, I'm just using it. Now I have a need to calculate the dominator trees of the direct children of the root node and possibly recurse down the graph to a certain depth repeating this operation. I.e. when I calculate the dominator tree for a child of the root node I want to pretend that the root node has been removed from the graph.</p> <p>My question is whether there is an efficient solution to this that makes use of immediate dominator information already calculated in the initial dominator tree for the root node? In other words I don't want to start from scratch for each of the children because the whole process is quite time consuming.</p> <p>Naively it seems it must be possible since there will be plenty of nodes deep down in the graph that have idoms just a little way above them and are unaffected by changes at the top of the graph.</p> <p>BTW just as aside: it's bizarre that the subject of dominator trees is "owned" by compiler people and there is no mention of it in books on classic graph theory. The application I'm using it for - my FindRoots java heap analyzer - is not related to compiler theory.</p> <p>Clarification: I'm talking about directed graphs here. The "root" I refer to is actually the node with the greatest reachability. I've updated the text above replacing references to "tree" with "graph". I tend to think of them as trees because the shape is <em>mainly</em> tree-like. The graph is actually of the objects in a java heap and as you can imagine is reasonably hierarchical. I have found the dominator tree useful when doing OOM leak analysis because what you are interested in is "what keeps this object alive?" and the answer ultimately is its dominator. Dominator trees allow you to &lt;ahem&gt; see the wood rather than the trees. But sometimes lots of junk floats to the top of the tree so you have a root with thousands of children directly below it. For such cases I would like to experiment with calculating the dominator trees rooted at each of the direct children (in the original graph) of the root and then maybe go to the next level down and so on. (I'm trying not to worry about the possibility of back links for the time being :)</p>
<p><a href="http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/lengauer_tarjan_dominator.htm" rel="noreferrer"><code>boost::lengauer_tarjan_dominator_tree_without_dfs</code></a> might help.</p>
<p>I do not fully understand your question, but it seems to me you want to have some incremental update feature. I researched a while ago what algorithms are their but it seemed to me that there's no known way for large graphs to do this quickly (at least from a theoretical standpoint). </p> <p>You may just search for "incremental updates dominator tree" to find some references. </p> <p>I guess you are aware <a href="http://www.eclipse.org/mat/" rel="nofollow noreferrer">the Eclipse Memory Analyzer</a> does use dominator trees, so this topic is not completely "owned" by the compiler community anymore :)</p>
31,054
<p>I recently learned about the basic structure of the .docx file (it's a specially structured zip archive). However, docx is not formated like a doc.</p> <p>How does a doc file work? What is the file format, structure, etc?</p>
<p>The full format for binary .doc files is documented in <a href="http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Word97-2007BinaryFileFormat(doc)Specification.pdf" rel="noreferrer">this pdf</a> from (<a href="http://en.wikipedia.org/wiki/DOC_(computing)" rel="noreferrer">the Wikipedia article on .doc</a>)</p>
<p>There's Microsoft Word's .doc and then there's plain text .doc. It sounds like you're wondering about the proprietary Microsoft format.</p> <p>From <a href="http://en.wikipedia.org/wiki/DOC_(computing)" rel="nofollow noreferrer">Wikipedia</a>:</p> <blockquote> <p>The DOC format varies among Microsoft Office Word Formats. Word versions up to 97 used a different format from Microsoft Word version between 97 and 2003.</p> </blockquote> <p>It wasn't until Word 2007 where <a href="http://en.wikipedia.org/wiki/DOCX" rel="nofollow noreferrer">.docx</a>, although a packaged file, is not necessarily a .zip archive. It is a structured XML document.</p>
15,182
<p>I've an image that is wrapped in an anchor tag that, through jQuery, triggers an action somewhere else on the page. When I click on the image, two tiny 1px by 1px boxes show up in the upper and lower left corners of the image.</p> <p>My CSS styles explicitly state no borders for images: <code>a,img { border: 0; }</code></p> <p>It also seems to only happen in Firefox 3. Anyone else had this issue?</p> <hr> <p>Here's a screenshot of the left part of the image (the graphic has a white background):</p> <p><a href="http://neezer.net/img/ss.png" rel="nofollow noreferrer">alt text http://neezer.net/img/ss.png</a></p> <p>It's not the background, or the border of any other element. I checked.</p>
<p>Browsers (and Dashcode) provide an XMLHttpRequest object which can be used to make HTTP requests from JavaScript:</p> <pre><code>function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); // false for synchronous request xmlHttp.send( null ); return xmlHttp.responseText; } </code></pre> <p>However, synchronous requests are discouraged and will generate a warning along the lines of:</p> <blockquote> <p>Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), <strong>synchronous requests on the main thread have been deprecated</strong> due to the negative effects to the user experience.</p> </blockquote> <p>You should make an asynchronous request and handle the response inside an event handler.</p> <pre><code>function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 &amp;&amp; xmlHttp.status == 200) callback(xmlHttp.responseText); } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } </code></pre>
<p>You can do it with pure JS too:</p> <pre><code>// Create the XHR object. function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // XDomainRequest for IE. xhr = new XDomainRequest(); xhr.open(method, url); } else { // CORS not supported. xhr = null; } return xhr; } // Make the actual CORS request. function makeCorsRequest() { // This is a sample server that supports CORS. var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html'; var xhr = createCORSRequest('GET', url); if (!xhr) { alert('CORS not supported'); return; } // Response handlers. xhr.onload = function() { var text = xhr.responseText; alert('Response from CORS request to ' + url + ': ' + text); }; xhr.onerror = function() { alert('Woops, there was an error making the request.'); }; xhr.send(); } </code></pre> <p>See: for more details: <a href="https://www.html5rocks.com/en/tutorials/cors/" rel="nofollow noreferrer">html5rocks tutorial</a></p>
30,745
<p>I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this?</p>
<p>TortoiseSVN has an export function. This will create the entire SVN tree elsewhere without the <code>.svn</code> folders.</p> <p>Also, a lot of FTP clients have filtering, which you can add <code>.svn</code> to just in case you forget one day.</p>
<p>Do <code>svn export &lt;url&gt;</code> to export a clean copy without .svn folders.</p>
19,404
<p>I have a <code>POCO</code> object that goes 4 levels deep contained objects (like <code>Invoice</code> has line items that have taxes that have gl entries), and I want to turn the entire thing into a <code>DataSet</code>. So there would be 4 tables, each with constraints being applied to the parent table.</p> <p>Does anyone know of something that would automated this?</p>
<p>How do you populate this object? If it's from the database, there are two methods to structure your query such that the dataset is populated with separate, automatically related DataTable-s. Old and probably not supported anymore is the <a href="http://support.microsoft.com/kb/189657" rel="nofollow">SHAPE command</a>. A better and more recent approach is to use <a href="http://dotnetslackers.com/articles/ado_net/MappingDataSetToXMLAndBackwards.aspx" rel="nofollow">FOR XML</a>. </p> <p>The later approach will also allow you to load a dataset from XML-serialized representation of your `POCO' (not FOR XML, but loading XML into DataSet)</p>
<p>Better JSON serialize your POCO object and then deserialize it to Dataset. Hope this will do.</p>
27,072
<p>Actually my question is all in the title.<br> Anyway:<br> I have a class and I use explicit constructor: <br>.h<br></p> <pre><code>class MyClass { public: explicit MyClass(const string&amp; s): query(s) {} private: string query; } </code></pre> <p>Is it obligatory or not to put <b>explicit</b> keyword in implementation(.cpp) file?</p>
<p>No, it is not. The <code>explicit</code> keyword is only permitted in the header. My gcc says:</p> <pre><code>test.cpp:6: error: only declarations of constructors can be 'explicit' </code></pre> <p>for the following code:</p> <pre><code>class foo { public: explicit foo(int); }; explicit foo::foo(int) {} </code></pre>
<p>Re the followup question (which you really should have submitted as a separate question), the initialization list goes with the constructor's implementation (its function body), which might be in either the header or the cpp file.</p>
34,475
<p>For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is:</p> <pre><code>WebBrowser webControl = new WebBrowser(); webControl.DocumentText = html; HtmlDocument doc = webControl.Document; </code></pre> <p>There are two problems:</p> <ol> <li>Requires the <code>WebBrowser</code> object! </li> <li>This can't be used with multiple threads; I need something that would work on different thread (other than the main thread).</li> </ol> <p>Any ideas?</p>
<p>I did a search to GooglePlex for HTML and I found <a href="https://html-agility-pack.net/" rel="noreferrer">Html Agility Pack</a> I do not know if it's for that or not, I am downloading it right now to give a try.</p>
<p>This is an old question. Now there are:</p> <ul> <li><a href="https://github.com/zzzprojects/html-agility-pack" rel="nofollow noreferrer">The HTML Agility Pack</a> (You have already found this)</li> <li><a href="https://github.com/jamietre/CsQuery" rel="nofollow noreferrer">CsQuery</a>, a .Net jQuery port, which will be great for jQuery developers</li> </ul>
28,717
<p>I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista:</p> <pre><code>"Decryption failed. Key not valid for use in specified state." </code></pre> <p>As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update).</p> <p>More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off.</p> <p>Anyone seen this one before?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa380882.aspx" rel="nofollow noreferrer">CryptUnprotectData function</a> documentation states that it usually only works when the user has the same logon credentials as the encrypter.</p> <p>This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens.</p> <p>Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers?</p>
<p>Nice. Hopefully this is my bone-head move of the week! ;-)</p> <blockquote> <p>This suggests to me that maybe the key is tied to the user's current token.</p> </blockquote> <p>That was it. Turns out I was using encrypted data from another machine (the XP one) and trying to decrypt on the Vista machine.</p> <p>As the MSDN documentation states:</p> <blockquote> <p>Usually, only a user with the same logon credentials as the encrypter can decrypt the data. In addition, <strong>the encryption and decryption must be done on the same computer.</strong></p> </blockquote> <p>Once I re-encrypted the data on the Vista machine, decryption works as expected.</p> <p>Thanks.</p>
8,977
<p>I'm an absolute n00b into the java platform I would like to know whether I need to change anything in my code to get the benefits of 64bit JRE ? </p> <p>or is it something like when I initiate it with "java -d64" its gonna run in some turbo mode?</p> <p>Your help is highly appreciated</p>
<p>My previous version, while not false, was a quickly written oversimplification.</p> <p>Changing from 32 to 64 bits will not automatically make your application run faster, it may in some cases lead to the opposite. On the "negative" side Doing de-referencing of memory pointers in the JVM can take a longer time with 64 bit pointers than 32 bit. A full garbage collect and compaction of a 16 GB heap will likely take a longer time than with a 2 GB heap. </p> <p>On the positive side: There 64 bit processor instructions that are more effective than the 32 bit ones. 64 bit JVM will allow you to have a heap size 2^32 times bigger than the, slightly less than, 4 GB one you can get with 32 bit. (If you can afford to buy that amount of RAM) Some JVMs can work with compressed references if you have a heap size less than 4 GB, giving you the advantage of 64 bit instructions without having to pay the 64 bit de-referencing price. </p> <p>If you have a good JVM I would go to 64 bits no matter the heap size, just be prepared that you may have to take a performance hit for having a really big heap.</p>
<p>I have found that 64-bit JVMs have been slower than 32-bit versions. However with the latest version Java 6 update 14 I have seen many of my tests are marginally faster with the 64-bit version vs the 32-bit. Either way there is only 5% to 10% difference.</p> <p>Whether your program uses a 32-bit or 64-bit version is down to the choice of JVM you use. As has been mentioned you need to check you have appropriate shared libraries. (or ideally none)</p> <p>The main difference is being able to use more memory esp if you need 4 GB or more.</p>
24,405
<p>I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota.</p> <pre><code>DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); </code></pre> <p>No matter what approach I tried (like <code>SecureString</code>), I am easily able to see the password (<strong>m_pwd</strong>) either using Reflector or using strings tab of Process Explorer for the executable.</p> <p>I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account.</p> <p>Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers?</p> <p>Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.</p>
<p>The sanctified method is to use CryptoAPI and the Data Protection APIs.</p> <p>To encrypt, use something like this (C++):</p> <pre><code>DATA_BLOB blobIn, blobOut; blobIn.pbData=(BYTE*)data; blobIn.cbData=wcslen(data)*sizeof(WCHAR); CryptProtectData(&amp;blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &amp;blobOut); _encrypted=blobOut.pbData; _length=blobOut.cbData; </code></pre> <p>Decryption is the opposite:</p> <pre><code>DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast&lt;BYTE*&gt;(data); blobIn.cbData=length; CryptUnprotectData(&amp;blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &amp;blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); </code></pre> <p>If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.</p>
<p>If you store it as a secure string and save the secure string to a file (possibly using <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="nofollow noreferrer">Isolated Storage</a>, the only time you will have a plain text password is when you decrypt it to create your mbstore. Unfortunately, the constructor does not take a SecureString or a Credential object.</p>
6,212
<p>I've just built a VS C++ 6.0 program using VS 2008. When I attempt to run or debug the application, Vista asks for permission. What is it about how the program is built that causes this? The program is being built and run from a subfolder of C:\Dev</p> <p><a href="http://www.vistax64.com/vista-installation-setup/138053-vista-asks-permission-run-installed-programs.html" rel="nofollow noreferrer">This response</a> made no sense to me as a solution to the problem.</p>
<p>Possibility 1:</p> <p>Your program is marked as needing admin rights in its manifest</p> <p>Possibility 2:</p> <p>Your program is called setup.exe or install.exe - such program names always cause administrator rights to be required</p> <p>For detailed explanation of those and other possibilities why you see this check <a href="http://technet.microsoft.com/en-us/library/cc512679.aspx" rel="nofollow noreferrer" title="Getting to Know User Account Control">Getting to Know User Account Control Technet article</a></p>
<p>If you're not an admin, then you probably don't have permission to execute programs in C:\Dev.</p>
12,108
<p>I have three TextBox controls on the page</p> <pre><code>&lt;asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="1"&gt; &lt;asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="2"&gt; &lt;asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="3"&gt; </code></pre> <p>and an event handler</p> <pre><code>protected void TextBox_TextChanged(object sender, EventArgs e) { WebControl changed_control = (WebControl)sender; var next_controls = from WebControl control in changed_control.Parent.Controls where control.TabIndex &gt; changed_control.TabIndex orderby control.TabIndex select control; next_controls.DefaultIfEmpty(changed_control).First().Focus(); } </code></pre> <p>The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see <a href="https://stackoverflow.com/questions/173810/autopostback-with-textbox-loses-focus-question-made-clearer">Little JB's problem</a>). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl. </p> <p>I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb360913.aspx" rel="noreferrer">OfType</a></p> <pre><code>from control in changed_control .Parent .Controls .OfType&lt;WebControl&gt;() </code></pre>
<p>The problem is that LiteralControl does not inherit from WebControl. It can't have the focus though, so it's OK to not select them. In your LINQ statement, add another condition checking for a WebControl. So your where line should be <code>where control.TabIndex &gt; changed_control.TabIndex &amp;&amp; control is WebControl</code>.</p>
21,510
<p>I'm finding a couple for Java in general but no plugins for netbeans that I can see.</p> <p>Thanks</p>
<p>I've used the <a href="http://sourceforge.net/project/showfiles.php?group_id=56262&amp;package_id=63621" rel="nofollow noreferrer">PMD NetBeans plugin</a>, and <a href="http://pmd.sourceforge.net/integrations.html#netbeans" rel="nofollow noreferrer">here</a> are the installation instructions (may be a little outdated, due to the speed of NetBeans development, but I got them to work).</p> <p>Here's a list of <a href="http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#Java_2" rel="nofollow noreferrer">tools for static analyisis</a>. Maybe you can cross-check for others that offer NetBeans support.</p> <p><strong>EDIT:</strong> Those instruction are a little bit old, so I put a more up-to-date set <a href="http://www.billthelizard.com/2008/11/netbeans-pmd-plugin.html" rel="nofollow noreferrer">here</a> (links to my blog).</p>
<p>I found the <a href="https://sqe.dev.java.net/" rel="nofollow noreferrer">SQE Plugin</a>, it integrates FindBugs, CheckStyle and PMD into one convenient Plugin. </p> <p>CheckStyle configuration was not complete yet, but the functionality is there in full.</p>
34,295
<p>I want to get my Ender 5 plus to print at 300 °C. As such, I've edited the firmware and increased the <code>HEATER_0_MAXTEMP</code> to 315 °C.</p> <p>In my slicer, I can slice and print at 300 °C, however, I cannot manually adjust the temperature on the LCD screen past the stock setting of 260 °C.</p> <p>Any help in getting the manual adjustment fixed would be greatly appreciated.</p>
<p>Your formula doesn't seem to take into account two important factors: layer height and average speed.</p> <p>Do the math differently:</p> <p>voumetric flow rate [mm^3/s] = layer height [mm] * line width [mm] * speed [mm/s]</p> <p>For example, 0.2 * 0.45 * 70 = 6.3 mm^3/s</p> <p>which is realistic, the extruder on the Ender 3 cannot go much faster than that reliably.</p> <p>PLA weighs 1.24 g/cm^3 = 0.00124 g/mm^3</p> <p>To extrude 1 kg you need 1000/(0.00124 * 6.3) = 35 hours (70 for 2 kg).</p> <p>However the printer does not reach 70 mm except on straight long moves, the average speed may be lower or much lower depending on what you print.</p> <p>If you print technical parts with straight edges, maybe you can multiply by 1.5 (50 hours/kg), but if you print models and small statues or similar you may need to double it (70 hours/kg).</p> <p>I use Klipper as firmware and I have a macro which keeps track of printing time and filament length used.</p>
<p>Your math looks correct, and is also a good approximation for what I've seen in the first few weeks with my own Ender 3.</p> <p>Another way to calculate (to check yourself) is to calculate the volume extruded (nozzle area times extrusion percentage times print speed -- be sure you convert everything to the same units!) in a given second, multiply by the density of your filament (common PLA runs about 1.2 g/cm^3), and get a rough figure for how long it takes to print a kilogram of filament. Your actual print time will always be higher than this approximation, because there are moves during which the extruder isn't running, infill is often set to lower extrusion level, and of course there's setup and cleanup time to account for.</p>
1,951
<h1>The Problem</h1> <p>I use a tool at work that lets me do queries and get back HTML tables of info. I do not have any kind of back-end access to it.</p> <p>A lot of this info would be much more useful if I could put it into a spreadsheet for sorting, averaging, etc. <strong>How can I screen-scrape this data to a CSV file?</strong></p> <h2>My First Idea</h2> <p>Since I know jQuery, I thought I might use it to strip out the table formatting onscreen, insert commas and line breaks, and just copy the whole mess into notepad and save as a CSV. <strong>Any better ideas?</strong></p> <h1>The Solution</h1> <p>Yes, folks, it really was as easy as copying and pasting. Don't I feel silly.</p> <p>Specifically, when I pasted into the spreadsheet, I had to select &quot;Paste Special&quot; and choose the format &quot;text.&quot; Otherwise it tried to paste everything into a single cell, even if I highlighted the whole spreadsheet.</p>
<ul> <li>Select the HTML table in your tools's UI and copy it into the clipboard (if that's possible</li> <li>Paste it into Excel.</li> <li>Save as CSV file</li> </ul> <p>However, this is a manual solution not an automated one.</p>
<p>Have you tried opening it with excel? If you save a spreadsheet in excel as html you'll see the format excel uses. From a web app I wrote I spit out this html format so the user can export to excel.</p>
32,360
<p>I have this in some WSDL:</p> <pre><code>&lt;element name=&quot;startDate&quot; type=&quot;xsd:dateTime&quot;/&gt; &lt;element name=&quot;endDate&quot; type=&quot;xsd:dateTime&quot;/&gt; </code></pre> <p>Which results in the following text in the SOAP envelope:</p> <pre><code>&lt;startDate&gt;2008-10-29T12:01:05&lt;/startDate&gt; &lt;endDate&gt;2008-10-29T12:38:59.65625-04:00&lt;/endDate&gt; </code></pre> <p>Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?</p>
<p>I suspect your endDate value has the Kind property set to DateTimeKind.Local.</p> <p>You can change this to DateTimeKind.Unspecified as follows:</p> <pre><code>endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Unspecified) </code></pre> <p>after which I believe it will be serialized without the timezone offset.</p> <p>Note that you will get a DateTime with DateTimeKind.Local if you have initialized it using DateTime.Now or DateTime.Today, and DateTimeKind.Utc if you have initialized it using Datetime.UtcNow.</p>
<p>What are you using to generate the date? If you are building this XML in your code rather than using some serializer (WCF or XmlSerializer) you could use System.Xml.XmlConvert to generate and interpret the date as follows:</p> <p>To create the string to put in the XML:</p> <pre><code>DateTime startDate = DateTime.Now; string startDateString = System.Xml.XmlConvert.ToString(startDate); </code></pre> <p>To get the date out of the XML:</p> <pre><code>DateTime startDateFromXml = System.Xml.XmlConvert.ToDateTime(startDateString); </code></pre> <p>If you start with two DateTime instances that differ by 37 minutes and 54 seconds before you push them into XML they will still differ by 37 minutes and 54 seconds after you pull them out of the XML.</p>
30,811
<p>I am using an api which interacts with a db. This api has methods for querying, loading and saving elements to the db. I have written integration tests which do things like create a new instance, then check that when I do a query for that instance, the correct instance is found. This is all fine. </p> <p>I would like to have faster running unit tests for this code but am wondering about the usefulness of any unit test and if they are actually giving me anything. for example, lets say I have a class for saving some element I have via the API. This is psuedo code, but get the idea of how the api I am using works across.</p> <pre><code>public class ElementSaver { private ITheApi m_api; public bool SaveElement(IElement newElement, IElement linkedElement) { IntPtr elemPtr = m_api.CreateNewElement() if (elemPtr==IntPtr.Zero) { return false; } if (m_api.SetElementAttribute(elemPtr,newElement.AttributeName,newElement.AttributeValue)==false) { return false; } if (m_api.SaveElement(elemPtr)==false) { return false; } IntPtr linkedElemPtr = m_api.GetElementById(linkedElement.Id) if (linkedElemPtr==IntPtr.Zero) { return false; } if (m_api.LinkElements(elemPtr,linkedElemPtr)==false) { return false; } return true; } } </code></pre> <p>is it worth writing unit tests which mock out the m_api member? it seems that I can test that if any of the various calls fail that false is returned, and that if all of the various calls succeed that true is returned, and I could set expectations that the various methods are called with the expected parameters, but is this useful? If I were to refactor this code so that it used some slightly different methods of the api, but achieved the same result, this would break my tests and I would need to change them. This brittleness doesn't seem very useful. </p> <p>Should I bother with unit tests for code like this, or should I just stick with the integration tests that I've got?</p>
<p>Look at what the tests are like. If you're only testing if stuff that comes in ends up in the database etc. Your probably doing the right thing by only doing automated integration tests. If there's logic you want to test then you might want to look if you can factor out your logic into separate classes that you can unit test and facades around the infrastructure code that contain no logic.</p>
<p>It is a good idea to mock out m_api in my code for the following reasons (not all of which apply to your psuedo-code example):</p> <ul> <li>As you mentioned, you can verify that your class performs error handling properly</li> <li>In cases where you have more complex code in your class (e.g., cacheing), you can use expectations on your mock to ensure that the class is behaving properly. For example, retrieve the same object twice but ensure that m_api is only called once.</li> <li>Your unit test can test behavior without creating an appropriate data set. This increase maintainability over time as the data model underneath m_api changes.</li> </ul>
43,222
<p>I have a jQuery datepicker that I want to restrict non work days - weekends, public holidays etc. I have seen examples on how to do this from the client side (javascript), but is there a way to restrict the dates from server side ASP.NET code?</p> <p>I figure you could do using Page.RegisterClientScriptBlock, but was wondering is there a neater way?</p>
<p>The JQuery stuff is all client side, so there is no server side to speak of. My recommendation would be to create some thin server-side wrappers that automagically do the equivalent of writing RegisterClientScriptBlock. That way you only have to fiddle around with the Javascript once, and it always just works.</p>
<p>You just do it when you validate the data being posted, using the same logic you use client-side. You should always be validating data at server-side, NOTHING from the client side can EVER be trusted, even if you have "validation code" there and think you're requiring javascript to be on for it to work. </p> <p>Doing validation client-side should be a secondary thing, just to provide a nice user experience. There is no security in any client-side code. (Go install firebug and/or the "tamper data" extensions for firefox if you don't believe me).</p>
27,705
<p>I'm trying to serve dynamically generated xml pages from a web server, and provide a custom, static, xslt from the same web server, that will offload the processing into the client web browser.</p> <p>Until recently, I had this working fine in Firefox 2, 3, IE5, 6 and Chrome. Recently, though, something has changed, and Firefox 3 now displays just the text elements in the source.</p> <p>The page source starts like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!-- Firefox 2.0 and Internet Explorer 7 use simplistic feed sniffing to override desired presentation behavior for this feed, and thus we are obliged to insert this comment, a bit of a waste of bandwidth, unfortunately. This should ensure that the following stylesheet processing instruction is honored by these new browser versions. For some more background you might want to visit the following bug report: https://bugzilla.mozilla.org/show_bug.cgi?id=338621 --&gt; &lt;?xml-stylesheet type="text/xsl" href="/WebObjects/SantaPreview.woa/Contents/WebServerResources/Root.xsl"?&gt; &lt;wrapper xmlns="http://www.bbc.co.uk/ContentInterface/Content" xmlns:cont="http://www.bbc.co.uk/ContentInterface/Content" sceneId="T2a_INDEX" serviceName="DSat_T2"&gt; .... </code></pre> <p>Firebug shows that the Root.xsl file is being loaded, and the response headers for it include the line</p> <pre><code>Content-Type text/xml </code></pre> <p><em>I've also tried it with application/xml as the content type, but it makes no difference :-(</em></p> <p>The Web Developer Extension shows the correct generated source too, and if you save this and load the page in Firefox, it displays correctly.</p> <p>The version of Firefox displaying the problem is 3.0.3</p> <p>Any ideas what I might be doing wrong?</p>
<p>Displaying just the text elements is the behavior you would get out of an empty XSL stylesheet.</p> <p>To me, that suggests that something fishy is going on with your xpath expressions, and that the xsl:template/@match attributes do not match the source document.</p> <p>You do not provide enough information to diagnose further, so this blind guess is all I can offer.</p> <p>EDIT: It turned out the problem was that IE and Chrome silently accept a nodeset as argument to <a href="http://www.w3.org/TR/xpath#function-string-length" rel="noreferrer">string-length</a>, while FF3 does not. Note that the specification mandates an optional string argument and does not specify behavior with a nodeset argument.</p>
<p>try serving it as application/xml instead of text/xml</p>
27,293
<p>I always run into the same problem when creating web pages. When I add a font that is larger then about 16-18px it looks terrible. Its jagged, and pixelated. I have tried using different fonts and weights, however I haven't had much luck there. </p> <p>Note: Its only in windows that it is like this. Mainly in Opera and FF also in IE7 but not quite as bad. In Linux the font looks good. I haven't looked at a Mac.</p> <p>What do you guys do to fix this? if anything. I noticed that the titles here on SO are also pretty jagged but they are just small enough not to look bad. </p>
<p>There is nothing you can do to force the user to change the way that their operating system renders fonts. If it is that big a deal to you then you can replace the large headings with images, this allows you to control exactly how the font is rendered (and ensures that the heading looks exactly as you wish, even if the user doesnt have your suggested font installed). </p> <p>If you do this make sure that you provide an alternative text representation for those who do not see images. I tend to use CSS to show a background image, and hide the contents of the heading. Like this.</p> <pre><code>&lt;style&gt; h1 { height: 32px; width: 100px; background: url("path/to/image") } h1 span { display: none; } &lt;/style&gt; &lt;h1&gt; &lt;span&gt; Heading Text &lt;span&gt; &lt;/h1&gt; </code></pre> <p>To be honest this does seem like overkill if it is on all large text. And be aware that it will increase the amount of data that your clients need to download. However for a large heading this method can lead to something that looks nicer than OS rendered text.</p>
<p>Enabling anti-aliasing should solve the display problem. </p>
5,400
<p>I have a page that uses </p> <pre><code>$(id).show("highlight", {}, 2000); </code></pre> <p>to highlight an element when I start a ajax request, that might fail so that I want to use something like</p> <pre><code>$(id).show("highlight", {color: "#FF0000"}, 2000); </code></pre> <p>in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?</p>
<p>From the jQuery docs: </p> <p><a href="http://docs.jquery.com/Effects/stop" rel="nofollow noreferrer">http://docs.jquery.com/Effects/stop</a></p> <blockquote> <p><em>Stop the currently-running animation on the matched elements.</em>...</p> <p>When <code>.stop()</code> is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with <code>.slideUp()</code> when <code>.stop()</code> is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.</p> <p>If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When <code>.stop()</code> is called, the next animation in the queue begins immediately. If the <code>clearQueue</code> parameter is provided with a value of <code>true</code>, then the rest of the animations in the queue are removed and never run.</p> <p>If the <code>jumpToEnd</code> argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above <code>.slideUp()</code> example, the element would be immediately hidden. The callback function is then immediately called, if provided...</p> </blockquote>
<p>In my case, using below code does not work and keep your opacity value remain: </p> <pre><code>$('#identifier').stop(true, true).effect("pulsate", { times: 1 }, 1); </code></pre> <p>For me just remove opacity are working:</p> <pre><code>$('#identifier').stop(true, true).css('opacity',''); </code></pre>
8,467
<p>I'm a contract programmer with lots of experience. I'm used to being hired by a client to go in and do a software project of one form or another on my own, usually from nothing. That means a clean slate, almost every time. I can bring in libraries I've developed to get a quick start, but they're always optional. (and depend on getting the right IP clauses in the contract) Many times I can specify or even design the <em>hardware</em> platform... so we're talking serious freedom here.</p> <p>I can see uses for constructing automated tests for certain code: Libraries with more than trivial functionality, core functionality with a high number of references, etc. Basically, as the value of a piece of code goes up through heavy use, I can see it would be more and more valuable to automatically test that code so that I know I don't break it.</p> <p>However, <em>in my situation</em>, I find it hard to rationalize anything more than that. I'll adopt things as they prove useful, but I'm not about to blindly follow anything.</p> <p>I find many of the things I do in 'maintenance' are actually small design changes. In this case, the tests would not have saved me anything and now they'd have to change too. A highly iterative, stub-first design approach works very well for me. I can't see actually saving myself that much time with more extensive tests.</p> <p>Hobby projects are even harder to justify... they're usually anything from weekenders up to a say month long. Edge-case bugs rarely matter, it's all about playing with something.</p> <p>Reading questions such as <a href="https://stackoverflow.com/questions/67898/tdd-and-productivity">this one</a>, The most voted on response seems to say that in that poster's experience/opinion TDD actually wastes time if you've got less than 5 people (even assuming a certain level of competence/experience with TDD). However, that appears to be covering initial development time, not maintenance. It's not clear how TDD stacks up over the entire life cycle of a project.</p> <p>I think TDD could be a good step in the worthwhile goal of improving the quality of the products of our industry as a whole. Idealism on it's own is no longer all that effective at motivating me, though.</p> <p>I <em>do</em> think TDD would be a good approach in large teams, or any size team containing at least one unreliable programmer. That's not my question.</p> <p><strong><em>Why would a sole developer with a good track record adopt TDD?</em></strong></p> <p>I'd love to hear of any kind of metrics done (formally or not) on TDD... focusing on solo developers or very small teams. </p> <p>Failing that, anecdotes of your personal experiences would be nice, too. :)</p> <p>Please avoid stating opinion without experience to back it. Let's not make this an ideology war. Also the skip greater employment options argument. <em>This is simply an efficiency question.</em></p>
<blockquote> <p>I'm not about to blindly follow anything.</p> </blockquote> <p>That's the right attitude. I use TDD all the time, but I don't adhere to it as strictly as some.</p> <p>The best argument (in my mind) in favor of TDD is that you get a set of tests you can run when you finally get to the refactoring and maintenance phases of your project. If this is your only reason for using TDD, then you can write the tests any time you want, instead of blindly following the methodology.</p> <p>The other reason I use TDD is that writing tests gets me thinking about my API up front. I'm forced to think about how I'm going to use a class before I write it. Getting my head into the project at this high level works for me. There are other ways to do this, and if you've found other methods (there are plenty) to do the same thing, then I'd say keep doing what works for you.</p>
<p>We are all developers with a good track record. After all, we are all reading Stackoverflow. And many of us use TDD and perhaps those people have a great track record. I get hired because people want someone who writes great test automation and can teach that to others. When working alone, I do TDD on my coding projects at home because I found that if I don’t, I spent time doing manual testing or even debugging, and who needs that. (Perhaps those people have only good track records. I don’t know.)</p> <p>When it comes to being a good automobile driver, everyone believes they are a “good driver.” This is a cognitive bias all drivers have. Programmers have their own biases. The reasons developers such as the OP don’t do TDD are covered in this <a href="https://agilenoir.biz/en/agilethoughts/why-developers-dont-tdd-a-radio-drama/" rel="nofollow noreferrer">Agile Thoughts podcast series</a>. The podcast archive also has content on test automation concepts such as the <a href="https://agilenoir.biz/en/agilethoughts/test-automation-pyramid-series/" rel="nofollow noreferrer">test pyramid</a>, and an intro about what is TDD and why write tests first starting with episode 9 in the <a href="https://agilenoir.biz/series/agile-thoughts/" rel="nofollow noreferrer">podcast archive</a>.</p>
19,071
<p>Is it possible to determine the MAC address of the originator of a remote connection under Windows NT 4? The remote PC opens a socket connection into my application and I can get the IP address. However I need to determine the MAC address from the information available from the socket such as the IP address of the remote device.</p> <p>I have tried using <code>SendARP</code> but this doesn't seem to be supported in Windows NT4.</p>
<p>Try GetIpNetTable. This function is documented as supported as of NT 4.0 SP4.</p>
<p>Hope the machine isn't <em>too</em> remote. MAC addresses will only be known for the local network (subnet).</p>
8,836
<p>A colleague of mine and I have been discussing how to declare variables in a function.</p> <p>Let's say you have a class called TStrings (using Delphi for the sake of explanation) that has at least one abstract method and a descendant class called TStringList which obviously implements the abstract method, but it introduces nothing else you need that is not already implemented in the ancestor, how would you declare a function variable of type TStringList?</p> <p>Here are two examples. Which is considered better practice and why?</p> <pre><code>procedure AddElements; var aList: TStringList; begin aList := TStringList.Create; try aList.Add('Apple'); aList.Add('Pear'); finally aList.free; end; end; procedure AddElementsII; var aList: TStrings; begin aList := TStringList.Create; try aList.Add('Apple'); aList.Add('Pear'); finally aList.free; end; end; </code></pre>
<p>It is a TStringList, so you should also declare it as TStringList (first example). Everything else could confuse you or others that read the code later.</p>
<p>My vote is the second form - the idea being that TStrings defines a contract/interface and its better to code to them.</p>
45,885
<p>I <em>think</em> I know how to create custom encrypted RSA keys, but how can I read one encrypted like ssh-keygen does?</p> <p>I know I can do this:</p> <pre><code>OpenSSL::PKey::RSA.new(File.read('private_key')) </code></pre> <p>But then OpenSSL asks me for the passphrase... How can I pass it to OpenSSL as a parameter?</p> <p>And, how can I create one compatible to the ones generated by ssh-keygen?</p> <p>I do something like this to create private encrypted keys:</p> <pre><code>pass = '123456' key = OpenSSL::PKey::RSA.new(1024) key = "0000000000000000#{key.to_der}" c = OpenSSL::Cipher::Cipher.new('aes-256-cbc') c.encrypt c.key = Digest::SHA1.hexdigest(pass).unpack('a2' * 32).map {|x| x.hex}.pack('c' * 32) c.iv = iv encrypted_key = c.update(key) encrypted_key &lt;&lt; c.final </code></pre> <p>Also, keys generated by OpenSSL::PKey::RSA.new(1024) (without encryption), don't work when I try password-less logins (i.e., I copy the public key to the server and use the private one to login).</p> <p>Also, when I open an ssh-keygen file via OpenSSL and then check its contents, it appears to have additional characters at the beginning and end of the key. Is this normal?</p> <p>I don't really understand some of this security stuff, but I'm trying to learn. What is it that I'm doing wrong?</p>
<p>According to the blog post here:</p> <p><a href="http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/" rel="noreferrer">http://stuff-things.net/2008/02/05/encrypting-lots-of-sensitive-data-with-ruby-on-rails/</a></p> <p>You can simply do:</p> <p>OpenSSL::PKey::RSA.new(File.read('private_key'), 'passphrase')</p> <p>Best of luck.</p>
<p>I've made some progress on this. If I use the Net::SSH library, I can do this:</p> <pre><code>Net::SSH::KeyFactory.load_private_key 'keyfile', 'passphrase' </code></pre> <p>By reading the source code I have yet to figure out what the library does to OpenSSL's PKey::RSA.new to accomplish this... And then I go and test again, and sure enough, OpenSSL can open the private key just fine without Net::SSH... I've made so much tests that somehow I didn't test this correctly before.</p> <p>But I still have the issue of creating an SSH compatible key pair... and maybe I'll go test again and have the answer :P ... nah, I'm not that interested in that part</p>
29,179
<p>I don’t have advanced knowledge in JavaScript, and I am trying to learn how to use Ext&nbsp;JS framework in ASP.NET (C# or VB.NET) environment. I’ve got couple of samples, but was unable get the project working. Is there such as website or book so I can go a read up about Ext&nbsp;JS in more details and how can I include this into my website?</p>
<p>Mike,</p> <p>The best example site out there is <a href="http://examples.extjs.eu/" rel="noreferrer">http://examples.extjs.eu/</a>. Each example has a link for viewing HTML, javascript and CSS separately.</p> <p>We are successfully integrating ExtJS with the ASP.NET MVC framework. A separate post detailing how to put everything together is probably in order.</p>
<p>i wrote a <a href="http://thekindofme.wordpress.com/2009/02/05/a-grid-with-ajax-pagination-sorting-filtering-on-aspnet-mvc-with-extjs-and-ef/" rel="nofollow noreferrer">post</a> on using extjs grid with asp.net mvc. although you are not planning to use ext on mvc fm. i think other details like how to render it using javascript, parsing parameters in requests sent by the grid, json serialization...etc will be relavant and helpful to you.</p>
25,204
<p>Do you use any of these technologies? Which ones are current and hence sensible to include in a site?</p> <p>Documentation on any seems to be relatively sparse, and usage of any of them limited, as search engines get better, are they even relevant any more?</p>
<p>I use microformats whenever I can. Usually it just makes sense anyway, as frequently when I have an address block, I may want to style some elements differently then other elements, and that makes it super easy. It's not like microformats are that hard to figure out.</p> <p>There has been a couple of instances where, because I was using a microformat, I was able to re-use the markup of a certain portion of a site somewhere else (as an include), and not have to change the markup, only the styling.</p> <p>Finally, ever since I really stated exploring microformats, I got better at writing semantic markup and better at naming CSS classes.</p>
<p>I've used all three, but of the lot I'd have to say microformats have the most momentum these days. It has the advantage of being very easy to implement, even as an afterthought, on existing sites. And while there don't seem to be a lot of microformat consumers in the wild at this point, that situation is starting to change with the next generation of browsers.</p> <p>As for the relevance of semantic markup in general, anything that makes it easier to automate the gathering of data is going to contribute to a richer ecosystem of applications that use that data. Relying on search engines for this kind of contextual processing does not address the needs of more focused or niche applications.</p>
18,164
<p>I have a project where there are multiple applications that have some common configuration values. I would like to have a shared .config file that is available to all of the applications using the .Net configuration object model. Each application would also have its own app.config file</p> <p>How can this best be done. I'd rather avoid using the registry as much as possible. In looking through the documentation, the OpenExeConfiguration(string exePath) method seems promising for accessing a specified config file. Is this a reasonable approach? Any other suggestions?</p>
<p>Some sections in the app.config allow for a reference to an external file.</p> <pre><code>&lt;appSetting configSource="somefile.config"/&gt; </code></pre>
<p><a href="https://stackoverflow.com/questions/239687/easiest-way-to-read-a-config-file-belonging-to-another-application#239715">Here's</a> a discussion that addresses OpenExeConfiguration which may be helpful.</p>
36,056