instruction
stringlengths 27
22.5k
| chosen
stringlengths 27
28.2k
| rejected
stringlengths 19
24.9k
| __index_level_0__
int64 0
10k
|
|---|---|---|---|
<p>Are there any utilities out there which can draw pictures of the merge history of a subversion repo - we always commit merges with a (fairly) consistent log message, and it would be handy to be able to automatically extract this info into a single picture that shows what branches occurred when, and what the state of merges is.</p>
<p>I'm just interested in an informational tool, not something to help with actually performing merges.</p>
|
<p>I use <a href="https://www.smartsvn.com/features/" rel="nofollow noreferrer">SmartSVN</a> for this; I has a very quick and easy to use revision graph, which can show svm:mergeinfo as colour coded links and arrows between branches. It's pretty hard to beat when looking at a good-size source tree</p>
|
<p>I think Tortoise svn does <a href="http://svn.haxx.se/tsvnusers/archive-2008-05/0149.shtml" rel="nofollow noreferrer"><strong>not yet</strong></a> support version tree.</p>
<p>So far, Clearcase explorer is the best i've come across.</p>
| 7,997
|
<p>I have a PHP script that runs as a CGI program and the HTTP <code>Authenticate</code> header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored.</p>
<p>I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials.</p>
<p>So how would you implement this?</p>
<p>Cookies?</p>
<p>I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.</p>
|
<p>A few ways you could do this.</p>
<ol>
<li><a href="http://fragments.turtlemeat.com/htaccess.php" rel="nofollow noreferrer">htaccess</a> -- have your webserver handle securing the pages in question (not exactly cgi form based though).</li>
<li>Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to <a href="http://www.codinghorror.com/blog/archives/000949.html" rel="nofollow noreferrer">salt</a> your hashes for extra security vs rainbow tables. (This method is a bit naive... be <em>very</em> careful with security if you go this route)</li>
<li>use something like a <a href="http://www.sqlite.org/" rel="nofollow noreferrer">sqlite</a> database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend.</li>
</ol>
<p>Theoretically, you could also store session data in a flat file, even if you can't have a database.</p>
|
<p>... About salt, add the username in your hash salt will prevent someone who knows your salt and have access to your password file to write a rainbow table and crack number of your users's password.</p>
| 3,805
|
<p>Is there any way to include the SVN repository revision number in the version string of a .NET assembly? Something like Major.Minor.SVNRev</p>
<p>I've seen mention of doing this with something like CC.NET (although on ASP.NET actually), but is there any way to do it without any extra software? I've done similar things in C/C++ before using build batch scripts, but in was accomplished by reading the version number, then having the script write out a file called "ver.h" everytime with something to the effect of:</p>
<pre><code>#define MAJORVER 4
#define MINORVER 23
#define SOURCEVER 965
</code></pre>
<p>We would then use these defines to generate the version string.</p>
<p>Is something like this possible for .NET?</p>
|
<p>Here's and C# example for updating the revision info in the assembly automatically. It is based on the answer by Will Dean, which is not very elaborate.</p>
<p>Example :</p>
<ol>
<li>Copy AssemblyInfo.cs to AssemblyInfoTemplate.cs in the project's
folder <em>Properties</em>.</li>
<li>Change the <em>Build Action</em> to <em>None</em> for AssemblyInfoTemplate.cs.</li>
<li><p>Modify the line with the AssemblyFileVersion to: </p>
<p><code>[assembly: AssemblyFileVersion("1.0.0.$WCREV$")]</code></p></li>
<li><p>Consider adding: </p>
<p><code>[assembly: AssemblyInformationalVersion("Build date: $WCNOW=%Y-%m-%d %H:%M:%S$; Revision date: $WCDATE=%Y-%m-%d %H:%M:%S$; Revision(s) in working copy: $WCRANGE$$WCMODS?; WARNING working copy had uncommitted modifications:$.")]</code>, </p>
<p>which will give details about the revision status of the source the assembly was build from.</p></li>
<li><p>Add the following Pre-build event to the project file properties:</p>
<p><code>subwcrev "$(SolutionDir)." "$(ProjectDir)Properties\AssemblyInfoTemplate.cs" "$(ProjectDir)Properties\AssemblyInfo.cs" -f</code></p></li>
<li><p>Consider adding AssemblyInfo.cs to the svn ignore list. Substituted revision numbers and dates will modify the file, which results in insignificant changes and revisions and $WCMODS$ will evaluate to true. AssemblyInfo.cs must, of course, be included in the project.</p></li>
</ol>
<p>In response to the objections by Wim Coenen, I noticed that, in contrast to what was suggested by Darryl, the AssemblyFileVersion also does <strong>not</strong> support numbers above 2^16. The build will complete, but the property <em>File Version</em> in the actual assembly will be AssemblyFileVersion modulo 65536. Thus, 1.0.0.65536 as well as 1.0.0.131072 will yield 1.0.0.0, etc. In this example, there is always the true revision number in the AssemblyInformationalVersion property. You could leave out step 3, if you consider this a significant issue.</p>
<p>Edit: some additional info after having used this solution for a while.</p>
<ol>
<li>It now use AssemblyInfo.cst rather than AssemblyInfoTemplate.cs, because it will automatically have <em>Build Action</em> option <em>None</em>, and it will not clutter you Error list, but you'll loose syntax highlighting.</li>
<li><p>I've added two tests to my AssemblyInfo.cst files:</p>
<pre><code>#if(!DEBUG)
$WCMODS?#error Working copy has uncommitted modifications, please commit all modifications before creating a release build.:$
#endif
#if(!DEBUG)
$WCMIXED?#error Working copy has multiple revisions, please update to the latest revision before creating a release build.:$
#endif
</code></pre>
<p>Using this, you will normally have to perform a complete SVN Update, after a commit and before you can do a successful release build. Otherwise, $WCMIXED will be true. This seems to be caused by the fact that the committed files re at head revision after the commit, but other files not.</p></li>
<li>I have had some doubts whether the first parameter to subwcrev, "$(SolutionDir)", which sets the scope for checking svn version info, does always work as desired. Maybe, it should be $(ProjectDir), if you are content if each individual assembly is in a consistent revision.</li>
</ol>
<p><strong>Addition</strong>
<em>To answer the comment by @tommylux.</em></p>
<p>SubWcRev can be used for any file in you project. If you want to display revision info in a web page, you could use this VersionInfo template:</p>
<pre><code>public class VersionInfo
{
public const int RevisionNumber = $WCREV$;
public const string BuildDate = "$WCNOW=%Y-%m-%d %H:%M:%S$";
public const string RevisionDate = "$WCDATE=%Y-%m-%d %H:%M:%S$";
public const string RevisionsInWorkingCopy = "$WCRANGE$";
public const bool UncommitedModification = $WCMODS?true:false$;
}
</code></pre>
<p>Add a pre-build event just like the one for AssemblyInfo.cst and you will have easy access to all relevant SubVersion info.</p>
|
<p>You can use a shared Assembly Version file that you can reference in all of your projects.</p>
<p><a href="http://uppercut.googlecode.com" rel="nofollow noreferrer">UppercuT</a> does this - <a href="http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx" rel="nofollow noreferrer">http://ferventcoder.com/archive/2009/05/21/uppercut---automated-builds---versionbuilder.aspx</a></p>
<p>This will give you an idea of what you can do to get versions in your assemblies.</p>
| 3,327
|
<p>As you may or may not know, this is the third iteration of a proposal site that covers 3D Printing. The first 2 made it to the beta phase, but did not graduate from the beta successfully:</p>
<ul>
<li><a href="http://area51.stackexchange.com/proposals/41850/digital-fabrication">Digital Fabrication</a></li>
<li><a href="http://area51.stackexchange.com/proposals/22246/personal-manufacturing">Personal Manufacturing</a></li>
</ul>
<p>Would it be acceptable to extract <code>good</code>/<code>relevant</code> questions out of these beta site question dumps and post them in the 3D Printing site?</p>
|
<p>If someone has a question from one of those older sites, they should go ahead and ask it. But a wholesale importing of content from elsewhere is not really a desirable way to build this site. </p>
<p>There is a lot of ownership and careful curation that goes with vetting the content of this site. Questions imported from elsewhere would always have that air of odd, forgotten legacy content back-dated and <em>anonymous</em> with no owners or real-time vetting at all. If someone posts another answer or asks for some followup to one of these questions, no one will receive the notification. Essentially, we would be loading this site up with a lot of questions asked and answered a long time ago without imparting any of the benefits of reputation, ownership, or experience into the community that is supposed to take care of it.</p>
<p>That's why we don't do it.</p>
|
<p>Although I was sad to see the <a href="http://area51.stackexchange.com/proposals/41850/digital-fabrication">Digital Fabrication</a> beta close, I think there would be little to be gained by trying to import it's questions. The scope was different, and it was a very different group of comitters - only 1.8% of <a href="http://area51.stackexchange.com/proposals/41850/digital-fabrication">Digital Fabrication</a> committers also committed to <em>3D Printing</em> for instance.</p>
| 18
|
<p>I've inherited a desktop application which has a custom .NET file chooser that is embedded in a control, but it has some issues.<br>
I'd like to replace it with a non-custom File Chooser (like the <code>OpenFileDialog</code>). </p>
<p>However, for a variety of reasons it needs to be embedded in the parent control not a popup dialog.<br>
Is there a control I'm missing, or does MS only provide the popup dialog out of the box?</p>
|
<p>The .Net control is a thin wrapper for the common dialog built into windows, and that <em>is</em> a dialog. So there is no way to embed it as though it were a control.</p>
|
<p>Depending on your needs, you COULD abuse the web browser control to show local files and folders. It won't match all the functionality of the OpenFileDialog, but it could work.</p>
<p>Here's one that I remembered from way-back. <a href="http://www.ssware.com/megapack.htm" rel="nofollow noreferrer">The Shell Mega-Pack</a>. It has ActiveX and .NET versions. It looks promising.</p>
<p>Alternatively, if you want to build your own, you could start here on CodeProject: <a href="http://www.codeproject.com/KB/miscctrl/ExplorerTree.aspx" rel="nofollow noreferrer">A Windows Explorer in a User Control</a>. That looks like a good start. Here's another one: <a href="http://www.codeproject.com/KB/cpp/VbNetExpTree.aspx" rel="nofollow noreferrer">An All VB.NET Explorer Tree Control with ImageList Management</a>.</p>
| 7,888
|
<p>I am using a wxGenericDirCtrl, and I would like to know if there is a way to hide directories, I'd especially like to hide siblings of parent nodes.</p>
<p>For example if my directory structure looks like this:</p>
<pre><code>+-a
|
+-b
| |
| +-whatever
|
+-c
| |
| +-d
| |
| +-e
| |
| +-f
|
+-g
|
+-whatever
</code></pre>
<p>If my currently selected directory is /a/c/d is there any way to hide b and g, so that the tree looks like this in my ctrl:</p>
<pre><code>+-a
|
+-c
|
+-[d]
|
+-e
|
+-f
</code></pre>
<p>I'm currently working with a directory structure that has lots and lots directories that are irrelevant to most users, so it would be nice to be able to clean it up.</p>
<p><strong>Edit</strong>:
If it makes a difference, I am using wxPython, and so far, I have only tested my code on linux using the GTK backend, but I do plan to make it multi-platform and using it on Windows and Mac using the native backends.</p>
|
<p>Listing/walking directories in Python is very easy, so I would recommend trying to "roll your own" using one of the simple tree controls (such as TreeCtrl or CustomTreeCtrl). It should really be quite easy to call the directory listing code when some directory is expanded and return the result.</p>
|
<p>I don't think that's possible.</p>
<p>It would be relatively easy to add this functionality to the underlying C++ wxWidgets control, but since you're using wxPython, you'd then have to rebuild that as well which is a tremendous issue.</p>
| 7,619
|
<p>ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="nofollow noreferrer">here</a>, but that does not work with ASP.net AJAX properly.</p>
<p>Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.</p>
<p>So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?</p>
|
<p>Found it and <a href="http://www.stum.de/2008/09/08/gracefully-handling-httprequestvalidationexception-with-aspnet-ajax/" rel="nofollow noreferrer">blogged about it</a>. Basically, the EndRequestHandler and the args.set_errorHandled are our friends here.</p>
<pre><code><script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() != undefined)
{
var errorMessage;
if (args.get_response().get_statusCode() == '200')
{
errorMessage = args.get_error().message;
}
else
{
// Error occurred somewhere other than the server page.
errorMessage = 'An unspecified error occurred. ';
}
args.set_errorHandled(true);
$get('<%= this.newsletterLabel.ClientID %>').innerHTML = errorMessage;
}
}
</script>
</code></pre>
|
<p>hmmmm, it seems you would need to find some sort of JavaScript to check for html input or a client side validator. </p>
| 7,017
|
<p><a href="https://photos.app.goo.gl/O6yPf3sDeV1yhS0C2" rel="nofollow noreferrer">https://photos.app.goo.gl/O6yPf3sDeV1yhS0C2</a></p>
<p>I tried to illustrate my problem in the videos above, two of them show the weird movement and the other shows me clicking on the home button repeatedly.</p>
<p>Some Info:</p>
<ul>
<li>Marlin 1.1.8 or 2.0.0 (same problem in both)</li>
<li>Robotdyn RAMPS 1.4</li>
<li>0.9 angle stepper motors</li>
<li>DRV8825 drivers configured at 0.8V Vref</li>
<li>Anet A2 Plus stock for all the rest</li>
</ul>
|
<p>As far as I can see on the attached videos your homing movement is reversed.
as per Marlin, the homing for X shall move towards the left side and for Y to the back of the printer.</p>
<p>That could occur when: cable connectors to stepper motors are reversed, or the motor is assembled the other way (you can set reverse direction in Marlin)</p>
<p>The other issue is steps/mm calibration need to be done see source below.</p>
<p>The high pitch in the video could also point that the drv8825 is shutting down the movement as it is overloaded.</p>
<p>please also check that for vref</p>
<blockquote>
<p>Configuring Vref In order to measure Vref you first need to turn on
your printer as you normally would. If you only connecct using USB,
but not external power, you get a wrong reading.</p>
<p>You need to turn on your multimeter and set it at 2v. Put the red one
on the potentiometer and the Black one on the Gnd pin. Both are marked
on the images here.</p>
<p>Before starting this I read they come with a very high vref setting,
and it is recommended to start around 0.5v Vref. After measuring mine,
I can confirm they come with a very high initial setting. Mine both
came at 1,65v or so! - Yours might be different, which just underlines
the importance of doing this.</p>
<p>Contrary to normal potentiometer usage, the ones on most copies/clones
of DRV8825 are lowered by turning clock-wise, so that is what we will
do, to we hit 0,5v on each. - A quarter of a full turn lowered it to
0,7v, - after that it goes very, very rapidly down, so aim for the
quarter of a turn + a tiny tad more. If you buy your DRV8825 directly
from pololu.com the Potentiometer are dialed up by turning it
clock-wise:</p>
</blockquote>
<p><a href="http://www.instructables.com/id/Installing-and-Configuring-DRV8825-Stepper-Drivers/" rel="nofollow noreferrer">source</a></p>
|
<p>The problem was the logic of the endstops that were reversed</p>
| 859
|
<p>I have a Windows 2008 Server (x64) running Microsoft SQL 2008 (x64) and I'm creating a Linked Server connection to an Oracle server. I'm able to make the connection, but I cannot see any information regarding which schema a table belongs to.</p>
<p>In SQL 2005, my linked servers show the schema information as I would expect.</p>
<p>Does anyone know how to resolve this issue? Is it an issue with the provider, OraOLEDB.Oracle?</p>
<p>Any help or pointers would be appreciated.</p>
|
<p>@Boojiboy - When you are looking at the tables via a linked server, there used to be a column for what schema. It appears that in the latest the new Oracle OLEDB drivers don't show this information any longer.</p>
|
<p>Also in the SQL 08 > Server Objects > Providers
make sure your OraOLEDB.Oracle provider is allowing inprocessing</p>
| 4,632
|
<p>everyone.</p>
<p>I'm a relative newcomer to 3D printing, so I don't know what constitutes an unacceptably bad spool of filament.</p>
<p>About 1/6 of the way into a roll of PETG (and maybe 4 hours into a 6-hour print), an over/under wrap brought things to a screeching halt. I aborted the print, then snipped the filament and started unspooling it, looking for more cross-wraps. I found a ton of them, along with a ton of kinks.</p>
<p>I stopped about 1/3 of the way into the spool, still finding kinks and cross-wraps, and said to heck with it. The only way to use it would have been to run the entire length onto another spool, carefully avoiding cross-wraps, and hope the kinks wouldn't affect the print quality.</p>
<p>I complained to the supplier but never even got a reply, so now I'm wondering if this is just one of those things I can expect from time to time. Any thoughts & opinions would be much appreciated.</p>
<p>Cheers,</p>
<p>Glasseyed</p>
|
<p>Filament should come off of the roll without overlapping itself. That being said depending on what you paid for it would determine if you should complain. Normally you get what you pay for. If you paid \$10 for it, I would think that is why it was so cheap, but if you paid >\$25 it should be nice stuff.</p>
|
<p>Knot happens when you loosen the filament yourself and then leave it like that or try to manually re-spool it.
To avoid this kind of situation as well as the curly filament coming off the spool and getting tangled there, try to not loosen it and also build or print a "spool guide" for your 3d printer: <a href="http://www.thingiverse.com/search/page:1?q=filament+spool+guide&sa=" rel="nofollow">http://www.thingiverse.com/search/page:1?q=filament+spool+guide&sa=</a></p>
| 194
|
<p>I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example:</p>
<pre><code> date name earnings source location
-----------------------------------------------------------
12-AUG-2008 Tom $50.00 washing cars uptown
12-AUG-2008 Dick $100.00 washing cars downtown { main report }
12-AUG-2008 Harry $75.00 mowing lawns around town
total earnings for washing cars: $150.00 { subreport }
total earnings for mowing lawns: $75.00
date name earnings source location
-----------------------------------------------------------
13-AUG-2008 John $95.00 dog walking downtown
13-AUG-2008 Jane $105.00 washing cars around town { main report }
13-AUG-2008 Dave $65.00 mowing lawns around town
total earnings for dog walking: $95.00
total earnings for washing cars: $105.00 { subreport }
total earnings for mowing lawns: $65.00
</code></pre>
<p>In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data?</p>
|
<p>Hmm... as nice as it is to call the stored proc from the report and have it all contained in one location, however we found (like you) that you eventually hit a point where you can't get crystal to do what you want even tho the data is right there.</p>
<p>We ended up introducing a business layer which sits under the report and rather than "pulling" data from the report we "push" the datasets to it and bind the data to the report. The advantage is that you can manipulate the data in code in datasets or objects before it reaches the report and then simply bind the data to the report.</p>
<p><a href="http://www.codeguru.com/csharp/.net/net_general/toolsand3rdparty/article.php/c13253" rel="nofollow noreferrer">This article</a> has a nice intro on how to setup pushing data to the reports. I understand that your time/business constraints may not allow you to do this, but if it's at all possible, I'd highly recommend it as it's meant we can remove all "coding" out of our reports and into managed code which is always a good thing.</p>
|
<p>The only way I can think of doing this without a second run through the data would be by creating some formulas to do running totals per group. The problem I assume you are running into with the existing running totals is that they are intended to follow each of the groups that they are totaling. Since you seem to want the subtotals to follow after all of the 'raw' data this won't work. </p>
<p>If you create your own formulas for each group that simply adds on the total from those rows matching the group you should be able to place them at the end of the report. The downside to this approach is that the resulting subtotals will not be dynamic in relationship to the groups. In other words if you had a new 'source' it would not show up in the subtotals until you added it or if you had no 'dog walking' data you would still have a subtotal for it.</p>
| 3,012
|
<p>The company I work for is protective of IP and has security procedures for disposing of anything that could be stolen for industrial espionage. Paper gets shredded and sent to trusted recycling center, all old data storage media gets obliterated, but what do we do with 3D prints? For any functional prototype, I have 10 or more early versions and failed prints. Is there a good way to dispose of these so that they are unrecognizable? Given the volume of prints I need to dispose of, it should be safe, cheap, and able to handle large batches.</p>
|
<p>Big batches need you to be time efficient - or use a method that uses little work. So my suggestions are mainly needing oversight. Keep a fire extinguisher and safety gear handy though!</p>
<h1>Melting together</h1>
<p>Most filaments are melting at or around 200 °C.</p>
<p>I recently got rid of my box of (PLA) waste material by putting them on a tray and melting them together in a standard kitchen oven at 200 °C for about 1-2 hours. The resulting plate of plastic destroyed all structure that could be identified. This plate can be then broken up or recycled without the risk to disclose any company secrets.</p>
<p>I suggest to use a baking paper under the filament to be molten or a teflon coated tray, as the filament will be REALLY sticky to a blank metal surface.</p>
<p>About 4 liters of broken prints resulted in approximately a 5x450x300 mm sheet. If you make sure that no filament can touch the heating elements, you can get rid of quite a lot of material in each batch.</p>
<p><strong>Don't do this with ABS</strong> and don't contaminate your food trays with plastic rests - use specially marked ones that are for disposal of prints only.</p>
<h3>Green destruction</h3>
<p>If you want to be green when destroying prints: <a href="https://insteading.com/blog/solar-cooker/" rel="nofollow noreferrer">a box solar cooker</a> with a glass lid easily runs at 200 °C, is decently cheap and runs all day on just a couple seconds of adjusting every hour or so. You have to set it up in an access restricted area, but as long as the sun shines, it runs pretty much for free. Just make sure to put the prints to be destroyed onto some kind of non-combustible carriers, like tinfoil or aluminium trays.</p>
<h2>ABS in Acetone</h2>
<p>If you use ABS, exposing it to acetone fumes for a short time (seconds to half a minute will smooth the surface. Give it some minutes can destroy the structure into a batch of plastic waste without heat that hardens as the acetone evaporates again, though complex structures might need as much as an hour. Dunking ABS into acetone results in pure chemical waste, that is just a waste of acetone.</p>
<p>To save acetone and a way to the chemical waste disposal, try this:</p>
<p>Put a batch of several prints into a large, airtight box that isn't made from ABS. Pour some acetone on a tray and add a paper towel to generate a consistent acetone atmosphere in the box. Make sure to keep the tray on the floor of the box but in a way so no print will fall into it. This should dispose of the prints by merging them into a huge lump within about an hour.</p>
<p><strong>Do this outside & keep fire away</strong>.</p>
|
<p>If your company has a shredder which would handle large amounts of paper at one time, it should be able to handle the plastics from 3D printing. Most larger shredders can handle paper clips and staples. 3D plastics would be even less of a burden than them. You may need to break the pieces down into smaller chunks, but I doubt it would be an issue. Even destroying most prints by hand shouldn't be too arduous. </p>
<p>Secondarily, you could also melt them using something hot ... a heat gun would probably do the job without issue. <a href="https://home.howstuffworks.com/heat-gun.htm" rel="nofollow noreferrer">They get in excess of 1100°F</a>. Since we <em>usually</em> melt filament at around 200°C (~392°F), a heat gun should be more than hot enough to make it an unrecognizable blob of plastic.</p>
| 1,028
|
<p>How can I exclude the bin folder from SourceSafe in a Visual Studio 2008 web application? I want to be able to check in everything recursively from the solution node without picking up anything in the bin folder.</p>
|
<ul>
<li>Right-click the folder in your
project</li>
<li>select "Exclude from project"</li>
</ul>
|
<p>You can hide the folder through Windows explorer, although it'll disappear from your Visual Studio Solution Exporer, I don't think that'll affect the website.</p>
| 9,890
|
<p>I have an application that sends messages to an external web service. I build and deploy this application using <a href="http://msdn.microsoft.com/en-us/library/wea2sca5(VS.80).aspx" rel="nofollow noreferrer">MSBuild</a> and <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">Cruisecontrol.NET</a>. As CCNET build and deploys the app it also runs a set of test using <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">NUnit</a>. I'd now like to test the web service communication as well. </p>
<p>My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service). </p>
<p>Are there any <strong>existing utilities out there</strong> that easily mock a web service based on a WSDL? Anyone <strong>done something similar using MSBuild?</strong> </p>
<p>Are there <strong>other ways of testing this scenario?</strong> </p>
|
<p>I just started looking into <a href="http://www.soapui.org/" rel="nofollow noreferrer">http://www.soapui.org/</a> and it seems like it will work nicely for testing web services.</p>
<p>Also, maybe look at adding an abstraction layer in your web service, each service call would directly call a testable method (outside of the web scope)? I just did this with a bigger project I'm working on, and it's testability is working nicely.</p>
|
<p>At my work place we are using <a href="http://www.typemock.com/index.php" rel="nofollow noreferrer">Typemock</a> and <a href="http://www.nunit.org/" rel="nofollow noreferrer">nUnit</a> for our unit testing.</p>
| 5,497
|
<p>I want to make an etag that matches what Apache produces. How does apache create it's etags?</p>
|
<p>Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP:</p>
<pre><code>$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));
</code></pre>
|
<p>If you're dynamically generating your page though, this probably won't make sense. If you're in PHP, you can pick the inode and file size of the main script, but the modify time won't tell you if your data has changed. Unless you have a good caching process or just generate static pages, etags aren't helpful. If you do have a good caching process, the inode and file size are probably irrelevant.</p>
<p>Edit: For people who don't know what <a href="http://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow noreferrer">etag</a>s are - they're just supposed to be a value that changes when the content has changed, for caching purposes. The browser gets the etag from the web server, compares it to the etag for its cached copy and then fetches the whole page if the etag has changed.</p>
| 6,671
|
<p>I found this low temperature filament for 3d printing, <a href="https://www.sainsmart.com/products/low-temperature-filament-0-5kg-1-75mm-white" rel="nofollow noreferrer">Low Temperature Filament 0.5kg 1.75mm, White</a> </p>
<p>Correct me if I'm wrong but I'm pretty sure I can use it for a <em>really</em> precise nozzle because it's so runny at normal printing temperature, the thing is, you obviously can't get nozzles at the size I'm taking about, so with that said, who could I hire to make one?</p>
|
<p>You won't need specialized nozzles, you understand the material wrong:</p>
<p>The benefit the properties of this material grant is not super fine prints (which you can get with small nozzles like 0.1 mm already), it is that you can print at super low temperatures. Printing it at standard 200°C will mean, that it won't solidify in the time the printer needs it to, and your walls will all melt down - in worst case it boils off and degrades into useless goop!</p>
<p>You might print PCL onto an already completed print made from a different material with higher printing temperature (if your slicer lets you do that...), like to make a form-shaped piece.</p>
<p>It's low melting point also means you could print parts with it that you <em>want</em> to deform under low heat, like a standard shaped flat shin and then just dunk it into 60°C water or put onto a (towel shielded) pocket heater before molding it around the patient, making perfect fits from easy transportable (flat) parts. Or you print "rivets", which you heat, put through the holes in other prints and then flatten with a pair of pliers.</p>
<p>Also, it is one of the cheaper conductive filaments. You might find <a href="http://www.fabbaloo.com/blog/2016/6/24/the-unusual-properties-of-pcl-3d-printer-filament" rel="noreferrer">this article</a> or the <a href="http://reprap.org/wiki/Polycaprolactone" rel="noreferrer">RepRap Wiki</a> enlightening.</p>
<p>Beware though: Many printers have a MinTemp set! For example the Ultimaker at 175°C, and you have to force the machine to ignore this with M302.</p>
|
<p>I have been looking for some where that could make a custom nozzle and the only place I have found so far that I think might be able to is: <a href="https://www.emachineshop.com/" rel="nofollow noreferrer">https://www.emachineshop.com/ </a></p>
<p>You would need to draw up the design of the nozzle in the software on their web site and see if they could make what you want.</p>
| 764
|
<p>Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?</p>
|
<p>I think the cleanest way is as described <a href="http://www.iis-aid.com/articles/how_to_guides/redirect_http_to_https_iis_7" rel="nofollow noreferrer">here on IIS-aid.com</a>. It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works.</p>
<pre><code><configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
</code></pre>
|
<p>I think by 'cleanly' you mean like with a 300 redirect. Config for a lot of servers & languages <a href="http://www.somacon.com/p145.php" rel="nofollow noreferrer">here</a>.</p>
| 6,844
|
<p>I have replaced the stock extruder on my Ender 3 with one of these:</p>
<p><a href="https://i.stack.imgur.com/wDmXL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wDmXL.jpg" alt="New Extruder"></a></p>
<p>The grip gear has a smaller diameter, so I calibrated the esteps as per the top google search: <a href="https://all3dp.com/2/extruder-calibration-6-easy-steps-2/" rel="nofollow noreferrer">Extruder Calibration – 6 Easy Steps to Calibrate Your Extruder...</a></p>
<p>If I set the esteps so that it's spot on with 100 mm of filament is used up when I ask it to extrude 100 mm, then during a print I get the occasional skip on the extruder.</p>
<p>If I dial it back a bit and set it so that it extrudes 90 mm of filament when I ask it to extrude 100 mm, then I don't get the skips.</p>
<p>In both cases the print looks normal.</p>
<p>I've tried changing the nozzle as well in case there was some blockage, but it doesn't make a difference.</p>
<p>Should I just go with the under extrusion? or is these likely to be some other problem that isn't apparent?</p>
<p>I didn't notice any issues with the stock extruder and the stock estep setting, but I didn't think to check the calibration.</p>
|
<p>Consider that the extruder is skipping because it is unable to push filament at the rate you are requesting. By reducing the steps to ninety percent, you are reducing the rate by that much as well.</p>
<p>Typically, a skipping extruder is an indication of clogging, but it does not have to be clogging caused by particulates jamming the nozzle. At higher rates of filament travel, one needs higher temperatures to compensate for the cooling at those higher rates.</p>
<p>Consider to reduce the print speed to ninety percent of the current figure, or raise the nozzle temperature by five to ten degrees (in steps) to see if you'll get rid of the cold blocking that may be causing this problem.</p>
|
<p>I have this same extruder on my Voxelab Aquila.
Default E-steps are 93. Using the printer menu to feed 100 mm of eSun black PETG filament I measured a feed length of 66 mm, so 34 mm under extruded.</p>
<p>Using the formula 100 / 66 * 93 gave me a new E-step value of 140.9.
Upon re-testing, I found I was now over extruding by 34mm.</p>
<p>This formula is missing something. I've chased E-step values up and down before so decided to try something different.</p>
<p>Since the new E-step value was over extruding by the same as the original E-step under extruding value, I added the original E-step value to the new E-step value and took the average. 93 + 140.9 / 2 = 116.9.
I re-tested this value and found it was over extruding by 0.4 mm. Since I was still over extruding slightly I calculated a new E-step, 100 / 100.4 * 116.9 = 116.4. Took the average between the 2 again and got a final E-step value of 116.6.</p>
<p>Hope this helps anyone else having issues calibrating E-steps.</p>
| 1,469
|
<p>I need to copy files using Windows command-line (available on XP Pro or later by default) and show progress during the process.</p>
<p>The progress indicator could be in a terminal or a GUI window. It is intended to be used during batch file scripting.</p>
|
<p>I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.</p>
|
<p>Here is the script I use:</p>
<pre><code>@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
mode con:cols=210 lines=50
ECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...
robocopy.exe M:\ G:\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD "$RECYCLE.BIN" "System Volume Information" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log
ECHO Finished with backup.
pause
</code></pre>
| 8,324
|
<p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>
|
<p>A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.</p>
<p>I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:</p>
<pre><code>powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
</code></pre>
<p>To explain it:</p>
<ul>
<li><code>powershell</code> starts up powershell.exe, which is included in Windows 7</li>
<li><code>-Command "... "</code> is a command line arg for powershell.exe containing the command to run</li>
<li><code>(gc myFile.txt)</code> reads the content of <code>myFile.txt</code> (<code>gc</code> is short for the <code>Get-Content</code> command)</li>
<li><code>-replace 'foo', 'bar'</code> simply runs the replace command to replace <code>foo</code> with <code>bar</code></li>
<li><code>| Out-File myFile.txt</code> pipes the output to the file <code>myFile.txt</code></li>
<li><code>-encoding ASCII</code> prevents transcribing the output file to unicode, as the comments point out</li>
</ul>
<p>Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is <code>C:\WINDOWS\system32\WindowsPowerShell\v1.0</code></p>
<p><strong>Update</strong><br/>Apparently modern windows systems have PowerShell built in allowing you to access this directly using</p>
<pre><code>(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
</code></pre>
|
<p>I have faced this problem several times while coding under Visual C++.
If you have it, you can use Visual studio Find and Replace Utility. It allows you to select a folder and replace the contents of any file in that folder with any other text you want.</p>
<p>Under Visual Studio:
Edit -> Find and Replace
In the opened dialog, select your folder and fill in "Find What" and "Replace With" boxes.
Hope this will be helpful. </p>
| 8,483
|
<p><a href="https://i.stack.imgur.com/Bujra.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bujra.png" alt="0.200 mm layer height, single wall" /></a></p>
<p><a href="https://i.stack.imgur.com/gCYkr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gCYkr.png" alt="0.075 mm layer height, 2walls, no infill" /></a></p>
<ul>
<li>These lines exist on all prints, PLA, ABS.</li>
<li>They're 0.8 mm apart [20T 2GT pulley, 1.8°/step motor = 1 line/4 full-steps]</li>
<li>Start to disappear above 75 mm/s but will still appear on slower axis when printing diagonal lines or curves</li>
<li>Custom built frame, cross bar (Ultimaker style) using linear rails</li>
<li>dual-motor (4 total on X-Y) + separate driver (1 motor/driver)</li>
<li>Running Smoothieware on Smoothieboard 5X [A5984 drivers, 32 microstep]</li>
</ul>
<p>Tried all these with no improvement:</p>
<p><strong>TL;DR problem is somewhere between drivers and motors</strong></p>
<ul>
<li>Switched to 6.625:1 geared extruder</li>
<li>Tried parallel, series, single coil on the 8 wires motor and 2 other different motors</li>
<li>Enable fast decay mode on A5984</li>
<li>Motor current from 0.5 A to 1.8 A</li>
<li>PLA temp from 170~200 °C</li>
<li>Acceleration as low as 100 mm/s2</li>
<li>**Changed 20T to 16T pulleys. The pattern scaled down proportional to the change in tooth count. Ruled out mechanical issues.</li>
</ul>
|
<p>The fact that these are all perfectly spaced, and don't mirror the edges of irregular prints, makes me think it's definitely not ghosting. That said, I can't see the Y direction on either print, just the X direction, so this all assumes it's only happening in one direction.
One thing to think about: Your motors have typically 2 opposing coils, and they get activated by taking 4 steps: (North, off, South):
N/o
o/N
S/o
o/S
If these are spaced out exactly 4 steps apart, that would imply that one of your coils is either underpowered or overpowered on the motor controlling that direction's movement. That would lead to your motor torque dipping and increasing, leading to slightly uneven print speed. This is 100% speculative and might be a goose chase since you've got 4 X/Y motors and it seems to happen in both the X and Y axis. The chances of having that many motors exhibit the same deficiency is astronomical.</p>
<p>That said, I've got little experience with multiple motors per axis. Another thing you might look into is whether the motors are fighting each other at all. If, for example, the motor-side pulley isn't aligned exactly the same way on both X motors, or the motors get out of sync with each other, because of the way the motor's holding torque falls as you get away from a full step position, you might find that one motor is holding the other back slightly, or pulling it forward towards the nearest full step. Again, this is all speculative, but it might be worth looking into. You can typically figure out the full step location by killing power to the machine and letting the motors settle into a full step on their own without the belts or other drive mechanisms attached. I'd unhook the belts, kill the power, get the motors settled (with a bit of a nudge if necessary), and then see if your belt perfectly settles into both pulleys in that location. You might find that the belt teeth don't quite line up on both pulleys, and the only way I can think of that would fix that specific problem is spinning the motor until it matches, or even physically relocating the motor closer or farther relative to the other on the same axis.</p>
<p>YMMV, best of luck.</p>
|
<p>This is a great blog post, <a href="https://www.evernote.com/shard/s211/client/snv?noteGuid=701c36c4-ddd5-4669-a482-953d8924c71d&noteKey=1ef992988295487c98c268dcdd2d687e&sn=https%3A%2F%2Fwww.evernote.com%2Fshard%2Fs211%2Fsh%2F701c36c4-ddd5-4669-a482-953d8924c71d%2F1ef992988295487c98c268dcdd2d687e&title=Taxonomy%2Bof%2BZ%2Baxis%2Bartifacts%2Bin%2Bextrusion-based%2B3d%2Bprinting" rel="nofollow noreferrer">Taxonomy of Z axis artifacts in extrusion-based 3d printing</a>, explaining what I think I am seeing, although I'm not entirely sure what I'm seeing in your photos.</p>
<p>The short version is if your z-rods are threaded in an imperial unit, inches/fractions of inches, instead of metric, you get a repeating decimal value (think about converting 1/3 to decimal), which can lead to a rounding error depending on the chosen layer height.</p>
<p>Without knowing how exactly you built your machine it's hard to say more but the post goes over a number of things I almost did wrong (like anti-wobble caps on top of the z rods for Prusa i3s...)</p>
| 1,189
|
<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>For a typical Web client -to- Servlet/WS -to- Business Tier (Spring or EJB) app, what are the trade-offs of approaches like remote RPC or messaging for Web (Servlet) tier to remote Business tier, aside from the basic sync/async aspects?</p>
|
<p>By web client do you mean web browser? If so looking at stuff like DWR or JAX-RS are my recommendations. RMI or JMS only really work when both sides are Java code.</p>
<p>With any remoting technology the biggest issue using them tends to be how intrusive the technology becomes on your business objects. e.g. using RMI interface/exceptions everywhere or using the JMS APIs inside your business code.</p>
<p>My recommendation is to use POJOs everywhere in Java then use a technology like <a href="http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html" rel="nofollow noreferrer">Spring Remoting</a> to layer on your middleware whether its RMI or JMS or whatever - but totally de-couple the middleware code from your business logic so you can switch between technologies at any time (and keep your business logic code simpler and focussed on your business problem).</p>
<p>For example see the <a href="http://activemq.apache.org/camel/spring-remoting.html" rel="nofollow noreferrer">Camel implementation of Spring Remoting</a> which then allows you to use <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">any of these transports and protocols</a> such as RMI, JMS or even plain HTTP, email, files or XMPP - then switch between them trivially using a simple URI string change.</p>
|
<p>SUN RMI broke for us. </p>
<p>The settings and garbage collection for a very long running application with continuous meassaging. We are patching to make it work continuously. JMS applications we run don't get the out of memory errors or gc problems that RMI does. Anything that needs to call System.gc() periodically and doesn't work with incremental collection to recover resources is coded wrong. </p>
<p>RMI reliability improves with the JDK 6 and the correct property settings, but JHC, it's a bodgey framework. RMI would be vastly improved by using channels in nio and fixing the sun nio uses of system.gc(). </p>
<p>The correct answer - seperate communication (mechanism) from the domain code. RPC is tightly coupled, and the protocol and application can interfere with each other. JMS seperates the protocol from the application, a much better paradigm. </p>
| 9,657
|
<p>How, if you have a database per client of a web application instead of one database used by all clients, do you go about providing updates and enhancements to all databases efficiently?</p>
<p>How do you roll out changes to schema and code in such a scenario?</p>
|
<p><a href="http://www.bittorrent.com/" rel="nofollow noreferrer">bittorrent</a>?</p>
<p>There have been a few web-based versions already (<a href="http://www.bitlet.org/" rel="nofollow noreferrer">bitlet</a>, <a href="http://torrentfreak.com/w3btorrent-a-bittorrent-client-for-your-web-server/" rel="nofollow noreferrer">w3btorrent</a>), and <a href="http://azureus.sourceforge.net/" rel="nofollow noreferrer">Azureus</a> was built using java, so it's definitely possible.</p>
<p>Edit: @TonyB is it limited to port 80?</p>
|
<p>@travis</p>
<p>Unfortunately It has to be over HTTP inside the users browser.
I'll update the question to be more clear about that.</p>
| 5,571
|
<p>I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.</p>
<p>My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read happen.</p>
<p>For example, think of a value = 0x0000FFFF that gets incremented value of 0x00010000.</p>
<p>Is there a time where the value looks like 0x0001FFFF that I should be worried about? Certainly the larger the type, the more possible something like this to happen.</p>
<p>I've always synchronized these types of accesses, but was curious what the community thinks.</p>
|
<p>At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a nice and cross-platform interface. For now if you are using a platform abstraction layer it may provide these functions. <a href="http://www.cse.wustl.edu/~schmidt/ACE.html" rel="noreferrer">ACE</a> does, see the class template <a href="http://www.dre.vanderbilt.edu/~schmidt/DOC_ROOT/ACE/ace/Atomic_Op.inl" rel="noreferrer">ACE_Atomic_Op</a>.</p>
|
<p>The only portable way is to use the sig_atomic_t type defined in signal.h header for your compiler. In most C and C++ implementations, that is an int. Then declare your variable as "volatile sig_atomic_t."</p>
| 7,779
|
<p>What is the best way to layout a large django project? The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely dependent on the project) and how/where general templates should be kept.</p>
<p>Does anyone have examples, suggestions, and <em>explanations</em> as to why a certain project layout is better than another? I am particularly interested in the incorporation of large numbers of unit tests (2-5x the size of the actual code base) and string externalization / templates.</p>
|
<p>The major guidelines are similar to any other large code project. Apps should address a single, clearly-defined responsibility. The name "application" is a misnomer; Django apps should be thought of more as reusable components which can be plugged together to create a real application. Tests for each app should be contained within that app. Apps should be decoupled from each other as much as possible, but clearly there will be dependencies, so the goal should be to keep the dependency graph as simple and sane as possible.</p>
<p>I prefer to keep all the templates for a project under a single project-wide templates directory, with a subdirectory for each app (using a template subdirectory for each app is a very strong convention in Django, as it avoids template name collisions between apps). The reason for a single project-wide templates directory is that templates, template inheritance trees, and block names can be quite project-specific, so it's hard to provide "default" app templates that can plug in to any project. There have been some attempts to settle on standard naming conventions for base site-wide templates and the blocks they define, but I haven't seen a standard emerge yet (the way they do things over at <a href="http://pinaxproject.com" rel="noreferrer">Pinax</a> is probably the closest we have to a standard).</p>
<p>Re "string externalization", if you mean i18n and l10n, Django has strong support for that and standard places where it puts the .po files - check the <a href="http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n" rel="noreferrer">docs</a>.</p>
|
<p>My current layout stems from me wanting to have a test-version of my sites. This means having two projects for every site, since they need different configurations, and forces me to move all the applications out of the projects.</p>
<p>I've created two folders: $APP_ROOT/devel and $APP_ROOT/prod. These contain all the apps. Using source control (in my case git) I have the apps in devel at the HEAD revision, while the apps in prod are locked to the PROD tag. The templates also have their own folder with the same layout as the apps.</p>
<p>Now I'm able to do all my development in the devel-apps folder and the matching template-folder. When I have something I'm happy with, I tag that revision and update prod.</p>
| 6,580
|
<p>After reading a bit more about how Gnutella and other P2P networks function, I wanted to start my own peer-to-peer system. I went in thinking that I would find plenty of tutorials and language-agnostic guidelines which could be applied, however I was met with a vague simplistic overview.</p>
<p>I could only find very small, precise P2P code which didn't do much more than use client/server architecture on all users, which wasn't really what I was looking for. I wanted something like Gnutella, but there doesn't seem to be any articles out in the open for joining the network.</p>
|
<p>I had to write a basic Gnutella client in C# using Web Services and I think the class notes on the P2P stuff are still available <a href="http://www.cs.virginia.edu/~humphrey/cs451/ClassNotes/CS451_DisSys_0327.pdf" rel="nofollow noreferrer">here</a> and <a href="http://www.cs.virginia.edu/~humphrey/cs451/ClassNotes/CS451_DisSys_0329.pdf" rel="nofollow noreferrer">here</a>.</p>
|
<p>You might have better success researching Bittorrent, I believe that the creator has written some papers, and it seems others are as well.</p>
<p><a href="http://bittyrant.cs.washington.edu/#papers" rel="nofollow noreferrer">BitTyrant</a>
<a href="http://bittorrent.org/" rel="nofollow noreferrer">Bittorent.org, see the developers section</a></p>
| 4,360
|
<p>So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this</p>
<pre><code>if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
</code></pre>
<p>I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.</p>
|
<p>Specifically, like this in C#:</p>
<pre><code>#if (DEBUG)
Debug Stuff
#endif
</code></pre>
<p>C# has the following preprocessor directives:</p>
<pre><code>#if
#else
#elif // Else If
#endif
#define
#undef // Undefine
#warning // Causes the preprocessor to fire warning
#error // Causes the preprocessor to fire a fatal error
#line // Lets the preprocessor know where this source line came from
#region // Codefolding
#endregion
</code></pre>
|
<p>Compiler constants. I don't remember the C# syntax, but this is how I do it in VB:</p>
<pre><code>#If CONFIG = "Debug" Then
'do somtehing
#Else
'do something else
#EndIf
</code></pre>
| 7,372
|
<p>Of course I'm referring to side by side and not stacking or overlapping. 200 x 200 mm PEI and Kapton sheets are more readily available than 400 x 400 sheets. I'm wondering if anyone has tried this and if the edges of the sheets cause a problem.</p>
|
<p>Aligning build surfaces isn't the main issue with 1 mm thick surfaces when aligning four 200 x 200 mm surfaces to make one 400 x 400 surface. The main issue is slight bucking at the seams from thermal mismatch. Using this with PETG tends to tear up the build surface at the seams. The image shows aligned surfaces.</p>
<p><a href="https://i.stack.imgur.com/14q3L.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/14q3L.jpg" alt="enter image description here" /></a></p>
<p>The above was a poor design because prints tended to always print on the seams, which are more susceptible to damage when removing the print.</p>
<p>More reliable was to put one 200 x 200 mm surface in the center of the bed, cut the other three in half, and tile them along the sides. Glue stice helps fill the seams.</p>
<p><a href="https://i.stack.imgur.com/mC4ea.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mC4ea.jpg" alt="enter image description here" /></a></p>
<p>The center of the surface tends to wear out first. In that case only the center surface would need changing.</p>
|
<p>I haven't tried such a thing, but a speculative answer covering the constraints and expected failure modes may suffice here.</p>
<p>Unless the sheets have squared (rather than rounded) corners, the corners will almost certainly be a problem. In particular you'd end up with a hole right at the middle of the bed.</p>
<p>If the sides aren't entirely square (perpendicular) with each other then you'll have large gaps at one end or another.</p>
<p>As Trish noted in a comment, it's also possible that you may hit problems due to mismatch in thickness between the different sheets, although I'd expect these are fairly well-controlled in the manufacturing process; otherwise I'd expect bed leveling issues even with just a single sheet. If you do hit this kind of issue, it may be possible to avoid it with shimming of some sort.</p>
<p>Assuming you can avoid all of the above potential problems, I would expect what you've proposed to work reasonably well, especially if you're ok with very minor surface defects at the seams.</p>
| 1,755
|
<p>I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?</p>
|
<p>I suggest jquery tree view plugins for making it function like a tree, but as for render, just put it in a recursive lambda helper to do the nesting.</p>
|
<p>For that (rendering hierarchical menu, treeview, etc) i use recursive calls of custom component (ascx, or aspx in new preview5).<br>
I give component first level of items (List of items), and component then check for each item in list if there's any child items and call itself with list of that child items.<br>
You can build hierarchical graph of objects in controller, or just 1 dimensional list with ParentID property.</p>
| 8,256
|
<p>Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.</p>
<p>What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?</p>
<p>Does LINQ simplify the solution?</p>
|
<p>On MS SQL Server 2005 and above, <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="noreferrer">ROW_NUMBER()</a> seems to work:</p>
<p><a href="http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx" rel="noreferrer">T-SQL: Paging with ROW_NUMBER()</a></p>
<pre><code>DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;
WITH OrdersRN AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum
,OrderID
,OrderDate
,CustomerID
,EmployeeID
FROM dbo.Orders
)
SELECT *
FROM OrdersRN
WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
AND @PageNum * @PageSize
ORDER BY OrderDate
,OrderID;
</code></pre>
|
<p>There is a discussion about this <a href="https://web.archive.org/web/20211020131201/https://www.4guysfromrolla.com/webtech/042606-1.shtml" rel="nofollow noreferrer">Here</a></p>
<p>The technique gets page number 100,000 from a 150,000 line database in 78ms</p>
<blockquote>
<p>Using optimizer knowledge and SET ROWCOUNT, the first EmployeeID in the page that is requested is stored in a local variable for a starting point. Next, SET ROWCOUNT to the maximum number of records that is requested in @maximumRows. This allows paging the result set in a much more efficient manner. Using this method also takes advantage of pre-existing indexes on the table as it goes directly to the base table and not to a locally created table. </p>
</blockquote>
<p>I am afraid I am not able to judge if it is better than the current accepted answer.</p>
| 3,141
|
<p>Anti aliasing <a href="http://forums.msdn.microsoft.com/en-US/wpf/thread/1ad9a62a-d1a4-4ca2-a950-3b7bf5240de5" rel="noreferrer">cannot be turned off</a> in WPF. But I want to remove the blurred look of WPF fonts when they are small. </p>
<p>One possibility would be to use a .net 2.0 component. This looks like it would lose the transparency capability and Blend support. Never tried it though.</p>
<p>Anyone has a solution for this? Any drawbacks from it?</p>
<p>Thank you</p>
|
<p>Have you tried putting a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.integration.windowsformshost?redirectedfrom=MSDN&view=net-5.0" rel="nofollow noreferrer">WindowsFormsHost</a> control on a WPF window/control? That will allow WPF to render a WinForms control.</p>
<p><strong>UPDATE November 2012</strong>: This question and answer is 4 years old. <a href="https://web.archive.org/web/20160122031626/http://blogs.msdn.com/b/text/archive/2009/08/24/wpf-4-0-text-stack-improvements.aspx" rel="nofollow noreferrer">Text rendering has since improved in WPF</a>. Please don't put WinForms controls in WPF apps; that was a hackish way to fix font rendering. It's no longer needed.</p>
|
<p>Try using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.snapstodevicepixels.aspx" rel="nofollow noreferrer">UIElement.SnapsToDevicePixels</a> property on the UI elements of your window. People tend to report it works best for <a href="http://blogs.msdn.com/seema/archive/2006/10/31/on-some-monitors-it-seems-that-thin-wpf-lines-are-blurred-across-two-pixels-instead-of-one-ick-how-do-i-get-sharply-rendered-lines.aspx" rel="nofollow noreferrer">graphics and lines</a>, but I've noticed improvment in text rendering with it as well.</p>
| 4,201
|
<p>Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.</p>
<pre><code>if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
</code></pre>
|
<p>As far as I know, there's no method to do what you want; at least not directly. I'd store the <code>photosLocation</code> as a path relative to the application; for example: <code>"~/Images/"</code>. This way, you could use MapPath to get the physical location, and <code>ResolveUrl</code> to get the URL (with a bit of help from <code>System.IO.Path</code>):</p>
<pre><code>string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
if (files.Length > 0)
{
string filenameRelative = photosLocation + Path.GetFilename(files[0])
return Page.ResolveUrl(filenameRelative);
}
}
</code></pre>
|
<p>I think this should work. It might be off on the slashes. Not sure if they are needed or not.</p>
<pre><code>string url = Request.ApplicationPath + "/" + photosLocation + "/" + files[0];
</code></pre>
| 3,676
|
<p>I have a personal pet project I'd like to start on, targeted at windows mobile 6. I've never done win mobile dev and would like to know what resources are out there, good tools to use, perhaps a jump start tutorial, as well as any gotchas I might want to keep in mind when developing for the platform?</p>
|
<p>Windows Mobile 6 devices come with .NET Compact Framework 2.0 in ROM and also expose .NET APIs for a lot of things (camera, system notifications, email, contacts, ...).</p>
<p>I'd recommend using Visual Studio 2008 and the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=06111A3A-A651-4745-88EF-3D48091A390B&displaylang=en" rel="nofollow noreferrer">refresh version of the Windows Mobile 6 SDK</a>, which includes emulators, documentation, tools and samples.</p>
<p>Besides MSDN, a good resource for Windows Mobile samples is Chris Craft's Blog, <a href="http://www.cjcraft.com/blog/CategoryView,category,30%2BDay%2Bof%2B.NET.aspx" rel="nofollow noreferrer">who recently built 30 mobile applications in 30 days</a>. There are samples for a lot of different techniques which you can use for a jumpstart.</p>
|
<p>A good reference book to check out is "Microsoft Mobile Development Handbook" by Wigley, Moth, and Foot. It covers a lot of topics in mobile development with the .NET compact framework, and also the Windows Mobile platform. </p>
<p>You also might want to learn about Windows CE, which Windows Mobile is a flavor of. A good place to start learning about Windows CE is windowsembedded.com. From there you can download an evaluation version of "Platform Builder" which is the tool to create a Windows CE image to test with.</p>
| 9,442
|
<p>If not, what are the significant differences?</p>
<hr>
<p><strong>Edit:</strong> Daren Thomas asks:</p>
<blockquote>
<p>which ones?</p>
<p>I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...</p>
</blockquote>
<p>By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.</p>
|
<p>I use <a href="http://ftp.gnu.org/pub/gnu/emacs/windows/" rel="nofollow noreferrer">GNU emacs built for Windows</a>, and have found very few, if any, differences. There's the option to load your .emacs file from _emacs or .emacs (although .emacs works fine on XP and above). You can configure it to use Windows-style or Unix-style line endings by default (which I suppose you could do on a Unix system too...).</p>
<p>You may want to tweak such settings as Emacs's startup directory and home directory. To do the former, modify the shortcut that starts emacs. To do the latter, add a HOME environment variable - this will control where your .emacs is loaded from. For more information, check the always-excellent EmacsWiki's <a href="http://www.emacswiki.org/cgi-bin/wiki/MsWindowsInstallation" rel="nofollow noreferrer">MsWindowsInstallation</a> page.</p>
|
<p>which ones?</p>
<p>I use <code>gvim</code> on Windows and <code>MacVim</code> on the mac. Seem similar enough to be the same to me...</p>
| 6,285
|
<p>I've seen this done in Borland's <a href="https://en.wikipedia.org/wiki/Turbo_C++" rel="noreferrer">Turbo C++</a> environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?</p>
|
<p>Some sample code:</p>
<pre><code> public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e) {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) Console.WriteLine(file);
}
}
</code></pre>
|
<p>You can implement Drag&Drop in WinForms and WPF. </p>
<ul>
<li>WinForm (Drag from app window)</li>
</ul>
<p>You should add mousemove event:</p>
<pre><code>private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
{
...
if (e.Button == MouseButtons.Left)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
}
...
}
</code></pre>
<ul>
<li>WinForm (Drag to app window)</li>
</ul>
<p>You should add DragDrop event:</p>
<p>private void YourElementControl_DragDrop(object sender, DragEventArgs e)</p>
<pre><code> {
...
foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
{
File.Copy(path, DirPath + Path.GetFileName(path));
}
...
}
</code></pre>
<p><a href="https://www.brainbeast.best/drag-and-drop-on-c-sharp-in-wpf-dot-net/" rel="nofollow noreferrer">Source with full code</a>.</p>
| 9,412
|
<p>My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists!</p>
<p>so far, <a href="http://www.zend.com/en/products/studio/features" rel="noreferrer">Zend studio 6</a>, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this?</p>
<p>edit: a bit more information: right now, using zend-6 under eclipse, i type in</p>
<pre><code><?php
p //(a single letter "p")
</code></pre>
<p>and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however).</p>
<p>However, I get nothing when I do:</p>
<pre><code><style>
b /* (a single letter "b") */
</code></pre>
<p>I'd love it if I could get, from that "b" suggestions for "border", "bottom", etc. The same applies for Javascript.</p>
<p>Any ideas?</p>
|
<p>I think the JavaScript and CSS need to be in separate files for this to work.</p>
<p>Example of CSS autocomplete in Eclipse:</p>
<p>Starting to type <code>border</code></p>
<blockquote>
<p><img src="https://i.stack.imgur.com/h4Sj9.png" alt="css example in eclipse"></p>
</blockquote>
<p>Then setting thickness</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/mmaEe.png" alt="autocompleting border thickness"></p>
</blockquote>
<p>Then choosing the color</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/Up41q.png" alt="autocompleting border color"></p>
</blockquote>
<p>Chose red, and it added the ; for me</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/Up41q.png" alt="alt text"></p>
</blockquote>
<p>Works pretty good IMHO.</p>
|
<p>The default CSS and HTML editors for Eclipse are really good. The default javascript editor does an OK job, but it needs a little work.</p>
<p>I just tested this in Eclipse 3.3.2</p>
<pre><code>function test(){
}
te<CTRL+SPACE>
</code></pre>
<p>and it completed the method for me as did this:</p>
<pre><code>var test = function(){
};
te<CTRL+SPACE>
</code></pre>
<p>Can you expand on what more you wanted it to do?</p>
| 2,681
|
<p>Large pages are available in <code>Windows Server 2003</code> and <code>Windows Vista</code>. </p>
<p>But how do I enable large pages for my application? </p>
|
<p>Martin's answer is correct on Windows Server 2003:</p>
<blockquote>
<p>You will have to assign the "Lock pages in memory" privilege to any user that runs your > application. This includes administrators</p>
<ol>
<li>Select Control Panel -> Administrative Tools -> Local Security Policy</li>
<li>Select Local Policies -> User Rights Assignment</li>
<li>Double click "Lock pages in memory", add users and/or groups</li>
<li>Reboot the machine</li>
</ol>
</blockquote>
<p>On Windows Vista you need also make sure that the application is run as Administrator (by right-clicking on the application or the shell and choosing "Run as adminstrator".</p>
<p>In addition, it helps to have a freshly booted machine since the large pages can "run out" due to fragmentation of the heap.</p>
|
<p>You will have to assign the <code>Lock pages in memory</code> privilege to any user that runs your application. This includes administrators.</p>
<ol>
<li>Select Control <strong>Panel -> Administrative Tools -> Local Security</strong> Policy </li>
<li>Select Local <strong>Policies -> User Rights Assignment</strong></li>
<li>Double click "Lock pages in memory", add users and/or groups </li>
<li>Reboot the machine </li>
</ol>
| 6,007
|
<p>I equipped my Makerbot Replicator 2x with <a href="https://www.aliexpress.com/item/Makerbot-Replicator-2-3D-Printer-Part-Makerbot-TMC2100-V1-0-Stepper-Motor-Driver-Module-With-Heatsink/32870918354.html" rel="nofollow noreferrer">silent stepper drivers TMC2100</a>. According to the product page I reduced V<sub>ref</sub> from 127 (factory default) to 25 in the printer settings as well as in my start G-code.</p>
<p>With this I get horrible layer shifting (a few millimeters!), even if I reduce print- and travel-acceleration to 300. The layer shifting is mostly happening on the Y-axis, but also on X-axis. Not only layer shifting was happening, also the extruder-motors lost many steps.</p>
<p>To fight this problem I increased the V<sub>ref</sub> little by little. At around 70 for X and Y axis (and 50 for extruders) all layer shift- and extrusion problems were gone. Also I had to install a dedicated fan for the stepper drivers, because they got very hot. </p>
<p>I was happy with this solution for about 10 minutes, then I noticed that the stepper motors are getting so hot I burned my fingertips by touching them. My guess for the motor temperature would be 80~90 °C.</p>
<p>So my question is: Are those TMC2100 stepper driver unsuitable for my usecase somehow or am I missing something? Is there a way to get the 3D printer silent while not overheating?</p>
<hr>
<p>On behalf of advice in the comments, I mounted some <a href="https://www.amazon.de/Schwarz-Aluminium-K%C3%BChlk%C3%B6rper-Heizk%C3%B6rper-Heatsink/dp/B07C7SJHTH" rel="nofollow noreferrer">heat sinks</a> and measured the temperature via an <a href="https://www.amazon.de/Thermometer-ber%C3%BChrungslos-Temperaturmessger%C3%A4t-Temperaturmesser-Beleuchtung/dp/B01I4TB2IM/" rel="nofollow noreferrer">IR-thermometer</a>. With the old original stepper drivers I get 60 °C for the Y-axis and 66 °C for the X-axis. With TMC2100 it is 86 °C for both. (Each temperature measured at the heatsink)</p>
|
<p>Most Stepper drivers will have lots of energy passing through them so it is crucial to having a moderately sized heatsink to cool them off otherwise they will get too hot. Most stepper drivers found online come with heatsinks but you could search online for mini heatsinks.</p>
|
<p>What constitutes too hot? A Hybrid stepper motor operating at 80 degrees is normal. They dissipate heat via their mounting plate (which should not be plastic), otherwise you may need to use active cooling. Now if the motors are dying from the heat then you have a problem.</p>
| 1,255
|
<p>I have the original Prusa i3m3 printer. Prusa recommends cleaning the bed before each print with isopropanol (isopropyl alcohol), with only occasional cleaning with acetone. The textured bed prohibits using acetone.</p>
<p>Given the SARS-COV-2 situation and COVID-19, isopropanol is impossible to find, and will not be in stock on shelves in the US for months.</p>
<p>What would you suggest as an alternative that might still be found on store shelves?</p>
|
<p><strong>Ethanol</strong> (Ethyl Alcohol) should work just fine as long as it's around 80% or more. It's very similar to isopropanol as a cleaning solvent. What you're basically doing is removing any stray grease from the bed with a solvent that evaporates quickly. </p>
<p><strong>Methanol</strong> would also probably work. It's very poisonous though, and shouldn't come into contact with your skin, so it requires a bit more careful handling. Methanol also has the benefit that it can't be used for hand sanitizer (since it's absorbed through the skin), so supplies shouldn't run out. </p>
<p>Look for alternative sources, for example, methanol is often sold as de-icing agent for pneumatic brakes on trucks. Just make sure it's pure alcohol without anything funky added. </p>
|
<p>Dish soap will remove grease very well. Once you rinse it with a moist sponge and dry with a clean cloth most residues will be gone.</p>
| 1,618
|
<p>I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? </p>
<p>Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? </p>
<p>I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. </p>
<p>Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. </p>
<p>Do you have good WCF learning references besides just continuing to Google the bejebus out of things?</p>
|
<p>Okay, here we go. First, Michele Leroux Bustamante's book has been updated for VS2008. The website for the book is not gone. It's up right now, and it has tons of great WCF info. On that website she provides updated code compatible with VS2008 for all the examples in her book. If you order from Amazon, you will get the reprint which is updated.</p>
<p>WCF is not <em>only</em> a replacement for ASMX. Sure it can (and does quite well) replace ASMX, but the real benefit is that it allows your services to be self-hosted. Most of the functionality from WSE has been baked in from the start. The framework is <em>highly</em> configurable, and the ability to serve multiple endpoints over multiple protocols is amazing, IMO.</p>
<p>While you can still generate proxy classes from the "Add Service Reference" option, it's not necessary. All you really have to do is copy your ServiceContract interface and tell your code where to find the endpoint for the service, and that's it. You can call methods from the service with very little code. Using this method, you have complete control over the implementation. Regardless of the method you choose to generate a proxy class, Michele shows both and uses both in her <strong>excellent</strong> series of webcasts on the subject.</p>
<p>Michele has tons of great material out there, and I recommend you check out her website(s). Here's some links that were incredibly helpful for me as I was learning WCF. I hope that you'll come to realize how strong WCF really is, and how easy it is to implement. The learning curve is a little bit steep, but the rewards for your time investment are well worth it:</p>
<ul>
<li>Michele's webcasts: <a href="http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx" rel="noreferrer">http://www.dasblonde.net/2007/06/24/WCFWebcastSeries.aspx</a></li>
<li>Michele's book website (alive and updated for VS2008): <a href="http://www.thatindigogirl.com/" rel="noreferrer">http://www.thatindigogirl.com/</a></li>
</ul>
<p>I recommend you watch at least 1 of Michele's webcasts. She is a very effective presenter, and she's obviously incredibly knowledgeable when it comes to WCF. She does a great job of demystifying the inner workings of WCF from the ground up.</p>
|
<p>MSDN? I usually do pretty well with the Library reference itself, and I usually expect to find valuable articles there.</p>
| 7,275
|
<p>Although the general case is undecidable, many people still do solve problems that are equivilent well enough for day to day use.</p>
<p>In cohen's phd thesis on computer viruses, he showed how virus scanning is equivilent to the halting problem, yet we have an entire industry based around this challenge.</p>
<p>I also have seen microsoft's terminator project - <a href="http://research.microsoft.com/Terminator/" rel="noreferrer">http://research.microsoft.com/Terminator/</a> </p>
<p>Which leads me to ask - is the halting problem overrated - do we need to worry about the general case?</p>
<p>Will types become turing complete over time - dependant types do seem like a good development?</p>
<p>Or, to look the other way, will we begin to use non turing complete languages to gain the benefits of static analysis ?</p>
|
<blockquote>
<p>Is solving the halting problem easier than people think?</p>
</blockquote>
<p>I think it is exactly as difficult as people think.</p>
<blockquote>
<p>Will types become turing complete over time?</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/C%2B%2B#Templates" rel="noreferrer">My dear, they already are!</a></p>
<blockquote>
<p>dependant types do seem like a good development?</p>
</blockquote>
<p>Very much so.</p>
<p>I think there could be a growth in non-Turing complete-but-provable languages. For quite some time, SQL was in this category (it isn't any more), but this didn't really diminish its utility. There is certainly a place for such systems, I think.</p>
|
<p>The Halting Problem is really only interesting if you look at it in the general case, since if the Halting problem were decidable, all other undecidable problems would also be decidable via reduction.</p>
<p>So, my opinion on this question is, no, it is not easy in the cases that matter. That said, in the real world, it may not be such a big deal.</p>
<p>See also: <a href="http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences</a></p>
| 6,196
|
<pre><code>public static IList<T> LoadObjectListAll<T>()
{
ISession session = CheckForExistingSession();
var cfg = new NHibernate.Cfg.Configuration().Configure();
var returnList = session.CreateCriteria(typeof(T));
var list = returnList.List();
var castList = list.Cast<typeof(T)>();
return castList;
}
</code></pre>
<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>
|
<p><code>T</code> is not a type nor a <code>System.Type</code>. <code>T</code> is a type parameter. <code>typeof(T)</code> returns the type of <code>T</code>. The <code>typeof</code> operator does not act on an object, it returns the <code>Type</code> object of a type. <a href="http://msdn.microsoft.com/en-us/library/58918ffs.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/58918ffs.aspx</a></p>
<p>@John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the <code>ISessionFactory</code> <em>after</em> getting the <code>ISession</code>, for example.</p>
<pre><code>public static T[] LoadObjectListAll()
{
var session = GetNewSession();
var criteria = session.CreateCriteria(typeof(T));
var results = criteria.List<T>();
return results.ToArray();
}
</code></pre>
|
<p>The most glaring error I can see is that an <code>IList</code> is definitely different from an <code>IList<T></code>. An <code>IList</code> is non-generic (e.g., <code>ArrayList</code>).</p>
<p>So your method signature should be:</p>
<pre><code>public static IList<T> LoadObjectListAll()
</code></pre>
| 6,472
|
<p>If you had a differential of either venturing into Delphi land or Qt land which would you choose? I know they are not totally comparable. I for one have Windows development experience with Builder C++ (almost Delphi) and MFC (almost Qt), with a bit more time working with Builder C++. Please take out the cross platform ability of Qt in your analysis.</p>
<p>I'm hoping for replies of people who have worked with both and how he or she would compare the framework, environment, etc.?</p>
<p>Thank you in advance for your replies.</p>
|
<p>If you are talking UI frameworks, then you should be comparing Qt with the VCL, not the IDE (Delphi in this case). I know I'm being a stickler, but Delphi is the IDE, Object-Pascal is the language, and VCL is the graphical framework.</p>
<p>That being said, I don't think there is anything that even comes close to matching the power and simplicity of the VCL. Qt is great, but it is no VCL.</p>
|
<p>I'd choose delphi. Only because I have more experience with it. I don't think that there is other reasonabl criterias. </p>
| 9,841
|
<p>I've got a menu that contains, among other things, some most-recently-used file paths. The paths to these files can be long, so the text sometimes gets clipped like "C:\Progra...\foo.txt"</p>
<p>I'd like to pop a tooltip with the full path when the user hovers over the item, but this doesn't seem possible with the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx" rel="noreferrer">Tooltip</a> class in .NET 2.0.</p>
<p>Am I missing something obvious?</p>
|
<p>If you are creating your menu items using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.menuitem.aspx" rel="noreferrer" title="MenuItem Members">System.Windows.Forms.MenuItem</a> class you won't have a "ToolTipText" property.</p>
<p>You should use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripmenuitem.aspx" rel="noreferrer" title="ToolStripMenuItem class">System.Windows.Forms.ToolStripMenuItem</a> class which is new as of .Net Framework 2.0 and DOES include the "ToolTipText" property.</p>
<p>You also have to remember to specify ShowItemToolTips = True on the MenuStrip control</p>
|
<p>Maybe you forgot to associate the tooltip with the control using <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.settooltip.aspx" rel="nofollow noreferrer">SetToolTip</a>.</p>
| 8,262
|
<p>I have to develop an application which parses a log file and sends specific data to a server. It has to run on both Linux and Windows. </p>
<p>The problem appears when I want to test the log rolling system (which appends .1 to the name of the creates a new one with the same name). On Windows (haven't tested yet on Linux) I can't rename a file that I have opened with std::ifstream() (exclusive access?) even if I open it in "input mode" (ios::in).</p>
<p>Is there a cross-platform way to open file in a non-exclusive way?</p>
|
<blockquote>
<p>Is there a way to open file in a non-exclusive way,</p>
</blockquote>
<p>Yes, using Win32, passing the various FILE_SHARE_Xxxx flags to CreateFile.</p>
<blockquote>
<p>is it cross platform?</p>
</blockquote>
<p>No, it requires platform-specific code.</p>
<p>Due to annoying backwards compatibility concerns (DOS applications, being single-tasking, assume that nothing can delete a file out from under them, i.e. that they can fclose() and then fopen() without anything going amiss; Win16 preserved this assumption to make porting DOS applications easier, Win32 preserved this assumption to make porting Win16 applications easier, and it's awful), Windows defaults to opening files exclusively.</p>
<p>The underlying OS infrastructure supports deleting/renaming open files (although I believe it does have the restriction that memory-mapped files cannot be deleted, which I think isn't a restriction found on *nix), but the default opening semantics do not.</p>
<p>C++ has no notion of any of this; the C++ operating environment is much the same as the DOS operating environment--no other applications running concurrently, so no need to control file sharing.</p>
|
<p>I'd make sure you don't keep files open. This leads to weird stuff if your app crashes for example.
What I'd do:</p>
<ol>
<li>Abstract (reading / writing / rolling over to a new file) into one class, and arrange closing of the file when you want to roll over to a new one in that class. (this is the neatest way, and since you already have the roll-over code you're already halfway there.)</li>
<li>If you must have multiple read/write access points, need all features of fstreams and don't want to write that complete a wrapper then the only cross platform solution I can think of is to always close the file when you don't need it, and have the roll-over code try to acquire exclusive access to the file a few times when it needs to roll-over before giving up.</li>
</ol>
| 4,734
|
<p>I want to print a flowerpots, for advanced watering system.</p>
<p>Plants are going to be eaten.</p>
<p>What is the most suitable material, when we consider the fact, that we do not want to just make forms and do clay flowerpots(which may seem most healthier), but having them directly printed.</p>
<p>What are the temperatures that makes plastics emit dangerous components in surrounding water, and what are those components?</p>
<p>Is there some "totally safe" material out there? I was thinking of PLA or PETG, because I've already heard that ABS is not safe for edibles.</p>
|
<p>If you break up a large piece into multiple smaller pieces and properly glue them together, you basically add stiffeners (as a result of printing walls). This could lead to a more stiff model; this might have been confused by calling large prints more brittle opposed to constructed models.</p>
<p>If printing is conducted at similar conditions on large printers, there shouldn't be a reason why the model becomes more brittle unless the conditions aren't the same. But that would be true for printing at small printers too, e.g. if one print was printed in a draft.</p>
|
<p>I'd recommend getting the object to fit together by design, rather than glue - though I tend (if the item is never to be disassembled) use Zap-a-gap - that stuff sticks like crazy though you must not squeeze the parts together but let it naturally sit.</p>
| 1,353
|
<p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
|
<p>Opening sockets in python is pretty simple. You really just need something like this:</p>
<pre><code>import socket
sock = socket.socket()
sock.connect((address, port))
</code></pre>
<p>and then you can <code>send()</code> and <code>recv()</code> like any other socket</p>
|
<p>For developing portable network programs of any sort in Python, <a href="http://twistedmatrix.com" rel="noreferrer">Twisted</a> is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs.</p>
| 9,432
|
<p>I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?</p>
|
<pre><code>ls -atrd */ | head --lines=-4 | xargs rm -rf
</code></pre>
<p><strong>Edit:</strong> added 'a' argument to ls</p>
|
<p>Another, BSD-safe, way to do it, with arrays (why not?)</p>
<pre><code>#!/bin/bash
ARRAY=( `ls -td */` )
ELEMENTS=${#ARRAY[@]}
COUNTER=4
while [ $COUNTER -lt $ELEMENTS ]; do
echo ${ARRAY[${COUNTER}]}
let COUNTER=COUNTER+1
done
</code></pre>
| 9,743
|
<p>I'm trying to write a blog post which includes a code segment inside a <code><pre></code> tag. The code segment includes a generic type and uses <code><></code> to define that type. This is what the segment looks like:</p>
<pre><code><pre>
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
</pre>
</code></pre>
<p>The resulting HTML removes the <code><></code> and ends up like this:</p>
<pre><code>PrimeCalc calc = new PrimeCalc();
Func del = calc.GetNextPrime;
</code></pre>
<p>How do I escape the <code><></code> so they show up in the HTML?</p>
|
<pre><code><pre>
PrimeCalc calc = new PrimeCalc();
Func&lt;int, int&gt; del = calc.GetNextPrime;
</pre>
</code></pre>
|
<p>It's probably something specific to your blog software, but you might want to give the following strings a try (remove the underscore character):
&_lt; &_gt;</p>
| 6,359
|
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p>
<p>I found <a href="http://barryp.org/software/bpgsql/" rel="noreferrer">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
|
<p>MySQLdb is what I have used before.</p>
<p>If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it.</p>
<p>Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.</p>
|
<p>Take a pick at</p>
<p><a href="https://docs.djangoproject.com/en/1.8/ref/databases/" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/databases/</a></p>
<p>MySQLdb is mostly used driver, but if you are using python3 and django 1.8.x that will not work, then you should use mysqlclient that is a folk of MySQLdb on the following link</p>
<p><a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">https://pypi.python.org/pypi/mysqlclient</a></p>
| 2,319
|
<p>I feel like questions along the lines of, "my printer is crashing for no obvious reason, what should I do?" may be too broad and open-ended for this format. It's better handled by a forum where people can have running discussions to rule out a series of tests. What do you guys think?</p>
|
<p>For common problems that get asked a lot, I wouldn't just close these as <em>too broad.</em> A better solution is to create a <strong>canonical post</strong> like this:</p>
<p><a href="https://superuser.com/a/260078/697"><strong>How do I troubleshoot when I have no clue where to start?</strong></a></p>
<p>These attract a <em>lot</em> of users. </p>
<p>The goal is to create a step-by-step trouble-shooting guide to explain what lights, nozzles, and sneedles to look when you're kwigger isn't going <em>zong.</em></p>
<p>And don't just answer with a hyperlink to some other discussion group somewhere. Do everything you can to really overkill it. Write a detailed, step-by-step, ultra-clear guide, so when zillions of people with this problem go searching, you stand a good chance of the best possible answer on the web. </p>
<p>This is one of those opportunities to attract some great new users who will add value for years to come.</p>
|
<p>In addition to <a href="https://3dprinting.meta.stackexchange.com/a/84/63">Robert Cartaino♦</a>'s suggestion, I think that there is value in this class of question.</p>
<p>Over on <em>Robotics</em> we find that troubleshooting questions can often lead to interesting and often more generalised answers, and can lead to further, more specific questions. These types of questions also tend to be the kind which are difficult to answer through a google search, as not knowing what to search for is a big part of the problem.</p>
<p>Sadly this kind of question is often a new users first question, poorly written and difficult to answer in it's original form, so we tend to close these as <em>Unclear what you are asking</em> and clarify that with the <a href="https://robotics.meta.stackexchange.com/a/177/37">following comment</a>:</p>
<p><code>Welcome to *robotics* XXX, but I'm afraid that it is not clear what you are asking. We prefer *[practical, answerable questions based on actual problems that you face](http://robotics.stackexchange.com/help/dont-ask)*, so it is a good idea to include details of what what you would like to achieve, what you have tried, what you expected to see and what you actually saw. Take a look at [ask] and [about] for more information on how stack exchange works. If you edit your question to make it more clear, flag it for moderator attention and we can reopen it for you.</code></p>
<p><sup>The point of leaving this unrendered is so that you can easily copy the raw text to paste into a comment.</sup></p>
<p>Note that Comments render slightly differently to answers, for instance <code>[chat]</code> renders as <a href="http://chat.stackexchange.com/">3D Printing Chat</a> in a comment but as [chat] in a question or answer.</p>
| 19
|
<p>In one of the answers to <a href="https://stackoverflow.com/questions/31572/broadcast-like-udp-with-the-reliability-of-tcp#31629">Broadcast like UDP with the Reliability of TCP</a>, a user mentions the <a href="http://spread.org" rel="noreferrer">Spread</a> messaging API. I've also run across one called <a href="http://zeromq.org" rel="noreferrer">ØMQ</a>. I also have some familiarity with <a href="http://www-unix.mcs.anl.gov/mpi/" rel="noreferrer">MPI</a>. </p>
<p>So, my main question is: why would I choose one over the other? More specifically, why would I choose to use Spread or ØMQ when there are mature implementations of MPI to be had?</p>
|
<p>MPI was deisgned tightly-coupled compute clusters with fast, reliable networks. Spread and ØMQ are designed for large distributed systems. If you're designing a parallel scientific application, go with MPI, but if you are designing a persistent distributed system that needs to be resilient to faults and network instability, use one of the others.</p>
<p>MPI has very limited facilities for fault tolerance; the default error handling behavior in most implementations is a system-wide fail. Also, the semantics of MPI require that all messages sent eventually be consumed. This makes a lot of sense for simulations on a cluster, but not for a distributed application.</p>
|
<p>You're addressing very different APIs here, with different notions about the kind of services provided and infrastructure for each of them. I don't know enough about MPI and Spread to answer for them, but I can help a little more with ZeroMQ.</p>
<p>ZeroMQ is a simple messaging communication library. It does nothing else than send a message to different peers (including local ones) based on a restricted set of common messaging patterns (PUSH/PULL, REQUEST/REPLY, PUB/SUB, etc.). It handles client connection, retrieval, and basic congestion strictly based on those patterns and you have to do the rest yourself. </p>
<p>Although appearing very restricted, this simple behavior is mostly what you would need for the communication layer of your application. It lets you scale very quickly from a simple prototype, all in memory, to more complex distributed applications in various environments, using simple proxies and gateways between nodes. However, don't expect it to do node deployment, network discovery, or server monitoring; You will have to do it yourself.</p>
<p>Briefly, use zeromq if you have an application that you want to scale from the simple multithread process to a distributed and variable environment, or that you want to experiment and prototype quickly and that no solutions seems to fit with your model. Expect however to have to put some effort on the deployment and monitoring of your network if you want to scale to a very large cluster.</p>
| 5,598
|
<p>Yes, I know. The existence of a running copy of <code>SQL Server 6.5</code> in 2008 is absurd.</p>
<p>That stipulated, what is the best way to migrate from <code>6.5</code> to <code>2005</code>? Is there any direct path? Most of the documentation I've found deals with upgrading <code>6.5</code> to <code>7</code>.</p>
<p>Should I forget about the native <code>SQL Server</code> upgrade utilities, script out all of the objects and data, and try to recreate from scratch?</p>
<p>I was going to attempt the upgrade this weekend, but server issues pushed it back till next. So, any ideas would be welcomed during the course of the week.</p>
<p><em>Update. This is how I ended up doing it:</em></p>
<ul>
<li>Back up the database in question and Master on <code>6.5</code>.</li>
<li>Execute <code>SQL Server 2000</code>'s <code>instcat.sql</code> against <code>6.5</code>'s Master. This allows <code>SQL Server 2000</code>'s OLEDB provider to connect to <code>6.5</code>.</li>
<li>Use <code>SQL Server 2000</code>'s standalone <code>"Import and Export Data"</code> to create a DTS package, using <code>OLEDB</code> to connect to 6.5. This successfully copied all <code>6.5</code>'s tables to a new <code>2005</code> database (also using <code>OLEDB</code>).</li>
<li>Use <code>6.5</code>'s Enterprise Manager to script out all of the database's indexes and triggers to a .sql file.</li>
<li>Execute that .sql file against the new copy of the database, in 2005's Management Studio.</li>
<li>Use 6.5's Enterprise Manager to script out all of the stored procedures.</li>
<li>Execute that <code>.sql</code> file against the <code>2005</code> database. Several dozen sprocs had issues making them incompatible with <code>2005</code>. Mainly <code>non-ANSI joins</code> and <code>quoted identifier issues</code>.</li>
<li>Corrected all of those issues and re-executed the <code>.sql</code> file.</li>
<li>Recreated the <code>6.5</code>'s logins in <code>2005</code> and gave them appropriate permissions.</li>
</ul>
<p>There was a bit of rinse/repeat when correcting the stored procedures (there were hundreds of them to correct), but the upgrade went great otherwise.</p>
<p>Being able to use Management Studio instead of <code>Query Analyzer</code> and <code>Enterprise Manager 6.5</code> is such an amazing difference. A few report queries that took 20-30 seconds on the <code>6.5 database</code> are now running in 1-2 seconds, without any modification, new indexes, or anything. I didn't expect that kind of immediate improvement.</p>
|
<p>Hey, I'm still stuck in that camp too. The third party application we have to support is FINALLY going to 2K5, so we're almost out of the wood. But I feel your pain 8^D</p>
<p>That said, from everything I heard from our DBA, the key is to convert the database to 8.0 format first, and then go to 2005. I believe they used the built in migration/upgrade tools for this. There are some big steps between 6.5 and 8.0 that are better solved there than going from 6.5 to 2005 directly.</p>
<p>Your BIGGEST pain, if you didn't know already, is that DTS is gone in favor of SSIS. There is a shell type module that will run your existing DTS packages, but you're going to want to manually recreate them all in SSIS. Ease of this will depend on the complexity of the packages themselves, but I've done a few at work so far and they've been pretty smooth.</p>
|
<p>I am by no means authoritative, but I believe the only supported path is from 6.5 to 7. Certainly that would be the most sane route, then I believe you can migrate from 7 directly to 2005 pretty painlessly.</p>
<p>As for scripting out all the objects - I would advise against it as you will inevitably miss something (unless your database is truly trivial).</p>
| 2,270
|
<p>I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to <a href="https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java">this question</a> only in .Net.</p>
|
<p>I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it.</p>
<pre><code>using System.Runtime.InteropServices;
</code></pre>
<p>...</p>
<pre><code> [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
System.UInt32 pBC,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
System.UInt32 cbSize,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
System.UInt32 dwMimeFlags,
out System.UInt32 ppwzMimeOut,
System.UInt32 dwReserverd
);
public static string getMimeFromFile(string filename)
{
if (!File.Exists(filename))
throw new FileNotFoundException(filename + " not found");
byte[] buffer = new byte[256];
using (FileStream fs = new FileStream(filename, FileMode.Open))
{
if (fs.Length >= 256)
fs.Read(buffer, 0, 256);
else
fs.Read(buffer, 0, (int)fs.Length);
}
try
{
System.UInt32 mimetype;
FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
System.IntPtr mimeTypePtr = new IntPtr(mimetype);
string mime = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
return mime;
}
catch (Exception e)
{
return "unknown/unknown";
}
}
</code></pre>
|
<p>When working with Windows Azure Web role or any other host that runs your app in Limited Trust do not forget that you will not be allowed to access registry or unmanaged code. Hybrid approach - combination of try-catch-for-registry and in-memory dictionary looks like a good solution that has a bit of everything. </p>
<p>I use this code to do it : </p>
<pre><code>public class DefaultMimeResolver : IMimeResolver
{
private readonly IFileRepository _fileRepository;
public DefaultMimeResolver(IFileRepository fileRepository)
{
_fileRepository = fileRepository;
}
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private static extern System.UInt32 FindMimeFromData(
System.UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
[MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
System.UInt32 cbSize,
[MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
System.UInt32 dwMimeFlags,
out System.UInt32 ppwzMimeOut,
System.UInt32 dwReserverd);
public string GetMimeTypeFromFileExtension(string fileExtension)
{
if (string.IsNullOrEmpty(fileExtension))
{
throw new ArgumentNullException("fileExtension");
}
string mimeType = GetMimeTypeFromList(fileExtension);
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromRegistry(fileExtension);
}
return mimeType;
}
public string GetMimeTypeFromFile(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("filePath");
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException("File not found : ", filePath);
}
string mimeType = GetMimeTypeFromList(Path.GetExtension(filePath).ToLower());
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromRegistry(Path.GetExtension(filePath).ToLower());
if (String.IsNullOrEmpty(mimeType))
{
mimeType = GetMimeTypeFromFileInternal(filePath);
}
}
return mimeType;
}
private string GetMimeTypeFromList(string fileExtension)
{
string mimeType = null;
if (fileExtension.StartsWith("."))
{
fileExtension = fileExtension.TrimStart('.');
}
if (!String.IsNullOrEmpty(fileExtension) && _mimeTypes.ContainsKey(fileExtension))
{
mimeType = _mimeTypes[fileExtension];
}
return mimeType;
}
private string GetMimeTypeFromRegistry(string fileExtension)
{
string mimeType = null;
try
{
RegistryKey key = Registry.ClassesRoot.OpenSubKey(fileExtension);
if (key != null && key.GetValue("Content Type") != null)
{
mimeType = key.GetValue("Content Type").ToString();
}
}
catch (Exception)
{
// Empty. When this code is running in limited mode accessing registry is not allowed.
}
return mimeType;
}
private string GetMimeTypeFromFileInternal(string filePath)
{
string mimeType = null;
if (!File.Exists(filePath))
{
return null;
}
byte[] byteBuffer = new byte[256];
using (FileStream fileStream = _fileRepository.Get(filePath))
{
if (fileStream.Length >= 256)
{
fileStream.Read(byteBuffer, 0, 256);
}
else
{
fileStream.Read(byteBuffer, 0, (int)fileStream.Length);
}
}
try
{
UInt32 MimeTypeNum;
FindMimeFromData(0, null, byteBuffer, 256, null, 0, out MimeTypeNum, 0);
IntPtr mimeTypePtr = new IntPtr(MimeTypeNum);
string mimeTypeFromFile = Marshal.PtrToStringUni(mimeTypePtr);
Marshal.FreeCoTaskMem(mimeTypePtr);
if (!String.IsNullOrEmpty(mimeTypeFromFile) && mimeTypeFromFile != "text/plain" && mimeTypeFromFile != "application/octet-stream")
{
mimeType = mimeTypeFromFile;
}
}
catch
{
// Empty.
}
return mimeType;
}
private readonly Dictionary<string, string> _mimeTypes = new Dictionary<string, string>
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm", "application/vnd.ms-word.document.macroEnabled.12"},
{"dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htc", "text/x-component"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
}
</code></pre>
| 8,285
|
<p>I've just coded a 700 line class. Awful. I hang my head in shame. It's as opposite to <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself" rel="nofollow noreferrer">DRY</a> as a British summer.</p>
<p>It's full of cut and paste with minor tweaks here and there. This makes it's a prime candidate for refactoring. Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?</p>
<p>For the record, mine are probably using:</p>
<ol>
<li>Generic classes and methods</li>
<li>Method overloading/chaining.</li>
</ol>
<p>What are yours?</p>
|
<p>#region</p>
<p>I made a 1,000 line class only one line with it!</p>
<p>In all seriousness, the best way to avoid repetition is the things covered in your list, as well as fully utilizing polymorphism, examine your class and discover what would best be done in a base class, and how different components of it can be broken away a subclasses.</p>
|
<p>First of all, I would recommend refactoring much sooner than when you are done with the first version of the class. Anytime you see duplication, eliminate it ASAP. This may take a little longer initially, but I think the results end up being a lot cleaner, and it helps you rethink your code as you go to ensure you are doing things right.</p>
<p>As for my favorite way of removing duplication.... Closures, especially in my favorite language (Ruby). They tend to be a really concise way of taking 2 pieces of code and merging the similarities. Of course (like any "best practice" or tip), this can not be blindly done... I just find them really fun to use when I can use them.</p>
| 8,491
|
<p>Where is the correct Marlin firmware file and location to add code that I want to shop up in the LCD menu of my printer, and then execute the function I write when the button is pressed?</p>
<p>For example I want to add a menu item that says "Preheat Custom" that is in the same menu as "preheat PLA" and "preheat ABS" and then runs code to heat to values I specify.</p>
<p><em>I'm running Marlin Firmware version 1.1.9 on a Creality Ender 3.</em></p>
|
<p>The answer to your question (baring in mind that the question is raised for Marlin 1.1.9) is the file <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a>. Nowadays, you can also enable extra option through the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration_adv.h#L1546" rel="nofollow noreferrer">Configuration_adv.h</a> file, just enable:</p>
<pre><code>#define CUSTOM_USER_MENUS
</code></pre>
<p>and edit the options beneath it to your needs (otherwise it will use the preset values from the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h#L1255" rel="nofollow noreferrer">Configuration.h</a> file).</p>
<hr />
<p><strong>Add custom items using ultralcd.cpp</strong></p>
<p>This is how I used to do it if you want to add items to the menu in Marlin Firmware through the ultralcd.cpp. It is best to first look at the current implementation of the menu items. As you already mention <code>Preheat PLA</code>, that would be the first to search for. Searching in files is easy when you go to the github website with the Marlin firmware sources, functionality is available for searching in the files. Alternatively, download a copy of the firmware and use a free "grep" utility to search in files.</p>
<p>Searching for <code>Preheat PLA</code> will show you a bunch of language translation files. These point to the use of a constant <code>MSG_PREHEAT_1</code> which finds its presence in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a>. This hints to function <code>lcd_preheat_m1_menu</code> that is called by <code>MENU_ITEM</code> which adds menu items to LCD. You could start there to add your own option.</p>
<hr />
<p><strong>Demonstration</strong></p>
<p>As a quick demonstration, I've added a <code>CUSTOM PREHEAT</code> item by copying the <code>lcd_preheat_m2_menu</code> function in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a> and renamed this <code>lcd_preheat_m3_menu</code> (a full functional item needs changes within the <code>lcd_preheat_m3_menu</code> as it now uses the constants from the ABS preheat option).</p>
<p>You then add the item to the menu by changing this part of the code:</p>
<pre>
//
// Preheat for Material 1 and 2
//
#if TEMP_SENSOR_1 != 0 || TEMP_SENSOR_2 != 0 || TEMP_SENSOR_3 != 0 || TEMP_SENSOR_4 != 0 || HAS_HEATED_BED
MENU_ITEM(submenu, MSG_PREHEAT_1, lcd_preheat_m1_menu);
MENU_ITEM(submenu, MSG_PREHEAT_2, lcd_preheat_m2_menu);
// ADD THIS LINE:
MENU_ITEM(submenu, "CUSTOM PREHEAT", lcd_preheat_m3_menu);
#else
MENU_ITEM(function, MSG_PREHEAT_1, lcd_preheat_m1_e0_only);
MENU_ITEM(function, MSG_PREHEAT_2, lcd_preheat_m2_e0_only);
#endif
</pre>
<p>After compiling and uploading to the printer board, enter the <code>Prepare</code> menu and scroll down to see:</p>
<p><a href="https://i.stack.imgur.com/X5eUD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X5eUD.jpg" alt="LCD showing custom preheat option" /></a></p>
|
<p>Preheat Constants - Up to 5 are supported without changing the code just add a new one and then build</p>
<pre><code>#define PREHEAT_1_LABEL "PLA"
#define PREHEAT_1_TEMP_HOTEND 215
#define PREHEAT_1_TEMP_BED 70
#define PREHEAT_1_TEMP_CHAMBER 35
#define PREHEAT_1_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_2_LABEL "PETG"
#define PREHEAT_2_TEMP_HOTEND 235
#define PREHEAT_2_TEMP_BED 70
#define PREHEAT_2_TEMP_CHAMBER 35
#define PREHEAT_2_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_3_LABEL "ABS"
#define PREHEAT_3_TEMP_HOTEND 270
#define PREHEAT_3_TEMP_BED 100
#define PREHEAT_3_TEMP_CHAMBER 35
#define PREHEAT_3_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_4_LABEL "NYLON"
#define PREHEAT_4_TEMP_HOTEND 260
#define PREHEAT_4_TEMP_BED 65
#define PREHEAT_4_TEMP_CHAMBER 35
#define PREHEAT_4_FAN_SPEED 0 // Value from 0 to 255
<span class="math-container">```</span>
</code></pre>
| 1,132
|
<p>I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.</p>
<p>Any ideas about how to detect which mode the user is in and re-format the forms on the fly?</p>
<hr>
<p>Post Answer Edit:</p>
<p>Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.</p>
<p>I'm doing the following:</p>
<p><strong>Function Declaration:</strong>
<pre><code> Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
</pre></code></p>
<p><strong><em>Code Body:</em></strong>
<pre><code>
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)</p>
<p>GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
</pre></code></p>
<p>The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.</p>
|
<p>Try using a combination of <a href="http://www.pinvoke.net/default.aspx/uxtheme/GetCurrentThemeName.html" rel="nofollow noreferrer">GetCurrentThemeName</a> (<a href="http://msdn.microsoft.com/en-us/library/bb773365%28VS.85%29.aspx" rel="nofollow noreferrer">MSDN Page</a>) and <a href="http://msdn.microsoft.com/en-us/library/aa969518%28VS.85%29.aspx" rel="nofollow noreferrer">DwmIsCompositionEnabled</a></p>
<p>I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:</p>
<pre><code>[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
</code></pre>
<p>See what results you get out of those two functions; they should be enough to determine when you want to use a different theme!</p>
|
<p>There's the <a href="http://msdn.microsoft.com/en-us/library/bb759813%28VS.85%29.aspx" rel="nofollow noreferrer">IsThemeActive</a> WinAPI function.</p>
| 5,506
|
<p>I'm using Delphi and need to get the current Windows DNS server IP address so I can do a lookup. What function should I call to find it? The only solution I have right now does an ipconfig/all to get it, which is horrible.</p>
|
<p>Found a nice one using the function GetNetworkParams().Seems to work quite good.
You can find it here:
<a href="http://www.swissdelphicenter.ch/torry/showcode.php?id=2452" rel="nofollow noreferrer">http://www.swissdelphicenter.ch/torry/showcode.php?id=2452</a></p>
|
<p>See <em><a href="http://msdn.microsoft.com/en-us/library/aa365968(VS.85).aspx" rel="nofollow noreferrer">GetNetowrkParams</a></em> method (Platform SDK: IP Helper)</p>
| 8,748
|
<p>I have a serious problem and I can't find a way to solve it because I have no idea why is it happening.
For some reason the things I print get really messy, like a mountain range growing on the print. It looks like overflow but it can't be because I'm already using 0.82 flow modifier and if I go any lower the printout will fall apart as the extrusions won't touch at all. I've double checked my extruder steps and my filament and also my nozzle width, all are set up correctly. The whole thing looks like the printer is over-extruding just in some parts of the print.
<a href="https://i.stack.imgur.com/CgpKL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CgpKL.jpg" alt="enter image description here"></a></p>
|
<p>It definitely looks like over extruding. But similar effect can appear with proper extruding (or not too much exceeded) but with too high temperature.</p>
<p>If it appears only on some parts of the first layer then it can be:</p>
<ul>
<li>bed leveling issue (or eventually bed is bent)</li>
<li>caret mechanism issue (dispositioned/bent)</li>
</ul>
<p>You can also check different speeds just to be sure.</p>
|
<p>This is happening on the first or second layer, correct? It looks like your nozzle is trammed too close to the build plate. If there is less gap between the nozzle and bed than the slicer expects, it will over-extrude the first layer. That tends to produce "bacon" patterns of ripples on the bottom of the print as the plastic gets unevenly squeezed out to the side of the strand. </p>
| 334
|
<p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p>
<pre><code>import urllib
import re
url = "http://www.someurl.com"
# Download the page locally
f = urllib.urlopen(url)
html = f.read()
f.close()
f = open ("temp.htm", "w")
f.write (html)
f.close()
# List only the .TXT / .ZIP files
fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)
for fname in fnames:
print fname, "..."
f = urllib.urlopen(url + "/" + fname)
#### Here I want to check the filesize to download or not ####
file = f.read()
f.close()
f = open (fname, "w")
f.write (file)
f.close()
</code></pre>
<hr>
<p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p>
<p>Examples:</p>
<pre><code>Local Size Server Size
2.223.533 2.115.516
664.603 662.121
</code></pre>
<p>It has anything to do with the CR/LF conversion?</p>
|
<p>I have reproduced what you are seeing:</p>
<pre><code>import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
meta = site.info()
print "Content-Length:", meta.getheaders("Content-Length")[0]
f = open("out.txt", "r")
print "File on disk:",len(f.read())
f.close()
f = open("out.txt", "w")
f.write(site.read())
site.close()
f.close()
f = open("out.txt", "r")
print "File on disk after download:",len(f.read())
f.close()
print "os.stat().st_size returns:", os.stat("out.txt").st_size
</code></pre>
<p>Outputs this:</p>
<pre><code>opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16861
</code></pre>
<p>What am I doing wrong here? Is os.stat().st_size not returning the correct size?</p>
<hr>
<p>Edit:
OK, I figured out what the problem was:</p>
<pre><code>import urllib, os
link = "http://python.org"
print "opening url:", link
site = urllib.urlopen(link)
meta = site.info()
print "Content-Length:", meta.getheaders("Content-Length")[0]
f = open("out.txt", "rb")
print "File on disk:",len(f.read())
f.close()
f = open("out.txt", "wb")
f.write(site.read())
site.close()
f.close()
f = open("out.txt", "rb")
print "File on disk after download:",len(f.read())
f.close()
print "os.stat().st_size returns:", os.stat("out.txt").st_size
</code></pre>
<p>this outputs:</p>
<pre><code>$ python test.py
opening url: http://python.org
Content-Length: 16535
File on disk: 16535
File on disk after download: 16535
os.stat().st_size returns: 16535
</code></pre>
<p>Make sure you are opening both files for binary read/write.</p>
<pre><code>// open for binary write
open(filename, "wb")
// open for binary read
open(filename, "rb")
</code></pre>
|
<p>@PabloG Regarding the local/server filesize difference</p>
<p>Following is high-level illustrative explanation of why it may occur:</p>
<p>The size on disk sometimes is different from the actual size of the data.
It depends on the underlying file-system and how it operates on data.
As you may have seen in Windows when formatting a flash drive you are asked to provide 'block/cluster size' and it varies [512b - 8kb].
When a file is written on the disk, it is stored in a 'sort-of linked list' of disk blocks.
When a certain block is used to store part of a file, no other file contents will be stored in the same blok, so even if the chunk is no occupuing the entire block space, the block is rendered unusable by other files.</p>
<p>Example:
When the filesystem is divided on 512b blocks, and we need to store 600b file, two blocks will be occupied. The first block will be fully utilized, while the second block will have only 88b utilized and the remaining (512-88)b will be unusable resulting in 'file-size-on-disk' being 1024b.
This is why Windows has different notations for 'file size' and 'size on disk'.</p>
<p>NOTE:
There are different pros & cons that come with smaller/bigger FS block, so do a better research before playing with your filesystem.</p>
| 2,778
|
<p>I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).</p>
<p>The rows, of course, will not be perfect duplicates because of the existence of the <code>RowID</code> identity field.</p>
<p><strong>MyTable</strong></p>
<pre><code>RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null
</code></pre>
<p>How can I do this?</p>
|
<p>Assuming no nulls, you <code>GROUP BY</code> the unique columns, and <code>SELECT</code> the <code>MIN (or MAX)</code> RowId as the row to keep. Then, just delete everything that didn't have a row id:</p>
<pre><code>DELETE FROM MyTable
LEFT OUTER JOIN (
SELECT MIN(RowId) as RowId, Col1, Col2, Col3
FROM MyTable
GROUP BY Col1, Col2, Col3
) as KeepRows ON
MyTable.RowId = KeepRows.RowId
WHERE
KeepRows.RowId IS NULL
</code></pre>
<p>In case you have a GUID instead of an integer, you can replace</p>
<pre><code>MIN(RowId)
</code></pre>
<p>with</p>
<pre><code>CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn)))
</code></pre>
|
<p><strong>A very simple way to delete duplicate rows of table in postgresql.</strong></p>
<pre><code>DELETE FROM table1 a
USING table1 b
WHERE a.id < b.id
AND a.column1 = b.column1
AND a.column2 = b.column2;
</code></pre>
| 3,944
|
<p>I'm about to create a web application that requires a lot of different web forms where the user needs to be able to input a lot of different types of information. What I mean is that one of those forms may require some text input fields, some integer input fields, some decimal input fields, some date input fields, some datetime input fields, etc.</p>
<p>I would like to have a, maybe JavaScript-based, control library that I can simple provide with some text labels, input types and default values. The control library would then somehow render the form in HTML without me having to create an HTML table, select the appropriate standard web controls and all that.</p>
<p>I have used <a href="http://www.dhtmlx.com/" rel="nofollow noreferrer">dhtmlxGrid</a> to create quite a lot of tables and that works well for me. What I need now is something that can help me in a similar way when creating something like card forms.</p>
<p>I have also found <a href="http://www.activewidgets.com/" rel="nofollow noreferrer">ActiveWidgets</a>, but it looks like it will require a lot of work on my behalf. I'm not only looking for individual web controls, but rather something like a library that can help me with the overall card.</p>
<p>I'm guessing many of you have had this problem before. Looking forward to hearing what solutions you have found to be the best. BTW: I'm working in VisualStudio with ASP.NET.</p>
|
<p>I would be tempted to look at Ext JS for this. </p>
<p><a href="http://extjs.com/products/extjs/" rel="nofollow noreferrer">Ext JS</a></p>
|
<p>have you had a look at <a href="http://javascript.neyric.com/inputex/" rel="nofollow noreferrer">InputEx</a></p>
| 6,548
|
<p>I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.</p>
<p>How should I go about doing that?</p>
|
<p>You can probably do this by setting your own <a href="https://docs.oracle.com/javase/8/docs/api/javax/swing/filechooser/FileSystemView.html" rel="noreferrer">FileSystemView</a>.</p>
|
<p>No need to be that complicated. You can easily set selection mode of a JFileChooser like this</p>
<pre><code>JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
</code></pre>
<p>You can read more reference here <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html" rel="nofollow">How to Use File Choosers</a></p>
| 5,246
|
<p>How can I <strong>pre pend</strong> (insert at beginning of file) a file to all files of a type in folder and sub-folders using <code>Powershell</code>?</p>
<p>I need to add a standard header file to all <code>.cs</code> and was trying to use <code>Powershell</code> to do so, but while I was able to append it in a few lines of code I was stuck when trying to <strong>pre-pend</strong> it.</p>
|
<p>Here is a very simple example to show you one of the ways it could be done.</p>
<pre><code>$Content = "This is your content`n"
Get-ChildItem *.cs | foreach-object {
$FileContents = Get-Content -Path $_
Set-Content -Path $_ -Value ($Content + $FileContents)
}
</code></pre>
|
<p>Have no idea, but if you have the code to append just do it the other way round. Something like</p>
<ol>
<li>rename existing file,</li>
<li>create an empty file named the same as above </li>
<li>append header to new empty file,</li>
<li>append renamed file to previous,</li>
<li>delete renamed file</li>
</ol>
| 9,959
|
<p>I would like to get a pretty accurate method to do finite element analysis (FEA) on my 3d designs considering the infill. I use <em>Autodesk Inventor</em> to design parts but the FEA can only be applied to a solid body (100% infill). Does anyone know software that can convert a 3d design to another but considering the infill so I can use FEA more accurately?</p>
|
<p>This is the throat block for direct drive extrusion, Anet8 is a cheap clone of Prusa printers, so it's easy to find parts for Anet printers. </p>
<p>This is one extruder kit that may help your needs, <a href="https://es.aliexpress.com/store/product/1Set-3D-Printer-makerbot-MK8-Extruder-Aluminum-extrusion-Frame-Block-DIY-Kit-for-Reprap-i3/1962255_32715673423.html?spm=a219c.search0104.3.269.W5yIqd&ws_ab_test=searchweb0_0,searchweb201602_2_10152_10065_10151_10344_10068_10345_10342_10343_10173_10340_10341_10541_10562_10084_10083_10307_10060_10155_5680016_10154_10056_10055_10539_10537_10312_10059_10313_10314_10534_10533_100031_10103_10073_10102_10557_10142_10107,searchweb201603_25,ppcSwitch_5&btsid=79693e48-00b7-4029-908d-314b37935569&algo_expid=64c2aa2b-e9de-4722-8ecb-0ba5542f5a86-34&algo_pvid=64c2aa2b-e9de-4722-8ecb-0ba5542f5a86" rel="nofollow noreferrer">1 Unidades Impresora 3D makerbot MK8 Extrusora De extrusión de Aluminio Bloque de DIY Kit para Reprap i3</a>. This is a link for Aliexpress - of course there are other dealers.</p>
|
<p>Like @ZuOverture said the name of this component is the filament drive. Most of the manufactures sell the whole extrusion device already assembled, to avoid mismatches between the components of the extrusion device. If your device is somehow damaged, and without possibilities to be used in the printer the easiest solution would be to buy a new extrusion device. If financially is unfeasible for you, you may have the option to generate the 3D model of this piece and share the file to someone who could print this component for you. </p>
| 742
|
<p>I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:</p>
<pre><code>var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
</code></pre>
<p>This is not allowed. How do I get something like this working?</p>
<p>I'm amazed that LINQ queries are not allowed on DataTables!</p>
|
<p>You can't query against the <code>DataTable</code>'s <em>Rows</em> collection, since <code>DataRowCollection</code> doesn't implement <code>IEnumerable<T></code>. You need to use the <code>AsEnumerable()</code> extension for <code>DataTable</code>. Like so:</p>
<pre><code>var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
</code></pre>
<p>And as <a href="https://stackoverflow.com/a/10893/5519709">@Keith</a> says, you'll need to add a reference to <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.aspx" rel="noreferrer">System.Data.DataSetExtensions</a></p>
<p><code>AsEnumerable()</code> returns <code>IEnumerable<DataRow></code>. If you need to convert <code>IEnumerable<DataRow></code> to a <code>DataTable</code>, use the <code>CopyToDataTable()</code> extension.</p>
<p>Below is query with Lambda Expression,</p>
<pre><code>var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1);
</code></pre>
|
<p>I propose following solution:</p>
<pre><code>DataView view = new DataView(myDataTable);
view.RowFilter = "RowNo = 1";
DataTable results = view.ToTable(true);
</code></pre>
<p>Looking at the <a href="https://learn.microsoft.com/de-de/dotnet/api/system.data.dataview?view=netframework-4.8" rel="nofollow noreferrer">DataView Documentation</a>, the first thing we can see is this:</p>
<blockquote>
<p>Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.</p>
</blockquote>
<p>What I am getting from this is that DataTable is meant to only store data and DataView is there enable us to "query" against the DataTable. </p>
<p>Here is how this works in this particular case:</p>
<p>You try to implement the SQL Statement</p>
<pre><code>SELECT *
FROM myDataTable
WHERE RowNo = 1
</code></pre>
<p>in "DataTable language". In C# we would read it like this:</p>
<pre><code>FROM myDataTable
WHERE RowNo = 1
SELECT *
</code></pre>
<p>which looks in C# like this:</p>
<pre><code>DataView view = new DataView(myDataTable); //FROM myDataTable
view.RowFilter = "RowNo = 1"; //WHERE RowNo = 1
DataTable results = view.ToTable(true); //SELECT *
</code></pre>
| 3,202
|
<p>I'm trying to install <a href="http://laconi.ca/" rel="noreferrer">Laconica</a>, an open-source Microblogging application on my Windows development server using XAMPP as per the <a href="http://laconi.ca/trac/wiki/InstallationWindows" rel="noreferrer">instructions provided</a>.</p>
<p>The website cannot find PEAR, and throws the below errors:</p>
<blockquote>
<p>Warning: require_once(PEAR.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampplite\htdocs\laconica\lib\common.php on line 31</p>
<p>Fatal error: require_once() [function.require]: Failed opening required 'PEAR.php' (include_path='.;\xampplite\php\pear\PEAR') in C:\xampplite\htdocs\laconica\lib\common.php on line 31</p>
</blockquote>
<ol>
<li>PEAR is located in <code>C:\xampplite\php\pear</code></li>
<li><code>phpinfo()</code> shows me that the include path is <code>.;\xampplite\php\pear</code></li>
</ol>
<p>What am I doing wrong? Why isn't the PEAR folder being included?</p>
|
<p>You need to fix your <code>include_path</code> system variable to point to the correct location. </p>
<p>To fix it edit the <code>php.ini</code> file. In that file you will find a line that says, "<code>include_path = ...</code>". (You can find out what the location of php.ini by running <code>phpinfo()</code> on a page.) Fix the part of the line that says, "<code>\xampplite\php\pear\PEAR</code>" to read "<code>C:\xampplite\php\pear</code>". Make sure to leave the semi-colons before and/or after the line in place.</p>
<p>Restart PHP and you should be good to go. To restart PHP in IIS you can restart the application pool assigned to your site or, better yet, restart IIS all together.</p>
|
<p>Try adding the drive letter:</p>
<pre><code>include_path='.;c:\xampplite\php\pear\PEAR'
</code></pre>
<p>also verify that PEAR.php is actually there, it might be in \php\ instead:</p>
<pre><code>include_path='.;c:\xampplite\php'
</code></pre>
| 8,815
|
<p>This is probably best shown with an example. I have an enum with attributes:</p>
<pre><code>public enum MyEnum {
[CustomInfo("This is a custom attrib")]
None = 0,
[CustomInfo("This is another attrib")]
ValueA,
[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}
</code></pre>
<p>I want to get to those attributes from an instance:</p>
<pre><code>public CustomInfoAttribute GetInfo( MyEnum enumInput ) {
Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum )
//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() );
//get the attribute from the field
return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}
</code></pre>
<p>As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it.</p>
<p>Does anyone have a better way?</p>
|
<p>This is probably the easiest way.</p>
<p>A quicker way would be to Statically Emit the IL code using Dynamic Method and ILGenerator. Although I've only used this to GetPropertyInfo, but can't see why you couldn't emit CustomAttributeInfo as well. </p>
<p>For example code to emit a getter from a property</p>
<pre><code>public delegate object FastPropertyGetHandler(object target);
private static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type)
{
if (type.IsValueType)
{
ilGenerator.Emit(OpCodes.Box, type);
}
}
public static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo)
{
// generates a dynamic method to generate a FastPropertyGetHandler delegate
DynamicMethod dynamicMethod =
new DynamicMethod(
string.Empty,
typeof (object),
new Type[] { typeof (object) },
propInfo.DeclaringType.Module);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// loads the object into the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
// calls the getter
ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null);
// creates code for handling the return value
EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType);
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastPropertyGetHandler delegate
// to get the property
FastPropertyGetHandler getter =
(FastPropertyGetHandler)
dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler));
return getter;
}
</code></pre>
|
<p>I generally find reflection to be quite speedy as long as you don't dynamically invoke methods.<br>
Since you are just reading the Attributes of an enum, your approach should work just fine without any real performance hit.</p>
<p>And remember that you generally should try to keep things simple to understand. Over engineering this just to gain a few ms might not be worth it.</p>
| 3,835
|
<p>I know the colours are changed in Environment > Fonts and Colors but I haven't found out which Display Item the object is.</p>
<p>Can someone please tell how I can colour the following code:</p>
<blockquote>
<p>lblMessage.Text = "You have successfully answered my question!"</p>
</blockquote>
<p>I have the string coloured pink, I would like the lblMessage purple and the .Text a light green.</p>
<p>For me the darker the colour the less it will "change". I won't often change object names, I'll more often change properties and am always changing strings - although I have another question about this that I'll post later.</p>
<p>Thanks</p>
|
<p>For my big apps I just use a incrementing version number id (1.0, 1.1, ...) that i store in a comment of the main file (usually index.php).<Br />
For just websites I usually just have a revision number (1,2,3,...).</p>
|
<p>I maintain a system of web applications with various components that live in separate SVN repos. To be able to version track the system as a whole, I have another SVN repo which contains all other repos as external references. It also contains install / setup script(s) to deploy the whole thing. With that setup, the SVN revision number of the "metarepository" could possibly be used for versioning the complete system.</p>
<p>In another case, I include the SVN revision via <a href="http://svnbook.red-bean.com/en/1.2/svn.advanced.props.html#svn.advanced.props.special.keywords" rel="nofollow noreferrer" title="SVN keywords">SVN keywords</a> in a class file that serves no other purpose (to avoid the risk of keyword substitution breaking my code). The class in that file contains a string variable that is manipulated by SVN and parsed by a class method.</p>
<p>An inconvenience with both approaches is that the revision number is not automatically updated by changes in the externals (approach 1) or the rest of the code (approach 2).</p>
| 4,959
|
<p>I'm using Google App Engine and Django templates.<br>
I have a table that I want to display the objects look something like:<br></p>
<pre><code>Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
</code></pre>
<p>The Django template is:</p>
<pre><code><table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</code></pre>
<p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="noreferrer">Django documention</a> states that when it sees a <strong>.</strong> in variables<br>
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
|
<p>I found a "nicer"/"better" solution for getting variables inside
Its not the nicest way, but it works.</p>
<p>You install a custom filter into django which gets the key of your dict as a parameter</p>
<p>To make it work in google app-engine you need to add a file to your main directory,
I called mine <em>django_hack.py</em> which contains this little piece of code</p>
<pre><code>from google.appengine.ext import webapp
register = webapp.template.create_template_register()
def hash(h,key):
if key in h:
return h[key]
else:
return None
register.filter(hash)
</code></pre>
<p>Now that we have this file, all we need to do is tell the app-engine to use it...
we do that by adding this little line to your main file</p>
<pre><code>webapp.template.register_template_library('django_hack')
</code></pre>
<p>and in your template view add this template instead of the usual code</p>
<pre><code>{{ user|hash:item }}
</code></pre>
<p>And its should work perfectly =)</p>
|
<p>shouldn't this:</p>
<pre><code>{{ user.item }}
</code></pre>
<p>be this?</p>
<pre><code>{{ item }}
</code></pre>
<p>there is no user object in the context within that loop....?</p>
| 5,654
|
<p>A few weeks ago I got a thermal runaway message on my modded Ender 3 during a print, and I have not been able to get it working since then! I have tried fixing and replacing everything, and I still keep getting the message!</p>
<p>When the printer starts/heats up, the thermistor is able to read the temperature with no problem, but when a print starts, the thermistor starts reading strangely and I get the thermal runaway message! Basically, whenever I start a print the temperature being read slowly drops until it gets to around 20 degrees below the set temperature. I then get the thermal runaway message.</p>
<p>So far, in an attempt to fix it, I have replaced the thermistor twice, the heating element, the wiring was replaced, the firmware and even the entire motherboard! I have no idea how/why I’m still having the message, it just doesn’t make sense.</p>
<p>Also, the thermistor is snuggly attached to the printer.</p>
<p>Please note I’ve tried another thermistor that was glass and had the exact same issues. This lead me to think that this had something to do with the heating element being overwhelmed by something. So, as a test I simply just extruded filament from my nozzle with my fan on to see if that would have the same effect and it didn’t! The temperature stayed up fine. This is leading me to believe that this is some sort of issue with starting a print. Maybe a G-code issue.</p>
|
<p>If the error only happens when the printer starts moving it's logical that the issue is in the wire loom that starts to bend and flex once the print starts.</p>
<p>As a quick test and if your comfortable with a little wiring work a temporarily line could be connected directly from the sensor to board. Skipping rewiring the loom until its confirmed to be the issue.</p>
<p>Same logic for the heater wires if it has a connector at the extruder.</p>
<p>Another potential cause for this is if the extruder is already near printing temperature and a new print is started, the printer could think that the temperature shot up way faster then expected even though in reality it was just a bit preheated. If you made any changes to your start G-code, like changing the heating command type or order in witch the extruder/bed is heated, see this stack: <a href="https://3dprinting.stackexchange.com/questions/13353/thermal-runaway-triggers-when-raising-temperature-amid-cooldown?rq=1">Thermal runaway triggers when raising temperature amid cooldown</a>.</p>
<p>Edit:
<a href="https://www.youtube.com/watch?v=JcG7fIcF24k&ab_channel=DaHaiZhu" rel="nofollow noreferrer">This video</a> demonstrates a test to show if Thermal Runaway is enabled. While this setting is not in question here it might be a way to troubleshoot the underling cause for this kind of issue. If the extruder temperatures drop rapidly the same way it does when a print is attempted it might show that the temperature sensor is reading the correct temperature. And thus may indicate a issue with the extruder heating system and not the temperature sensor itself.</p>
|
<p>I've had this problem on a Prusa MK2s. The print was always at the center of the build plate and that's the location (underneath) of the thermistor. The part was small, the cooling fan was chilling the bed at the same time it was trying to maintain temperature. Moving the part a few centimeters away from the center resolved the problem.</p>
<p>In the case of this PEI coated bed, always centering the print caused the PEI to wear in that area, requiring replacement. The operators were informed to place the build in random, non-centered locations in the future.</p>
| 2,002
|
<p>I have a string, say <code>'123'</code>, and I want to convert it to the integer <code>123</code>.</p>
<p>I know you can simply do <code>some_string.to_i</code>, but that converts <code>'lolipops'</code> to <code>0</code>, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful <code>Exception</code>. Otherwise, I can't distinguish between a valid <code>0</code> and something that just isn't a number at all.</p>
<p><strong>EDIT:</strong> I was looking for the standard way of doing it, without regex trickery.</p>
|
<p>Ruby has this functionality built in:</p>
<pre><code>Integer('1001') # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
</code></pre>
<p>As noted in answer by <a href="https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/53359#53359">Joseph Pecoraro</a>, you might want to watch for strings that are valid non-decimal numbers, such as those starting with <code>0x</code> for hex and <code>0b</code> for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.</p>
<p>Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:</p>
<pre><code>Integer('23') # => 23
Integer('0x23') # => 35
Integer('023') # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10) # => 23
</code></pre>
|
<p>Re: <a href="https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby#49280">Chris's answer</a></p>
<p>Your implementation let's things like "1a" or "b2" through. How about this instead:</p>
<pre><code>def safeParse2(strToParse)
if strToParse =~ /\A\d+\Z/
strToParse.to_i
else
raise Exception
end
end
["100", "1a", "b2", "t"].each do |number|
begin
puts safeParse2(number)
rescue Exception
puts "#{number} is invalid"
end
end
</code></pre>
<p>This outputs:</p>
<pre><code>100
1a is invalid
b2 is invalid
t is invalid
</code></pre>
| 7,179
|
<p>I am about to reenter the MFC world after years away for a new job. What resources to people recommend for refreshing the memory? I have been doing mainly C# recently.</p>
<p>Also any MFC centric websites or blogs that people recommend?</p>
|
<ul>
<li>For blogs: Your best bet would be the <a href="http://blogs.msdn.com/vcblog/default.aspx" rel="nofollow noreferrer">Visual C++ Team Blog</a>.</li>
<li>For books: <a href="https://rads.stackoverflow.com/amzn/click/com/1572316950" rel="nofollow noreferrer" rel="nofollow noreferrer">Programming Windows with MFC</a> is one of the best book on the subject.</li>
<li>For tutorials: Simply <a href="http://www.google.ca/search?q=mfc+tutorial&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a" rel="nofollow noreferrer">search google for various tutorials on MFC</a>.</li>
</ul>
<p><img src="https://i.stack.imgur.com/cc1ng.jpg" alt="enter image description here"></p>
|
<p>Books are one thing, but I always found that practice was the key with MFC. <a href="http://www.codeguru.com" rel="nofollow noreferrer">CodeGuru</a> was my favourite destination to answer anything MFC-related. </p>
<p>There's also that new website. What's it called...that's it - <a href="https://stackoverflow.com/">StackOverflow</a>!</p>
| 4,745
|
<p>I have a Maker Farm Prusa i3v 8" i just finished building. Initially when i first homed it, it ran fine, it even ran a test g code for movement. The problem is now the Z axis wont move anymore. First i checked for physical issues such as binding or nuts coming out of traps, everything's OK there. In Pronterface i can move x & y no problem, but Z will not move, there is no noise from the steppers. Also unusual is the the Z axis is not on the endstop, its resting on its own in a spot (the hotend is about 2mm off the bed). I ordered some new end stop switches to try on my Z axis....any thoughts? I'll update after switch install.</p>
|
<p>If you are using Repetier the code to test the endstops is m119 I think. If your z stop is triggered, you may have to invert it in the config.h file. I had this same issue for days before i figured out the control board was reading the switch as normal close instead of normal open. Hope that helps!</p>
|
<p>Try sending a motion command manually, such as G1 X20 Z10, to eliminate any bugginess from the software interface as a reason for the Z not moving properly when commanded to. Next you could check the park location in Pronterface, perhaps the extruder head is sitting there waiting for the next command.</p>
| 682
|
<p>Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include</p>
<pre><code>\ / < > ? * :
</code></pre>
<p>I know HOW to validate names (a regular expression).</p>
<p>I need to validate filenames entered by users. </p>
<p>My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!</p>
|
<p>No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.</p>
<p>Also, if trying to port an Windows app to Mac or Unix it is best to use:</p>
<pre><code>File.separator
</code></pre>
<p>To determine the correct file separator to use on each platform.</p>
|
<p>When you create a <code>new File</code> the inputted arguments will be normalized by a platform specific implementation of the <code>java.io.FileSystem</code> class. There are no Java specific restrictions that I know of.</p>
<p>and yes, always use <code>File.separator</code>.</p>
| 8,926
|
<p>I am trying to get the <code>Edit with Vim</code> context menu to open files in a new tab of the previously opened Gvim instance (if any).</p>
<p>Currently, using <code>Regedit</code> I have modified this key:</p>
<pre><code>\HKEY-LOCAL-MACHINE\SOFTWARE\Vim\Gvim\path = "C:\Programs\Vim\vim72\gvim.exe" -p --remote-tab-silent "%*"
</code></pre>
<p>The registry key type is <code>REG_SZ</code>.</p>
<p>This almost works... Currently it opens the file in a new tab, but it also opens another tab (which is the active tab) the tab is labeled <code>\W\S\--literal</code> and the file seems to be trying to open the following file. </p>
<pre><code>C:\Windows\System32\--literal
</code></pre>
<p>I think the problem is around the <code>"%*"</code> - I tried changing that to <code>"%1"</code> but if i do that I get an extra tab called <code>%1</code>.</p>
<p><strong>Affected version</strong></p>
<ul>
<li>Vim version 7.2 (same behaviour on 7.1) </li>
<li>Windows vista home premium</li>
</ul>
<p>Thanks for any help. </p>
<p>David. </p>
|
<p>Try setting it to: "C:\Programs\Vim \vim72\gvim.exe" -p --remote-tab-silent "%1" "%*"</p>
<p>See: <a href="http://www.vim.org/tips/tip.php?tip_id=1314" rel="noreferrer">http://www.vim.org/tips/tip.php?tip_id=1314</a></p>
<p>EDIT: As pointed out by Thomas, vim.org tips moved to: <a href="http://vim.wikia.com/" rel="noreferrer">http://vim.wikia.com/</a></p>
<p>See: <a href="http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows" rel="noreferrer">http://vim.wikia.com/wiki/Add_open-in-tabs_context_menu_for_Windows</a></p>
|
<p>I would recommend trying <a href="http://cream.sourceforge.net/index.html" rel="nofollow noreferrer">Cream</a>.</p>
<p> Cream is a set of scripts and add-ons that sit on top of gVim. Cream doesn't change the appearance of gVim, but it does change the way it behaves.</p>
<p>One of those behaviours is a tabbed document interface. Other behaviours are listed <a href="http://cream.sourceforge.net/featurelist.html" rel="nofollow noreferrer">here</a>. The downloads page is <a href="http://cream.sourceforge.net/download.html" rel="nofollow noreferrer">here</a>.</p>
| 9,306
|
<p>I need to do some post processing of my 3D-printed models that includes adding some holes. For each of PLA, ABS, PETG and other 3D-printing materials:</p>
<p>In what ways is drilling a hole in a model made from that material like or unlike drilling wood? Is it worth getting special "plastic drilling bits" that cost tons of money or can I use regular high speed drill bits? Do these plastics have grain that they will split on when drilled into, and if so, what are ways to avoid such splitting? Are higher speeds better, or lower speeds, or should I only use a finger-twirled bit holder?</p>
<p>Are some 3D-printing materials easier to drill than others?</p>
<p>What other methods also work for creating a hole in the different types of plastics?</p>
|
<p>Have to get this out of the way... Can you just print the hole into the part instead of drilling? That's usually best, when possible. </p>
<p>If you need to drill, you'll definitely want to print an undersized hole and then ream it out with the drill. This both provides alignment for the drill and adds extra plastic around the region you'll be weakening. If you don't know where the hole needs to go in advance, fill the model with a hex pattern of tiny holes in the general region of the future drilling. This is an easy way to strengthen the area with more plastic without making the entire part solid. (Using a slicer that allows localized print settings will also work.)</p>
<p>The hole should be aligned more or less vertical or "across the grain" (+/-45 degrees aligned with the Z axis) to ensure there are nice, strong hoops of plastic around the hole to keep it from splitting. Drilling into a printed part (particularly PLA) from the side / parallel to the XY plane is highly likely to split it. It may even be ok at first but crack later under load or due to creep. </p>
<p>Regular wood drill bits work ok, but you need to go slow and take nibbles, leaving the plastic time to cool so it doesn't melt and stick to the bit. (Coolant is an option.) Use a pilot hole, piloted bit, or step drill to remove less plastic per pass. A really sharp bit will perform dramatically better than a dull bit. </p>
<p>Put something hard and drillable like wood behind the plastic part to help avoid breakage and bit-jamming when you break through the opposite side. </p>
|
<p>I realize this is an old post .. but playing around with drilling PLA myself ..
100 % infill .. and use dish soap for a lubricant .. it seemed to work really well ..
I am a hobby machinist .. had a lathe and mill years back and used all the proper oils etc .. but in this case didnt want to expose the pla to oils and I did that once on a part I was trying to wet sand .. and it appeared as though the pla absorbed some of the oil ..
Well that just gave me all kinds of thoughts and ideas as far as oil absorption goes .. lol
Maybe need to experiment with how much a piece of PLA will absorb if its even measureable ..
Anyways .. agree with all above .. and could give the dish soup a try in hopes that it will help lessen the amount of heat generated .. </p>
| 164
|
<p>I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share?</p>
<p>I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.</p>
|
<p>I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule.</p>
<pre><code>svnadmin hotcopy m:\Source\Q4Press\Repo m:\SvnOut\Q4Press
</code></pre>
<p>I use the hotcopy but the svn dump would work just as well.</p>
|
<p>svnadmin dump C:\SVNRepositorio\Repositorio > \\Backups\BkTmpSubversion\subversiontemp.dump</p>
<p>Try this.</p>
| 4,077
|
<p>I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in.</p>
<p>Essentially, I'm using the attachment-fu plugin on two levels.</p>
<ol>
<li>Is for user avatars in the user class.</li>
<li>Is to allow file attachments (<strong><em>PDFs</em></strong>, etc) in a messaging system.</li>
</ol>
<p>My question is what the best use practice would be in these situations to remain <strong><em>DRY</em></strong>, clear, and consistent.</p>
<p>Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class.</p>
<p>Is there something in between, or is the parent class the way to go?</p>
<p>Thanks!</p>
|
<p>Is "outsourcing" avatar support entirely to <a href="http://en.gravatar.com/" rel="nofollow noreferrer">Gravatar</a> an option? There are some Rails plugins that will display avatars hosted by Gravatar. You might not need to re-invent the wheel there.</p>
|
<p>Couldn't you use <a href="http://wiki.rubyonrails.org/rails/pages/UnderstandingPolymorphicAssociations" rel="nofollow noreferrer">Polymorphic Associations</a>?</p>
<p>I'm about to hit this in my app with attachment_fu, so I'm not exactly sure on attachment_fu, but for the old school <a href="http://wiki.rubyonrails.org/rails/pages/File+Column+Plugin" rel="nofollow noreferrer">File Column</a> plugin, I would use Polymorphic Associations.</p>
<p>My "file" model would be:</p>
<pre><code> class FileUpload < ActiveRecord::Base
belongs_to :fileable, :polymorphic => true
file_column :name
end
</code></pre>
<p>and then any models that needed a file attachment would be like:</p>
<pre><code> class Company < ActiveRecord::Base
has_many :file_uploads, :as => :fileable
end
</code></pre>
<p>File Column is no good anymore as it borks on Safari 3.x and is no longer maintained. It was nice and simple though... Ah, the good old days...</p>
| 4,032
|
<p>I have a query that originally looks like this:</p>
<pre><code>select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode
from dbo.Customer as c
left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id
left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id
where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%'
or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%')
</code></pre>
<p>On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing). </p>
<p>I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term.</p>
<p>Is there a way to do this in full-text search?</p>
<hr>
<p>@David</p>
<p>Yep, there are indexes on the Ids.</p>
<p>I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this.</p>
<p>Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still.</p>
|
<p>You've asked for the canonical reason why Boost::MultiIndex was made: list insertion order with fast lookup by key. <a href="http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/tutorial/basics.html#list_fast_lookup" rel="nofollow noreferrer">Boost MultiIndex tutorial: list fast lookup</a></p>
|
<p>@wesc: STL has std::map... so what's the difference with unordered_map? I don't think STL would implement twice the same thing and call it differently.</p>
| 5,656
|
<p>I tried printing a <a href="https://www.thingiverse.com/thing:2939079" rel="nofollow noreferrer">"improved" calibration cube</a> and noticed that the printer was laying down dots instead of a solid line. This was right after switching out my extruder motor and tweaking retraction settings. I believe my first setting was 0.3 mm, then I tried 0.1 mm. I didn't get a picture of the first setting, but shown below is when retraction was set to 0.1 mm. I think the print was at layer 3 roughly. The difference is 0.1 mm had a higher frequency of dotting, ie more dots that were closer together.</p>
<p>This was only present in the first couple of layers. The dots weren't occurring in the same spot so the picture shows dots overlapping each other making a sort of "twisted" or braided look. This also happened on both the x-axis movements and the right side of the y-axis movements. The rest of the cube came out relatively well.</p>
<h2>Settings</h2>
<ul>
<li><strong>Printer:</strong> Creality CR-10S</li>
<li><strong>Temp:</strong> 205 °C at nozzle; 60 °C on bed</li>
<li><strong>Retraction:</strong> 0.3 mm initially, 0.1 mm (pictured)</li>
<li><strong>Bed Distance:</strong> ~0.1 mm</li>
<li><strong>Nozzle Diameter:</strong> 0.4 mm</li>
<li><strong>Layer Height:</strong> 0.2 mm. I usually do 0.4, but I was lazy with slicer presets (AstroPrint)</li>
<li><strong>Hotend:</strong> e3D Hemera direct, e3D v6 heater and nozzle</li>
<li><strong>Filament:</strong> Hatchbox PLA white</li>
</ul>
<p>I never saw this issue before on my printer nor have I seen it mentioned in various articles/videos online.</p>
<p><a href="https://i.stack.imgur.com/usdSs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/usdSs.jpg" alt="Dotting when laying down initial layers"></a></p>
|
<p>I have seen this a lot of times on my tronXY-X1 with an e3d-v6 via Bowden tube. It is <em>not</em> related to retraction but a different settin: Your first layer is set too thin or not leveled to the right height. </p>
<p>Having the first layer too thin, means that with a tiny error, the calculated correct extrusion becomes either a massive overextrusion or a barely sticking underextrusion. For example, the repeatability of the probing is the biggest error source. A well calibrated probing might varry about 0.05 mm between extremes, so would be written as (layer thickness)+-0.025 mm. On a 0.1 mm layer, that is a 25 % over- or underextrusion; overextrusion of that degree is well known to create such ripples.</p>
<p>Setting it to 0.2 mm for the first layer in Cura, Slic3r and PrusaSlic3r (look in your advanced settings!) did eliminate such rippling for me. My understanding is, that the extra distance gives the filament better ability to flow and stick on this first layer. Also, remember to set your line width to ca. 10 % wider than the nozzle - 0.45 mm is my typical setting.</p>
|
<p>It's not about printing settings but only about the bed: the bed is too close to the nozzle.</p>
<p>Maybe you adjusted it when it was cold, instead of doing it when it's already heated to the desired temperature and the nozzle is heated at about 180°C to get close to operating temperature without oozing.</p>
<p>Or maybe you used a too thin paper sheet.</p>
| 1,561
|
<p>What are good libraries for C with datastructures like vectors, deques, stacks, hashmaps, treemaps, sets, etc.? Plain C, please, and platform-independent.</p>
|
<p>The <a href="http://library.gnome.org/devel/glib/stable/" rel="noreferrer">Glib</a> library used on the Gnome project may also be some use. Moreover it is pretty well tested.</p>
<p>IBM developer works has a good tutorial on its use: <a href="https://www.ibm.com/developerworks/linux/tutorials/l-glib/" rel="noreferrer">Manage C data using the GLib collections</a></p>
|
<p>Maybe <a href="http://sglib.sourceforge.net/" rel="nofollow noreferrer">http://sglib.sourceforge.net/</a> if you want an easy to use, very fast, macro based library.</p>
| 2,467
|
<p>When manually controlling the z-axis in reprap, it works fine. If I use the home button, it doesn't move. Instead, it stalls/freezes/hangs. It attempts to turn, but can't successfully make a full turn. </p>
|
<p>lower the moving speed of the Z-axis motor, search for </p>
<blockquote>
<p>homing feed rate</p>
</blockquote>
<p>in config.h as it looks like the given speed is to high.</p>
|
<p>Looks like endstop signal for Z is inverted. In this case Z will move in manual mode but when homing it will try and stop as limit detected immediately. Change Z_MIN_ENDSTOP_INVERTING to opposite value.</p>
| 1,030
|
<p>I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p>
<p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
|
<p>In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking:</p>
<p><strong>How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?</strong></p>
<p>A fairly straight forward solution that you already mentioned is the <em>sp_xml_preparedocument</em>, combined with <em>openxml</em>. </p>
<p>Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on <a href="http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx" rel="nofollow noreferrer">Using OPENXML</a>.</p>
<pre><code>declare @XmlDocumentHandle int
declare @XmlDocument nvarchar(1000)
set @XmlDocument = N'<ROOT>
<Customer>
<FirstName>Will</FirstName>
<LastName>Smith</LastName>
</Customer>
</ROOT>'
-- Create temp table to insert data into
create table #Customer
(
FirstName varchar(20),
LastName varchar(20)
)
-- Create an internal representation of the XML document.
exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument
-- Insert using openxml allows us to read the structure
insert into #Customer
select
FirstName = XmlFirstName,
LastName = XmlLastName
from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 )
with
(
XmlFirstName varchar(20) 'FirstName',
XmlLastName varchar(20) 'LastName'
)
where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' )
-- Cleanup xml document
exec sp_xml_removedocument @XmlDocumentHandle
-- Show the data
select *
from #Customer
-- Drop tmp table
drop table #Customer
</code></pre>
<p>If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a <em>string</em> should give you a fairly straight forward way of importing xml into your existing table(s).</p>
|
<p>If your XML conforms to a particular XSD schema, you can look into using the "xsd.exe" command line tool to generate C# object classes that you can bind the XML to, and then form your insert statements using the properties of those objects: <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx" rel="nofollow noreferrer">MSDN XSD Doc</a></p>
| 8,449
|
<p>On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day <em>after</em> the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.</p>
<p>Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?</p>
|
<p>I'm not a fan of putting java code in your jsp.</p>
<p>I'd use a static method and a taglib to accomplish this.</p>
<p>Just my idea though. There are many ways to solve this problem.</p>
<pre><code>public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
</code></pre>
<p>functions.tld</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>functions library</description>
<display-name>functions</display-name>
<tlib-version>1.1</tlib-version>
<short-name>xfn</short-name>
<uri>http://yourdomain/functions.tld</uri>
<function>
<description>
Adds 1 day to a date.
</description>
<name>addDay</name>
<function-class>Functions</function-class>
<function-signature>java.util.Date addDay(java.util.Date)</function-signature>
<example>
${xfn:addDay(date)}
</example>
</function>
</taglib>
</code></pre>
|
<p>Unfortunately there is no tag in the standard JSP/JSTL libraries that I know of that would allow you to do this date calculation.</p>
<p>The simplest, and most inelegant, solution is to just use some scriptlet code to do the calculation. You've already stated that you think this is a clunky solution, and I agree with you. I would probably write a custom JSP taglib to get this if I were you.</p>
| 9,991
|
<p>Lately I've been having a lot of trouble with printing overhangs in TPU. The failures are very geometry/toolpath dependent, entirely reproducible in their location (same gcode gives same failures each time it's printed), and seem to occur where there is a convex (model-inward) curve over an overhang of more than 40° or so. My original test case for this was frog model with more severe overhang, but I since made a simplified conical overhang test piece at only 50° that's faster to reprint and shows the issue:</p>
<p><a href="https://i.stack.imgur.com/2Ny6d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Ny6d.jpg" alt="Two upside-down 3D printed frogs" /></a></p>
<p>The frog print on the left is pretty much a complete failure. The one on the right is mostly a success, but shows some moderate flaws around one side (left, as viewed) and the front of the belly, and even slight flaws (hard to see in pic) around the other side of the belly. It was done using some of the mitigations described below.</p>
<p><a href="https://i.stack.imgur.com/Ei5Lh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ei5Lh.jpg" alt="3 elongated conical test pieces - convex hull of two translations of a truncated cone with 8 mm diameter at bottom, rising 50°, turned upside down to show overhang print problems" /></a></p>
<p>The test piece on the left is nearly perfect. The other two show varying degrees of the overhang problem I'm experiencing, and make it easier to see what exactly is happening than with the frog. The extrusion seems to bunch up, then get stretched out too thin, in an oscillating pattern that builds up and shifts with each layer.</p>
<p>I've tried printing overhangs significantly slower and reducing speed and acceleration quite a bit on the outer walls and even on the inner walls too, and none of that seems to help. Nor does increasing the number of walls or the wall line thickness help. However a number of things do seem to help, and it takes two or more of these in combination to get a mostly acceptable result at 0.2 mm layer height:</p>
<ul>
<li>Increasing flow to a level where the extruded mass is the expected amount (this makes wall dimensions excess so I usually don't do it)</li>
<li>Taking the infill up to 20% or higher and using an infill pattern where the infill meets the walls frequently (gyroid 20% or more seems best; I'm trying not to do this because I want to final objects to be more flexible in some cases)</li>
<li>Increasing Klipper square corner velocity to 30+ so that the entire approximated curves are traversed at constant speed with no acceleration/deceleration</li>
<li>Increasing Klipper PA smooth time window from 10ms to 40ms</li>
</ul>
<p>Generally I'm able to choose some subset of the above that works, but it ends up being a matter of per-model trial-and-error, wasting lots of time and materials if the settings don't work, so I'd like to figure out what's really going on here so I can make predictions about what will work and ideally get a base configuration that "always" works. Also, I still don't have this working at thinner layer heights, which I'd like to be able to use for better detail, as TPU is flow-bound not motion-bound and I could in theory print much higher detail at the same speed with thinner layers.</p>
<p>My best guess at the root cause so far is that the overhanging walls simply do not have enough rigidity to avoid being displaced by the toolhead attempting to extrude against them, so any oscillation of the toolhead velocity or extrusion pressure causes them to deform in the pattern of the oscillation. Does this seem plausible, and if so, what might some other possible mitigations be?</p>
<p>For completeness, my printer is a heavily modified Ender 3 with (remote) direct drive extruder and fairly extreme cooling, but turning the cooling way down or even off (assuming sufficient layer time for passive cooling) does not seem to affect the behavior here significantly. So I think the question is mostly printer-agnostic and is really a matter of material behavior and slicing.</p>
|
<p>The root cause was a badly worn nozzle.</p>
<p>The problem described in this question gradually became more and more severe and began affecting PLA and PET prints with thin layers too. Eventually I traced it to the CHT nozzle, by swapping in a 50¢ plain brass nozzle, and found someone with otherwise very similar extrusion system to test on their CHT and confirm that the prints giving me problems came out fine for them. Replacing my CHT with a new one has now made it all better. My old one was roughly 0.16 mm shorter (by difference in Z offset) presumably from wear, and to look at the orifice, it was probably nearly 0.8 mm wide. If so, it was like trying to print 0.4 mm lines with an 0.8 mm nozzle, which is expected to fail moderately to badly, especially on overhangs. And this explains why increasing flow (or, as I later tried and had success with, using wider line widths) partly succeeded.</p>
<p>I did still have a minor variant of the problem with TPU after switching to the new nozzle, before recalibrating pressure advance, which I'd calibrated down somewhat before (due to less pressure with an excessively wide orifice). After recalibrating, the problem seems to be entirely gone.</p>
<p>I still don't want to discount the factors I found before. It seems very plausible that this could come back whenever TPU is being printed without a firm surface to extrude against. In my case, the primary mechanism of that seems to have been a nozzle whose opening was excessively wide from wear, but the same should still happen if the wall is wobbling from lack of reinforcement.</p>
|
<p>I fixed my overhangs by increasing the nozzle temp. You need to heat it up enough that the elasticity is lost which makes it misbehave on overhangs and curl up.</p>
| 2,174
|
<p>I got this message from my Creality Ender 6 printer.</p>
<p>Now every time I want to print, or when it heats up, the printer gives me this message.</p>
<p>Can anyone please help with this?</p>
<p><a href="https://i.stack.imgur.com/oCLzI.jpg" rel="nofollow noreferrer" title="Heating failed error"><img src="https://i.stack.imgur.com/oCLzI.jpg" alt="Heating failed error" title="Heating failed error" /></a></p>
|
<p>I've seen a version of this error on my Ender 3 when I heated the hot end without the silicone sock (or any other insulating wrap).</p>
<p>If this occurred after changing a nozzle, replacing a heat break (or entire hot end), installing a new cooling duct, or similar, it's likely you just inadvertently left off the insulation that should surround the heat block, making it take much longer and require much more power to reach working temperature than is normal.</p>
<p>This can also occur if the thermistor or heater cartridge are not correctly seated in the heat block -- the same problems that can result in a thermal runaway halt (assuming your printer has that feature) if it does get to temperature before timing out.</p>
|
<p>Someone with experience using an Ender may give a more specific answer to you question. This is a general answer, not for a specific model.</p>
<p>"Soon enough" is saying the printer timed out before reaching temperature.</p>
<ol>
<li><p>Do you see the temperature increasing on both the hot end and bed? If one doesn't, that's where the failure occurs.</p>
</li>
<li><p>Are you setting a temperature higher than you have ever used on this printer? If so, check to see if you are beyond the printers capability.</p>
</li>
<li><p>The hotend will reach temperature first. Does it reach the target temperature? If so, the issue is probably with your bed heater. If not, the issue is with your hot end.</p>
</li>
<li><p>If you are pushing the extremes of your heaters, especially the bed heater, and your printer isn't in an enclose, you may need and enclosure to run that temperature.</p>
</li>
</ol>
<p>Once you determine where the issue is at, there are things to can do to determine what is failing.</p>
| 1,848
|
<p>I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx" rel="noreferrer" title="MSDN">System.Text.RegularExpressions.Regex.Replace()</a> is what you seek - IF your tokens are odd enough that you need a regex to find them.</p>
<p><a href="http://blogs.msdn.com/debuggingtoolbox/archive/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance.aspx" rel="noreferrer">Some kind soul did some performance testing</a>, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.</p>
|
<p>This is an ideal use of Regular Expressions. Check out <a href="http://regular-expressions.info" rel="nofollow noreferrer">this helpful website</a>, the <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx" rel="nofollow noreferrer">.Net Regular Expressions class</a>, and this very helpful book <a href="http://books.google.com/books?id=ucwR4KIvExMC" rel="nofollow noreferrer">Mastering Regular Expressions</a>.</p>
| 4,063
|
<p>How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?</p>
<p><strong>Edit due to camainc's answer:</strong> I also have a constraint that I have to have all the code in a single project.</p>
<p><strong>Edit to finalise question:</strong> As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.</p>
|
<p>I'm not sure if this is what you are asking, but this is how we do it.</p>
<p>We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.</p>
<p>Each solution gets a namespace like this:</p>
<pre><code>[CompanyName].[SolutionName].[ProjectName]
</code></pre>
<p>So, our user controls are normally in a project called "Controls," which would have a namespace of:</p>
<pre><code>OurCompany.ThisSolution.Controls
</code></pre>
<p>If we have controls that might span several different solutions, we just namespace it like so:</p>
<pre><code>OurCompany.Common.Controls
</code></pre>
<p>Then, in our code we will import the library, or add the project to the solution.</p>
<pre><code>Imports OurCompany
Imports OurCompany.Common
Imports OurCompany.Common.Controls
</code></pre>
<p>We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):</p>
<p>\Projects<br>
\Projects\MySolution<br>
\Projects\MySolution\Controls</p>
<p>-- or --</p>
<p>\Projects\<br>
\Projects\Common<br>
\Projects\Common\Assemblies<br>
\Projects\Common\Controls</p>
<p>etc.</p>
<p>Hope that helps...</p>
|
<p>Do you mean you want to be able to access user controls at runtime (in code) via </p>
<blockquote>
<p><code>[ProjectNamespace].[YourSpecialNamespace].Controls</code></p>
</blockquote>
<p>rather than the default of </p>
<blockquote>
<p><code>[ProjectNamespace].Controls</code></p>
</blockquote>
<p>? Because I don't believe that is possible. If I'm not mistaken, the <code>Controls</code> collection of your project/app is built-in by the framework - you can't change it. You can, as camainc noted, use the project settings window (or code) to place the controls themselves in a specific namespace thusly:</p>
<blockquote>
<p><code>Namespace [YourSpecialNamespace]</code></p>
<p><code>Public Class Form1</code></p>
<p><code>[...]</code></p>
<p><code>End Class</code></p>
<p><code>End Namespace</code></p>
</blockquote>
<p>Of course, thinking about it some more, I suppose you could design and build your own <code>Controls</code> collection in your namespace - perhaps as a wrapper for the built-in one... </p>
| 8,808
|
<p>What is BODMAS and why is it useful in programming?</p>
|
<p><a href="http://www.easymaths.com/What_on_earth_is_Bodmas.htm" rel="noreferrer">http://www.easymaths.com/What_on_earth_is_Bodmas.htm</a>:</p>
<blockquote>
<p>What do you think the answer to 2 + 3 x 5 is?</p>
<p>Is it (2 + 3) x 5 = 5 x 5 = 25 ?</p>
<p>or 2 + (3 x 5) = 2 + 15 = 17 ?</p>
<p>BODMAS can come to the rescue and give us rules to follow so that we always get the right answer:</p>
<p>(B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction</p>
<p>According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 .</p>
</blockquote>
<p>Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this:</p>
<pre><code>result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER;
</code></pre>
<p>with BODMAS you can make this a bit clearer:</p>
<pre><code>result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;
</code></pre>
<p>I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors?</p>
<p>Just guessing at that part though.</p>
<p>Mike Stone EDIT: Fixed math as Gaius points out</p>
|
<p>I read somewhere that especially in C/C++ splitting your expressions into small statements was better for optimisation; so instead of writing hugely complex expressions in one line, you cache the parts into variables and do each one in steps, then build them up as you go along.</p>
<p>The optimisation routines will use registers in places where you had variables so it shouldn't impact space but it can help the compiler a little.</p>
| 2,561
|
<p>I am currently writing a small calendar in ASP.Net C#. Currently to produce the rows of the weeks I do the following for loop:</p>
<pre><code>var iWeeks = 6;
for (int w = 0; w < iWeeks; w++) {
</code></pre>
<p>This works fine, however, some month will only have 5 weeks and in some rare cases, 4.</p>
<p>How can I calculate the number of rows that will be required for a particular month?</p>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
<hr>
<p>This is an example of what I am creating:</p>
<p><img src="https://i.stack.imgur.com/NkxN7.png" alt="enter image description here"></p>
<p>As you can see for the above month, there are only 5 rows required, however. Take the this month (August 2008) which started on a Saturday and ends on a Monday on the 6th Week/Row.</p>
<p><strong><em>Image found on google</em></strong></p>
|
<p>Here is the method that does it:</p>
<pre><code>public int GetWeekRows(int year, int month)
{
DateTime firstDayOfMonth = new DateTime(year, month, 1);
DateTime lastDayOfMonth = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);
System.Globalization.Calendar calendar = System.Threading.Thread.CurrentThread.CurrentCulture.Calendar;
int lastWeek = calendar.GetWeekOfYear(lastDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
int firstWeek = calendar.GetWeekOfYear(firstDayOfMonth, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return lastWeek - firstWeek + 1;
}
</code></pre>
<p>You can customize the calendar week rule by modifying the System.Globalization.CalendarWeekRule.FirstFourDayWeek part. I hope the code is self explanatory.</p>
|
<p>How about checking which week the first and last days will be in?</p>
| 3,116
|
<p>What does it mean when you get or create a date in UTC format in JavaScript?</p>
|
<p>A date represents a specific point in time. This point in time will be called differently in different places. As I write this, it's 00:27 on Tuesday in Germany, 23:27 on Monday in the UK and 18:27 on Monday in New York.</p>
<p>To take an example method: getDay returns the day of the week in the local timezone. Right now, for a user in Germany, it would return 2. For a user in the UK or US, it would return 1. In an hour's time, it will return 2 for the user in the UK (because it will then be 00:27 on Tuesday there).</p>
<p>The ..UTC.. methods deal with the representation of the time in UTC (also known as GMT). In winter, this is the same timezone as the UK, in summer it's an hour behind the time in the UK.</p>
<p>It's summer as I write this. getUTCDay will return 1 (Monday), getUTCHours will return 22, getUTCMinutes will return 27. So it's 22:27 on Monday in the UTC timezone. Whereas the plain get... functions will return different values depending on where the user is, the getUTC.. functions will return those same values no matter where the user is.</p>
|
<p>getUTC is for converting times to Coordinated Universal Time (UTC, the acronym is ordered differently than what it stands for) which is the standard time based on the time in Greenwich, London.</p>
<p>The universal time is calculated using a time offset (in minutes when in JavaScript.) This offset is based on the time zone configured on the client browser's operating system.</p>
<p>If you plan on storing dates for users in multiple time zones, this is what you should use.</p>
| 3,610
|
<p>Is there any free or commercial component written in .NET (no COM interop) that will work with most twain scanners?</p>
|
<blockquote>
<h3><a href="https://github.com/tmyroadctfig/twaindotnet" rel="noreferrer">TwainDotNet</a></h3>
</blockquote>
<p>I've just wrapped up the code from Thomas Scheidegger's article (<a href="http://www.codeproject.com/KB/dotnet/twaindotnet.aspx" rel="noreferrer">CodeProject: .NET TWAIN image scanning</a>) into a Google code project: <a href="https://github.com/tmyroadctfig/twaindotnet" rel="noreferrer">http://code.google.com/p/twaindotnet/</a></p>
<p>I've cleaned up the API a bit and added WPF support, so check it out. :)</p>
|
<p>Just started a project in .net and found great info <a href="http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=60471" rel="nofollow noreferrer">here</a> (*dead link as of Feb 2014) about using Windows Image Acquisition. Lots of sample VB code and some c#.</p>
| 6,032
|
<p>I'm troubleshooting a problem with creating Vista shortcuts.</p>
<p>I want to make sure that our Installer is reading the Programs folder from the right registry key.</p>
<p>It's reading it from:</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Programs
</code></pre>
<p>And it's showing this directory for Programs:</p>
<pre><code>C:\Users\NonAdmin2 UAC OFF\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
</code></pre>
<p>From what I've read, this seems correct, but I wanted to double check.</p>
|
<p>Don't use the registry to read this. Use <a href="http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx" rel="nofollow noreferrer">SHGetFolderPath</a> with CSIDL_PROGRAMS.</p>
<p>For a reason why, see Raymond Chen's comments on the "Shell Folders" key:</p>
<p><a href="http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx</a></p>
|
<p>Sounds correct to me.</p>
| 8,228
|
<p>Is it okay to directly connect together the grounds of the logic supply and the motor supply when using a Pololu style stepper driver?</p>
<p><a href="https://i.stack.imgur.com/yijCn.jpg" rel="nofollow noreferrer" title="A4988 connection schematic"><img src="https://i.stack.imgur.com/yijCn.jpg" alt="A4988 connection schematic" title="A4988 connection schematic"></a></p>
<p>If yes/no, why so?</p>
|
<p>That depends on how much noise you have on your motor power supply ground. You definitely want the 100 µF capacitor to have a good high frequency response. Motors turning on and off can be noisy, and that noise can cause false clock signals in your logic circuitry if you tie the grounds together. </p>
|
<p>That depends on how much noise you have on your motor power supply ground. You definitely want the 100 µF capacitor to have a good high frequency response. Motors turning on and off can be noisy, and that noise can cause false clock signals in your logic circuitry if you tie the grounds together. </p>
| 1,341
|
<p>I'm sure this is easy but I can't figure it out:</p>
<p>I have an ASP.NET page with some UpdatePanels on it. I want the page to <em>completely</em> load with some 'Please wait' text in the UpdatePanels. Then once the page is <em>completely loaded</em> I want to call a code-behind function to update the UpdatePanel.</p>
<p>Any ideas as to what combination of Javascript and code-behind I need to implement this idea?</p>
<p>SAL</p>
<p>PS: I've tried putting my function call in the Page_Load but then code is run <em>before</em> the page is delivered and, as the function I want to run takes some time, the page simply takes too long to load up.</p>
|
<p>I fiddled around with the ScriptManager suggestions - which I reckon I would have eventually got working but it seems to me that the Timer idea is easier to implement and not really(!) that much of a hack?!</p>
<p>Here's how I got my panel updated <em>after</em> the initial page render was complete...</p>
<p>default.aspx</p>
<pre><code> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAXPostLoadCall._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<h2>And now for a magic trick...</h2>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="2000" ontick="Timer1_Tick" />
<asp:Label ID="Label1" runat="server">Something magic is about to happen...</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
</code></pre>
<p>and the code behind default.aspx.cs reads</p>
<pre><code>using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace AJAXPostLoadCall
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void DoMagic()
{
Label1.Text = "Abracadabra";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
// Do the magic, then disable the timer
DoMagic();
Timer1.Enabled = false;
}
}
}
</code></pre>
<p>So, the page loads up and the Timer (contained within the UpdatePanel) fires 2 secs after the page has loaded up (I think - I'm not sure when the Timer actually starts?). The label text is rewritten and then the Timer is disabled to stop any more updates.</p>
<p>Simple enough - but can you purists out there tell me if this is a Horrible Hack?</p>
|
<p>The ScriptManager.RegisterStartupScript allows a script to run on startup inside of an update panel. if you use the old ClientScript.RegisterStartupScript then the script you render will be outside the bounds of the udpate panel, and thus won't be executed during async page loads.</p>
| 5,191
|
<p>Are there any specific type of FDM 3D printers that I should look for?</p>
|
<p>and welcome to 3D Printing Stack Exchange.</p>
<p>No. Not all 3D printers can print flexible material.</p>
<p>The first place you will have trouble is in the extruder itself. Flexible filament will find any way to escape from the confines of the rollers and the guide tube. Any opening will allow the filament to buckle and find a new path. It is common to find that the filament has filled any gaps inside the extruder, and wrapped itself tightly around the drive roller.</p>
<p>@0scar describes this in <a href="https://3dprinting.stackexchange.com/a/6761/5740">his answer</a>. If the extruder does not have tight tolerances, with 1/4mm or less clearance between the drive roller on all sides, AND if there isn't a tube mated right up into the place where the filament is pressed between the drive roller and the idler, your extruder will fail to print Ninjaflex (a very flexible filament).</p>
<p>Oscar also mentions that Bowden feed doesn't work well. It is fundamentally the same buckling problem. There is always a gap around the filament inside the Bowden tube. A still filament will rub at some points, but a soft filament will compress and ripple, filling the entire lumen inside the tube, and greatly increasing the friction. Higher friction means more extruder pressure, so more buckling, more friction, and more failure.</p>
<p>Even if you are lucky and don't experience the run-away friction problem, the flexible filament is more compressible. With a Bowden feed system, that compression must be preloaded at the beginning of each extrusion movement and relieved for each retraction. With direct drive, the filament also compresses, but the amount of filament is much less, so the compression is less, and the problems are less.</p>
|
<p>Not all printers are suitable to print flexible filament. E.g. 1.75 mm filament printers with a Bowden extruder/hotend combination will not work (you may have more luck using 2.85 mm filament, which is stiffer because of the increased diameter). For 1.75 mm filament you require a direct drive extruder, e.g. with the stepper mounted onto the hotend, even then some additional guide parts need to be printed to make it work. This also depends on the amount of flexibility of the filament, some are more flexible than others.</p>
<hr>
<p>E.g. Ultimaker 3D printers use 2.85 mm filament with a Bowden setup. They also sell a flexible filament that can be printed with these printers. Even for direct drive extruder printers like the Anet A8 (a cheap Chinese Prusa i3 clone) inserts exist (e.g. <a href="https://www.thingiverse.com/thing:1829810" rel="nofollow noreferrer">this</a> or <a href="https://www.thingiverse.com/thing:2217215" rel="nofollow noreferrer">this one</a>) to even better guide the filament to prevent it to buckle. </p>
| 1,019
|
<p>I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?</p>
|
<p>What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes. </p>
<p>First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing <code>int x</code> you will write <code>(int) x</code>. Here are some handy macros to help with typed expressions:</p>
<pre><code>#define REM(...) __VA_ARGS__
#define EAT(...)
// Retrieve the type
#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)
#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)
#define DETAIL_TYPEOF_HEAD(x, ...) REM x
#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),
// Strip off the type
#define STRIP(x) EAT x
// Show the type without parenthesis
#define PAIR(x) REM x
</code></pre>
<p>Next, we define a <code>REFLECTABLE</code> macro to generate the data about each field(plus the field itself). This macro will be called like this:</p>
<pre><code>REFLECTABLE
(
(const char *) name,
(int) age
)
</code></pre>
<p>So using <a href="http://www.boost.org/doc/libs/1_49_0/libs/preprocessor/doc/index.html" rel="noreferrer">Boost.PP</a> we iterate over each argument and generate the data like this:</p>
<pre><code>// A helper metafunction for adding const to a type
template<class M, class T>
struct make_const
{
typedef T type;
};
template<class M, class T>
struct make_const<const M, T>
{
typedef typename boost::add_const<T>::type type;
};
#define REFLECTABLE(...) \
static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \
friend struct reflector; \
template<int N, class Self> \
struct field_data {}; \
BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))
#define REFLECT_EACH(r, data, i, x) \
PAIR(x); \
template<class Self> \
struct field_data<i, Self> \
{ \
Self & self; \
field_data(Self & self) : self(self) {} \
\
typename make_const<Self, TYPEOF(x)>::type & get() \
{ \
return self.STRIP(x); \
}\
typename boost::add_const<TYPEOF(x)>::type & get() const \
{ \
return self.STRIP(x); \
}\
const char * name() const \
{\
return BOOST_PP_STRINGIZE(STRIP(x)); \
} \
}; \
</code></pre>
<p>What this does is generate a constant <code>fields_n</code> that is number of reflectable fields in the class. Then it specializes the <code>field_data</code> for each field. It also friends the <code>reflector</code> class, this is so it can access the fields even when they are private:</p>
<pre><code>struct reflector
{
//Get field_data at index N
template<int N, class T>
static typename T::template field_data<N, T> get_field_data(T& x)
{
return typename T::template field_data<N, T>(x);
}
// Get the number of fields
template<class T>
struct fields
{
static const int n = T::fields_n;
};
};
</code></pre>
<p>Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor:</p>
<pre><code>struct field_visitor
{
template<class C, class Visitor, class I>
void operator()(C& c, Visitor v, I)
{
v(reflector::get_field_data<I::value>(c));
}
};
template<class C, class Visitor>
void visit_each(C & c, Visitor v)
{
typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range;
boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));
}
</code></pre>
<p>Now for the moment of truth we put it all together. Here is how we can define a <code>Person</code> class that is reflectable:</p>
<pre><code>struct Person
{
Person(const char *name, int age)
:
name(name),
age(age)
{
}
private:
REFLECTABLE
(
(const char *) name,
(int) age
)
};
</code></pre>
<p>Here is a generalized <code>print_fields</code> function using the reflection data to iterate over the fields:</p>
<pre><code>struct print_visitor
{
template<class FieldData>
void operator()(FieldData f)
{
std::cout << f.name() << "=" << f.get() << std::endl;
}
};
template<class T>
void print_fields(T & x)
{
visit_each(x, print_visitor());
}
</code></pre>
<p>An example of using the <code>print_fields</code> with the reflectable <code>Person</code> class:</p>
<pre><code>int main()
{
Person p("Tom", 82);
print_fields(p);
return 0;
}
</code></pre>
<p>Which outputs:</p>
<pre><code>name=Tom
age=82
</code></pre>
<p>And voila, we have just implemented reflection in C++, in under 100 lines of code. </p>
|
<p>If you declare a pointer to a function like this:</p>
<pre><code>int (*func)(int a, int b);
</code></pre>
<p>You can assign a place in memory to that function like this (requires <code>libdl</code> and <code>dlopen</code>)</p>
<pre><code>#include <dlfcn.h>
int main(void)
{
void *handle;
char *func_name = "bla_bla_bla";
handle = dlopen("foo.so", RTLD_LAZY);
*(void **)(&func) = dlsym(handle, func_name);
return func(1,2);
}
</code></pre>
<p>To load a local symbol using indirection, you can use <code>dlopen</code> on the calling binary (<code>argv[0]</code>).</p>
<p>The only requirement for this (other than <code>dlopen()</code>, <code>libdl</code>, and <code>dlfcn.h</code>) is knowing the arguments and type of the function.</p>
| 6,275
|
<p>Is there an equivalent operator to Haskell's list difference operator <code>\\</code> in F#?</p>
|
<p>Was bounced, yet I believe it is worth to write here the implementation of <code>( /-/ )</code> (the F# version of Haskell's <code>\\</code>):</p>
<pre><code>let flip f x y = f y x
let rec delete x = function
| [] -> []
| h :: t when x = h -> t
| h :: t -> h :: delete x t
let inline ( /-/ ) xs ys = List.fold (flip delete) xs ys
</code></pre>
<p>This will operate as Haskell's <code>\\</code>, so that <code>(xs @ ys) /-/ xs = ys</code>. For example: <code>(7 :: [1 .. 5] @ [5 .. 11]) /-/ [4 .. 7]</code> evaluates into <code>[1; 2; 3; 5; 7; 8; 9; 10; 11]</code>.</p>
|
<p>Assuming you really want conventional set difference rather than the weird ordered-but-unsorted multiset subtraction that Haskell apparently provides, just convert the lists to sets using the built-in <code>set</code> function and then use the built-in <code>-</code> operator to compute the set difference:</p>
<pre><code>set xs - set ys
</code></pre>
<p>For example:</p>
<pre><code>> set [1..5] - set [2..4];;
val it : Set<int> = seq [1; 5]
</code></pre>
| 8,438
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.