instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I want to allow users to upload avatar-type images in a variety of formats (<strong>GIF, JPEG, and PNG at least</strong>), but to save them all as <strong>PNG database BLOBs</strong>. If the images are oversized, pixelwise, I want to resize them before DB-insertion.</p> <p><strong>What is the best way to use GD to do the resizing and PNG conversion?</strong></p> <p>Edit: Sadly, only <a href="http://php.net/manual/en/book.image.php" rel="nofollow noreferrer">GD</a> is available on the server I need to use, no <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>.</p>
<pre><code>&lt;?php /* Resizes an image and converts it to PNG returning the PNG data as a string */ function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig &lt; 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.'); } </code></pre>
<p><a href="http://www.phpit.net/article/image-manipulation-php-gd-part2/" rel="nofollow noreferrer">This article</a> seems like it would fit what you want. You'll need to change the saving imagejpeg() function to imagepng() and have it save the file to a string rather than output it to the page, but other than that it should be easy copy/paste into your existing code.</p>
4,224
<p>I believe that we can allow Firefox to sent NTLM data to SharePoint sites to do automatic authentication, and I think that this is doable with IIS.</p> <p>I'd like to do the same thing with an internal Rails site.</p> <p>Does anyone know of way that I could authenticate NTLM type user information through a Apache/mongrel setup (provided of course that it's already running on a Windows box inside of an Active Directory domain)?</p>
<p>I'm assuming you've already worked out which HTTP headers you need to send in order to get firefox and IE to send back the NTLM authentication stuff, and are just needing to handle that on the server side?</p> <p>You could use some of ruby's <a href="http://raa.ruby-lang.org/cat.rhtml?category_major=Library;category_minor=Win32" rel="nofollow noreferrer">win32 libraries</a> to access the underlying windows authentication functions which handle the NTLM.</p> <p>I'd suggest the path of least resistance might be to see if there is a COM component which can do the authentication for you, and if so, to use it using the Win32OLE ruby library.</p> <p>If there's no COM component, you might be able to find something in one of those other libraries which can invoke the native win32 methods for you.</p> <p>If you can't find that, you'd have to write a ruby C extension. I've done this on linux, and extending ruby is pretty easy, but you may find the microsoft authentication API's a bit painful.</p> <p>Hope that gets you started on the right track :-)</p>
<p>Check out <a href="http://waffle.codeplex.com" rel="nofollow noreferrer">Waffle</a>. It provides SSO on Windows to Java servers using Win32 API. There're a number of implemented filters (servlet, tomcat valve, spring-security).</p>
18,129
<p>I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:</p> <pre><code>public Booking createVehicleBooking(Long officeId, Long start, Long end, String origin, String destination, String purpose, String requirements, Integer numberOfPassengers) throws ServiceException { /*..Code..*/ } </code></pre>
<p>A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either:</p> <ul> <li><p>There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object.</p></li> <li><p>The method is called <code>create...</code></p></li> </ul> <p>So your above code could become (pardon my C++, I'm a Java developer):</p> <pre><code>class BuildVehicleBooking { Long officeId; Long start; Long end; String origin; String destination; String purpose; String requirements; Integer numberOfPassengers; Booking createVehicleBooking () throws ServiceException { ... } } </code></pre> <p>This is the <strong>Builder Pattern</strong>. The advantage of this pattern is that you can build up a complex set of parameters in pieces, including multiple variations on how the parameters relate to each other, and even overwriting parameters as new information becomes available, before finally calling the <code>create</code> method at the end.</p> <p>Another potential advantage is that you could add a <code>verifyParameters</code> method that checked their consistence before you go as far as <code>creating</code> the final object. This is applicable in cases where creating the object involves non-reversible steps, such as writing to a file or database.</p> <p>Note that, as with all patterns, this doesn't apply in every case and may not apply in yours. If your code is simple enough then this pattern may be over-engineering it. If the code is getting messy, refactoring into this pattern can be a good way to simplify it.</p>
<p>I like the one param per line approach that you're showing. I find it's very easy to scan it visually and see what's present.</p> <p>I find that when people use something like Guice you often end up with a large number of params and this makes it easier to read.</p>
23,023
<p>I want to create the 26 neighbors of a cubic-voxel-node in 3-d space. The inputs are the x,y,z position of the node and the size of the cube side . I am trying to do this using a for loop but haven't managed yet. I am quite newbie in programming please help me.</p>
<pre><code>for (int dz = z - 1; dz &lt;= z + 1; ++dz) { for (int dy = y - 1; dy &lt;= y + 1; ++dy) { for (int dx = x - 1; dx &lt;= x + 1; ++dx) { // all 27 if ((dx != x) || (dy != y) || (dz != z)) { // just the 26 neighbors } } } } </code></pre>
<pre><code>for(int i = 0; i &lt; 27, i++) { if(i == 13) continue; int dx = i%3 -1; int dy = (i/3)%3 -1; int dz = i/9 - 1; process(x+dx,y+dy,z+dz); } </code></pre>
42,351
<p>I'm looking for a regex that can pull out quoted sections in a string, both single and double quotes.</p> <p>IE:</p> <pre><code>"This is 'an example', \"of an input string\"" </code></pre> <p>Matches:</p> <ul> <li>an example</li> <li>of an input string</li> </ul> <p>I wrote up this:</p> <pre><code> [\"|'][A-Za-z0-9\\W]+[\"|'] </code></pre> <p>It works but does anyone see any flaws with it?</p> <p>EDIT: The main issue I see is that it can't handle nested quotes.</p>
<p>How does it handle single quotes inside of double quotes (or vice versa)?</p> <pre><code>"This is 'an example', \"of 'quotes within quotes'\"" </code></pre> <p>should match</p> <ul> <li>an example <li>of 'quotes within quotes' </ul> <p>Use a backreference if you need to support this.</p> <pre><code>(\"|')[A-Za-z0-9\\W]+?\1 </code></pre> <p>EDIT: Fixed to use a reluctant quantifier.</p>
<p>It works but doesn't match other characters in quotes (e.g., non-alphanumeric, like binary or foreign language chars). How about this:</p> <pre><code>[\"']([^\"']*)[\"'] </code></pre> <p>My C# regex is a little rusty so go easy on me if that's not exactly right :)</p>
25,766
<p>I deleted millions of rows of old data from a production SQL database recently, and it didn't seem to shrink the size of the .MDF file much. We have a finite amount of disk space.</p> <p>I am wondering if there is anything else I can do to "tighten" the file (like something analogous to Access' Compact and Repair function)?</p>
<p>Use the Shrink File option in Sql Server Management Studio Right-click on Database > Tasks > Shrink > Database (or Files)</p>
<p>This worked for me and shrank my log files by a thousand.</p> <ol> <li>Using the SQL Server Manager.</li> <li>Right Click on the database in question.</li> <li>Choose Properties, then the options tab. </li> <li>Change the Recovery Model to Simple From Full.</li> </ol> <p>If you need it in full mode switch it back after it shrinks. That's it!</p>
19,691
<p><strong>EDIT:</strong> <em>I'm still waiting for more answers. Thanks!</em></p> <p>In SQL 2000 days, I used to use temp table method where you create a temp table with new identity column and primary key then select where identity column between A and B.</p> <p>When <strong>SQL 2005</strong> came along I found out about <code>Row_Number()</code> and I've been using it ever since...</p> <p>But now, I found a serious performance issue with <code>Row_Number()</code>. It performs very well when you are working with not-so-gigantic result sets and sorting over an identity column. However, <strong>it performs very poorly</strong> when you are working with <strong>large result sets</strong> like over 10,000 records and <strong>sorting it over non-identity column</strong>. <code>Row_Number()</code> performs poorly even if you sort by an identity column if the result set is over 250,000 records. For me, it came to a point where it throws an error, "<strong>command timeout!</strong>"</p> <p><strong>What do you use to do paginate a large result set on SQL 2005?</strong> Is temp table method still better in this case? I'm not sure if this method <a href="https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml" rel="noreferrer">using temp table with SET ROWCOUNT</a> will perform better... But some say there is an issue of giving wrong row number if you have multi-column primary key.</p> <p>In my case, I need to be able to sort the result set by a date type column... for my production web app.</p> <p>Let me know what you use for <strong>high-performing pagination in SQL 2005</strong>. And I'd also like to know a smart way of creating indexes. <strong>I'm suspecting choosing right primary keys and/or indexes (clustered/non-clustered) will play a big role here.</strong></p> <p>Thanks in advance.</p> <p>P.S. <strong>Does anyone know what stackoverflow uses?</strong></p> <p><strong>EDIT:</strong> Mine looks something like...</p> <pre><code>SELECT postID, postTitle, postDate FROM (SELECT postID, postTitle, postDate, ROW_NUMBER() OVER(ORDER BY postDate DESC, postID DESC) as RowNum FROM MyTable ) as DerivedMyTable WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1 </code></pre> <p>postID: Int, Identity (auto-increment), Primary key</p> <p>postDate: DateTime</p> <p><strong>EDIT:</strong> Is everyone using Row_Number()?</p>
<p>The row_number() technique should be quick. I have seen good results for 100,000 rows.</p> <p>Are you using row_number() similiar to the following:</p> <pre><code>SELECT column_list FROM (SELECT column_list ROW_NUMBER() OVER(ORDER BY OrderByColumnName) as RowNum FROM MyTable m ) as DerivedTableName WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1 </code></pre> <p>...and do you have a covering index for the column_list and/or an index on the 'OrderByColumnName' column?</p>
<p>Well, for your sample query ROW_COUNT should be pretty fast with thousands of rows, provided you have an index on your PostDate field. If you don't, the server needs to perform a complete clustered index scan on your PK, practically load every page, fetch your PostDate field, sort by it, determine the rows to extract for the result set and again fetch those rows. It's kind of creating a temp index over and over again (you might see an table/index spool in the plain).</p> <p>No wonder you get timeouts.</p> <p>My suggestion: set an index on PostDate DESC, this is what ROW_NUMBER will go over - (ORDER BY PostDate DESC, ...)</p> <p>As for the article you are referring to - I've done pretty much paging and stuff with SQL Server 2000 in the past without ROW_COUNT and the approach used in the article is the most efficient one. It does not work in all circumstances (you need unique or almost unique values). An overview of some other methods is <a href="http://www.codeproject.com/KB/aspnet/PagingLarge.aspx" rel="nofollow noreferrer">here</a>.</p> <p>.</p>
20,474
<p>In Django 1.0, what is the best way to catch and show an error if user enters only whitespace (" ") in a form field?</p> <pre><code>class Item(models.Model): description = models.CharField(max_length=100) class ItemForm(ModelForm): class Meta: model = Item </code></pre> <p>if user enters only whitespace (" ") in description CharField, what change needs to done to class Item or class ItemForm so that form.is_valid() fails and shows an error?</p> <p>After form.is_valid(), I could write the code to check for only whitespaces in description field and raise a validation error but there has to be a better way. Can RegexField be used to specify description entered should not be just whitespaces. Any suggestions?</p>
<pre><code>class ItemForm(forms.ModelForm): class Meta: model = Item def clean_description(self): if not self.cleaned_data['description'].strip(): raise forms.ValidationError('Your error message here') </code></pre> <p>The <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow noreferrer">forms validation documentation</a> might provide a good read.</p>
<p>Figured it out. Just adding <strong>description = forms.RegexField(regex=r'[^(\s+)]')</strong> to class ItemForm will cause the form.is_valid() to fail and show the error</p> <pre><code>class ItemForm(ModelForm): description = forms.RegexField(regex=r'[^(\s+)]') class Meta: model = Item </code></pre> <p>To include your own message, add error_message=... to forms.RegexField</p> <pre><code>description = forms.RegexField(regex=r'[^(\s+)]', error_message=_("Your error message here.")) </code></pre>
43,020
<p>I imagine I can compile a C# DLL and then expose it as a COM object so that it can be CreateObject'd from VBscript. I'm just not sure the steps involved in doing this...</p>
<p>It can be very simple to do this. But there are a lot of places where it's not so simple. It depends a lot on what your class needs to be able to do, and how you intend to deploy it.</p> <p>Some issues to consider:</p> <ul> <li>Your class has to have a parameterless constructor.</li> <li>It can't expose static methods.</li> <li>Is deploying your COM DLL in the global assembly cache OK? If not, you're going to have to give it a strong name and register it using <code>regasm /codebase</code>.</li> <li>Do you care what GUIDs identify the class and its interfaces? If not, you can let <code>regasm</code> assign them, but they'll be different every time (and every place) the class is registered. If you need the GUIDs to remain invariant across installations, you'll need to mark members with the <code>Guid</code> attribute.</li> <li>Are you going to use the default marshaling of data types between .NET and COM? If not, you're going to need to mark properties and methods with the <code>MarshalAs</code> attribute.</li> <li>Does it matter to you what kind of COM interface your class exposes? If so, you're going to need to deal with the <code>InterfaceType</code> attribute.</li> <li>Does your class need to raise or respond to events? If so, there are implications for how you design your class interface.</li> </ul> <p>There's a very good (if dated) article about COM interop and .Net <a href="http://www.codeproject.com/KB/COM/cominterop.aspx" rel="noreferrer">here</a>. (A lot of things that article talks about, like generating type libraries, is handled for you automatically now.) And <a href="http://msdn.microsoft.com/en-us/library/zsfww439.aspx" rel="noreferrer">Microsoft's documentation</a> is up to date, but not quite so detailed.</p>
<p>There's a "COM Accessible" option for each project you can select. Then, of course, you have to register the assembly to use it, but that's about it.</p> <hr> <p>I had to go hunting a bit to find it for C# (I'm used to VB.Net), but you can find the option by double-clicking on the <code>Properties</code> folder in the Solution Explorer, choosing the <code>Application</code> tab and then clicking the <code>Assembly Information...</code> button. </p>
46,606
<p>There's a lot to C# &amp; ASP.net. Where should I start? What should I not bother focusing on?</p> <p>Should I learn Winforms then WPF? Ditto for webforms / Silverlight? Should I learn ASP.MVC or classic ASP.NET? If both, which first?</p> <p>In the either/or cases - which will make more sense having known the other first?</p> <p>What major .NET feature(s) should I learn upfront that will open the doors of understanding to what lies ahead?</p> <p>I am deliberately not mentioning fundamentals like value / reference Types, Classes, object-oriented concepts, etc since they should come first, before specifics. Here, I am interested in specifics.</p> <p>[edit - added detail of what my goals are] Good points raised - "what do I want to write"?</p> <p>Basically, an intranet application that monitors a set of documents and implements a workflow as a change control process. The app will also audit the documents and report problems, self-correcting common errors. A lot of the parameters will need to be end-user definable and pluggable. The document format needs to be adaptable to different proprietary formats although they are fundamentally the same. The app will be very modular.</p> <p>I'm leaning towards a web interface because the client specs &amp; admin rights will vary - a browser is really the only thing I can count on.</p> <p>As you can see, it's a bit of everything.</p>
<p>What do you want to write? If you want to write a Windows client-side app, look into WinForms and WPF (no real need to learn WinForms before WPF, other than the way that a lot of tutorials/books will probably compare WPF concepts with WinForms concepts). If you're looking at a web app, then ASP.NET or ASP.MVC - I don't know whether you really need the "normal" ASP.NET before MVC.</p> <p>Silverlight is a bit of both, in a way - rich client probably talking to a server for interesting data etc.</p> <p>Before learning any of these though, I suggest you learn the fundamentals which are one step up from the topics you mentioned - things like how text works in .NET (including encodings and regular expressions), I/O, perhaps threading. Oh, and LINQ :) There are a few books which are very good on this front:</p> <ul> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0596527578" rel="noreferrer" rel="nofollow noreferrer">C# 3.0 in a Nutshell</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0735621632" rel="noreferrer" rel="nofollow noreferrer">CLR via C#</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/1590598733" rel="noreferrer" rel="nofollow noreferrer">Accelerated C# 2008</a></li> </ul>
<p>I highly recommend the following books, for learning about whats new in ASP.NET 3.5</p> <ul> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0470410957" rel="nofollow noreferrer" rel="nofollow noreferrer">ASP.NET MVC 1.0 Website Programming</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0470384611" rel="nofollow noreferrer" rel="nofollow noreferrer">Professional ASP.NET MVC 1.0</a></li> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0470187581" rel="nofollow noreferrer" rel="nofollow noreferrer">ASP.NET 3.5 Website Programming</a></li> </ul>
35,712
<p>How to remove the program icon from the Programs folder?</p>
<p>A shortcut file is a normal file that happens to redirect (on click) the call to another file, program or directory. To remove a shortcut you can use the <a href="http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx" rel="nofollow noreferrer">File.Delete</a> method.</p> <pre><code>File.Delete(path_to_lnk_file); </code></pre>
<p>1- Be sure to get actual file link use OpenFileDialog</p> <hr> <p>OpenFileDialog od = new OpenFileDialog(); od.DereferenceLinks = false; </p> <p><a href="http://www.vbforums.com/showthread.php?549631-RESOLVED-Shortcut-path-in-VB-NET" rel="nofollow noreferrer">use DereferenceLinks</a></p> <p>2 use shell lib to get all information including the path</p> <hr> <p><a href="http://csharphelper.com/blog/2018/06/get-information-about-windows-shortcuts-in-c/" rel="nofollow noreferrer">GetShortcutInfo</a></p> <hr> <h2>finaly usse c# file.move or delete according to the path</h2>
26,012
<p><strong>Here is the updated question:</strong></p> <p>the current query is doing something like:<br></p> <pre><code>$sql1 = "TRUNCATE TABLE fubar"; $sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu"; </code></pre> <p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p> <p>Is my only option to do the <code>CREATE TABLE</code>, run the <code>TRUNCATE TABLE</code>, and then fill the table? (3 separate queries)</p> <p><strong>original question was:</strong></p> <p> I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:</p> <pre><code>CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar </code></pre> <p>If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.</p> <p>This code will be executed using PHP.</p>
<p>shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.</p> <p>Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it <strong>doesn't</strong> exist isn't quite right.</p> <p>You will indeed need multiple statements. Either conditionally create then populate:</p> <ol> <li>CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )</li> <li>TRUNCATE TABLE fubar</li> <li>INSERT INTO fubar SELECT * FROM barfu</li> </ol> <p>or just drop and recreate</p> <ol> <li>DROP TABLE IF EXISTS fubar</li> <li>CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu</li> </ol> <p>With pure SQL those are your two real classes of solutions. I like the second better.</p> <p>(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)</p>
<p>OK then, not bad. To be more specific, the current query is doing something like:</p> <pre> $sql1 = "TRUNCATE TABLE fubar"; $sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu"; </pre> <p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p> <p>Is my only option to do the "CREATE TABLE", run the "TRUNCATE TABLE", and then fill the table? (3 separate queries)</p> <p>PS - thanks for responding so quickly!</p>
10,991
<p>I was going through some code and came across a scenario where my combobox has not been initialized yet. This is in .NET 2.0 and in the following code, this.cbRegion.SelectedValue is null.</p> <pre><code>int id = (int)this.cbRegion.SelectedValue; </code></pre> <p>This code threw a null reference exception instead of an invalid cast exception. I was wondering if anyone knew why it would throw a null reference exception instead of a invalid cast?</p>
<p>It has to do with <a href="http://www.csharphelp.com/archives/archive100.html" rel="noreferrer">Boxing</a> and unboxing. It is trying to pull an int out of the box (unbox), but the object is null, so you get a null reference exception before it ever gets the change to cast.</p>
<p>The exception is on the Selected Value which is null. It's never even getting to the cast.</p>
47,143
<p>I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware.</p> <p>I'd love to know if anyone has a way of redirecting the output from Tornado?</p> <p>I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end.</p> <p>Any ideas anyone?</p> <p><strong>[Edit]</strong> I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control.</p> <p><strong>[Edit2]</strong> The window in question in Tornado is an 'AfxFrameOrView42' according to WinID.</p>
<p>here is another potential way:</p> <pre> -> saveFd = open("myfile.txt",0x102, 0777 ) -> oldFd = ioGlobalStdGet(1) -> ioGlobalStdSet(1, saveFd) -> runmytest() ... -> ioGlobalStdSet(1, oldFd) </pre> <p>this will redirect <strong>all</strong> stdout activity to the file you opened. You might have to play around with the file name of the open to make it write on the host (e.g. use "host:/myfile.txt" or something like this)</p>
<p>rlogin vxWorks-target | tee redirected-output.txt</p>
13,199
<p>I would like to make custom insoles for my wife.</p> <p>This company makes a flexible filament that will be soft to stand on: <a href="http://recreus.com/en/" rel="noreferrer">http://recreus.com/en/</a></p> <p>I do not currently own a printer.</p> <p>How can I measure her feet and transfer the measurements to the printer? (one of these comes to mind: <a href="http://www.eggheadtoys.com/pin-art/" rel="noreferrer">http://www.eggheadtoys.com/pin-art/</a>)</p> <p>How can I measure the inside of the shoe?</p> <p>What kind of printer can print with the flexible filament?</p>
<p>Here is a post that covers how to scan a foot and make a form fitting insole - <a href="https://web.archive.org/web/20180429035945/http://www.gyrobot.co.uk/blog/my-adventures-with-3d-printed-insoles-part-4-4" rel="nofollow noreferrer">https://web.archive.org/web/20180429035945/http://www.gyrobot.co.uk/blog/my-adventures-with-3d-printed-insoles-part-4-4</a></p> <p>Here are links to the rest of the blog - <a href="https://web.archive.org/web/20180307181312/http://www.gyrobot.co.uk:80/blog/my-adventures-with-3d-printed-insoles-part-1-4" rel="nofollow noreferrer">Part 1 of 4</a> - <a href="https://web.archive.org/web/20180307181409/http://www.gyrobot.co.uk:80/blog/my-adventures-with-3d-printed-insoles-part-2-4" rel="nofollow noreferrer">Part 2 of 4</a> - <a href="https://web.archive.org/web/20180305020707/http://www.gyrobot.co.uk:80/blog/my-adventures-with-3d-printed-insoles-part-3-4" rel="nofollow noreferrer">Part 3 of 4</a></p> <p>Any printer should be capable of the temperature required for flexible filament. The main problem with flexible filament is the path between the drive gears and entrance to the hotend must be completely constrained or the filament will push out of any gap. Ninjaflex is very flexible and absolutely will not work unless you constrain it right after the contact point with the drive gear. Semiflex is another flexible filament but quite a bit stiffer than Ninjaflex, I've never used it but it should be a bit more forgiving on the path requirements.</p> <p>I know there are several other flexible filaments but I've never worked with them so I only mentioned Ninjaflex which I have used.</p> <p>The model used in the blog can be found here - <a href="http://www.thingiverse.com/thing:586514" rel="nofollow noreferrer">http://www.thingiverse.com/thing:586514</a></p>
<p>Many questions in one post, but I'll address only the first. Consider to use a shoe with a flat insole, perhaps even what is commonly called a flip-flop. If your objective is to perfectly match the curve of her foot bottom, this should work. Apply a layer of polymer modeling clay, plasticine or similar material. It should be warm enough to permit her foot/feet to settle in and push enough material away to remove any voids. If voids appear, one could then add a few blobs and repeat the pressure.</p> <p>Obviously some will ooze from the sides, which will have to be trimmed away. Trim a sufficient amount to fit her regular shoes and you'll have a reasonable match of the necessary fit.</p> <p>The resulting shape can then be scanned with a 3d scanner and converted to a 3d model. Even if the clay is excessively thick, the typical 3d model editor can slice away the excess, although one would have to make an almost arbitrary judgement for the location of the slicing plane.</p> <p>Another option comes to mind. There are various silicone molding products. I've used one from makeyourownmolds.com that is of a consistency of frosting. When mixed together and applied, it makes a perfect duplicate of the item, in reverse. Another product sold at the local HobbyLobby is a similar molding compound that is more akin to the modeling clay.</p> <p>Both compounds will release easily from skin, are non-toxic and would provide a more durable model from which to scan. </p> <p>I think one difficulty you may have is how to determine the correct foot pressure and posture to achieve the desired results. The modeling clay would give you more support and probably be more accurate. If your objective is to provide the same support as a bare foot, the silicone molding method would be more accurate.</p> <p>If you stretch the concept even further, once you have the silicone or clay mold, you would be able to use the pin-art concept. The idea of measuring each tiny pin is mind-boggling, though.</p>
226
<p>I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.<br> e.g. <a href="http://metachat.org/recent" rel="nofollow noreferrer">http://metachat.org/recent</a> </p> <p>I've a feeling this is a bad way of doing this, but it's code I inherited...</p> <p>Although the page displays correctly on most browsers, I'm getting a situation where AVG Anti-Virus is hijacking the page and redirecting it to an offsite 404 page. </p> <p>I've tried to force a header (Status: 200 OK) using the header command in PHP, but if I do a curl -I of the page, I get the following...</p> <pre><code>HTTP/1.1 404 Not Found Date: Fri, 03 Oct 2008 11:43:01 GMT Server: Apache/2.0.54 (Debian GNU/Linux) DAV/2 SVN/1.1.4 PHP/4.3.10-16 mod_ssl/2 .0.54 OpenSSL/0.9.7e X-Powered-By: PHP/4.3.10-16 Status: 200 OK Content-Type: text/html </code></pre> <p>I guess that first line is the line AVG traps for its forced redirect. Without rewriting the software to use Mod_rewrite (which I don't really understand), how can I (in PHP) stop the "HTTP:/1/1 404 Not Found" line being sent in the headers when displaying this page?</p> <p>Thanks. </p>
<p>There's no way other than using URL rewriting (mod_rewrite) or creating the missing pages. What's happening is that the client requests a page which doesn't exist. Apache is configured to serve a special page upon 404 errors, but it still sends the 404 status code, then AVG traps that.</p> <p>So, you could do something like:</p> <pre><code>RewriteEngine On RewriteCond %{REQUEST_URI} !-f RewriteCond %{REQUEST_URI} !-d RewriteRule (.*) index.php?missing_content=$1 </code></pre> <p>That will rewrite everything that doesn't exist (and would thus give a 404) to your index.php with the URL path in the missing_content query string parameter </p>
<p>Some browsers don't display the content of 404 pages if that content is quite small. If there's larger page content they do display it. This rule varies per browser. Try adding more content to your 404 page and see whether that helps.</p>
20,108
<p>I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?</p> <p><strong>Update Oct 1, 2008:</strong></p> <p>Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <code>&lt;div&gt;</code> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.</p> <p>It then got me thinking about online image editors like <a href="http://www.picnik.com/" rel="noreferrer">Picnik</a> and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?</p>
<p>I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.</p> <pre><code>&lt;img id="img1" src="imgfile1.png"&gt; &lt;img id="img2" src="imgfile2.png"&gt; &lt;canvas id="canvas"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; var img1 = document.getElementById('img1'); var img2 = document.getElementById('img2'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = img1.width; canvas.height = img1.height; context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); &lt;/script&gt; </code></pre> <p>Or, if you want to load the images on the fly:</p> <pre><code>&lt;canvas id="canvas"&gt;&lt;/canvas&gt; &lt;script type="text/javascript"&gt; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var img1 = new Image(); var img2 = new Image(); img1.onload = function() { canvas.width = img1.width; canvas.height = img1.height; img2.src = 'imgfile2.png'; }; img2.onload = function() { context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 0.5; //Remove if pngs have alpha context.drawImage(img2, 0, 0); }; img1.src = 'imgfile1.png'; &lt;/script&gt; </code></pre>
<p>I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.</p>
19,203
<p>I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?</p>
<p>Here's a UDF that will do the trick...</p> <pre><code>create function ProperCase(@Text as varchar(8000)) returns varchar(8000) as begin declare @Reset bit; declare @Ret varchar(8000); declare @i int; declare @c char(1); if @Text is null return null; select @Reset = 1, @i = 1, @Ret = ''; while (@i &lt;= len(@Text)) select @c = substring(@Text, @i, 1), @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end, @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end, @i = @i + 1 return @Ret end </code></pre> <p>You will still have to use it to update your data though.</p>
<p>I know the devil is in the detail (especially where people's personal data is concerned), and that it would be very nice to have properly capitalised names, but the above kind of hassle is why the pragmatic, time-conscious amongst us use the following: </p> <p><code>SELECT UPPER('Put YoUR O'So oddLy casED McWeird-nAme von rightHERE here')</code></p> <p>In my experience, people are fine seeing THEIR NAME ... even when it's half way through a sentence.</p> <p>Refer to: the Russians used a pencil!</p>
28,490
<p>Note: I am just consuming webservice I have no control over webservice code.</p> <p>So in .net 2.0 I reference the webservice and see a class in the webservice namespace, say foobar. It's defined as:</p> <pre><code>public class foobar : System.Web.Services.Protocols.SoapHttpClientProtocol </code></pre> <p>but in .net 3.5 when i add a reference to the same webservice I no longer have this foobar class available. I do see foobarSoap which is an interface which exposes all of the methods in the foobar class above. It's defined as:</p> <pre><code>public interface foobarSoap </code></pre> <p>However it doesn't expose the properties (for obvious reasons).</p> <p>I need to access these properties. How do I do it?</p>
<p>You can try using the <strong>Web Service Description Language Tool</strong> (<code>Wsdl.exe</code>) to generate an actual class file:</p> <blockquote> <p><code>wsdl.exe /language:cs http://www.example.com/FooService.wsdl</code></p> </blockquote> <p>You can get more information about the <a href="http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx" rel="nofollow noreferrer" title="Web Services Description Language Tool (Wsdl.exe)"><strong>WSDL Tool</strong></a> on it's <a href="http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx" rel="nofollow noreferrer" title="Web Services Description Language Tool (Wsdl.exe)">MSDN Page</a>.</p>
<p>I have a sneaky feeling that the properties will not be part of the service definition (WSDL) which would mean you may not be able to use them. If possible try to convince who ever maintains the service to expose the properties as actual methods.</p> <p>It is quite likely that you will be unable to access the properties in which case you may just be out of luck. Sorry.</p> <p>I am going to try exposing a property and then I will report the results back here.</p> <p>EDIT: Cannot expose an interface property using WCF, it simply will not compile</p> <pre><code>[ServiceContract] public interface IFooService { [OperationContract] // This is not allowed, it will not compile string Name { get; set; } } </code></pre> <p>EDIT: Cannot be done using ASMX web services either. : (</p> <pre><code>[WebService(Namespace = "http://tempuri.org/")] public class FooService : System.Web.Services.WebService { [WebMethod] // This is not allowed, it will not compile string Name { get; set; } } </code></pre>
27,662
<p>Here is the scenario: </p> <p>I have a table with a margin-bottom of 19px. Below that I have a form that contains some fieldsets. One of them is floated right. The problem is that the margin-bottom is not getting the full 19px in IE7. I've gone through all of the IE7 css/margin/float bugs that I can think of and have tried remedies but have been unsuccessful. I have been googling for a while now and cannot find anything that is helping out. </p> <p>Here is what I have tried. </p> <ol> <li>Wrapping the form or fieldset in an unstyled div. No apparent change.</li> <li>Nixing the margin-bottom on the table and instead wrapping that with a div and giving it a padding-bottom of 19px. No apparent change.</li> <li>Nixing the margin-bottom on the table and adding a div with a fixed height of 19px. No apparent change.</li> <li>Putting a clear between the table and the fieldset.</li> </ol> <p>I know there are some others that I am forgetting, but those are the things I have tried out recently. This happens to each fieldset. </p> <hr> <p>I am using a reset style sheet and have a xhtml transitional doctype. </p> <p><strong>Edit:</strong> I also have the IE7 web developer toolbar and Firebug. The style information for both browsers says that it has a margin-bottom: 19px; but it clearly is not for IE7.</p>
<p>if you have floated and unfloated elements, the only surefire way to ensure vertical space between them cross-browser is padding-top on the subsequent element.</p>
<p>I wouldn't know for sure without testing but try placing this between the table and the fieldset:</p> <pre><code>&lt;br style="clear:both;" /&gt; </code></pre>
3,614
<p>Is there any performance to be gained these days from compiling java to native code, or do modern hotspot compilers end up doing this over time anyway?</p>
<p>There was a similar discussion here recently, for the question <a href="https://stackoverflow.com/questions/48144/what-are-advantages-of-bytecode-over-native-code">What are advantages of bytecode over native code?</a>. You can find interesting answers in that thread.</p>
<p>Tried Hello-World in with six different implementations just to check the overhead and the difference was staggering. Java was off the charts while the compiled languages did equally well. I could proved all the evidence (in a reproducible) if needed.</p>
7,430
<p>I have been trying to set up my Beta 1 MVC app on IIS 6 and cannot get it to run correctly. I have added a Wildcard mapping to the .net isapi DLL as suggested in other blog posts but get the following error when I access the root of the website:</p> <pre><code>The incoming request does not match any route. .. [HttpException (0x80004005): The incoming request does not match any route.] System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +147 System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +36 System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +4 HCD.Intranet.Web.Default.Page_Load(Object sender, EventArgs e) +81 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436 </code></pre> <p>I am using the Default.aspx page supplied in the MVC template application that rewrites access to the root of the website properly.</p> <pre><code>public partial class Default : Page { public void Page_Load(object sender, System.EventArgs e) { HttpContext.Current.RewritePath(Request.ApplicationPath); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); } } </code></pre> <p>If I try and access a route within the application, such as /Project, I get the standard IIS 404 error page, not the .net error page.</p> <p>I tried adding the following line to my Web.config httpHandlers section:</p> <pre><code>&lt;add verb="*" path="*" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt; </code></pre> <p>This gave me a different error - the .net 404 error page.</p> <p>I added the following to my Global.asax, which did nothing:</p> <pre><code>protected void Application_BeginRequest(object sender, EventArgs e) { if (Context.Request.FilePath.Equals("/")) Context.RewritePath("Default.aspx"); } </code></pre> <p>I am using the following route configuration (uses the restful routing supplied by the MvcContrib project):</p> <pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); SimplyRestfulRouteHandler.BuildRoutes(routes); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre> <p>Any suggestions would be grealy received as I've exhausted all options for the time I have right now.</p> <p>Many thanks.</p>
<p>Here's what I did to get extensionless URLs working with IIS 6 and ASP.NET MVC Beta 1.</p> <ul> <li>Create a default ASP.NET MVC Beta project and compile it.</li> <li>Create a new IIS website pointing to the application directory.</li> <li>In the IIS properties for the website, click the HomeDirectory tab.</li> <li>Click the "Configuration..." button. In the "Mappings" tab, click "Insert..."</li> <li>Next to the "Wildcard application maps" label In the textbox, type in "c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll"</li> <li>Uncheck the box labelled "Verify that file exists" Click OK</li> <li>Navigate to /home It worked!</li> </ul> <p>You shouldn't need to change web.config at all. You just need to map all requests to IIS to the ASP.NET Isapi dll otherwise ASP.NET will never get those requests.</p>
<p>Unfortunatly IIS 6 needs a file extension to map the request to the right handler which means you will have to use the .mvc suffix on your controller names, such as <em>/{controller}.mvc/{action}</em></p> <pre><code>routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); SimplyRestfulRouteHandler.BuildRoutes(routes); routes.MapRoute( "Default", "{controller}.mvc/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre> <p>However, the are ways around this depending on your level of control on the IIS 6 server. Please refer to the following pages for more information</p> <ul> <li><a href="http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/" rel="nofollow noreferrer">http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/</a></li> <li><a href="http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx" rel="nofollow noreferrer">http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx</a></li> </ul>
34,779
<p>I'm learning Java and I'm wondering what everyone's Java rules are. The rules that you know intrinsically and if you see someone breaking them you try to correct them. Things to keep you out of trouble or help improve things. Things you should never do. Things you should always do. The rules that a beginner would not know.</p>
<p>Read <a href="http://java.sun.com/docs/books/effective/" rel="nofollow noreferrer">Effective Java</a> by Bloch.</p> <p>It's exactly what you're asking for, a set of rules for writing really great, idiomatic java code.</p>
<ol> <li><p>Use recursion as little as possible. There are uses for recursion, but most of the time a simple loop will do the same job without the overhead created with recursion. </p></li> <li><p>use Generics where possible. Many times a class can be used for an application that you never thought of when it was developed. Generics eases the process of reuse without refactoring.</p></li> </ol>
21,747
<p>I have always found this to be a very useful feature in Visual Studio. For those who don't know about it, it allows you to edit code while you are debugging a running process, re-compile the code <em>while the binary is still running</em> and continue using the application seamlessly with the new code, without the need to restart it.</p> <p>How is this feature implemented? If the code I am modifying is in a DLL loaded by the application, does the application simply unload the DLL and reload it again? This would seem to me like it would be prone to instability issues, so I assume it would be smarter than this. Any ideas?</p>
<p>My understanding is that when the app is compiled with support for Edit and Continue enabled, the compiler leaves extra room around the functions in the binary image to allow for adding additional code. Then the debugger can compile a new version of the function, replace the existing version (using the padding space as necessary), fix up the stack, set the instruction pointer, and keep going. That way you don't have to fix up any jump pointers, as long as you have enough padding.</p> <p>Note that Edit and Continue doesn't usually work on code in libs/dlls, only with the main executable code.</p>
<p>My guess is all objects are aligned to a 4096 byte memory boundary. So if you make small changes to some code then the objects will still be within those boundaries and therefore run as before.</p> <p>I've had instances where changing a couple of lines will cause a full recompile and link and others where a fairly substantial refactoring of a function will e&amp;c just fine.</p>
27,740
<p>I've created a Silverlight project that produces [something].xap file to package a few silverlight UserControls. I would like to manipulate that .xap file through the use of javascript in the browser to show and hide user controls based upon java script events.</p> <p>Is it possible to do this?</p> <p>If so any sample could or links to documentation would be appreciated.</p> <p>Thanks in advance</p> <p>Kevin</p>
<p>Here's my solution...not sure if it's the "best-practices" way...comments????</p> <p>In the App class within my Silverlight application I have the following code:</p> <pre><code> private Page _page = null; private void Application_Startup(object sender, StartupEventArgs e) { _page = new Page(); this.RootVisual = _page; HtmlPage.RegisterScriptableObject("App", this); } </code></pre> <p>Also to the App class I add a [ScriptableMember] to be called from JavaScript</p> <pre><code> [ScriptableMember] public void ShowTeamSearch(Guid ctxId, Guid teamId) { _page.ShowTeamSearcher(ctxId, teamId); } </code></pre> <p>The Page class is the default one that get's created within the Silverlight Control project, it really doesn't have any UI or logic, it's just used to swap in/out the views.</p> <pre><code> Login oLogin; TeamSearcher oSearcher; public Page() { InitializeComponent(); oLogin = new Login(); oSearcher = new TeamSearcher(); oLogin.Visibility = Visibility; this.LayoutRoot.Children.Add(oLogin); } </code></pre> <p>Also a method is added to show/hide the views...this could/will probably get more advanced/robust with animations etc...but this shows the basic idea:</p> <pre><code> public void ShowTeamSearcher(Guid ctxId, Guid teamId) { oSearcher.UserTeamId = teamId; oSearcher.UserContextId = ctxId; LayoutRoot.Children.Remove(oLogin); LayoutRoot.Children.Add(oSearcher); } </code></pre> <p>Then to invoke this in the JavaScript after assigning the id of oXaml to the instance of the silverlight host.</p> <pre><code> var slControl = document.getElementById('oXaml'); slControl.Content.App.ShowTeamSearch(sessionId, teamId); </code></pre> <p>This seems to work and isn't all that bad of a solution, but there might be something better...thoughts?</p>
<p>Here is a my collections of my links for this subject.</p> <ul> <li><a href="http://weblogs.asp.net/albertpascual/archive/2008/08/13/javascript-communication-to-silverlight-2-0.aspx" rel="nofollow noreferrer">Javascript communication to Silverlight 2.0</a></li> <li><a href="http://www.wilcob.com/Wilco/Articles/silverlight-interoperability.aspx" rel="nofollow noreferrer">Silverlight interoperability</a></li> <li><a href="http://pietschsoft.com/post/2008/06/Silverlight-and-JavaScript-Interop-Basics.aspx" rel="nofollow noreferrer">Silverlight and JavaScript Interop Basics</a></li> </ul>
32,317
<p>We recently had a problem where, after a series of commits had occurred, a backend process failed to run. Now, we were good little boys and girls and ran <code>rake test</code> after every check-in but, due to some oddities in Rails' library loading, it only occurred when we ran it directly from Mongrel in production mode.</p> <p>I tracked the bug down and it was due to a new Rails gem overwriting a method in the String class in a way that broke one narrow use in the runtime Rails code.</p> <p>Anyway, long story short, is there a way, at runtime, to ask Ruby where a method has been defined? Something like <code>whereami( :foo )</code> that returns <code>/path/to/some/file.rb line #45</code>? In this case, telling me that it was defined in class String would be unhelpful, because it was overloaded by some library. </p> <p>I cannot guarantee the source lives in my project, so grepping for <code>'def foo'</code> won't necessarily give me what I need, not to mention if I have <em>many</em> <code>def foo</code>'s, sometimes I don't know until runtime which one I may be using.</p>
<p>This is really late, but here's how you can find where a method is defined:</p> <p><a href="http://gist.github.com/76951" rel="noreferrer">http://gist.github.com/76951</a></p> <pre><code># How to find out where a method comes from. # Learned this from Dave Thomas while teaching Advanced Ruby Studio # Makes the case for separating method definitions into # modules, especially when enhancing built-in classes. module Perpetrator def crime end end class Fixnum include Perpetrator end p 2.method(:crime) # The "2" here is an instance of Fixnum. #&lt;Method: Fixnum(Perpetrator)#crime&gt; </code></pre> <p>If you're on Ruby 1.9+, you can use <a href="http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-source_location" rel="noreferrer"><code>source_location</code></a></p> <pre><code>require 'csv' p CSV.new('string').method(:flock) # =&gt; #&lt;Method: CSV#flock&gt; CSV.new('string').method(:flock).source_location # =&gt; ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180] </code></pre> <p>Note that this won't work on everything, like native compiled code. The <a href="http://www.ruby-doc.org/core-1.9.3/Method.html" rel="noreferrer">Method class</a> has some neat functions, too, like <a href="http://www.ruby-doc.org/core-1.9.3/Method.html#method-i-owner" rel="noreferrer">Method#owner</a> which returns the file where the method is defined.</p> <p>EDIT: Also see the <code>__file__</code> and <code>__line__</code> and notes for REE in the other answer, they're handy too. -- wg</p>
<p>You might be able to do something like this:</p> <p>foo_finder.rb:</p> <pre><code> class String def String.method_added(name) if (name==:foo) puts "defining #{name} in:\n\t" puts caller.join("\n\t") end end end </code></pre> <p>Then ensure foo_finder is loaded first with something like </p> <pre><code>ruby -r foo_finder.rb railsapp </code></pre> <p>(I've only messed with rails, so I don't know exactly, but I imagine there's a way to start it sort of like this.)</p> <p>This will show you all the re-definitions of String#foo. With a little meta-programming, you could generalize it for whatever function you want. But it does need to be loaded BEFORE the file that actually does the re-definition.</p>
21,162
<p>Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?</p> <p>For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.</p>
<p>Yes I have done so. I used Firebug to find out the Dot.Net JS functions and then hijacked the validator functions</p> <p>The following will be applied to all validators and is purely client side. I use it to change the way the ASP.Net validation is displayed, not the way the validation is actually performed. It must be wrapped in a $(document).ready() to ensure that it overwrites the original ASP.net validation.</p> <pre><code>/** * Re-assigns a couple of the ASP.NET validation JS functions to * provide a more flexible approach */ function UpgradeASPNETValidation(){ // Hi-jack the ASP.NET error display only if required if (typeof(Page_ClientValidate) != "undefined") { ValidatorUpdateDisplay = NicerValidatorUpdateDisplay; AspPage_ClientValidate = Page_ClientValidate; Page_ClientValidate = NicerPage_ClientValidate; } } /** * Extends the classic ASP.NET validation to add a class to the parent span when invalid */ function NicerValidatorUpdateDisplay(val){ if (val.isvalid){ // do custom removing $(val).fadeOut('slow'); } else { // do custom show $(val).fadeIn('slow'); } } /** * Extends classic ASP.NET validation to include parent element styling */ function NicerPage_ClientValidate(validationGroup){ var valid = AspPage_ClientValidate(validationGroup); if (!valid){ // do custom styling etc // I added a background colour to the parent object $(this).parent().addClass('invalidField'); } } </code></pre>
<p>What you can do is hook into the validator and assign a new evaluate method, like this:</p> <pre><code> &lt;script type="text/javascript"&gt; rfv.evaluationfunction = validator; function validator(sender, e) { alert('rawr'); } &lt;/script&gt; </code></pre> <p>rfv is the ID of my required field validator. You have to do this at the bottom of your page so that it assigns it after the javascript for the validator is registered.</p> <p>Its much easier just to use the CustomFieldValidator and assign its client side validation property.</p> <pre><code>&lt;asp:CustomValidator ControlToValidate="txtBox" ClientValidationFunction="onValidate" /&gt; &lt;script type='text/javascript'&gt; function onValidate(sender, e) { alert('do validation'); } &lt;/script&gt; </code></pre> <p>Check out the documentation <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx" rel="nofollow noreferrer">here</a> and <a href="http://msdn.microsoft.com/en-us/library/aa719700(VS.71).aspx" rel="nofollow noreferrer">here</a>.</p>
15,166
<p>In college I've had numerous design and <a href="http://en.wikipedia.org/wiki/Unified_Modeling_Language" rel="noreferrer">UML</a> oriented courses, and I recognize that UML can be used to benefit a software project, especially <a href="http://en.wikipedia.org/wiki/Use_case" rel="noreferrer">use-case</a> mapping, but is it really practical? I've done a few co-op work terms, and it appears that UML is not used heavily in the industry. Is it worth the time during a project to create UML diagrams? Also, I find that class diagrams are generally not useful, because it's just faster to look at the header file for a class. Specifically which diagrams are the most useful?</p> <p><strong>Edit:</strong> My experience is limited to small, under 10 developer projects.</p> <p><strong>Edit:</strong> Many good answers, and though not the most verbose, I belive the one selected is the most balanced.</p>
<p>In a sufficiently <strong>complex system</strong> there are some places where some <code>UML</code> is considered useful. </p> <p>The useful diagrams for a system, vary by applicability.<br> But the most widely used ones are: </p> <ul> <li>Class Diagrams</li> <li>State Diagrams</li> <li>Activity Diagrams</li> <li>Sequence Diagrams</li> </ul> <p>There are many enterprises who swear by them and many who outright reject them as an utter waste of time and effort. </p> <p>It's best not to go overboard and think what's best for the project you are on and pick the stuff that is applicable and makes sense.</p>
<p>UML is just one of methods for communication within people. Whiteboard is better.</p>
3,935
<p>I have a table named categories, which contains ID(long), Name(varchar(50)), parentID(long), and shownByDefault(boolean) columns. </p> <p>This table contains 554 records. All the shownByDefaultValues are 'false'.<br> When I execute 'select id, name from categories', pg returns me all the categories, orderer by its id.<br> Then I update some of the rows of the table('update categories set shownByDefault where parentId = 1'), update OK.<br> Then, when I try to execute the first query, which returns all the categories, they are returner with a very weird order.<br> I do not have problem to add 'order by', but since I am using JPA to get this values, anyone knows what the problem is or if there is a way to fix this?</p>
<p>That's not a problem. The order of rows returned by a SQL SELECT is undefined unless it has an <code>ORDER BY</code>. The order you get them is usually influenced by the order they are stored in the table and/or the indices that are used by the statement.</p> <p>So depending on that order without using <code>ORDER BY</code> is a very, very bad idea.</p> <p>If you need them in some order, simply specify that.</p> <p>It is important that a table is a <a href="http://en.wikipedia.org/wiki/Set_(mathematics)" rel="noreferrer">set</a> of rows and not a <a href="http://en.wikipedia.org/wiki/Sequence" rel="noreferrer">sequence</a> of rows.</p>
<p>The rows are returned in whatever their physical order on disk is; you can reorder them physically using the <code>CLUSTER</code> SQL command, but due to the way Postgres works they'll become unordered as soon as you start modifying rows.</p> <p>For what you're doing an <code>ORDER BY</code> is the right answer.</p>
48,239
<p>I'm writing this question here hoping someone will be able to help me with the fixing process that I'm currently involved in!</p> <p>Last week during a printing session my Ultimaker original unexpectedly stop working. The problem was on the extruder step motor which push the filament from the back and literally is not moving anymore! The first thing I have done was to check if the motor was burn or something similar. So I swap the extruder motor with the X-axis one and it then worked fine. </p> <p>Then later the X-axis motor into the extruder connector and is not moving! so I decided to check the step driver and they seems to work all well. So the problem must be on the Arduino or on the motherboard! I bought new step driver a new step motor and new Arduino + motherboard, connected all up and nothing, still not working for the same reason! It is just the extruder motor that won't work anymore!</p> <p>Do you guys have some idea or tips to find out what the problem can be or how can be fixed in alternative ways? Your help will be much appreciated and looking forward for some answers.</p>
<p>I'm not sure I know exactly what is wrong or what steps you've taken so far, but it seems like your extruder motor is broken and you've narrowed the problem down to electronics. <br> If so, replacing the Arduino, motor, and driver leaves only the Ultimaker PCB as the source of the problem. I would suggest ordering another - but not until you've contacted Ultimaker with the problem you're outlining here.</p>
<p>Your title says "x-axis" but your description leads me to think that your extruder is the part that's not working. Here are some tips which may (or may not) help...</p> <ul> <li>Make sure your extruder is not clogged.</li> <li>Make sure your temperature setting is high enough to allow the filament to melt quickly enough to support your print speed. If your extruder stepper is getting very hot, you may be pushing it too hard. Modern stepper drivers have various protections that will cause them to shut down in this situation. (Over current or thermal shutdown being the most likely in this case)</li> <li>If you swap stepper motors and swap stepper drivers and the issue stays with your extruder, look for other things that you haven't swapped. </li> <li>You haven't swapped the extruder, so the problem could be there as I mentioned above. </li> <li>If you haven't swapped wires, the problem could be there...I've struggled through troubleshooting many times because of intermittent connections in wires. Since 3d printers have moving wires, this is a prime suspect in older machines.</li> <li>Rule out all of the easy and cheap stuff before you conclude that it must be the main board...it could be, but it's probably not.</li> <li>Seek help in the Ultimaker forums or with their technical support. Printers, like cars, tend to have certain things that are more prone to failure as the machines get old and worn. The Ultimaker techs will know these things and can help you pin down your issue.</li> </ul> <p>Good luck! I hope you solve your issue and that this answer is helpful. :-)</p>
379
<p>I am getting the following error when an event (Add/Edit/Delete) occurs on my databound control.</p> <blockquote> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.</p> </blockquote> <p>I am using a custom DataList control, but this problem also occurs with GridView, DetailsView, FormView and Repeater control (and maybe with other databound controls).</p> <p>The answers I can find tell me to turn off the validation in the config file or page, but that does not sound like it is the best solution. What am I doing wrong?</p>
<p>The problem is loading the data for the control in the page Load event and calling the DataBind() method. However it appears that if the DataBind() method is called before the events are raised the above exception is generated as the control naming has changed.</p> <p>The solution is to change this to if(!IsPostback) DataBind() and then call the DataBind() method at the end of the event handler. You would need to call it most of the time anyway at the end of the handler to affect the changes.</p> <p>If this is not your problem, and you are modifying controls client side using JavaScript, check out <a href="http://odetocode.com/Blogs/scott/archive/2006/03/21/3153.aspx" rel="noreferrer">this article</a>.</p> <p><em>This is a self answered post as I was getting a lot of responses on my blog to this issue and thought I might share it further.</em></p>
<p>I was experiencing the same issue and it took me few hours to solve my problem. Robert answer partially helped me and despite databinding my repeater regardless of post back or not, problem still persisted. After lot of research i came across a post which suggested setting <strong>UseSubmitBehavior="false"</strong>, bingo and it solved the issue. Hopefully this will help. </p>
37,486
<p>The company I work for is thinking of developing a LAMP SaaS Web application that would be plan based. We want to monitor usage because it involves external references, and would draw bandwidth through the placement of an iframe or JavaScript snippet on a third-party site. My first thought was relying only on a page impression algorithm, but since this is really a bandwidth issue, I wonder if monitoring that is a better approach. What is the best way to do this monitoring in a fashion that would allow me to message the third-party site that the cap has been exceeded?</p>
<p>I think a web service gateway would be a good option. Most of them (IBM, Layer 7, Vordel) offer throttling and contract management features. They'll allow you to set thresholds on access to whatever is behind them. </p> <p>If you're using authorization and authentication for users and service, you can easily configure them to send a notification if the usage gets too high (from abuse, exceeding the SLA for requests, or whatever else you configure.</p> <p>Best of all, they'll work with whatever is consuming your application / data, be it users, batch processes, or services. </p>
<p>Maybe you should use cloud computing services, who will monitor the bandwidth usage for each client. It will allow you to set the cap for each client as well.</p> <p>I read <a href="http://www.mosso.com" rel="nofollow noreferrer">Mosso.com</a> can do this.</p> <p>regards</p>
34,467
<p>I have an application which <em>really</em> should be installed, but does work fine when deployed using JNLP.</p> <p>However, it would seem that some Java functions such as <code>Runtime.exec</code> don't work using the default security options.</p> <p>I would like to therefore <a href="http://www.joelonsoftware.com/items/2008/07/01.html" rel="nofollow noreferrer">disable</a> UI functionality that relies upon such functions. </p> <p>So my question is, <strong>how do I detect at runtime whether certain functions are available or not?</strong></p> <p>The case study, here of course, is <code>Runtime.exec</code>.</p>
<p>You want to ask to the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/SecurityManager.html" rel="nofollow noreferrer">SecurityManager</a> if you have Exec right with the checkExec method.</p>
<p>For the specific example of Runtime.exec there is a method on the SecurityManager class checkExec(String cmd) that will throw an exception that can be caught to determine if the necessary command can be executed. For more information see the javadoc for Runtime.exec and SecurityManager.checkExec.</p> <p>The more general case requires creating a Permission object representing the task being checked and running SecurityManager's checkPermission method. </p>
5,393
<p>when putting a ScrollViewer inside a window(not keeping all the window's size) inside the ScrollViewer there's (with other stuff) a WinFormsHost and a control inside (let's say a DateTimePicker). when scrolling, the inner winforms control keeps being visible when there's no longer a reason (it's outside of the scrolling region), so it "floats" above what's outside of the ScrollViewer</p> <p>any solutions for that?</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/ms752027.aspx" rel="noreferrer">this msdn link</a> </p> <blockquote> <p>WindowsFormsHost elements are always drawn on top of other WPF elements, and they are unaffected by z-order</p> </blockquote> <p>I don't think there's an easy solution. You might want to consider having the windows forms control handle the scrolling itself instead of using WPF's ScrollViewer.</p>
<p>Just add in ScrollViewer control property:</p> <pre><code>VerticalScrollBarVisibility="Auto" </code></pre> <p>and set Height to Your max height. That's all.</p>
14,869
<p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;myElement&gt;foo&lt;/myElement&gt; </code></pre> <p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;myElement&gt;bar&lt;/myElement&gt; </code></pre> <p>Once I am done, I want to save the changes. </p> <p>What is the easiest and simplest way to accomplish all this?</p>
<p>Use Python's <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow noreferrer">minidom</a></p> <p>Basically you will take the following steps:</p> <ol> <li>Read XML data into DOM object</li> <li>Use DOM methods to modify the document</li> <li>Save new DOM object to new XML document</li> </ol> <p>The python spec should hold your hand rather nicely though this process. </p>
<p>You also might want to check out Uche Ogbuji's excellent XML Data Binding Library, Amara: <a href="http://uche.ogbuji.net/tech/4suite/amara" rel="nofollow noreferrer">http://uche.ogbuji.net/tech/4suite/amara</a></p> <p>(Documentation here: <a href="http://platea.pntic.mec.es/~jmorilla/amara/manual/" rel="nofollow noreferrer">http://platea.pntic.mec.es/~jmorilla/amara/manual/</a>)</p> <p>The cool thing about Amara is that it turns an XML document in to a Python object, so you can just do stuff like:</p> <pre class="lang-python prettyprint-override"><code>record = doc.xml_create_element(u'Record') nameElem = doc.xml_create_element(u'Name', content=unicode(name)) record.xml_append(nameElem) valueElem = doc.xml_create_element(u'Value', content=unicode(value)) record.xml_append(valueElem </code></pre> <p>(which creates a Record element that contains Name and Value elements (which in turn contain the values of the name and value variables)).</p>
21,616
<p>I've an issue with the same piece of code running fine on my live website but not on my local development server.</p> <p>I've an Ajax function that updates a div. The following code works on the live site:</p> <pre>self.xmlHttpReq.open("POST", PageURL, true); self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length); //..update div stuff... self.xmlHttpReq.send(QueryString);</pre> <p>When I try to run this on my local machine, nothing is passed to the QueryString.</p> <p>However, to confuse matters, the following code <strong>does</strong> work locally:</p> <pre>self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //..div update stuff.. self.xmlHttpReq.send(QueryString);</pre> <p>But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!</p> <p>I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.</p> <p>Live Site is running IIS 6 (on a WIN 2003 box I think)</p> <p>Local Site is running IIS 5.1 (On XP Pro)</p> <p>Are there some updates or something I'm missing or something?</p>
<p>Is there a reason you're explicitly setting the <code>Content-Length</code> header in the first example? You... <em>shouldn't</em> need to do this, and i wouldn't be surprised to find it causing problems. </p> <p>Oh, and check your encoding routine. The rules are not <em>quite</em> the same for querystrings and POSTed form data.</p>
<p>I would guess that Shog9 is right, and that IIS 6 i smart enough to ignore your request and send the correct headers, while 5.2 throws an error.</p>
13,131
<p>We're doing a lot of large, but straightforward forms for a fairly big project (about 600 users using it throughout the day - that's big for me at least ;-) ).</p> <p>The forms have a lot of question/answer type sections, so it's natural for some people to type a sentence, while others type a novel. <strong>How beneficial would it be to put a character limit on some of these fields <em>really</em>?</strong></p> <p>(Please include references or citations, if necessary/possible - Thanks!)</p>
<p>If you have no limitations on the data size, then why worry. This doesn't sound like a mission critical project, even with 600 users and several thousand records. Use CLOB/BLOB and be done with it. I have doubts as to whether you would see any major gains in limiting sizes and risking data loss. That said, you should layout such boundaries before implementation.</p> <p>Usually varchar is best for storing values that you wish to use logically and perform "whole value" comparisons against. Text is for unstructured data. If your project is a survey result with unstructured text, use CLOB/BLOB</p> <p>Semi-Reference: I work with hundreds of thousands of call center records sometimes where we use a CLOB to store the dialog between employees and customers.</p>
<p>from: <a href="http://www.making-the-web.com/2008/03/24/saving-bytes-efficient-data-storage-mysql-part-1/" rel="nofollow noreferrer">http://www.making-the-web.com/2008/03/24/saving-bytes-efficient-data-storage-mysql-part-1/</a></p> <p>There are a few variations of the TEXT and BLOB types which affect size; they are:</p> <pre><code>Type - Maximum Length -Storage TINYBLOB, TINYTEXT 255 Length+1 bytes BLOB, TEXT 65535 Length+2 bytes MEDIUMBLOB, MEDIUMTEXT 16777215 Length+3 bytes LONGBLOB, LONGTEXT 4294967295 Length+4 bytes </code></pre>
30,134
<p>I wonder if there is an example which html files and java files are resides in different folders. </p>
<p>I don't recommend using a separate page directory unless you are quite comfortable with how resource streams work, which I am not.</p> <p>The vast majority of wicket projects I have seen keep class and html files in the source directory. I tried separating them myself but then found that getting my hands on other resources, like images and such, was a hassle; so, I wound up putting those resources in the package directory - in the end I had resources in several different places and it was more of a mess than putting everything in package directory would have been. </p> <p>That said, here's the code I used to put my html templates in a separate folder. It should be added to Init() in your application class.</p> <pre><code>IResourceSettings resourceSettings = getResourceSettings(); resourceSettings.addResourceFolder("pages"); //the full path to your folder, relative to the context root resourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator()); </code></pre> <p><a href="https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from" rel="nofollow noreferrer">https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from</a> has a tutorial on this.</p>
<p>This is one area where using Maven to manage your project is very nice. Since Maven has two locations that are included on the classpath, you can logically separate the Java source and the HTML files and still have them maintain the same package structure. The Java code goes into src/main/java and the HTML goes into src/main/resources. When building or running the code both of these locations are added to the classpath.</p> <p>If Maven isn't for you perhaps this idea could be applied to whatever environment you are using.</p>
34,490
<p>Let's say we have <code>index.php</code> and it is stored in <code>/home/user/public/www</code> and <code>index.php</code> calls the class <code>Foo-&gt;bar()</code> from the file <code>inc/app/Foo.class.php</code>. </p> <p>I'd like the bar function in the <code>Foo</code> class to get a hold of the path <code>/home/user/public/www</code> in this instance — I don't want to use a global variable, pass a variable, etc.</p>
<p>Wouldn't this get you the directory of the running script more easily?</p> <pre><code>$dir=dirname($_SERVER["SCRIPT_FILENAME"]) </code></pre>
<p>Found it. getcwd().</p>
16,906
<p>When building a VS 2008 solution with 19 projects I sometimes get:</p> <pre><code>The "GenerateResource" task failed unexpectedly. System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.IO.MemoryStream.set_Capacity(Int32 value) at System.IO.MemoryStream.EnsureCapacity(Int32 value) at System.IO.MemoryStream.WriteByte(Byte value) at System.IO.BinaryWriter.Write(Byte value) at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value) at System.Resources.ResourceWriter.Generate() at System.Resources.ResourceWriter.Dispose(Boolean disposing) at System.Resources.ResourceWriter.Close() at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer) at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename) at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile) at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass) at Microsoft.Build.Tasks.GenerateResource.Execute() at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean&amp; taskResult) C:\Windows\Microsoft.NET\Framework\v3.5 </code></pre> <p>Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.</p> <p>I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources.</p>
<p>From <a href="https://social.msdn.microsoft.com/Forums/vstudio/en-US/5154ef26-ccfe-44d5-a322-6804b61ac774/systemoutofmemoryexception?forum=clr" rel="nofollow noreferrer">https://social.msdn.microsoft.com/Forums/vstudio/en-US/5154ef26-ccfe-44d5-a322-6804b61ac774/systemoutofmemoryexception?forum=clr</a>:</p> <p>Try deleting the .suo file and re-opening the solution.</p>
<p>I have already passed by this erros sometimes. All you must do is delete all files in the obj path. After that clean and rebuild your solution and it´s done.</p>
3,580
<p>I'm using grails j2d which in turns uses <code>GraphicsBuilder</code> to make a simple service to scale an image. My problem is specifically accessing the downloaded image height and width attributes in order to pass the correct parameters to the scale method. How do I access these attributes inside the transformations closure? </p> <pre><code>Controller { def scale = { def targetW = new Integer(params?.w?:64) def targetH = new Integer(params?.h?:48) renderImage( [width: targetW ,height: targetH ] ) { image( url: params?.url ) { transformations { scale( x: 1 , y: 1 , interpolation: 'bicubic' ) } } } } } </code></pre>
<p>I don't know the J2D plugin at all, but you might check into what the delegate is for the closure you're passing to the image call. Add a line like "def d = delegate" before the transformations call, and debug this to see what type the delegate is. If it's an Image, then you ought to be able to get delegate.width or delegate.w or some such.</p>
<p>The neswest j2d plugin exposes those values so you can pass as parameters normally.</p>
40,320
<p>we're have a client that needs to get interactive messages from a server, from clients that are distributed around the world behind all kinds of firewalls with all kinds of ports closed. The only thing we can rely on is HTTP port 80 (and HTTPS 443).</p> <p>The design is basically modeled after XMPP (the Jabber protocol), using our client and IIS. The client issues GET requests to a .NET Handler; the handler holds the request open for a while looking for messages. If any messages arrive, they are immediately sent to the client; if not, after a timeout the connection is closed with a "no-data" response. The client immediately reopens the communication.</p> <p>Well, theoretically.</p> <p>What's actually happening is first, IIS can't handle more than about 100 simultaneous requests - others are all queued, and there can be a several minute lag between "connected" and IIS recognizing that the client called in. Second, about half the time the client times out without any response from the server (the client timeout is five minutes longer than the server's).</p> <p>POST always works. Other data served on the same web server works. Web services on the same server work. This is an out-of-the-box installation on Windows 2K3 Server.</p> <p>Is there a configuration option we're missing, or is there something else I should look at to address this?</p> <p>Thanks.</p>
<p>I think you're hitting ASP.NET thread pool limits, rather than IIS ones. Look into creating a asynchronous HTTP handler (<code>IHttpAsyncHandler</code>) as when they block/wait they aren't tying up the thread pool (they use completion ports instead).</p> <p><strong>Update</strong>: Came across this recently that seems to concur with my thinking: <a href="http://www.codeproject.com/KB/aspnet/CometAsync.aspx" rel="nofollow noreferrer">CodeProject: Scalable COMET Combined with ASP.NET</a></p>
<p>XMPP was never designed for high performance applications. The messages must traverse through the entire stack to the application layer, and there is a lot of XML parsing. Have you considered using some other standard besides XMPP?</p>
15,012
<p>Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a <code>Contains()</code> method. There are several ways of dealing with this.</p> <ul> <li>Implement your own <code>Contains()</code> method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.</li> <li>I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:</li> </ul> <blockquote> <pre><code>try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection } </code></pre> </blockquote> <p>My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?</p>
<p>I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable.</p> <p>My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result.</p> <p>For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject.</p> <p>All of these exceptions will get handled in the same way, which may not be your intention.</p> <p>These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:</p> <ul> <li><a href="http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx" rel="nofollow noreferrer">Foundations of Programming</a></li> <li><a href="http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx" rel="nofollow noreferrer">Throwing exceptions in c#</a></li> </ul> <p>I particularly like this quote from the second article:</p> <blockquote> <p>It is important that exceptions are thrown only when an unexpected or invalid activity occurs that prevents a method from completing its normal function. Exception handling introduces a small overhead and lowers performance so should not be used for normal program flow instead of conditional processing. It can also be difficult to maintain code that misuses exception handling in this way.</p> </blockquote>
<p>The latter is an acceptable solution. Although I would definitely catch on the specific exception (ElementNotFound?) that the collection throws in that case.</p> <p>Speedwise, it depends on the common case. If you're more likely to find the element than not, the exception solution will be faster. If you're more likely to fail, then it would depend on size of the collection and its iteration speed. Either way, you'd want to measure against normal use to see if this is actually a bottle neck before worrying about speed like this. Go for clarity first, and the latter solution is far more clear than the former.</p>
2,977
<p>What is the best way to store a user name and password for a Windows Service?</p> <p>The service has to be able to access an MS SQL Server database on a remote machine. We have to support MS SQL Server authentication (mixed mode) instead of NT Authentication. </p>
<p>The <a href="http://en.wikipedia.org/wiki/Data_protection_API" rel="nofollow noreferrer">DP API</a> is the standard way of locally storing sensitive data on Windows. You didn't mention the programming language you're using, but in .NET this is exposed from the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx" rel="nofollow noreferrer">System.Security.ProtectedData</a> class.</p>
<p>While I agree that, ideally, you would not need to store this password, if you do, there is no need to hash it yourself. <a href="http://msdn.microsoft.com/en-us/library/aa380261(VS.85).aspx" rel="nofollow noreferrer">CryptProtectData</a>. Read the warnings at the bottom of this article. Though, I actually used <a href="http://msdn.microsoft.com/en-us/library/ms721818(VS.85).aspx" rel="nofollow noreferrer">LsaStorePrivateData</a>, to store passwords. </p>
33,036
<p>I have a very eccentric, weird, unusual and strange idea. I need some advice and serious professional help.</p> <p>I'm interested in 3D printing in PLA a hollow complex structure with 0.2 thickness walls (Yes! That thin!). Fill it with very fine copper powder with a little borax powder thoroughly mixed. Use superglue to join halves or other shell pieces together, making sure the powder is very well compacted. Then in a separate container I want to make some thin plaster of Paris (calcium sulfate with a lot of water). Mix in it, some of my trimmed hair (about 5mm in length). No joke. Seriously. Please, I'm begging you with all my heart, hear me out! There's a very good useful reason for doing it. I then place the object (3D printed flimsy crappy shell filled with copper powder) in a DIY drywall box and pour in the plaster over the 3D printed shell object until the box is filled and object completely covered. Leave it to dry and completely solidify for a day. Then I bake the entire thing in a furnace making sure I'm over the copper melting temperature and voila! 3D printing in copper very complex intricate models with ease. Can it be that easy? Or am I deluding myself? The hair purpose, after it will burn inside the plaster while in the furnace, is to create very thin tubules or air holes for water and gases to escape and to prevent cracking of the plaster under intense heat. I don't want to use hay because the straws are too thick. I have to use very thin organic straws. I just can't think of anything more accessible than my hair. Do you know of something even thinner and more accessible than human hair? Please let me know. I know it sounds and looks very odd, weird and strange. I'm opened to alternatives or other suggestions, otherwise I wouldn't be here making a fool of myself with such an insane ridiculous idea.</p> <p>I was thinking to add some form of additional volume above the object, which is connected to the model by some thin hollow tube. All this volume (like an empty cube (shell) ) will also be filled with very fine copper powder providing additional melted copper to the model, in the case if the powder was not very well compacted inside the shell model.</p> <p>Could this absurd ridiculous insane crazy idea work? I have never heard of anything like this. This is so bizarre and strange. It seems to be some form of odd mix of multiple techniques. But besides all this, will it work in the end? Will the plaster hold while some of it(depends on the model) will be inside molten copper? Or do I have to mix in the plaster, not just hair, but also some individual singular fine strands of steel wool?</p> <p>I don't know who and where to ask such a thing. Am I in the right place? I don't know what this idea is, I don't know how to name it, I don't know how to ask or formulate this idea, I don't know how to google it or search it. I don't know anything. I really need some guidance, help and advice.</p>
<p><strong>I think this is just an overcomplicated lost-PLA (investment) casting.</strong></p> <p>What you're asking for is to create an object, create a mold around it, and then burn out the object and replace it with metal. Traditionally this is done with wax, <a href="https://en.wikipedia.org/wiki/Lost-wax_casting" rel="nofollow noreferrer">and called lost-wax casting</a>, but the same can be done with anything that melts/burns away, including PLA.</p> <p>Rather than worrying about burning hairs and pressure and compaction of metal powder, print a model, and use the correct kind of plaster (a search for &quot;investment casting plaster&quot; will get you going down the right path) to make your mold. Heat the metal powder in a crucible, instead of the mold itself, and pour it through the expansion/extra material tube you were talking about.</p>
<p>I don't see why it wouldn't work. It doesn't seem to be the optimal way but I haven't tried it.</p> <p>Only thing that might be an issue is that PLA doesn't burn away clean (not for me anyway) which can leave defects in the product. But there are filaments specifically made for casting which apparently burn away with no residue.</p> <p>This is assuming you can actually successfully print a complex object with walls that thin.</p>
2,134
<p>I am trying to <strong>replace the current selection in Word (2003/2007)</strong> by some <strong>RTF string</strong> stored in a variable.</p> <p>Here is the current code:</p> <pre><code>Clipboard.SetText(strRTFString, TextDataFormat.Rtf) oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) </code></pre> <p>Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?</p>
<p>Put the RTF in a file instead of the clipboard, then insert from the file, e.g.</p> <blockquote> <p><code>Selection.InsertFile FileName:="myfile.rtf", Range :="", _ ConfirmConversions:=False, Link:=False, Attachment:=False</code></p> </blockquote>
<p>You can use a RichTextbox to convert RTF to text or vice versa.</p> <pre><code>RichTextBox r = new RichTextBox(); r.Rtf = strRTFString; Console.WriteLine(r.Text); </code></pre>
4,233
<p>I'm working on an application that is supposed to create products (like shipping insurance policies) when PayPal Instant Payment Notifications are received. Unfortunately, PayPal sometimes sends duplicate notifications. Furthermore, there is another third-party that is performing web-service updates simultaneously when they get updates from PayPal as well.</p> <p>Here is a basic diagram of the database tables involved.</p> <pre><code>// table "package" // columns packageID, policyID, other data... // // table "insurancepolicy" // columns policyID, coverageAmount, other data... </code></pre> <p>Here is a basic diagram of what I want to do:</p> <pre><code>using (SqlConnection conn = new SqlConnection(...)) { sqlTransaction sqlTrans = conn.BeginTransaction(IsolationLevel.RepeatableRead); // Calls a stored procedure that checks if the foreign key in the transaction table has a value. if (PackageDB.HasInsurancePolicy(packageID, conn)) { sqlTrans.Commit(); return false; } // Insert row in foreign table. int policyID = InsurancePolicyDB.Insert(coverageAmount, conn); if (policyID &lt;= 0) { sqlTrans.Rollback(); return false; } // Assign foreign key to parent table. If this fails, roll back everything. bool assigned = PackageDB.AssignPolicyID(packageID, policyID, conn); if (!assigned) { sqlTrans.Rollback(); return false; } } </code></pre> <p>If there are two (or more) threads (or processes or applications) doing this at the same time, I want the first thread to lock the "package" row while it has no policyID, until the policy is created and the policyID is assigned to the package table. Then the lock would be released after the policyID is assigned to the package table. It is my hope that the other thread which is calling this same code will pause when it reads the package row to make sure it doesn't have a policyID first. When the first transaction's lock is released, it is my hope that the second transaction will see the policyID is there and therefore return without inserting any rows into the policy table.</p> <p>Note: Because of the CRUD database design, each the stored procedures involved either Read (select), Create (insert), or Update.</p> <p>Is this the right use of RepeatableRead transaction isolation?</p> <p>Thanks.</p>
<p>It would be safer and cleaner if <code>insert into Policy</code> just hit some uniqueness table constraint on attempt to insert duplicate. Raising isolation level can lower concurrency and lead to other nasty issues like deadlocks.</p> <p>Another way is to always insert Policy row, then roll it back if Package has been attached to a Policy already:</p> <pre><code>begin tran (read committed) /* tentatively insert new Policy */ insert Policy /* attach Package to Policy if it's still free */ update Package set Package.policy_id = @policy_id where Package.package_id = @package_id and Package.policy_id is null if @@rowcount &gt; 0 commit else rollback </code></pre> <p>This works best when conflicts are rare, which seems to be your case.</p>
<p>I agree with the "message queue" idea in aaronjensen's response. If you are concerned about multiple concurrent threads attempting to update the same row of data simultaneously, you should instead have the threads insert their data into a work queue, which is then processed sequentially by a single thread. This significantly reduces contention on the database, because the target table is updated by only one thread instead of "N", and the work queue operations are limited to inserts by the messaging threads, and a read/update by the data processing thread.</p>
15,125
<p>I work on a small web team where I am the only .NET developer currently using Visual Studio 2008 Professional to build and maintain a few web applications. I am about to start training another member of our team so we purchased him a copy of Visual Studio 2008 Professional. I've looked into Visual Source Safe, but I'm dubious. I don't like that is file system based. Ideally, the system would work with SQL Server 2005 and plug into Visual Studio. Windows based solutions are the best because of the IT environment of the organization I work for.</p> <p>What are my options for a source control system?</p> <p>(Forgive me if the answer exists in another thread.)</p>
<p><a href="http://subversion.tigris.org/" rel="noreferrer">Subversion</a> has good integration with Visual Studio 2008 through <a href="http://www.visualsvn.com/" rel="noreferrer">VisualSVN</a> and <a href="http://ankhsvn.open.collab.net/" rel="noreferrer">Ankh</a>. </p> <p>SourceSafe is dangerous. You're right that a filesharing-based SCM is a bad idea, and Microsoft themselves have downplayed it and replaced it with a new SCM that comes with the Team edition of Visual Studio.</p>
<p>Microsoft's Team Foundation Server integrates fully into VS2008 and uses SQL Server for its back end. The downside is that it's a very expensive solution.</p>
17,101
<p>I am looking for a way to clean up the mess when my top-level script exits.</p> <p>Especially if I want to use <code>set -e</code>, I wish the background process would die when the script exits.</p>
<p>To clean up some mess, <code>trap</code> can be used. It can provide a list of stuff executed when a specific signal arrives:</p> <pre><code>trap "echo hello" SIGINT </code></pre> <p>but can also be used to execute something if the shell exits:</p> <pre><code>trap "killall background" EXIT </code></pre> <p>It's a builtin, so <code>help trap</code> will give you information (works with bash). If you only want to kill background jobs, you can do</p> <pre><code>trap 'kill $(jobs -p)' EXIT </code></pre> <p>Watch out to use single <code>'</code>, to prevent the shell from substituting the <code>$()</code> immediately. </p>
<p>So script the loading of the script. Run a <code>killall</code> (or whatever is available on your OS) command that executes as soon as the script is finished.</p>
47,007
<p>I'm using C and sometimes I have to handle paths like</p> <ul> <li>C:\Whatever</li> <li>C:\Whatever\</li> <li>C:\Whatever\Somefile</li> </ul> <p>Is there a way to check if a given path is a directory or a given path is a file?</p>
<p>stat() will tell you this.</p> <pre><code>struct stat s; if( stat(path,&amp;s) == 0 ) { if( s.st_mode &amp; S_IFDIR ) { //it's a directory } else if( s.st_mode &amp; S_IFREG ) { //it's a file } else { //something else } } else { //error } </code></pre>
<p>Easier to try FileInfo.isDir() in qt</p>
17,689
<p>What is the best way to create a custom title for pages in a Rails app without using a plug-in?</p>
<p>In your views do something like this:</p> <pre><code>&lt;% content_for :title, "Title for specific page" %&gt; &lt;!-- or --&gt; &lt;h1&gt;&lt;%= content_for(:title, "Title for specific page") %&gt;&lt;/h1&gt; </code></pre> <p>The following goes in the layout file:</p> <pre><code>&lt;head&gt; &lt;title&gt;&lt;%= yield(:title) %&gt;&lt;/title&gt; &lt;!-- Additional header tags here --&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- If all pages contain a headline tag, it's preferable to put that in the layout file too --&gt; &lt;h1&gt;&lt;%= yield(:title) %&gt;&lt;/h1&gt; &lt;/body&gt; </code></pre> <p>It's also possible to encapsulate the <code>content_for</code> and <code>yield(:title)</code> statements in helper methods (as others have already suggested). However, in simple cases such as this one I like to put the necessary code directly into the specific views without custom helpers.</p>
<p>I would like to add my pretty simple variant.</p> <p>In the ApplicationController define this method:</p> <pre><code> def get_title @action_title_name || case controller_name when 'djs' 'Djs' when 'photos' 'Photos' when 'events' 'Various events' when 'static' 'Info' when 'club' 'My club' when 'news' 'News' when 'welcome' 'Welcome!' else 'Other' end end </code></pre> <p>After that you can call get_title from your layout's title tag. You can define more specific title for your page by defining @action_title_name variable in your actions.</p>
22,496
<p>I'm trying to insert a column into an existing DataSet using C#.</p> <p>As an example I have a DataSet defined as follows:</p> <pre><code>DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("column_1", typeof(string)); ds.Tables[0].Columns.Add("column_2", typeof(int)); ds.Tables[0].Columns.Add("column_4", typeof(string)); </code></pre> <p>later on in my code I am wanting to insert a column between column 2 and column 4.</p> <p>DataSets have methods for adding a column but I can't seem to find the best way in insert one.</p> <p>I'd like to write something like the following...</p> <pre><code>...Columns.InsertAfter("column_2", "column_3", typeof(string)) </code></pre> <p>The end result should be a data set that has a table with the following columns: column_1 column_2 column_3 column_4</p> <p>rather than: column_1 column_2 column_4 column_3 which is what the add method gives me</p> <p>surely there must be a way of doing something like this.</p> <p><strong>Edit</strong>...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:</p> <blockquote> <p>I am getting a data set from a stored procedure. I am then having to add additional columns to the data set which is then converted into an Excel document. I do not have control over the data returned by the stored proc so I have to add columns after the fact.</p> </blockquote>
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/system.data.datacolumn.setordinal.aspx" rel="noreferrer">DataColumn.SetOrdinal()</a> method for this purpose.</p> <pre><code>DataSet ds = new DataSet(); ds.Tables.Add(new DataTable()); ds.Tables[0].Columns.Add("column_1", typeof(string)); ds.Tables[0].Columns.Add("column_2", typeof(int)); ds.Tables[0].Columns.Add("column_4", typeof(string)); ds.Tables[0].Columns.Add("column_3", typeof(string)); //set column 3 to be before column 4 ds.Tables[0].Columns[3].SetOrdinal(2); </code></pre>
<p>Copy the first two columns into a new dataset, then add the third column, and add the remaining columns.</p> <p>You could wrap that in an InsertAfter function if necessary.</p>
45,776
<p>In a typical handheld/portable embedded system device Battery life is a major concern in design of H/W, S/W and the features the device can support. From the Software programming perspective, one is aware of MIPS, Memory(Data and Program) optimized code. I am aware of the H/W Deep sleep mode, Standby mode that are used to clock the hardware at lower Cycles or turn of the clock entirel to some unused circutis to save power, but i am looking for some ideas from that point of view:</p> <p>Wherein my code is running and it needs to keep executing, given this how can I write the code "power" efficiently so as to consume minimum watts?</p> <p>Are there any special programming constructs, data structures, control structures which i should look at to achieve minimum power consumption for a given functionality.</p> <p>Are there any s/w high level design considerations which one should keep in mind at time of code structure design, or during low level design to make the code as power efficient(Least power consuming) as possible? </p>
<ul> <li>Like <code>1800 INFORMATION</code> said, avoid polling; subscribe to events and wait for them to happen</li> <li>Update window content only when necessary - let the system decide when to redraw it</li> <li>When updating window content, ensure your code recreates as little of the invalid region as possible</li> <li>With quick code the CPU goes back to deep sleep mode faster and there's a better chance that such code stays in L1 cache</li> <li>Operate on small data at one time so data stays in caches as well</li> <li>Ensure that your application doesn't do any unnecessary action when in background</li> <li>Make your software not only power efficient, but also power aware - update graphics less often when on battery, disable animations, less hard drive thrashing</li> </ul> <p>And read some other <a href="https://software.intel.com/en-us/articles/partner-energy-efficient-software-guidelines" rel="nofollow noreferrer">guidelines</a>. ;)</p> <p>Recently a series of posts called <a href="http://software.intel.com/en-us/search/site/field_tags/software-17970/field_tags/acpi-18789/language/en/type/blog?query=Optimizing%20Software%20Applications%20for%20Power" rel="nofollow noreferrer">"Optimizing Software Applications for Power"</a>, started appearing on Intel Software Blogs. May be of some use for x86 developers.</p>
<p>also something that is not trivial to do is reduce precision of the mathematical operations, go for the smallest dataset available and if available by your development environment pack data and aggregate operations. </p> <p>knuth books could give you all the variant of specific algorithms you need to save memory or cpu, or going with reduced precision minimizing the rounding errors</p> <p>also, spent some time checking for all the embedded device api - for example most symbian phones could do audio encoding via a specialized hardware</p>
8,719
<p>Is it possible to embed a PowerPoint presentation (.ppt) into a webpage (.xhtml)?</p> <p>This will be used on a local intranet where there is a mix of Internet&nbsp;Explorer&nbsp;6 and Internet&nbsp;Explorer&nbsp;7 only, so no need to consider other browsers.</p> <hr> <p>I've given up... I guess Flash is the way forward.</p>
<p>Google Docs can serve up PowerPoint (and PDF) documents in it's document viewer. You don't have to sign up for Google Docs, just upload it to your website, and call it from your page:</p> <pre><code>&lt;iframe src="//docs.google.com/gview?url=https://www.yourwebsite.com/powerpoint.ppt&amp;embedded=true" style="width:600px; height:500px;" frameborder="0"&gt;&lt;/iframe&gt; </code></pre>
<p>The first few results on Google all sound like good options:</p> <p><a href="http://www.pptfaq.com/FAQ00708.htm" rel="nofollow noreferrer">http://www.pptfaq.com/FAQ00708.htm</a></p> <p><a href="http://www.webdeveloper.com/forum/showthread.php?t=86212" rel="nofollow noreferrer">http://www.webdeveloper.com/forum/showthread.php?t=86212</a></p>
6,100
<p>It seems like drag and drop upload widgets disappeared from the face of Web 2.0. The last one of these I remember using was an activex widget, and inability of using it in anything other than IE doomed it. Have you used or seen one of these recently?</p>
<p>The <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">Dojo Toolkit</a> JavaScript library supports some drag &amp; drop functionality that I've seen work in IE6+ and FF2+. The nice thing about Dojo and other JS libraries is that they abstract away all of the browser detection stuff.</p> <p>I'm sure other JS libraries support this functionality.</p>
<p><a href="http://widgets.yahoo.com/widgets/ftp-drop" rel="nofollow noreferrer">FTP Drop</a> for Yahoo Widgets allows you to drag files over the widget and the file will be sent to the defined ftp server.</p>
2,772
<p>I have a managed DLL (written in C++/CLI) that contains a class used by a C# executable. In the constructor of the class, I need to get access to the full path of the executable referencing the DLL. In the actual app I know I can use the Application object to do this, but how can I do it from a managed DLL?</p>
<pre><code>Assembly.GetCallingAssembly() </code></pre> <p>or</p> <pre><code>Assembly.GetExecutingAssembly() </code></pre> <p>or</p> <pre><code>Assembly.GetEntryAssembly() </code></pre> <p>Depending on your need.</p> <p>Then use Location or CodeBase property (I never remember which one).</p>
<p>@leppie: Thanks - that was the pointer I needed. </p> <p>For future reference, in C++/CLI this is the actual syntax that works:</p> <pre><code>String^ appPathString = Assembly::GetEntryAssembly()-&gt;Location; </code></pre> <p><code>GetExecutingAssembly()</code> provided the name of the DLL</p> <p><code>GetCallingAssembly()</code> returned something like System.Windows.Forms</p> <p><code>GetEntryAssembly</code> returned the full path, similar to <code>GetModulePath()</code> under Win32.</p>
14,730
<p>Anyone got an idea how to get from an Xserver the list of all open windows?</p>
<p>From the CLI you can use</p> <pre><code>xwininfo -tree -root </code></pre> <p>If you need to do this within your own code then you need to use the <code>XQueryTree</code> function from the <code>Xlib</code> library.</p>
<p>If your window manager implements EWMH specification, you can also take a look at the <code>_NET_CLIENT_LIST</code> value of the root window. This is set by most modern window managers:</p> <pre><code>xprop -root|grep ^_NET_CLIENT_LIST </code></pre> <p>That value can easily be obtained programmatically, see your Xlib documentation!</p>
31,513
<p>I have a solution in Visual Studio 2008 which has multiple projects. One of the projects is a WCF project. Sometimes I just want to debug other projects, but when I press F5, Visual Studio has wcfsvchost.exe launched to host the WCF project even it is not "StartUp Project". </p> <p>Currently, every time I debugging other projects, I Have to Unload the WCF project to prevent the annoying WcfSvcHost.exe host pop up. However, it is not convenient. Anybody know better idea to prevent WCF project to be hosted in debugging mode?</p>
<p>Go to WCF Options section in the property page of your WCF project and unselect the check box that says 'Start WCF Service Host when debugging another project in the same solution'.</p>
<p>Not sure if this would fix your issue or not, but if you click on the WCF project in solution explorer, see if it has a "Always Start When Debugging" property. If it does, set it to false. That property only shows up for some project types though, so it depends on exactly what type of project template you used.</p>
35,879
<p>I have implemented tracing based on System.Diagnostics. </p> <p>I am also using a System.Diagnostics.TextWriterTraceListener, and hooked the whole trace up to a MOSS 2007 Web Application. </p> <p>The trace for some reason is trying to (a) create the log file, and/or (b) write to the log file using <strong>the user that is currently browsing the SharePoint site</strong> , is there any way to configure the logging to use a particular user account instead?</p>
<p>Obviously MOSS is configured to use windows authentication (kerberos) and imersonation. If you don't need to impersonate the current user logged into moss, turn off impersonation (its in web.config). You'll find that the log files will be created and written by the user under which your moss installation's application pool is running.</p> <p>If you HAVE to use impersonation, then another solution is to give everyone rights to create and write files in the log directory (and ONLY in the log directory). This isn't exactly the best idea, however. You can disallow the read permissions for everybody but those that need to read the logs, but you still will have to worry about people trying to DoS you by filling up the disk.</p> <p>The third choice is to, before you log, switch identities. Something like this might work:</p> <pre><code>var wic = WindowsIdentity.Impersonate(IntPtr.Zero); // "revert to self" /* LOG GOES HERE K */ wic.Undo(); // return to impersonation </code></pre> <p>BIG CAVEAT: I'm just learning this stuff myself, so the above code may not work at all. If it does, its sweet because you won't have to p/invoke to log in your log-writing-identity, which also means you won't have to create that user and store their password in cleartext in your application.</p> <p>I wonder where's the ol' Skeeter on this one? Windows security requires some heavy lifting; I'm just starting with the bar right now...</p>
<p>Please don't tell me this is necessary - <a href="http://www.15seconds.com/Issue/040511.htm?voteresult=5" rel="nofollow noreferrer">http://www.15seconds.com/Issue/040511.htm?voteresult=5</a></p>
45,429
<p>Let's say I'm working on a little batch-processing console app in VB.Net. I want to be able to structure the app like this:</p> <pre class="lang-vb prettyprint-override"><code>Sub WorkerMethod() 'Do some work Trace.WriteLine("Work progress") 'Do more work Trace.WriteLine("Another progress update") '... End Sub Sub Main() 'Do any setup, like confirm the user wants to continue or whatever WorkerMethod() End Sub </code></pre> <p>Note that I'm using <code>Trace</code> rather than <code>Console</code> for my output. This is because the worker method may be called from elsewhere, or even live in a different assembly, and I want to be able to attach different trace listeners to it. So how can I connect the console to the trace? </p> <p>I can already do it by defining a simple class (shown below) and adding an instance to the Trace's listeners collection, but I'm wondering if there's a more accepted or built in way to accomplish this:</p> <pre class="lang-vb prettyprint-override"><code>Public Class ConsoleTrace Inherits Diagnostics.TraceListener Public Overloads Overrides Sub Write(ByVal message As String) Console.Write(message) End Sub Public Overloads Overrides Sub WriteLine(ByVal message As String) Console.WriteLine(message) End Sub End Class </code></pre>
<p>You can add the following to your exe's .config file.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.diagnostics&gt; &lt;trace autoflush="true"&gt; &lt;listeners&gt; &lt;add name="logListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="cat.log" /&gt; &lt;add name="consoleListener" type="System.Diagnostics.ConsoleTraceListener"/&gt; &lt;/listeners&gt; &lt;/trace&gt; &lt;/system.diagnostics&gt; &lt;/configuration&gt; </code></pre> <p>I included the TextWriter as well, in case you're interested in logging to a file.</p>
<p>Great solution, but I have a situation where I have different dll's being run by the same calling exe, so I don't want to modify the calling exe's .config file. I want each dll to handle it's own alteration of the trace output.</p> <p>Easy enough:</p> <pre><code>Stream outResultsFile = File.Create ("output.txt"); var textListener = new TextWriterTraceListener (outResultsFile); Trace.Listeners.Add (textListener); </code></pre> <p>This will, of course, output Trace output to the "output.txt" file.</p>
24,156
<p>Silverlight v2.0 is getting closer and closer to RTM but I have yet to hear any stats as to how many browsers are running Silverlight. If I ask Adobe (by googling "Flash install base") they're <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" rel="nofollow noreferrer">only too happy to tell me</a> that 97.7% of browsers are running Flash player 9 or better.</p> <p>Not that I believe everything I read, but <strong>where are these statistics from Microsoft or some other vendor about Silverlight?</strong> I'm going to be making a technology choice soon and a little bit of empirical evidence would be an asset at this point...</p> <p>All you Silverlight developers out there, show me your stats!</p>
<p>Quick Answer: <a href="http://www.riastats.com" rel="nofollow noreferrer">www.riastats.com</a></p> <p>This site compares the different RIA plugins using graphical charts and graphs.</p> <p>It gets its data from small snippets of javascripts running on sites accross the web (approx 400,000 last time I looked)</p> <p>At the time of this post, Silverlight 2 was sitting at close to 11%.</p> <p>I would not take this as the end-all, be-all in RIA stats, but it's the best site I've found so far.</p>
<p>The larger question is how many users will your site lose if implemented in Silverlight. And, it very much depends on your audience.</p> <p>If you're running a site about the joys of Linux kernel hacking or the virtues of Internet security, you'll probably lose a significant chunk of your audience. If you're running a more mainstream site, my experience is that, sadly, people will download anything they're told to most of the time. That's why spyware and malware work. And, as the NBC/Olympics deal shows, Microsoft will aggressively push its partners to use Silverlight until it's fairly ubiquitous.</p> <p>I won't be using Silverlight until it's more mature because I <em>do</em> cater to a fair number of Linux users, but I might for a less technically-oriented site.</p>
8,494
<p>I have a datagrid getting bound to a dataset, and I want to display the average result in the footer for a column populated with integers.</p> <p>The way I figure, there's 2 ways I can think of:</p> <p>1."Use the <strong>Source</strong>, Luke"<br> In the code where I'm calling DataGrid.DataBind(), use the DataTable.Compute() method (<em>or in my case DataSet.DataTable(0).Compute()</em>). For example: </p> <pre><code>Dim strAverage = DataTable.Compute("Avg(ColumnName)", "") </code></pre> <p>But once I have this, how can I insert it into the footer?</p> <p>2."<strong>Bound</strong> for Glory"<br> Using the DataGrid.ItemDataBound event, and calculating a running total from every ListItemType.Item and ListItemType.AlternatingItem, finally displaying in ListItemType.Footer. For example: </p> <pre><code>Select Case e.Item.ItemType Case ListItemType.Item, ListItemType.AlternatingItem runningTotal += CInt(e.Item.Cells(2).Text) Case ListItemType.Footer e.Item.Cells(2).Text = runningTotal/DataGrid.Items.Count End Select </code></pre> <p>This just feels wrong, plus I would have to make sure the runningTotal is reset on every DataBind. </p> <p>Is there a better way?</p>
<p>See this KB Article. <a href="http://support.microsoft.com/default.aspx?scid=kb;EN-US;914277" rel="noreferrer">How to configure SQL Server 2005 to allow remote connections</a>.<br> Oh, and remember that the SQLServer name will probably be MyMachineName\SQLExpress</p>
<p>If you're running it on a 2k3 box, you need to install all updates for Sql Server and the 2003 server. </p> <p>Check the event logs after you start the Sql Server. It logs everything well, telling you if its being blocked, and where it is listening for connections.</p> <p>From a remote machine, you can use telnet to see if a sql server is listening for remote connections. You just need the IP and the port of the server (default is 1433). From the command line:</p> <pre><code>telnet 192.168.10.10 1433 </code></pre> <p>If you get a blank screen, its listening. If you get thrown back to the command prompt, something is blocking you.</p>
3,082
<p>I have tried both of :</p> <pre><code>ini_set('include_path', '.:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes'); </code></pre> <p>and also :</p> <pre><code>php_value include_path ".:/usr/share/php5:/usr/share/php5/PEAR:lib:app/classes" </code></pre> <p>in the .htaccess file.</p> <p>Both methods actually <strong>do work</strong> but only intermittently. That is, they will work fine for about 37 pages requests and then fail about 42 pages requests resulting in an require() call to cause a fatal error effectively crashing the site.</p> <p>I'm not even sure where to begin trying to find out what is going on!</p> <hr> <p>@<a href="https://stackoverflow.com/questions/41836/setting-include-path-in-php-intermittently-fails-why#41877">cnote</a></p> <blockquote> <p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p> </blockquote> <p>The in script version was originally </p> <pre><code>ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'classes'); </code></pre> <p>and thus the .:.: was coming from the existing path:</p> <pre><code>ini_get('include_path') </code></pre> <p>I tried removing it anyway and the problem persists.</p>
<p>It turned out the issue was related to a PHP bug in 5.2.5</p> <p>Setting an "admin_flag" for include_path caused the include path to be empty in some requests, and Plesk sets an admin_flag in the default config for something or other. An update of PHP solved the issue.</p> <p><a href="http://bugs.php.net/bug.php?id=43677" rel="nofollow noreferrer">http://bugs.php.net/bug.php?id=43677</a></p>
<p>Looks like you duplicated the current directory in your include path. Try removing one of the '.:' from your string.</p>
6,321
<p>Is there a way to mount a folder on the hard disk as a device in Finder. The intend here is to provide the user with an easy way to get to a folder that my application uses to store data. I don't want my user to go searching for data in Application Data. I would rather allow them to make this data available as a mounted volume or device in Finder. I would also like this volume or device to be read/write, so that if the user makes any changes to the data files, the changes will get reflected in the original folder.</p> <p>Is there a way to do this in cocoa, carbon or applescript.</p>
<p>Try looking into FUSE. You can have all sorts of psuedo filesystems with that.</p> <p>But I'd caution a little against what you are trying to do. It may make more sense to just have a button that opens the folder in your application, rather than create a new device. I personally would find it hard to continue to use an application that does such a thing. It doesn't really fit with the rest of the available applications.</p> <p>You could also use an alias to point to your Application Data directory.</p>
<p>I would also urge caution with this, seems potentially somewhat confusing to most users. That said, have you considered simply creating a softlink to the directory in question?</p>
41,859
<p>I've found Ruby to be very attractive; I like the fact that everything is an object and its syntax is very appealing. </p> <p>I was hoping that it would gain a lot of popularity this year, but I don't see lot of activity in Ruby. </p> <p>For instance if we take the number of tags added in SO there are only about 700 questions tagged as "ruby." This may be because:</p> <ol> <li>Ruby is so easy, noone has any questions.</li> <li>This site attracts more from the.Net community and Ruby developers ignore its existence.</li> <li>There are not as many Ruby projects as there projects in other programming languages.</li> </ol> <p>Other resources show Ruby is not as popular as other programming languages.</p> <p>What reasons do you think are behind this?</p> <p>Links:</p> <p><a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" rel="nofollow noreferrer">TIOBE Programming Community Index for October 2008</a></p> <p><a href="https://stackoverflow.com/tags">StackOverflow tags</a></p> <p><a href="http://www.ohloh.net/" rel="nofollow noreferrer">Ohloh</a></p>
<p>You're mistakenly attributing something to Ruby. <a href="http://rubyforge.org/" rel="nofollow noreferrer">RubyForge</a> alone reports over 1,000 open-source projects, let alone all Ruby on Rails apps that exist, and the projects hosted on Github, Sourceforge, and elsewhere.</p> <p>Unless you spend a lot of time on other sites (Reddit is a good example) you will be unaware of just how .NET/Oracle/SQL Server/etc.-centric Stack Overflow is. (I use a Greasemonkey plugin to hide a broad swathe of these Windows- and "Enterprise"-centric technologies, because they don't interest me.)</p> <p>I actually had the complementary experience to you: I started spending time on Stack Overflow, and had something of a "woah" moment when I realized just how many people spend their days futzing with ASP.NET. That's not a world in which I'd spent any time, so I had underestimated its size.</p> <p>Some parts of the internet (e.g., Reddit) are primarily concerned with free software and its associated languages: Perl, Python, Ruby, PHP.</p> <p>Some parts (e.g., <a href="http://lambda-the-ultimate.org/" rel="nofollow noreferrer">Lambda the Ultimate</a>) are concerned with more esoteric languages: Haskell, Lisp, Joy, Coq.</p> <p>Other parts (e.g., Stack Overflow) are more mainstream: Java, .NET.</p> <p>You cannot draw any conclusions about the popularity of a language by sampling just one of these 'pools'.</p>
<p>More than likely because it is younger than a lot of other languages and, on the web side of things, isn't as easy to implement as PHP and Python. Ruby has also gained notoriety as a web scripting language due to Rails which may be turning off some developers who are looking for client-based languages to work with.</p> <p>Is Ruby not popular? I think it is but it hasn't really reached a critical mass yet to be widely accepted.</p>
29,969
<p>We are repurposing an application server running WebSphere 6.0.2.23. I would like to rename the various application server to better reflect its new role. </p> <p>How can you rename an application server? </p> <p>It seems like wsadmin can do it, but I'm struggling with the object hierarchy.</p>
<p><a href="http://www.ibm.com/developerworks/websphere/library/samples/SampleScripts.html" rel="nofollow noreferrer">IBM Sample Scripts</a></p> <p>download: </p> <blockquote> <p>ConfigScripts.zip</p> </blockquote> <p>from command line execute: </p> <pre><code>/usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/ws_ant.sh \ -profileName AppSrv01 \ -buildfile exportImport.xml \ -logfile rename.log \ -DoldServerName=server1 \ -DnewServerName=server2 \ -DnodeName=yourNode01 changeServerName </code></pre> <p><a href="http://biounix.blogspot.com/2009/01/how-to-change-websphere-app-server-name.html" rel="nofollow noreferrer">source</a></p>
<p>An easier option if you are running a clustered set up is to create a new cluster member with the required name. </p> <p>Delete the old server and keep note of all the ports for the original server and state them as the port numbers for this new server(if you need the same port numbers)</p> <p>If you are using a non-clustered environment, then create a template out of the existing server. Create your new server based on that template so you have all the required config. Now like earlier change the port numbers back to the original ones. </p> <p><strong>If the change in port numbers are not a problem for you then you don't need to perform that step.</strong> </p> <p>HTH</p> <p>Manglu</p>
35,280
<p>Very simply, what is tail-call optimization?</p> <p>More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?</p>
<p>Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.</p> <p>Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:</p> <pre class="lang-lisp prettyprint-override"><code>(define (fact x) (if (= x 0) 1 (* x (fact (- x 1))))) (define (fact x) (define (fact-tail x accum) (if (= x 0) accum (fact-tail (- x 1) (* x accum)))) (fact-tail x 1)) </code></pre> <p>The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:</p> <pre class="lang-scheme prettyprint-override"><code>(fact 3) (* 3 (fact 2)) (* 3 (* 2 (fact 1))) (* 3 (* 2 (* 1 (fact 0)))) (* 3 (* 2 (* 1 1))) (* 3 (* 2 1)) (* 3 2) 6 </code></pre> <p>In contrast, the stack trace for the tail recursive factorial looks as follows:</p> <pre class="lang-scheme prettyprint-override"><code>(fact 3) (fact-tail 3 1) (fact-tail 2 3) (fact-tail 1 6) (fact-tail 0 6) 6 </code></pre> <p>As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.</p>
<p>In a functional language, tail call optimization is as if a function call could return a partially evaluated expression as the result, which would then be evaluated by the caller.</p> <pre><code>f x = g x </code></pre> <p>f 6 reduces to g 6. So if the implementation could return g 6 as the result, and then call that expression it would save a stack frame.</p> <p>Also</p> <pre><code>f x = if c x then g x else h x. </code></pre> <p>Reduces to f 6 to either g 6 or h 6. So if the implementation evaluates c 6 and finds it is true then it can reduce,</p> <pre><code>if true then g x else h x ---&gt; g x f x ---&gt; h x </code></pre> <p>A simple non tail call optimization interpreter might look like this,</p> <pre><code>class simple_expresion { ... public: virtual ximple_value *DoEvaluate() const = 0; }; class simple_value { ... }; class simple_function : public simple_expresion { ... private: simple_expresion *m_Function; simple_expresion *m_Parameter; public: virtual simple_value *DoEvaluate() const { vector&lt;simple_expresion *&gt; parameterList; parameterList-&gt;push_back(m_Parameter); return m_Function-&gt;Call(parameterList); } }; class simple_if : public simple_function { private: simple_expresion *m_Condition; simple_expresion *m_Positive; simple_expresion *m_Negative; public: simple_value *DoEvaluate() const { if (m_Condition.DoEvaluate()-&gt;IsTrue()) { return m_Positive.DoEvaluate(); } else { return m_Negative.DoEvaluate(); } } } </code></pre> <p>A tail call optimization interpreter might look like this,</p> <pre><code>class tco_expresion { ... public: virtual tco_expresion *DoEvaluate() const = 0; virtual bool IsValue() { return false; } }; class tco_value { ... public: virtual bool IsValue() { return true; } }; class tco_function : public tco_expresion { ... private: tco_expresion *m_Function; tco_expresion *m_Parameter; public: virtual tco_expression *DoEvaluate() const { vector&lt; tco_expression *&gt; parameterList; tco_expression *function = const_cast&lt;SNI_Function *&gt;(this); while (!function-&gt;IsValue()) { function = function-&gt;DoCall(parameterList); } return function; } tco_expresion *DoCall(vector&lt;tco_expresion *&gt; &amp;p_ParameterList) { p_ParameterList.push_back(m_Parameter); return m_Function; } }; class tco_if : public tco_function { private: tco_expresion *m_Condition; tco_expresion *m_Positive; tco_expresion *m_Negative; tco_expresion *DoEvaluate() const { if (m_Condition.DoEvaluate()-&gt;IsTrue()) { return m_Positive; } else { return m_Negative; } } } </code></pre>
40,073
<p>I have a button control style and I want to change the padding from whatever the data-bound version is to adjust for a glyph that needs a 2 pixel offset. I'll use SimpleButton from SimpleStyles.xaml as an example (... shows where the trigger code was removed for conciseness):</p> <pre><code>&lt;Style x:Key="SimpleButton" TargetType="{x:Type Button}" BasedOn="{x:Null}"&gt; &lt;Setter Property="FocusVisualStyle" Value="{DynamicResource SimpleButtonFocusVisual}"/&gt; &lt;Setter Property="Background" Value="{DynamicResource NormalBrush}"/&gt; &lt;Setter Property="BorderBrush" Value="{DynamicResource NormalBorderBrush}"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;!-- We use Grid as a root because it is easy to add more elements to customize the button --&gt; &lt;Grid x:Name="Grid"&gt; &lt;Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"/&gt; &lt;!-- Content Presenter is where the text content etc is placed by the control. The bindings are useful so that the control can be parameterized without editing the template --&gt; &lt;ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/&gt; &lt;/Grid&gt; ... &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>What I want to do is add some extra margin where Padding="{TemplateBinding Padding}". Something like Padding="{TemplateBinding Padding} + 2,0,0,0".</p> <p>Is there a XAML syntax to that? If not, is there a best approach when doing this in code (Decorator?) ?</p>
<p>Currently XAML does not parse expressions in Binding syntax, etc. However, you can use an <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx" rel="noreferrer">IValueConverter</a> or <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx" rel="noreferrer">IMultiValueConverter</a> to help yourself out:</p> <p>XAML:</p> <pre><code>&lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type Button}"&gt; &lt;Grid x:Name="Grid"&gt; &lt;Grid.Resources&gt; &lt;local:ThicknessAdditionConverter x:Key="AdditiveThickness" /&gt; &lt;/Grid.Resources&gt; &lt;Border x:Name="Border"&gt; &lt;Border.Padding&gt; &lt;Binding Path="Padding" RelativeSource="{RelativeSource TemplatedParent}" Converter="{StaticResource AdditiveThickness}"&gt; &lt;Binding.ConverterParameter&gt; &lt;Thickness&gt;2,0,0,0&lt;/Thickness&gt; &lt;/Binding.ConverterParameter&gt; &lt;/Binding&gt; &lt;/Border.Padding&gt; &lt;/Border&gt; ... &lt;/Setter.Value&gt; </code></pre> <p>IValueConverter code behind:</p> <pre><code>public class ThicknessAdditionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return new Thickness(0, 0, 0, 0); if (!(value is Thickness)) throw new ArgumentException("Value not a thickness", "value"); if (!(parameter is Thickness)) throw new ArgumentException("Parameter not a thickness", "parameter"); var thickness = new Thickness(0, 0, 0, 0); var t1 = (Thickness)value; var t2 = (Thickness)parameter; thickness.Left = t1.Left + t2.Left; thickness.Top = t1.Top + t2.Top; thickness.Right = t1.Right + t2.Right; thickness.Bottom = t1.Bottom + t2.Bottom; return thickness; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } </code></pre>
<p><strong>You can do some simple math by taking advantage of transforms.</strong></p> <p>Check out this trick that Charles Petzold came up with a long time ago: <a href="http://www.charlespetzold.com/blog/2006/04/060223.html" rel="nofollow">http://www.charlespetzold.com/blog/2006/04/060223.html</a></p> <p>Unfortunately, it doesn't seem to help your particular scenario ... since you want only to change Left property of the Thickness type for the Padding ... and that is not a dependency property that you can bind to alone.</p> <p>However, I felt compelled to add this answer in the case it helps others who find their way here via Google or another search engine.</p>
42,493
<p>I've been hearing/reading a lot about the new language enhancements for C# 4. I'm a little curious if these same enhancements are also going to be applied to VB as well, or what. Does anyone know where I can get some insight here? With all the new changes happening to C#, it seems like there will very little reason left to be using VB unless you happen to like the syntax. Are there enhancements that MS isn't making to VB this time that are getting included in C#, or visa versa?</p>
<p>I'd actually overlook the dismissal of VB.Net by Lou Franco. Checkout Panopticon Central: </p> <ul> <li><a href="http://www.panopticoncentral.net/archive/2008/10/31/24803.aspx" rel="nofollow noreferrer">http://www.panopticoncentral.net/archive/2008/10/31/24803.aspx</a> </li> <li><a href="http://www.panopticoncentral.net/archive/2008/10/29/24764.aspx" rel="nofollow noreferrer">http://www.panopticoncentral.net/archive/2008/10/29/24764.aspx</a></li> </ul> <p>For example: </p> <blockquote> <p>Then Lucian did a really wonderful demo of VB 10.0, which is shipping in Visual Studio 2010. He showed (IIRC) the following features that should be familiar to the readers of this blog: array literals, collection initializers, automatic properties, implicit line continuations, statement lambdas, generic variance, and a feature that embeds primary interop assembly types in your assembly so you don’t have to deploy the PIA. I may have missed some, so check out the video when it’s posted!</p> </blockquote>
<p>Some of the changes to C# (e.g Named Optional Parameters) were already in VB. The main strength of VB.NET over C# was Office/COM integration, and the new C# is addressing that.</p> <p>If you need to target an older .NET version, VB.NET will still be the one to use if you need these features.</p>
32,386
<p>I know there are many ways to prevent image caching (such as via META tags), as well as a few nice tricks to ensure that the current version of an image is shown with every page load (such as image.jpg?x=timestamp), but is there any way to actually clear or replace an image in the browsers cache so that neither of the methods above are necessary?</p> <p>As an example, lets say there are 100 images on a page and that these images are named "01.jpg", "02.jpg", "03.jpg", etc. If image "42.jpg" is replaced, is there any way to replace it in the cache so that "42.jpg" will automatically display the new image on successive page loads? I can't use the META tag method, because I need everuthing that ISN"T replaced to remain cached, and I can't use the timestamp method, because I don't want ALL of the images to be reloaded every time the page loads.</p> <p>I've racked my brain and scoured the Internet for a way to do this (preferrably via javascript), but no luck. Any suggestions?</p>
<p>If you're writing the page dynamically, you can add the last-modified timestamp to the URL:</p> <p><code>&lt;img src="image.jpg?lastmod=12345678" ...</code></p>
<p>I have tried something ridiculously simple:</p> <p>Go to FTP folder of the website and rename the IMG folder to IMG2. Refresh your website and you will see the images will be missing. Then rename the folder IMG2 back to IMG and it's done, at least it worked for me in Safari.</p>
41,664
<p>So while doing some research I stumbled upon a <a href="https://reprap.org/wiki/Glass_Nozzles#Step_1_Assemble_Parts_and_Tools" rel="nofollow noreferrer">wiki page on reprap</a> from a few years back where the user was creating a glass nozzle to replace the brass and PTFE assembly.<a href="https://reprap.org/wiki/Glass_Nozzles#Step_1_Assemble_Parts_and_Tools" rel="nofollow noreferrer">1</a></p> <p>Does anyone know the theory behind this? Glass is a great insulator so I could see how that would be beneficial for the heat break part but I can't see how it is appropriate for the nozzle as this is normally brass which is a good conductor.</p> <p>Surely the glass takes much more energy to heat up?</p> <p>On a side note I've seen similar projects using ceramic instead.</p>
<p>First off, this is not a glass nozzle, it is a whole hotend design. A super simplistic one.</p> <p>Glass is, like ceramics, not a good thermal conductor but has a quite good thermal resistance - it only melts at about 1600 °C, which means you will never have to fight melting or warping of the filament path itself at all - the heater copper wire will melt at about 1084 °C, so way before the glass, and most plastics that are printable start to decompose at less than 400°C.</p> <p>Construction-wise, this design has some benefits:</p> <ul> <li>Due to the design and material properties, this hotend doesn't need cooling fins and a "coldend" is not needed at all.</li> <li>The whole hotend being one solid piece makes it pretty much a "plug and play" item and prevents leaks.</li> <li>Glass is extremely abrasive resistant. This means a glass nozzle could be used for stuff like carbon fiber filament very long.</li> <li>Glass can be molten, repaired and modified with fairly simple equipment, e.g. a burner and some skill.</li> <li>Glass could be easily cleaned up to medical and food-grade machine ratings. The simplicity of the hotend assembly could make it autoclavable as a whole piece.</li> </ul> <p>It has some downsides though:</p> <ul> <li>Glass is brittle and does not take lateral forces and sharp impacts kindly. In other words: Handle with extreme care.</li> <li>Due to the glass being an insulator, the inside of the hotend will have a lower temperature than the outside. <ul> <li>A fairly thin-walled meltzone could mitigate this problem to some degree at the downside of making it even more prone to breaking</li> <li>The insulating behavior means, that the meltzone has to directly feed into the nozzle with as little unheated area as possible to prevent the molten plastic from solidifying inside the nozzle again.</li> </ul></li> <li>The skill needed to create a properly sized nozzle from glass is tremendous.</li> </ul>
<p>One shortcoming would be that when it comes back to lay down a new line next to an existing line, I would think that it would need to be able to melt the previously printed plastic, especially any bumps and strings.<br> High thermal conductivity for good heat flow seems important.</p>
1,503
<p>I want subversion to commit a file even if it's unchanged. Is there a way to do this?</p>
<p>If you want the file contents to remain unchanged (meaning that you can't merely change whitespace as johnstok suggested) you can always change one of the properties on the file.</p> <p>eg.</p> <pre> svn propset dummyproperty 1 yourfile svn commit yourfile </pre> <p>That will perform a commit without having to change the file.</p> <p>Just make sure that you don't use one of the special <code>svn:</code> properties. Anything else should be ok.</p> <hr> <p>Edit: A number of other posters have asked why someone would want to do this - presumably the people who have marked this answer down have also had the same concerns.</p> <p>I can't speak for the original poster, but one scenario where I have seen this used is when attempting to automatically synchronise activities on a Visual Sourcesafe repository with a subversion repository.</p>
<p>I thought you could do it from the command line?</p> <pre><code>svn ci -force &lt;filename&gt; </code></pre> <p>I don't have a repository here to check that on, so I might be wrong.</p>
25,261
<p>Does C++ support '<a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html" rel="noreferrer"><strong>finally</strong></a>' blocks?</p> <p>What is the <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer"><strong>RAII idiom</strong></a>?</p> <p>What is the difference between C++'s RAII idiom and <a href="http://www.c-sharpcorner.com/uploadfile/dipalchoksi/usingstatement11092005065819am/usingstatement.aspx" rel="noreferrer"><strong>C#'s 'using' statement</strong></a>?</p>
<p>No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a <em>poor name</em><sup><strong>†</strong></sup> for a really useful concept. </p> <p>The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is <a href="http://www.stroustrup.com/bs_faq2.html#finally" rel="noreferrer"><strong>Bjarne Stroustrup's explanation</strong></a> of the topic.</p> <p>A common use for RAII is locking a mutex:</p> <pre><code>// A class with implements RAII class lock { mutex &amp;m_; public: lock(mutex &amp;m) : m_(m) { m.acquire(); } ~lock() { m_.release(); } }; // A class which uses 'mutex' and 'lock' objects class foo { mutex mutex_; // mutex for locking 'foo' object public: void bar() { lock scopeLock(mutex_); // lock object. foobar(); // an operation which may throw an exception // scopeLock will be destructed even if an exception // occurs, which will release the mutex and allow // other functions to lock the object and run. } }; </code></pre> <p>RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to <em>Mike B</em> for pointing this out.)</p> <p>For those familliar with C# or VB.NET, you may recognize that RAII is similar to <a href="https://web.archive.org/web/20091023110911/http://geocities.com/Jeff_Louie/deterministic_destructors.htm" rel="noreferrer"><strong>.NET deterministic destruction using IDisposable and 'using' statements</strong></a>. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.</p> <p>&nbsp;</p> <p>† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.</p>
<pre><code>try { ... goto finally; } catch(...) { ... goto finally; } finally: { ... } </code></pre>
19,481
<p>I get this error when I do an <code>svn update</code>:</p> <blockquote> <p>Working copy XXXXXXXX locked Please execute "Cleanup" command</p> </blockquote> <p>When I run cleanup, I get</p> <blockquote> <p>Cleanup failed to process the following paths: XXXXXXXX</p> </blockquote> <p>How do I get out of this loop?</p>
<p>One approach would be to:</p> <ol> <li>Copy edited items to another location.</li> <li>Delete the folder containing the problem path.</li> <li>Update the containing folder through Subversion.</li> <li>Copy your files back or merge changes as needed.</li> <li>Commit</li> </ol> <p>Another option would be to delete the top level folder and check out again. Hopefully it doesn't come to that though.</p>
<p>Spotlight is its usual rubbish self at finding the lock files recursively. </p> <p>EasyFind on Mac App Store works</p> <pre><code>http://itunes.apple.com/gb/app/easyfind/id411673888?mt=12 </code></pre> <p>search for 'lock'</p> <p>Select all / Delete</p>
15,573
<p>I have a web-server, that serves different domain-names, but has only one IP-address assigned. That works fine with virtual hosts in Apache. Now I want SSL-encrypted connections for the websites. How can I set different SSL-certificates for the different vhosts?</p> <p>Using different IP's for the different hostnames would be an solution - not very elegant but possible. But I want to know, how I can use different SSL-certificates for different vhosts. So I look for a solution with only one IP-address.</p>
<p><strong>UPDATE: 2013</strong></p> <p>It appears that SNI is finally beginning take hold as older browsers are falling away. Here are the <a href="http://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI" rel="nofollow noreferrer">docs for Apache SNI</a> and here is a <a href="http://en.wikipedia.org/wiki/Server_Name_Indication" rel="nofollow noreferrer">wikipedia article on SNI</a> that includes a chart on browsers that support it. In short, all the major browsers support it in supported versions; if supporting older browsers is important, you may have to take that into consideration.</p> <p><em>------ previous answer ------------</em></p> <p>SSL Hosts must be tied to a unique IP address/port combination, thus you cannot use virtual hosting (Or at least, it can only have one ssl host per IP address). This is due to the fact that https begins encryption before the Host: parameter is sent in http, and thus it cannot determine which cipher to use from the hostname - all it has is the IP address.</p> <p>This would be silly easy to fix if HTTP had a TLS command so it could start SSL after asking for the hostname, but no one asked me.</p> <p>For the definitive answer, see <a href="http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#vhosts2" rel="nofollow noreferrer">http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#vhosts2</a></p>
<p>You will need a separate IP:port combination for each vhost.</p> <p>RFC 3546 is not feasible yet. IE only supports it when running under Vista, and last I checked Safari doesn't manage it either.</p>
34,816
<p>My company, a C++ house, is always looking to hire recent grads. However due to the Java Schools phenomenon, we typically end up interviewing strong Java programmers with maybe a minute smattering of C++. Often the C++ classes don't really prepare students for working in C++. Nevertheless, often these are bright kids, eager to learn and do their best.</p> <p>Every interview, I struggle with this fundamental question: </p> <p>How hard is it to turn a "Java School" programmer into a C or C++ programmer? Has your company had experience turning the stereotypical "Java Schools" programmer into a strong C++ programmer? Is it worth the effort?</p> <p>One of the reasons I struggle with this is not just due to a C or C++ vs Java language difference, it's the fundamental skills that come with learning C or C++ that I think often get lost at the Java School. These include data structures, computational complexity, manual memory management, really everything Joel Spolsky says <a href="http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html" rel="noreferrer">here</a>.</p> <p>Often, as far as I can tell, a student will have some of those fundamental skills (be able to answer a few questions), but I'll still have this large part of my mind that's extremely skeptical with how well someone can learn these skills without getting their hands dirty in some C or C++. Maybe I need to be disabused of this stereotype. Am I just being unfair?</p> <p>Anyway whats your experience with turning the "Java School" programmer into a C or C++ programmer?</p>
<p>Well, if they don't understand data structures and algorithmic complexity, they aren't going to be much good at serious Java programming, so I don't see that the language is an issue here.</p> <p>They won't understand pointers, but good C++ programming typically doesn't use pointers in complicated ways. (There are exceptions, but since I don't know what your company does I can't tell whether they'd apply.) After all, you probably don't want your developers writing their own linked lists rather than using std::list.</p> <p>They won't understand manual memory management, but that's a lot easier in C++ than it used to be. In modern C++, doing your own memory management has become harder, due to the potential of exceptions, so you want to practice RAII with pretty much everything (using auto_ptr, boost::shared_ptr, whatever).</p> <p>If I were running things, I'd hire them if they looked good. I'd be aware that there might be problems (C++ is a more demanding language than Java, after all), and have some sort of idea how to deal with them.</p> <p>There's no reason to avoid hiring people out of college just because they don't have the exact skills you want. The smart ones will learn, and you probably don't want to hire the ones who aren't smart.</p>
<p>It's just another language. </p> <p>And if you stick with the relatively small subset of pure OOP features, there is really not that much to learn from a Java developers perspective. The only thing you should have to teach them in order for them to be generic OOP programmers is the fact that they have to implement a destructor to take care of their memory. </p> <p>However, if they should be using the STL, templates, exceptions and the likes, they'll probably need some more guidance. </p>
31,247
<p>My C code snippet takes the address of an argument and stores it in a volatile memory location (preprocessed code):</p> <pre><code>void foo(unsigned int x) { *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;x); } int main() { foo(1); while(1); } </code></pre> <p>I used an SVN version of GCC for compiling this code. At the end of function <code>foo</code> I would expect to have the value <code>1</code> stored in the stack and, at <code>0x40000d4</code>, an address pointing to that value. When I compile without optimizations using the flag <code>-O0</code>, I get the expected ARM7TMDI assembly output (commented for your convenience):</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 str r0, [sp, #4] @ 3. Store the argument on the stack mov r3, #67108864 add r3, r3, #212 add r2, sp, #4 @ 4. Address of the stack variable str r2, [r3, #0] @ 5. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>It clearly stores the argument first on the stack and from there stores it at <code>0x40000d4</code>. When I compile with optimizations using <code>-O1</code>, I get something unexpected:</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 mov r2, #67108864 add r3, sp, #4 @ 3. Address of *something* on the stack str r3, [r2, #212] @ 4. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>This time the argument is never stored on the stack even though <em>something</em> from the stack is still stored at <code>0x40000d4</code>.</p> <p>Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug&trade;?</p>
<p>Once you return from <code>foo()</code>, <code>x</code> is gone, and any pointers to it are invalid. Subsequently using such a pointer results in what the C standard likes to call "undefined behavior," which means the compiler is absolutely allowed to assume you won't dereference it, or (if you insist on doing it anyway) need not produce code that does anything remotely like what you might expect. If you want the pointer to <code>x</code> to remain valid after <code>foo()</code> returns, you must not allocate <code>x</code> on foo's stack, period -- even if you <em>know</em> that in principle, nothing has any reason to clobber it -- because that just isn't allowed in C, no matter how often it happens to do what you expect.</p> <p>The simplest solution might be to make <code>x</code> a local variable in <code>main()</code> (or in whatever other function has a sufficiently long-lived scope) and to pass the address in to foo. You could also make <code>x</code> a global variable, or allocate it on the heap using <code>malloc()</code>, or set aside memory for it in some more exotic way. You can even try to figure out where the top of the stack is in some (hopefully) more portable way and explicitly store your data in some part of the stack, if you're sure you won't be needing for anything else and you're convinced that's what you really need to do. But the method you've been using to do that isn't sufficiently reliable, as you've discovered.</p>
<blockquote> <p>Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug™?</p> </blockquote> <p>No bug just the defined behaviour that optimisation options can produce odd code which might not work :)</p> <p>EDIT:</p> <p>If you think you have found a bug in GCC the mailing lists will be glad you dropped by but generally they find some hole in your knowledge is to blame and mock mercilessly :(</p> <p>In this case I think it's probably the -O options attempting shortcuts that break your code that need working around.</p>
4,816
<p>What tweaks / addins / themes do you have rigged up to make your IDE awesome? For example, in Visual Studio I <a href="http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx" rel="nofollow noreferrer">color themes</a>, <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/" rel="nofollow noreferrer">CodeRush</a> draws lines between braces, I always install and use the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&amp;displaylang=en" rel="nofollow noreferrer">Consolas</a> font and I have it setup to <a href="http://blogs.msdn.com/saraford/archive/2008/06/30/did-you-know-you-can-use-team-settings-to-keep-visual-studio-settings-on-different-machines-in-sync-248.aspx" rel="nofollow noreferrer">sync my settings across computers</a> for when I change hotkeys and whatnot with the help of <a href="https://www.foldershare.com/welcome.aspx" rel="nofollow noreferrer">FolderShare</a>.</p> <p>Also, this isn't Visual Studio specific, please feel free to mention what you do with Emacs or Eclipse or whatnot as many of us use a few.</p>
<p><a href="http://www.jetbrains.com/resharper/" rel="noreferrer">ReSharper</a> 4.1 for Visual Studio 2008. It's a beautiful thing. It looks for all kinds of code errors, optimizations, etc. My code is cleaner thanks to this handy Visual Studio plugin.</p>
<p>I am using Vim <a href="http://cscope.sourceforge.net/" rel="nofollow noreferrer">Cscope</a> plugin.</p> <p>Cscope is like 'ctags' on steroids and makes traversing code much easier. I usually use it along with tags to find where a function is declared and then go directly to whatever code is calling this function.</p> <p>I also use Vim's Rgrep plugin (recursive search) to search for files in the code hierarchy.</p>
29,007
<p>I have a C extension module and it would be nice to distribute built binaries. Setuptools makes it easy to build extensions modules on OS X and GNU/Linux, since those OSs come with GCC, but I don't know how to do it in Windows.</p> <p>Would I need to buy a copy of Visual Studio, or does Visual Studio Express work? Can I just use Cygwin or MinGW?</p>
<p>You can use both MinGW and VC++ Express (free, no need to buy it).</p> <p>See:</p> <ol start="2"> <li><a href="http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/" rel="noreferrer">http://eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/</a></li> <li><a href="http://eli.thegreenplace.net/2008/06/27/creating-python-extension-modules-in-c/" rel="noreferrer">http://eli.thegreenplace.net/2008/06/27/creating-python-extension-modules-in-c/</a></li> </ol>
<p>Setuptools and distutils don't come with gcc, but they use the same compiler Python was built with. The difference is mostly that on the typical UNIX system that compiler is 'gcc' and you have it installed.</p> <p>In order to compile extension modules on Windows, you need a compiler for Windows. MSVS will do, even the Express version I believe, but it does have to be the same MSVC++ version as Python was built with. Or you can use Cygwin or MinGW; See the appropriate section of <a href="http://docs.python.org/install/index.html#gnu-c-cygwin-mingw" rel="nofollow noreferrer">Installing Python Modules</a>.</p>
12,641
<p>I am looking for an inverse version of "RunOnceEx".</p> <p>RunOnceEx does run some program, before the user's shell(desktop&amp;taskbar) start. The login progress will not continue before the runonceex complete.</p> <p>I want to do exact the same but on user logout. When she/he logout, all running program shutdown, leaving shell(desktop&amp;taskbar), then ""I wish my program will be execute this moment"", finally logout.</p> <p>I think it is possible because the "mobsync.exe" is doing that. But I cannot find where and how to do it.</p>
<p>Warning, as said <a href="http://www.eggheadcafe.com/software/aspnet/30020406/trouble-getting-logoff-sc.aspx" rel="nofollow noreferrer"><strong>here</strong></a>, <code>gpedit.msc</code> will allow you to configure a logoff script <strong>for <em>all</em> users</strong>.</p> <p>If you need that script only for one user, you need to declare it directly in the registry, both in <code>HKCU</code> and <code>HKLM</code>.</p>
<p>If you need something simple and working for a single (or any) user you can make a simple application in C++ or C# for example.</p> <p>The simplest is having a C# in tray (by simply adding the tray component to the form) and register and event handler for the <strong>FormClosing</strong> event. It'd look like this:</p> <pre><code> private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason != CloseReason.UserClosing) { // It's not the user closing the application, // Let's do whatever you want here, for example starting a process Process notePad = new Process(); notePad.StartInfo.FileName = "notepad.exe"; notePad.StartInfo.Arguments = "ProcessStart.cs"; notePad.Start(); } } </code></pre> <p>So your application will be started with Windows or with the user. It'll wait (using a little bit of memory) and will do something when the system shuts down, or the user log off, etc (by checking "CloseReason" above).</p>
41,986
<p>I have some complex stored procedures that may return many thousands of rows, and take a long time to complete.</p> <p>Is there any way to find out how many rows are going to be returned before the query executes and fetches the data?</p> <p>This is with Visual Studio 2005, a Winforms application and SQL Server 2005.</p>
<p>You mentioned your stored procedures take a long time to complete. Is the majority of the time taken up during the process of selecting the rows from the database or returning the rows to the caller?</p> <p>If it is the latter, maybe you can create a mirror version of your SP that just gets the count instead of the actual rows. If it is the former, well, there isn't really that much you can do since it is the act of finding the eligible rows which is slow.</p>
<p>make a stored proc to count the rows first.</p> <p>SELECT COUNT(*) FROM table</p>
31,662
<p>Are there any good books for a relatively new but not totally new *nix user to get a bit more in depth knowledge (so no "Linux for dummies")? For the most part, I'm not looking for something to read through from start to finish. Rather, I'd rather have something that I can pick up and read in chunks when I need to know how to do something or whenever I have one of those "how do I do that again?" moments. Some areas that I'd like to see are:</p> <ul> <li>command line administration</li> <li>bash scripting</li> <li>programming (although I'd like something that isn't just relevant for C programmers)</li> </ul> <p>I'd like this to be as platform-independent as possible (meaning it has info that's relevant for any linux distro as well as BSD, Solaris, OS X, etc), but the unix systems that I use the most are OS X and Debian/Ubuntu. So if I would benefit the most from having a more platform-dependent book, those are the platforms to target.</p> <p>If I can get all this in one book, great, but I'd rather have a bit more in-depth material than coverage of <strong>everything</strong>. So if there are any books that cover just one of these areas, post it. Hell, post it even if it's not relevant to any of those areas and you think it's something that a person in my position should know about.</p>
<p>I've wiki'd this post - could those with sufficient rep add in items to it.</p> <p>System administration, general usage books</p> <ul> <li><p>Nemeth et. al, <a href="https://rads.stackoverflow.com/amzn/click/com/0131480049" rel="noreferrer" rel="nofollow noreferrer">Linux System Administration</a></p></li> <li><p>The <a href="https://rads.stackoverflow.com/amzn/click/com/0596003439" rel="noreferrer" rel="nofollow noreferrer">Armadillo</a> book, as mentioned by Bill The Lizard <a href="https://stackoverflow.com/questions/236838/what-are-good-linuxunix-books-for-an-advancing-user#236932">below</a>.</p></li> <li><p>Anything by <a href="http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&amp;field-keywords=mark+G+sobell&amp;x=0&amp;y=0" rel="noreferrer">Mark Sobell</a>. He does a sort of theme-and-variations for various flavours of unix, so pick the book most appropriate to the environment in hand. The books are quite good. One of his was a prescribed text when I did my B.Sc.</p></li> <li><p>Stevens' <a href="https://rads.stackoverflow.com/amzn/click/com/0201633469" rel="noreferrer" rel="nofollow noreferrer">TCP/IP illustrated, vol. 1: The Protocols</a> for a comprehensive run down on how TCP/IP works in detail.</p></li> <li><p>I've never read this particular book, but many people here are recommending <a href="https://rads.stackoverflow.com/amzn/click/com/0596003307" rel="noreferrer" rel="nofollow noreferrer">Unix Power Tools</a> as mentioned by <a href="https://stackoverflow.com/questions/236838/what-are-good-linuxunix-books-for-an-advancing-user#236858">Hortitude.</a></p></li> </ul> <p>Programming:</p> <ul> <li><p>Anything by the late W. Richard Stevens, in particular <a href="https://rads.stackoverflow.com/amzn/click/com/0201433079" rel="noreferrer" rel="nofollow noreferrer">Advanced Programming in the Unix Environment</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/0131411551" rel="noreferrer" rel="nofollow noreferrer">Unix Network Programming Vol. 1</a> <a href="https://rads.stackoverflow.com/amzn/click/com/0130810819" rel="noreferrer" rel="nofollow noreferrer">and vol. 2</a></p></li> <li><p>Various classic c/unix books, such as <a href="https://rads.stackoverflow.com/amzn/click/com/013937681X" rel="noreferrer" rel="nofollow noreferrer">The Unix Programming Environment</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/0131411543" rel="noreferrer" rel="nofollow noreferrer">Advanced Unix Programming</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/0201657880" rel="noreferrer" rel="nofollow noreferrer">Programming Pearls</a> and of course <a href="https://rads.stackoverflow.com/amzn/click/com/0131103628" rel="noreferrer" rel="nofollow noreferrer">K&amp;R</a>. The C/Unix books tend to go into the underlying architecture, and will give a fair degree of insight that's relevant across the board - these are the underlying mechanisms within the system. Anyone trying to do system-level programming (basically anything using system services, no matter what the language) will find a grounding in this to be beneficial.</p></li> </ul> <p>Specific tools (e.g. Sendmail)</p> <p>Various of the books from O'Reilly and other publishers cover specific topics. Some of the key ones are:</p> <ul> <li><p>The <a href="https://rads.stackoverflow.com/amzn/click/com/0596510292" rel="noreferrer" rel="nofollow noreferrer">Bat</a> book on sendmail - if you have occasion to experience the joys of working with <a href="http://okmij.org/ftp/Computation/sendmail-as-turing-machine.txt" rel="noreferrer">sendmail.cf</a>. If you have a choice on MTA, <a href="http://www.postfix.org/" rel="noreferrer">postfix</a> or <a href="http://www.qmail.org/top.html" rel="noreferrer">qmail</a> are somewhat easier to work with (I've been using postfix since about 2000). O'reilly publish guides to <a href="https://rads.stackoverflow.com/amzn/click/com/0596002122" rel="noreferrer" rel="nofollow noreferrer">both</a> of <a href="https://rads.stackoverflow.com/amzn/click/com/1565926285" rel="noreferrer" rel="nofollow noreferrer">them</a>.</p></li> <li><p>Some classic works on <a href="http://www.cpan.org/" rel="noreferrer">perl</a>: the <a href="https://rads.stackoverflow.com/amzn/click/com/0596000278" rel="noreferrer" rel="nofollow noreferrer">Camel</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/0596520107" rel="noreferrer" rel="nofollow noreferrer">Llama</a> books (the latter written by none other than <a href="https://stackoverflow.com/users/22483/randal-schwartz">Randal Schwartz</a>).</p></li> <li><p><a href="https://rads.stackoverflow.com/amzn/click/com/1565922255" rel="noreferrer" rel="nofollow noreferrer">Sed and awk</a>. Not sure what the critters on the cover are. My copy went south a while ago. While on the subject of this, <a href="https://rads.stackoverflow.com/amzn/click/com/0596528124" rel="noreferrer" rel="nofollow noreferrer">Mastering Regular Expressions</a> has also gotten a mention here and is a good book on the subject. </p></li> <li><p><a href="http://us3.samba.org/samba/" rel="noreferrer">Samba</a>. <a href="https://rads.stackoverflow.com/amzn/click/com/0596007698" rel="noreferrer" rel="nofollow noreferrer">The hornbill (?)</a> book covers this; there is also <a href="http://us3.samba.org/samba/docs/man/Samba-HOWTO-Collection/" rel="noreferrer">quite</a> <a href="http://us3.samba.org/samba/docs/man/Samba-Guide/" rel="noreferrer">a lot</a> <a href="http://us3.samba.org/samba/docs/using_samba/toc.html" rel="noreferrer">of</a> <a href="http://us3.samba.org/samba/docs/" rel="noreferrer">on-line</a> <a href="http://wiki.samba.org/" rel="noreferrer">documentation</a>.</p></li> <li><p><a href="https://rads.stackoverflow.com/amzn/click/com/1565925106" rel="noreferrer" rel="nofollow noreferrer">NFS/NIS</a> for those using or maintaining unix or linux clients.</p></li> </ul> <p>Some of these books have been in print for quite a while and are still relevant. Consequently they are also often available secondhand at much less than list price. Amazon marketplace is a good place to look for such items. It's quite a good way to do a shotgun approach to topics like this for not much money. </p> <p>As an example, in New Zealand technical books are usurously expensive due to a weak kiwi peso (as the $NZ is affectionately known in expat circles) and a tortuously long supply chain. You could spend 20% of a week's after-tax pay for a starting graduate on a single book. When I was living there just out of university I used this type of market a lot, often buying books for 1/4 of their list price - including the cost of shipping to New Zealand. If you're not living in a location with tier-1 incomes I recommend this.</p> <p>E-Books and on-line resources (thanks to <a href="https://stackoverflow.com/questions/236838/what-are-good-linuxunix-books-for-an-advancing-user#237015">israkir</a> for reminding me):</p> <ul> <li><p>The Linux Documentation project (<a href="http://www.tldp.org/" rel="noreferrer">www.tldp.org</a>), has many specific topic guides known as <a href="http://www.tldp.org/docs.html#howto" rel="noreferrer">HowTos</a> that also often concern third party OSS tools and will be relevant to other Unix variants. It also has a series of <a href="http://www.tldp.org/docs.html#faq" rel="noreferrer">FAQ's</a> and <a href="http://www.tldp.org/guides.html" rel="noreferrer">guides</a>.</p></li> <li><p><a href="http://www.ugu.com/sui/ugu/warp.ugu" rel="noreferrer">Unix Guru's Universe</a> is a collection of unix resources with a somewhat more old-school flavour.</p></li> <li><p>Google. There are many, many unix and linux resources on the web. Search strings like <a href="http://www.google.co.uk/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla:en-GB:official&amp;hs=vbh&amp;q=unix+commands&amp;revid=120646170&amp;sa=X&amp;oi=revisions_inline&amp;resnum=0&amp;ct=broad-revision&amp;cd=2" rel="noreferrer">unix commands</a> or <a href="http://www.google.co.uk/search?hl=en&amp;client=firefox-a&amp;rls=org.mozilla:en-GB:official&amp;hs=vbh&amp;q=learn+unix&amp;revid=120646170&amp;sa=X&amp;oi=revisions_inline&amp;resnum=0&amp;ct=broad-revision&amp;cd=3" rel="noreferrer">learn unix</a> will turn up any amount of online resources.</p></li> <li><p><a href="http://safari.oreilly.com/?cid=orm-nav-global" rel="noreferrer">Safari</a>. This is a subscription service, but you can search the texts of quite a large number of books. I can recommend this as I've used it. They also do site licences for corporate customers.</p></li> </ul> <p>Some of the philosophy of Unix:</p> <ul> <li><p><a href="http://catb.org/esr/writings/taoup/" rel="noreferrer">The Art of UNIX Programming</a> by E S Raymond (available online and in print).</p></li> <li><p><a href="http://cm.bell-labs.com/cm/cs/tpop/" rel="noreferrer">The Practice of Programming</a> by B W Kernighan and R Pike.</p></li> </ul>
<p>Big agreement for <em>Essential System Adminstration</em> and <em>Unix Power Tools</em>.</p> <p>Also, whichever editor you prefer, vim or emacs, learn it back &amp; forth. If you like vim, then get Steve Oualline's vim book.</p>
29,306
<p>I've just started working on an <code>ASP.NET</code> project which I hope to open source once it gets to a suitable stage. It's basically going to be a library that can be used by existing websites. My preference is to support <code>ASP.NET 2.0</code> through <code>3.5</code>, but I wondered how many people I would be leaving out by not supporting <code>ASP.NET 1.1</code>? More specifically, how many people are there still using <code>ASP.NET 1.1</code> for whom <code>ASP.NET 2.0/3.5</code> is not an option? If upgrading your server is not an option for you, why not?</p>
<p>Increasingly I think not.</p> <p>The kind of large rigid organisation currently still clinging to 1.1 (probably because they're only just upgraded to it) is also the kind that's highly unlikely to look at open source solutions.</p> <p>If I were starting a new ASP.Net project right now I'd stick with .Net 3.5 and probably the new MVC previews.</p>
<p>I think you would be perfectly fine with targeting just 2.0 and above, someone who would use your library would most likely be doing new development and using at least ASP.NET 2.0. I think it would be a very small group of people doing new development in 1.1.</p>
3,412
<p>I develop using MAMP pro on my Mac. When I start MAMP it prompts me for a password if I use port 80. If I use a higher port it doesn't prompt me, but I have to append the port number in the URL ( eg dev.local:8888 ). Does anyone know how to make it not prompt for password when using standard ports? Thank you.</p>
<p>According to a living-e rep they are considering adding an option to store the password in the keychain:</p> <p><a href="http://forum.webedition.de/phpBB/viewtopic.php?f=4&amp;t=5517&amp;p=12019" rel="nofollow noreferrer">http://forum.webedition.de/phpBB/viewtopic.php?f=4&amp;t=5517&amp;p=12019</a></p> <p>Update: I pestered Living-e support and got them to add it as a feature request to their bug tracker. The link is here: <a href="http://qa.living-e.de/tracker/view.php?id=3648" rel="nofollow noreferrer">http://qa.living-e.de/tracker/view.php?id=3648</a> (requires registration) if you want to follow it.</p> <p>Another update: Still following this issue. Looks like living-e moved their bug tracker, the new link to this issue is:</p> <p><a href="http://bugs.mamp.info/view.php?id=3652" rel="nofollow noreferrer">http://bugs.mamp.info/view.php?id=3652</a></p> <p>It's in German but the Google translation is:</p> <blockquote> <p>When will start and stop the server in each case the admin password is required if port is used as low-1024th If we could get the password from the OS X Keychain / keyring, allowed themselves to avoid annoying popup ads.</p> </blockquote> <p>Or a German speaker's translation is:</p> <blockquote> <p>When the Server starts/stops it will ask for the admin password each time. If it could get the password from OS X Keychain / Keyring, the annoying popup could be avoided.</p> </blockquote>
<p>Its a security issue, and MacOS with its UNIX heritage like security (=Good Thing). That's why MacOS asks for passwords all the time. Not much you can do about it as far as I know.</p>
25,464
<p>Does anyone have some good hints for writing test code for database-backend development where there is a heavy dependency on state?</p> <p>Specifically, I want to write tests for code that retrieve records from the database, but the answers will depend on the data in the database (which may change over time).</p> <p>Do people usually make a separate development system with a 'frozen' database so that any given function should always return the exact same result set?</p> <p>I am quite sure this is not a new issue, so I would be very interested to learn from other people's experience.</p> <p>Are there good articles out there that discuss this issue of web-based development in general?</p> <p>I usually write PHP code, but I would expect all of these issues are largely language and framework agnostic.</p>
<p>You should look into DBUnit, or try to find a PHP equivalent (there must be one out there). You can use it to prepare the database with a specific set of data which represents your test data, and thus each test will no longer depend on the database and some existing state. This way, each test is self contained and will not break during further database usage.</p> <p>Update: A quick google search showed a <a href="http://www.ds-o.com/archives/63-PHPUnit-Database-Extension-DBUnit-Port.html" rel="noreferrer">DB unit extension</a> for PHPUnit.</p>
<p>I have the exact same problem with my work and I find that the best idea is to have a PHP script to re-create the database and then a separate script where I throw crazy data at it to see if it breaks it.</p> <p>I have not ever used any Unit testing or suchlike so cannot say if it works or not sorry.</p>
2,506
<p>Is there a method for handling errors from COM objects in RDML? For instance, when calling Word VBA methods like <code>PasteSpecial</code>, an error is returned and the LANSA application crashes. I cannot find anything in the documentation to allow handling of these errors.</p> <p>Actually, error handling in general is a weak-point for LANSA and RDML, but that's another topic.</p>
<blockquote> <ol> <li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li> </ol> </blockquote> <p>I have a few ideas and questions:<br> 1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.<br> 2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using <a href="http://pdfsharp.com/" rel="nofollow noreferrer">PDFSharp</a> after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.</p> <blockquote> <p>3. Does anyone else have any other theories as to why this runs on the server but not through the API?</p> </blockquote> <p>My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through. </p> <p>You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).</p> <p>Not solutions, per se, but ideas. Hope it helps.</p>
<blockquote> <ol> <li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li> </ol> </blockquote> <p>I have a few ideas and questions:<br> 1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.<br> 2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using <a href="http://pdfsharp.com/" rel="nofollow noreferrer">PDFSharp</a> after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.</p> <blockquote> <p>3. Does anyone else have any other theories as to why this runs on the server but not through the API?</p> </blockquote> <p>My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through. </p> <p>You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).</p> <p>Not solutions, per se, but ideas. Hope it helps.</p>
3,613
<p>This is a pretty-much theoretical question, but..</p> <p><strong>How much of an operating system could be written in a language like Python, Ruby, Perl, or Lisp, Haskell etc?</strong></p> <p>It seems like a lot of the stuff like init.d could trivially be done in a scripting language. One of the firewall-device-OS's (<a href="http://m0n0.ch/wall/" rel="noreferrer">m0n0wall</a>) uses PHP for its system-configuration (including on boot). And one could argue that "emacs is an OS, mostly written in Lisp"..</p> <p>Of course there are bits that would have to be assembly/C, but how much could be regular .py/rb/.pl/.el/.hk files..? It might not have the best performance, but it would be, by far, the most easiest-to-modify OS ever...</p>
<p>Technically, any of it could be, if you write a compiler to do so. OSes have been done in Java (JNode), .NET (MOSA, Singularity, SharpOS, Cosmos), Haskell (HOUSE), Python (Unununium), etc.</p> <p>Edit: I see a lot of people talking about the very lowest level being an area where this couldn't be done; this isn't true.</p> <p>There's no reason that the compiler for X language can't be extended to handle any low-level operation and expose it to the language. All functionality can be achieved from any language, it's simply a matter of picking the right tool for the job. Sometimes this is Python, sometimes this is C, sometimes this is assembly.</p> <p>Look to projects like Cosmos and SharpOS to see a pure high-level OS Done Right (TM).</p>
<p>I would say this is not possible. Responses to this question keep referring to changes to the language or using the language to generated low level (kernel) code. This is just using one language to write another language. While I agree that both of these would allow you to then write an operating system, I would then argue that it is now not the same language. So, an operating system could be written in many different languages but not every language (without change or language by pass) can be used to write an operating system.</p> <p>The finial answer to the original question is almost all, but not all. The only acceptation are languages which can access CPU level instructions.</p>
23,113
<p>Exactly what the topic title says, </p> <p>In which cases would you prefer using public functions to change local variables over just defining that variable as public and modifying it directly?</p>
<p>Obviously if you want changing the variable to have some other effect on the object's state (like recalculating some other property of the object) you must use a mutator function.</p> <p>If it's possible to set the variable to something that places the object in an invalid state, you should probably also use a mutator function. This way you can throw an exception (or return an error, or just ignore) if something illegal is about to happen. This does wonders for debugging.</p> <p>But if some variables can be modified with mutator functions, and others are public, the programmer needs to keep track of which is which. This is a waste of time and effort so in some cases it's easiest to just use mutator functions for everything.</p>
<p>If you want to change a variable inside a class, your best doing it through Properties.</p> <p>Its not good practice to have variable's modified on the outside.</p> <p>Think of future development too. You could put some logic behind a Property without changing the whole program.</p>
32,196
<p>I want to design a class that will parse a string into tokens that are meaningful to my application.</p> <p>How do I design it?</p> <ol> <li>Provide a ctor that accepts a string, provide a Parse method and provide methods (let's call them "minor") that return individual tokens, count of tokens etc. OR</li> <li>Provide a ctor that accepts nothing, provide a Parse method that accepts a string and minor methods as above. OR</li> <li>Provide a ctor that accepts a string and provide only minor methods but no parse method. The parsing is done by the ctor.</li> </ol> <p>1 and 2 have the disadvantage that the user may call minor methods without calling the Parse method. I'll have to check in every minor method that the Parse method was called.</p> <p>The problem I see in 3 is that the parse method may potentially do a lot of things. It just doesn't seem right to put it in the ctor.</p> <p>2 is convenient in that the user may parse any number of strings without instantiating the class again and again.</p> <p>What's a good approach? What are some of the considerations?</p> <p>(the language is c#, if someone cares).</p> <p>Thanks</p>
<p>I would have a separate class with a Parse method that takes a string and converts it into a separate new object with a property for each value from the string.</p> <pre><code>ValueObject values = parsingClass.Parse(theString); </code></pre>
<p>If the sole purpose of the class is to parse the input string into a group of properties, then I don't see any real downside in option 3. The parse operation may be expensive, but you have to do it at some point if you're going to use it.</p> <p>You mention that option 2 is convenient because you can parse new values without reinstantiating the object, but if the parse operation is that expensive, I don't think that makes much difference. Compare the following code:</p> <pre><code>// Using option 3 ParsingClass myClass = new ParsingClass(inputString); // Parse a new string. myClass = new ParsingClass(anotherInputString); // Using option 2 ParsingClass myClass = new ParsingClass(); myClass.Parse(inputString); // Parse a new string. myClass.Parse(anotherInputString); </code></pre> <p>There's not much difference in use, but with Option 2, you have to have all your minor methods and properties check to see if parsing had occurred before they can proceed. (Option 1 requires to you do everything that option 2 does internally, but also allows you to write Option 3-style code when using it.)</p> <p>Alternatively, you could make the constructor private and the Parse method static, having the Parse method return an instance of the object.</p> <pre><code>// Option 4 ParsingClass myClass = ParsingClass.Parse(inputString); // Parse a new string. myClass = ParsingClass.Parse(anotherInputString); </code></pre> <p>Options 1 and 2 provide more flexibility, but require more code to implement. Options 3 and 4 are less flexible, but there's also less code to write. Basically, there is no one right answer to the question. It's really a matter of what fits with your existing code best.</p>
39,911
<p>Is there an Eclipse command to surround the current selection with parentheses?</p> <p>Creating a template is a decent workaround; it doesn't work with the "Surround With" functionality, because I want to parenthesize an expression, not an entire line, and that requires <code>${word_selection}</code> rather than <code>${line_selection}</code>.</p> <p>Is there a way that I can bind a keyboard shortcut to this particular template? <kbd>Ctrl</kbd>-<kbd>space</kbd> <kbd>Ctrl</kbd>-<kbd>space</kbd> arrow arrow arrow isn't as slick as I'd hoped for.</p>
<p>Maybe not the correct answer, but at least a workaround:</p> <ol> <li><p>define a Java template with the name "parenthesis" (or "pa") with the following :</p> <p>(${word_selection})${cursor}</p></li> <li><p>once the word is selected, <kbd>ctrl</kbd>-<kbd>space</kbd> + <kbd>p</kbd> + use the arrow keys to select the template</p></li> </ol> <p>I used this technique for boxing primary types in JDK 1.4.2 and it saves quite a lot of typing.</p>
<p>Easy, Window->Prefs, then select Java->Editor->Templates</p> <p>Create a new template with : (${line_selection}${cursor})</p> <p>The "line_selection" means you have to select more than one line.</p> <p>You can try creating another one with "word_selection", too.</p> <p>Then, select text, right click, Surround With... and choose your new template.</p>
9,255
<p>Always was interested why are <a href="http://msdn.microsoft.com/en-us/library/system.array.sort.aspx" rel="nofollow noreferrer">Array.Sort()</a> and <a href="http://msdn.microsoft.com/en-us/library/system.array.indexof.aspx" rel="nofollow noreferrer">Array.IndexOf()</a> methods made static and similar <a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.sort.aspx" rel="nofollow noreferrer">ArrayList.Sort()</a> and <a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.indexof.aspx" rel="nofollow noreferrer">ArrayList.IndexOf()</a> are designed as member methods. Thank you for any ideas.</p>
<p>In my view Array class is basically a class representation of the fixed size arrays that we declare using [] in program (you can draw the analogy like int has it's class (structure) representation as System.Int32).</p> <p>Also Array class does not contain the actually array data in any instance variables but it provides just static utility functions which can be utilized to do sorting and searching in the declared fixed size arrays.</p> <p>On the other hand, ArrayList is a collection class, which provides dynamic size array implementation and it has it's own data-structure to contain the data. Therefore the said methods are instance methods, so that they can work on the that particular instance's data.</p>
<p>A collection class like <code>ArrayList</code> encapsules some kind of internal storage (presumably an array which is resized as needed, but it could also be a linked list or some other implementation). Metods like <code>IndexOf</code> and <code>Sort</code> needs access to the underlying private storage to be efficient, so they have to be instace methods.</p> <p>An <code>Array</code> on the other hand is not encapsulated, there is public access directly to the storage. The <code>Array.IndexOf</code> and <code>Array.Sort</code> methods does not need any special access to the array data, so they might as well be static metods.</p>
21,353
<p>I need to access a mysql database from c# code but I would prefer not to use ODBC for the reasons below.</p> <p>I have to create a demo and I am using xampp on a USB drive. My code (database Read/Write code) is written in C#. So to keep the USB drive isolated from the computer that the demo runs on I am moving away from ODBC because of setup reasons.</p>
<p><a href="http://dev.mysql.com/downloads/connector/net/5.2.html" rel="noreferrer">http://dev.mysql.com/downloads/connector/net/5.2.html</a></p> <p>Last time I tried it it worked fine but if you need to connect to, for example, MySQL and SQL Server you'll need to duplicate the code once using SqlConnection and the other using MysqlConnection.</p>
<p>Depending on your needs, you could also look at an ORM like <a href="http://subsonicproject.com/" rel="nofollow noreferrer">SubSonic</a>. It works with MySQL and will give you both database independence and ease of development.</p>
43,446
<p>It seems like <code>Info.plist</code> file has an ability to declare different roles for the same application bundle through the <code>UIRoleInfo</code> key. SpringBoard can recognize these roles after installing an app and may display separate icons for each application role.</p> <p>For instance, iPhone shows <code>MobileSlideShow.app</code> as 2 different programs: <code>Photos</code> and <code>Camera</code>.</p> <p>Unfortunately, there is no official Apple documentation about the subject at the moment. Would anybody advise how to organize the same behavior in a custom app?</p> <p>This feature is going to be used in the Enterprise product for ad hoc distribution.</p>
<p>This isn't a supported feature, so if you do this you might have a hard time getting your app through the approval process. I wouldn't recommend using it.</p>
<p>Have you tried it to see if it works? If it doesn't work, you could create a second app that does nothing but launch the first one, with a custom URL scheme. The first app can recognize when it is being launched with that URL. This is not ideal as you will see the second app launch &amp; quit (though it should be really fast).</p>
26,956
<p>I am a member of a team that is about to launch a beta of a python (Django specifically) based web site and accompanying suite of backend tools. The team itself has doubled in size from 2 to 4 over the past few weeks and we expect continued growth for the next couple of months at least. One issue that has started to plague us is getting everyone up to speed in terms of getting their development environment configured and having all the right eggs installed, etc.</p> <p>I'm looking for ways to simplify this process and make it less error prone. Both zc.buildout and virtualenv look like they would be good tools for addressing this problem but both seem to concentrate primarily on the python-specific issues. We have a couple of small subprojects in other languages (Java and Ruby specifically) as well as numerous python extensions that have to be compiled natively (lxml, MySQL drivers, etc). In fact, one of the biggest thorns in our side has been getting some of these extensions compiled against appropriate versions of the shared libraries so as to avoid segfaults, malloc errors and all sorts of similar issues. It doesn't help that out of 4 people we have 4 different development environments -- 1 leopard on ppc, 1 leopard on intel, 1 ubuntu and 1 windows.</p> <p>Ultimately what would be ideal would be something that works roughly like this, from the dos/unix prompt:</p> <p>$ git clone [repository url] ... $ python setup-env.py ...</p> <p>that then does what zc.buildout/virtualenv does (copy/symlink the python interpreter, provide a clean space to install eggs) then installs all required eggs, including installing any native shared library dependencies, installs the ruby project, the java project, etc.</p> <p>Obviously this would be useful for both getting development environments up as well as deploying on staging/production servers.</p> <p>Ideally I would like for the tool that accomplishes this to be written in/extensible via python, since that is (and always will be) the lingua franca of our team, but I am open to solutions in other languages.</p> <p>So, my question then is: does anyone have any suggestions for better alternatives or any experiences they can share using one of these solutions to handle larger/broader install bases?</p>
<p>Setuptools may be capable of more of what you're looking for than you realize -- if you need a custom version of lxml to work correctly on MacOS X, for instance, you can put a URL to an appropriate egg inside your setup.py and have setuptools download and install that inside your developers' environments as necessary; it also can be told to download and install a specific version of a dependency from revision control.</p> <p>That said, I'd lean towards using a scriptably generated virtual environment. It's pretty straightforward to build a kickstart file which installs whichever packages you depend on and then boot virtual machines (or production hardware!) against it, with puppet or similar software doing other administration (adding users, setting up services [where's your database come from?], etc). This comes in particularly handy when your production environment includes multiple machines -- just script the generation of multiple VMs within their handy little sandboxed subnet (I use libvirt+kvm for this; while kvm isn't available on all the platforms you have developers working on, qemu certainly is, or you can do as I do and have a small number of beefy VM hosts shared by multiple developers).</p> <p>This gets you out of the headaches of supporting N platforms -- you only have a single virtual platform to support -- and means that your deployment process, as defined by the kickstart file and puppet code used for setup, is source-controlled and run through your QA and review processes just like everything else.</p>
<p>Basically, you're looking for a <strong>cross-platform software/package installer</strong> (on the lines of apt-get/yum/etc.) I'm not sure something like that exists?</p> <p>An alternative might be specifying the list of packages that need to be installed via the OS-specific package management system such as Fink or DarwinPorts for Mac OS X and having a script that sets up the build environment for the in-house code?</p>
19,435
<p>I have a middle tier containing several related objects and a data tier that is using a DataSet with several DataTables and relationships.</p> <p>I want to call a Save method on one of my objects (a parent object) and have its private variable data transformed into a DataRow and added to a DataTable. Some of the private variable data are actually other objects (child object) that each need to have their own Save method called and their own variable data persisted.</p> <p>How do I "lace" this together? What parts of a DataSet should be instantiated in the ParentObject and what needs to be passed to the ChildObjects so they can add themselves to the dataset?</p> <p>Also, how do I wire the relationships together for 2 tables?</p> <p>The examples I have seen for an Order OrderDetail relationship create the OrderRow and the OrderDetailRow then call OrderDetailRow.SetParentRow(OrderDetail)</p> <p>I do not think this will work for me since my Order and OrderDetail (using their examples naming) are in separate classes and the examples have it all happening in a Big Honking Method.</p> <p>Thank you, Keith</p>
<p>I will not start another debate whether datasets are good or evil. If you continue to use them, here are something to consider:</p> <ul> <li>You need to keep the original dataset and update that, in order to get correct inserts and updates.</li> <li>You want your parents to know their children, but not the other way. Banish the ParentTable.</li> <li>An Order and its OrderDetails is an aggregate (from Domain Driven Design) and should be considered as a whole. A call to order.Save() should save everything.</li> </ul> <p>Well, that's the theory. How can we do that? One way is to create the following artifacts:</p> <ul> <li>Order</li> <li>OrderDetail</li> <li>OrderRepository</li> <li>OrderMap</li> </ul> <p>The OrderMap is where you manage the Order to Dataset relationships. Internally, it could use a Hashtable or a Dictionary.</p> <p>The OrderRepository is where you get your Orders from. The repository will get the dataset with all relations from somewhere, build the Order with all its OrderDetails, and store the Order/Dataset relationship in the OrderMap.</p> <p>The OrderMap must be kept alive as long as the Order is alive. The Order contains all OrderDetails.</p> <p>Pass the order to the repository and let it save it. The repository will get the dataset from the map, update the Order-table from the order and iterate all order-details to update the OrderDetail-table.</p> <p>Retrieve and save:</p> <pre><code>var order = repository.GetOrder(id); repository.Save(order); </code></pre> <p>Inside OrderRepository.GetOrder():</p> <pre><code>var ds = db.GetOrderAndDetailsBy(id); var order = new Order(); UpdateOrder(ds, order); UpdateOrderDetails(ds, order); // creates and updates OrderDetail, add it to order. map.Register(ds, order); </code></pre> <p>Inside OrderRepository.Save():</p> <pre><code>var ds = map.GetDataSetFor(order); UpdateFromOrder(ds, order); foreach(var detail in order.Details) UpdateFromDetail(ds.OrderDetail, detail); </code></pre> <p>Some final notes:</p> <ul> <li>You can implement the map as a singelton. </li> <li>Let the map use weak references. Then any order should be garbage-collected when it should, and memory will be freed. </li> <li>You need some way to associate an OrderDetail with its table-row</li> <li>If you have the slightest possibility to upgrade to .NET 3.5, do it. Linq to Sql or Linq to Entity will remove some of your pain.</li> <li>All of this is created out of thin air. I hope it's not too inaccurate.</li> </ul>
<p>So, What I am doing right now is passing a reference to the DataSet and a reference to the DataRow of the parent into the Save method of the Child Object.</p> <p>Here is a little code showing the concept of what I am doing.</p> <pre><code>// some random save event in a gui.cs// public void HandleSaveButtonClick() { parentObject.Save(); } // Save inside the parentObject.cs // public void Save() { CustomDataSet dataSet = new CustomDataSet(); ParentObjectTableAdapter parentTableAdapter = new ParentObjectTableAdapter(); DataTable dt = dataSet.ParentTable; DataRow newParentDataRow = dt.NewRow(); newParentDataRow["Property1"] = "Hello"; newParentDataRow["Property2"] = "World"; dt.Rows.Add(newParentDataRow); parentTableAdapter.Update(dataSet.ParentTable); //save children _child1.Save(dataSet, newParentDataRow) dataSet.AcceptChanges(); } //Save inside child1.cs // public void Save(CustomDataSet dataSet, DataRow parentRow) { Child1TableAdapter childTableAdapter= new Child1TableAdapter(); DataTable dt = dataSet.ChildTable; DataRow dr = dt.NewRow(); dr.SetParentRow(parentRow); dr["CProp1"] = "Child Property 1"; dt.Rows.Add(dr); childTableAdapter.Update(dataSet.ChildTable); } </code></pre> <p>Let me know how this looks. Is this a usable pattern or am I missing something critical? </p> <p>Thank you,<br> Keith</p>
18,079
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
<p>I may have found a way to do it.</p> <p>Create a file .pythonrc</p> <pre><code># ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") </code></pre> <p>then in your .bashrc file, add</p> <pre><code>export PYTHONSTARTUP=~/.pythonrc </code></pre> <p>That seems to work.</p>
<p>For older versions (2.x) above script works like charm :)</p> <pre class="lang-sh prettyprint-override"><code>fernanr@crsatx4 ~ $ cat .bashrc | grep -i python #Tab completion for python shell export PYTHONSTARTUP=~/.pythonrc fernanr@crsatx4 ~ $ . ~/.bashrc fernanr@crsatx4 ~ $ echo $? 0 fernanr@crsatx4 ~ $ python2 Python 2.7.5 (default, Jun 11 2019, 14:33:56) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os. Display all 249 possibilities? (y or n) os.EX_CANTCREAT os.O_WRONLY </code></pre>
30,628
<p>Tag <a href="https://3dprinting.stackexchange.com/questions/tagged/nylon" class="post-tag" title="show questions tagged &#39;nylon&#39;" rel="tag">nylon</a> exists already, but I think it would be incredibly useful to have a TPE/TPU tag and a tag for all flexibles as a category.</p> <p><strong>EDIT:</strong> It has come to my attention that the tag <a href="https://3dprinting.stackexchange.com/questions/tagged/flexible" class="post-tag" title="show questions tagged &#39;flexible&#39;" rel="tag">flexible</a> already exists. I still would like to see a tag <a href="https://3dprinting.stackexchange.com/questions/tagged/tpu" class="post-tag" title="show questions tagged &#39;tpu&#39;" rel="tag">tpu</a> though.</p>
<p>Let's stay with the classic $.</p> <p>Example: \$\$\frac{1 \times 2}{2} = 1\$\$</p> <hr> <p><em>Now that MathJax is enabled, it renders to: $$\frac{1 \times 2}{2} = 1$$</em></p>
<p>An alternative character could be the Tilde <code>~</code>.</p>
60
<p>I am downloading a text string from a web service into an RBuf8 using this kind of code (it works..)</p> <pre><code>void CMyApp::BodyReceivedL( const TDesC8&amp; data ) { int newLength = iTextBuffer.Length() + data.Length(); if (iTextBuffer.MaxLength() &lt; newLength) { iTextBuffer.ReAllocL(newLength); } iTextBuffer.Append(data); } </code></pre> <p>I want to then convert the RBuf8 into a char* string I can display in a label or whatever.. or for the purposes of debug, display in</p> <pre><code>RDebug::Printf("downloading text %S", charstring); </code></pre> <p><strong>edit</strong> for clarity..</p> <p>My conversion function looks like this..</p> <p>void CMyApp::DownloadCompleteL() { { RBuf16 buf; buf.CreateL(iTextBuffer.Length()); buf.Copy(iTextBuffer);</p> <pre><code> RDebug::Printf("downloaded text %S", buf); iTextBuffer.SetLength(0); iTextBuffer.ReAlloc(0); } </code></pre> <p>But this still causes a crash. I am using S60 3rd Edition FP2 v1.1</p>
<p>What you may need is something to the effect of:</p> <pre><code>RDebug::Print( _L( "downloaded text %S" ), &amp;buf ); </code></pre> <p><a href="http://wiki.forum.nokia.com/index.php/How_to_use_RDebug" rel="nofollow noreferrer">This tutorial</a> may help you.</p>
<p>As stated by quickrecipesonsymbainosblogspotcom, you need to pass a pointer to the descriptor.</p> <p><code>RDebug::Printf("downloaded text %S", &amp;buf); //note the address-of operator</code></p> <p>This works because <code>RBuf8</code> is derived from <code>TDes8</code> (and the same with the 16-bit versions).</p>
42,836
<p>I'm using the code below to save a password to the registry, how do I convert it back? The code below isn't mine but it encrypts well.</p> <p>Thanks</p> <pre><code>using System.Security.Cryptography; public static string EncodePasswordToBase64(string password) { byte[] bytes = Encoding.Unicode.GetBytes(password); byte[] dst = new byte[bytes.Length]; byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(dst); return Convert.ToBase64String(inArray); } </code></pre>
<p>SHA1 is a <em>hash</em> algorithm, not an encryption algorithm. A hash algorithm is a one-way function which transforms data into a hash of that data, but the original data cannot be gotten back from the hash. An encryption algorithm is a two-way function which transforms data into encrypted data, and the encrypted data can then be transformed back into the original data.</p>
<p>Using your own code snippet above, what you want to do is call that method when the user initially chooses a password - but add to the password what is called a <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)" rel="nofollow noreferrer">salt</a> somewhere in the password string (usually at the beginning or end). Then, when the user is attempting to authenticate later, they enter their password, you run that one along with the hash through this same method and if the two hashes are equal, it's a statistically excellent chance the passwords are equal and valid.</p> <p>This being said, SHA1 is known to have weaknesses and you should choose a stronger algorithm. If you want to stay in the SHA family, SHA512 is pretty good.</p>
33,793
<p>All of my users are a short walk down the hall, and all of my programs run on workstations on the same LAN. Some years ago, I had the staff write the log files for all of their programs to a shared folder hierarchy, naming each log file after the machine name in a sub-directory named after the app.</p> <p>But this arrangement wasn't that great, since if the file server went down then none of the programs anywhere could write logs. Yet keeping logs local to each workstation would make it a pain in the ass to read them whenever we had to debug a problem.</p> <p>We tried making a DNS alias for the logging fileserver so we could point it to a backup machine when necessary, but DNS aliases don't work with Windows file shares.</p> <p>Putting the path to the shared log folder in each program isn't great--even if it's field configurable--because we have dozens of programs on dozens of machines.</p> <p>We've also looked into using Microsoft's distributed file system, but the price is ridiculous.</p> <p>I'd like a way to gather the logging for many programs on the local network into one place so I can tail and analyze them without paying a visit to the remote machine. We use .Net for all our programs.</p> <p><strong>Edit:</strong> I'd like to avoid setting up a file-share on each user's workstation, or solutions that trawl for logs each night, since I want to be able to read fresh logs on demand, or moments after a problem is reported.</p>
<p>In an IT environment which I worked in a few years back, we had each machine write it's log files locally and wipe them every five days. The server would log in every night to grab the latest logs from each machine. If the server went down, it would just grab two days worth of logs from everyone. If a client went down, it's log could be grabbed the next day as well.</p>
<p>Can you have the log files writtin to peoples local machine and then have a script that pulls them to a common file server as a nightly batch job?</p>
17,149