instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>I'm looking for a c# snippet which I can insert in a Windows service. The code must empty the recycle bin for all users on the computer.</p> <p>I have previously tried using <code>SHEmptyRecycleBin</code> (ref <a href="http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/Empty_Recycle_Bin.aspx</a>) however the code doesn't work when ran from a windows service as the service is running with local system privileges.</p>
<p>I think doing something like this is against Microsoft recommended practices. What are you trying to do that requires emptying the Recycle Bin from a Windows service?</p>
<p>First, have you tried running the service on an interactive user account? Maybe SHEmptyRecycleBin requires an interactive user even though it doesn't necessarily display a Window.</p> <p>Second, I'm not sure it's a good idea to delete other users' stuff but I guess you have a very good reason?</p>
3,009
<p>How do I detect if the system has a default recording device installed? I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p> <p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
<p>Using the <a href="https://www.microsoft.com/en-in/download/details.aspx?id=6812" rel="nofollow noreferrer">DirectX SDK</a>, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device".</p> <p>If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs:</p> <pre><code>#include &lt;tchar.h&gt; #include &lt;windows.h&gt; #include "mmsystem.h" int _tmain( int argc, wchar_t *argv[] ) { UINT deviceCount = waveInGetNumDevs(); if ( deviceCount &gt; 0 ) { for ( int i = 0; i &lt; deviceCount; i++ ) { WAVEINCAPSW waveInCaps; waveInGetDevCapsW( i, &amp;waveInCaps, sizeof( WAVEINCAPS ) ); // do some stuff with waveInCaps... } } return 0; } </code></pre>
<p>There is an Open Source Audio API called <a href="http://www.portaudio.com/" rel="nofollow noreferrer">PortAudio</a> that has a method you could use. I think the method is called Pa_GetDeviceInfo() or something.</p>
6,263
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css">Avoiding repeated constants in CSS</a> </p> </blockquote> <p>We have some "theme colors" that are reused in our CSS sheet.</p> <p>Is there a way to set a variable and then reuse it?</p> <p>E.g.</p> <pre><code>.css OurColor: Blue H1 { color:OurColor; } </code></pre>
<p>There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so <em>flip it around</em>:</p> <pre><code>/* Theme color: text */ H1, P, TABLE, UL { color: blue; } /* Theme color: emphasis */ B, I, STRONG, EM { color: #00006F; } /* ... */ /* Theme font: header */ H1, H2, H3, H4, H5, H6 { font-family: Comic Sans MS; } /* ... */ /* H1-specific styles */ H1 { font-size: 2em; margin-bottom: 1em; } </code></pre> <p>This way, you avoid repeating styles that are <em>conceptually</em> the same, while also making it clear which parts of the document they affect. </p> <p>Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: <strong>two attributes sharing the same value does not necessarily mean they represent the same <em>concept</em></strong>. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors <em>will</em> vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will <em>always</em> share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid <em>value</em> repetition risks making future changes to styling incredibly error-prone; always focus on the <em>contextual meaning</em> of styles when looking to reduce repetition, ignoring their <em>current values</em>. </p>
<p>CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.</p> <p>Here are two major approaches to achieve more dynamic style handling:</p> <ul> <li>Server-side variables in inline css<br> Example (using PHP): <blockquote> <p><code>&lt;style&gt; .myclass{color:&lt;?php echo $color; ?&gt;;} &lt;/style&gt;</code></p> </blockquote></li> </ul> <p>&nbsp;</p> <ul> <li><p>DOM manipulation with javascript to change css client-side<br> Examples (using jQuery library):</p> <blockquote> <p><code>$('.myclass').css('color', 'blue');</code> </p> <p>OR</p> <p><code>//The jsvarColor could be set with the original page response javascript<br> // in the DOM or retrieved on demand (AJAX) based on user action. $('.myclass').css('color', jsvarColor);</code></p> </blockquote></li> </ul>
6,976
<p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher? Open CD tray exists, but I can't seem to make it close especially under W2k. </p> <p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
<p>Here is an easy way using the Win32 API:</p> <pre><code> [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)] protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback); public void OpenCloseCD(bool Open) { if (Open) { mciSendString("set cdaudio door open", null, 0, IntPtr.Zero); } else { mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero); } } </code></pre>
<p>To close the drive tray do as described <a href="https://stackoverflow.com/a/30512979/3969362">here</a> but instead of using DeviceIoControl with IOCTL_STORAGE_EJECT_MEDIA you need to call DeviceIoControl with IOCTL_STORAGE_LOAD_MEDIA.</p>
8,308
<p>This problem started <a href="http://forums.asp.net/t/1304033.aspx" rel="nofollow noreferrer">on a different board</a>, but <a href="https://stackoverflow.com/users/60/dave-ward">Dave Ward</a>, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p>Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">a nice article about using JavaScript</a>. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.</p> <p>I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like <code>Page.Response.BufferOutput = False</code>. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?</p> <p>For reference, a link to the working version of a simpler version of my application is located @ <a href="http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx" rel="nofollow noreferrer">http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx</a> and the same version that isn't working is located @ <a href="http://www.tabroom.org/Ajaxfun/Default.aspx" rel="nofollow noreferrer">http://www.tabroom.org/Ajaxfun/Default.aspx</a>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad.</p>
<p>Hey, Jason. Sorry you're still having trouble with this.</p> <p>What I would do is set up a simple page like:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { for (int i = 0; i &lt; 10; i++) { Response.Write(i + "&lt;br /&gt;"); Response.Flush(); Thread.Sleep(1000); } } </code></pre> <p>As we discussed before, make sure the .aspx file is empty of any markup other than the @Page declaration. That can sometimes trigger page buffering when it wouldn't have normally happened.</p> <p>Then, point the tech support guys to that file and describe the desired behavior (10 updates, 1 per second). I've found that giving them a simple test case goes a long way toward getting these things resolved.</p> <p>Definitely let us know what it ends up being. I'm guessing some sort of inline caching or reverse proxy, but I'm curious.</p>
<p>I don't know that you can force buffering - but a reverse proxy server between you and the server would affect buffering (since the buffer then affects the proxy's connection - not your browser's).</p>
4,446
<p>How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?</p>
<p>Another little nugget that I think will help people developing and being more productive in their database development. I am a fan of stored procedures and functions when I develop software solutions. I like my actual CRUD methods to be implemented at the database level. It allows me to balance out my work between the application software (business logic and data access) and the database itself. Not wanting to start a religious war, but I want to allow people to develop stored procedures more quickly and with best practices through templates.</p> <p>Let’s start with making your own templates in the SQL Server 2005 management Studio. First, you need to show the Template Explorer in the Studio.</p> <p><a href="http://www.cloudsocket.com/images/image-thumb10.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb10.png</a></p> <p>This will show the following:</p> <p><a href="http://www.cloudsocket.com/images/image-thumb11.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb11.png</a></p> <p><a href="http://www.cloudsocket.com/images/image-thumb12.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb12.png</a></p> <p><a href="http://www.cloudsocket.com/images/image-thumb13.png" rel="nofollow noreferrer">alt text http://www.cloudsocket.com/images/image-thumb13.png</a></p> <p>The IDE will create a blank template. To edit the template, right click on the template and select Edit. You will get a blank Query window in the IDE. You can now insert your template implementation. I have here the template of the new stored procedure to include a TRY CATCH. I like to include error handling in my stored procedures. With the new TRY CATCH addition to TSQL in SQL Server 2005, we should try to use this powerful exception handling mechanism through our code including database code. Save the template and you are all ready to use your new template for stored procedure creation.</p> <pre><code>-- ====================================================== -- Create basic stored procedure template with TRY CATCH -- ====================================================== SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: &lt;Author,,Name&gt; -- Create date: &lt;Create Date,,&gt; -- Description: &lt;Description,,&gt; -- ============================================= CREATE PROCEDURE &lt;Procedure_Name, sysname, ProcedureName&gt; -- Add the parameters for the stored procedure here &lt;@Param1, sysname, @p1&gt; &lt;Datatype_For_Param1, , int&gt; = &lt;Default_Value_For_Param1, , 0&gt;, &lt;@Param2, sysname, @p2&gt; &lt;Datatype_For_Param2, , int&gt; = &lt;Default_Value_For_Param2, , 0&gt; AS BEGIN TRY BEGIN TRANSACTION -- Start the transaction SELECT @p1, @p2 -- If we reach here, success! COMMIT END TRY BEGIN CATCH -- there was an error IF @@TRANCOUNT &gt; 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH GO </code></pre>
<p>You bring up <em>Template Explorer</em> using Ctrl+Alt+T or trough <em>View > Template Explorer</em>. Then you can right click tree nodes to add new Templates or new folders to organize your new templates.</p>
9,064
<p>I have a simple printer bot metal with a heated bed, the heated bed I am not using. I am using conductive pla by protopasta </p> <p>The conductive pla is not that strong, so when I take my pieces off the board, sometimes they break. The only time it appears to be invincibly strong is when it sticks to the bed plate! I cannot get the skirt off the bed plate, no matter what I try</p> <ul> <li>a razor blade does not work, even when the bed isn’t heated and after dumping a bunch of acetone on the board</li> <li>using no skirt does not work, as the printer clogs itself</li> <li>it is difficult enough to remove to the point that printing itself isn’t fun</li> <li>when scratching it off, the pieces only chip, because they stick better to the bed than they do to themselves (unlike PLA)</li> </ul> <p>What’s a good way to remove a conductive pla skirt from one of the beds? The skirt is the initial outline a printer lays down, it is very thin</p>
<p>I have no experience with your printer model nor with protopasta conductive PLA but since your problem is "too much adhesion" I would simply suggest to <strong>follow in reverse all the usual advices on how to make the first layer adhere better</strong> (a far more common problem). The list of suggestion could be:</p> <ul> <li>Print fast</li> <li>Do no squash the first layer (see @fred_dot_u answer)</li> <li>Make sure the part fan is on</li> <li>Reduce the temperature slightly</li> <li>...</li> </ul> <p>The problem could also be due to the chemical interaction between the surface of your plate and the specific material (for example: it is known that glass - a relatively difficult surface to use with PLA - bonds so well to PETG that sometimes it chips off the bed when you remove the print). If this is the case you could for example <strong>cover your bed in painter's tape</strong> and see if the protopasta conductive PLA adhere worse to it than to the bare bed. Worst case scenario, you could remove the tape with the print and scrub it off from it afterwards with a metal brush or a bit of sandpaper.</p>
<p>Based on your description "it is very thin" about the skirt, and by the other characteristics you've provided, I suggest that your z-height for the first layer is suspect of being too small, too close to the bed.</p> <p>If you have calibration specific to z-height only, re-calibrate and make a test print with skirt. If the test is better, this tells you that the previous setting was at fault. If the test is not better, use a different setting by 0.01 mm or 0.02 mm and run another test.</p>
865
<p>We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.</p>
<p>You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception.</p> <p>Some code might look like this:</p> <pre><code> public void onException (JMSException jsme) { if (!closeRequested) { this.disconnect(); this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector); } else { //Client requested close so do not try to reconnect } } </code></pre> <p>In your "establishConnection" code, you would then implement a <code>while(!initialized)</code> construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions.</p> <p>We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection.</p>
<p>Piece of advice from personal experience. <strong>Upgrade to <a href="http://www.jboss.org/jbossmessaging/" rel="nofollow noreferrer">JBoss Messaging</a>.</strong> I've seen it in production for 4 months without problems. It has fully transparent failover - amongst many other features.</p> <p>Also, if you do go with Spring, be <a href="http://wiki.jboss.org/wiki/JBMSpringJMSTemplateNotes" rel="nofollow noreferrer">very</a> <a href="http://activemq.apache.org/jmstemplate-gotchas.html" rel="nofollow noreferrer">careful</a> with the <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jms.html#jms-jmstemplate" rel="nofollow noreferrer">JmsTemplate</a>. </p>
6,993
<p>I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views. Are those views wasting CPU cycles and RAM during all the time that I am not reading from them? Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?</p> <p>I'm not a DBA so I don't know what's going on behind the scenes inside the database server.</p> <p>Is it possible to have too many database views? What's considered best practice?</p>
<p>For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.</p> <p>However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?</p> <p>The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.</p>
<p>The views are only going to take up cpu/memory resources when they are called.</p> <p>Anyhow, best practice would be to consolidate what can be consolidated, remove what can be removed, and if it's literally only used by your reports, choose a consistent naming standard for the views so they can easily be grouped together when looking for a particular view.</p> <p>Also, unless you really need transactional isolation, consider using the NOLOCK table hint in your queries.</p> <p>-- Kevin Fairchild</p>
6,140
<p>I'd like to know what's the way to actually set the icon of a <code>.bat</code> file to an arbitrary icon. How would I go about doing that programmatically, independently of the language I may be using.</p>
<p>Assuming you're referring to MS-DOS batch files: as it is simply a text file with a special extension, a <code>.bat</code> file doesn't store an icon of its own.</p> <p>You can, however, create a shortcut in the <code>.lnk</code> format that stores an icon.</p>
<p>i recommand to use BAT to EXE converter for your desires </p>
3,626
<p>There are many posts on the internet about the ReadDirectoryChangesW API function missing files when there is a lot of file activity. Most blame the speed at which the ReadDirectoryChangesW function loop is called. This is an incorrect assumption. The best explanation I have seen is in the following post, the comment on Monday, April 14, 2008 2:15:27 PM</p> <p><a href="http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/" rel="noreferrer">http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/</a></p> <p>The summary is that the ReadDirectoryChangesW function reports file changes as they leave the file-write-behind queue, not as they are added. And if too many are added before being committed, you lose notice on some of them. You can see this with your implementation, if you just write a program to generate a 1000+ files in a directory real quick. Just count how many file event notices you get and you will see there are times when you will not receive all of them.</p> <p>The question is, has anyone found a reliable method to use the ReadDirectoryChangesW function without having to flush the volume each time? This is not allowed if the user is not an Administrator and can also take some time to complete.</p>
<p>If the API is unreliable, then a workaround may be your only option. That of course likely involves keeping track of lastmodified and filenames. <s>What this doesn't mean is that you need to poll when looking for changes, rather, you can use the FileSystemWatcher as a means to trigger checking. </s></p> <p>So if you keep track of the last 50-100 times the ReadDirectoryChangesW<s>/FSW</s> event happened, and you see that it is being called rapidly, you can detect this and trigger the special condition to get all the files that have been changed (and set a flag to prevent future bogus FSW events temporarily) in a few seconds.</p> <p>Since some people are confused in the comments about this solution, I am proposing that you should monitor how fast events are arriving from the ReadDirectoryChangesW and when they are arriving too fast, try to attempt a workaround (usually a manual sweep of a directory). </p>
<p>I met same problem. But, I didn't find a solution that guarantee to get all of events. In several tests, I could know that ReadDirectoryChangesW function should be called again as fast as possible after GetQueuedCompletionStatus function returned. I guess if a processing speed of filesystem is very faster than my application processing speed, the application might be able to lose some events.</p> <p>Anyway, I separated a parsing logic from a monitoring logic and placed a parsing logic on a thread.</p>
8,147
<p>So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google.</p> <pre><code>CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } </code></pre> <p>As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? </p> <hr> <p>@Joel, thanks for the info. Here is what I tried based on your suggestion:</p> <pre><code>msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); </code></pre> <p>The form still comes up <em>under</em> the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes.</p> <p>Thnks for all the ideas so far folks.</p> <hr> <p>Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.</p>
<p>I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem.</p> <p>Basically, call ShowWindow() then SetForegroundWindow().</p> <pre><code>using System.Diagnostics; using System.Runtime.InteropServices; // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or minimize a window [DllImportAttribute("User32.DLL")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_RESTORE = 9; private void ActivateApplication(string briefAppName) { Process[] procList = Process.GetProcessesByName(briefAppName); if (procList.Length &gt; 0) { ShowWindow(procList[0].MainWindowHandle, SW_RESTORE); SetForegroundWindow(procList[0].MainWindowHandle); } } </code></pre>
<p>You shouldn't need to import any win32 functions for this. If .Focus() isn't enough the form should also have a .BringToFront() method you can use. If that fails, you can set it's .TopMost property to true. You don't want to <em>leave</em> it true forever, so then call Application.DoEvents so the form can process that message and set it back to false.</p>
6,807
<p>If you use the standard tab control in .NET for your tab pages and you try to change the look and feel a little bit then you are able to change the back color of the tab pages but not for the tab control. The property is available, you could set it but it has no effect. If you change the back color of the pages and not of the tab control it looks... uhm quite ugly.</p> <p>I know Microsoft doesn't want it to be set. <a href="http://msdn.microsoft.com/en/library/w4sc610z(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>: '<i>This property supports the .NET Framework infrastructure and is not intended to be used directly from your code. This member is not meaningful for this control.</i>' A control property just for color which supports the .NET infrastructure? ...hard to believe.</p> <p>I hoped over the years Microsoft would change it but they did not. I created my own TabControl class which overrides the paint method to fix this. But is this really the best solution?</p> <p>What is the reason for not supporting BackColor for this control? What is your solution to fix this? Is there a better solution than overriding the paint method?</p>
<p>The solution in Rajesh's blog is really useful, but it colours the tab part of the control only. In my case I had a tabcontrol on a different coloured background. The tabs themselves were grey which wasn't a problem, but the area to the right of the tabs was displaying as a grey strip. </p> <p>To change this colour to the colour of your background you need to add the following code to the DrawItem method (as described in Rajesh's solution). I'm using VB.Net:</p> <pre><code>... Dim r As Rectangle = tabControl1.GetTabRect(tabControl1.TabPages.Count-1) Dim rf As RectangleF = New RectangleF(r.X + r.Width, r.Y - 5, tabControl1.Width - (r.X + r.Width), r.Height + 5) Dim b As Brush = New SolidBrush(Color.White) e.Graphics.FillRectangle(b, rf) ... </code></pre> <p>Basically you need to get the rectangle made of the right hand side of the last tab to the right hand side of the tab control and then fill it to your desired colour.</p>
<p>Thanks, LauraM. You helped get me on the right track. I had already found the link Oskar provided but that didn't do anything for the strip at the end.</p> <p>In the end, I had to change quite a bit because I needed a background image on the form to bleed through or if the parent was something without a background image, the backcolor. I also needed icons to show if they were present. I have a full write-up with all the code in my <a href="http://blog.villainousmind.com/2009/04/fix-backcolor-for-tabcontrol-in-net.html" rel="nofollow noreferrer">TabControl BackColor fix post</a>.</p>
9,287
<p>What is a good complete <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> or some other process that would take the title:</p> <blockquote> <p>How do you change a title to be part of the URL like Stack Overflow?</p> </blockquote> <p>and turn it into </p> <pre class="lang-none prettyprint-override"><code>how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow </code></pre> <p>that is used in the SEO-friendly URLs on Stack&nbsp;Overflow?</p> <p>The development environment I am using is <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a>, but if there are some other platform-specific solutions (.NET, PHP, <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>), I would love to see those too. </p> <p>I am sure I (or another reader) will come across the same problem on a different platform down the line. </p> <p>I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.</p>
<p>Here's how we do it. Note that there are probably more edge conditions than you realize at first glance.</p> <p>This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page.</p> <pre><code>/// &lt;summary&gt; /// Produces optional, URL-friendly version of a title, "like-this-one". /// hand-tuned for speed, reflects performance refactoring contributed /// by John Gietzen (user otac0n) /// &lt;/summary&gt; public static string URLFriendly(string title) { if (title == null) return ""; const int maxlen = 80; int len = title.Length; bool prevdash = false; var sb = new StringBuilder(len); char c; for (int i = 0; i &lt; len; i++) { c = title[i]; if ((c &gt;= 'a' &amp;&amp; c &lt;= 'z') || (c &gt;= '0' &amp;&amp; c &lt;= '9')) { sb.Append(c); prevdash = false; } else if (c &gt;= 'A' &amp;&amp; c &lt;= 'Z') { // tricky way to convert to lowercase sb.Append((char)(c | 32)); prevdash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!prevdash &amp;&amp; sb.Length &gt; 0) { sb.Append('-'); prevdash = true; } } else if ((int)c &gt;= 128) { int prevlen = sb.Length; sb.Append(RemapInternationalCharToAscii(c)); if (prevlen != sb.Length) prevdash = false; } if (i == maxlen) break; } if (prevdash) return sb.ToString().Substring(0, sb.Length - 1); else return sb.ToString(); } </code></pre> <p>To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link).</p> <p>Also, the <code>RemapInternationalCharToAscii</code> method source code can be found <a href="https://meta.stackexchange.com/a/7696">here</a>.</p>
<p>Rewrite of Jeff's code to be more concise</p> <pre><code> public static string RemapInternationalCharToAscii(char c) { var s = c.ToString().ToLowerInvariant(); var mappings = new Dictionary&lt;string, string&gt; { { &quot;a&quot;, &quot;àåáâäãåą&quot; }, { &quot;c&quot;, &quot;çćčĉ&quot; }, { &quot;d&quot;, &quot;đ&quot; }, { &quot;e&quot;, &quot;èéêëę&quot; }, { &quot;g&quot;, &quot;ğĝ&quot; }, { &quot;h&quot;, &quot;ĥ&quot; }, { &quot;i&quot;, &quot;ìíîïı&quot; }, { &quot;j&quot;, &quot;ĵ&quot; }, { &quot;l&quot;, &quot;ł&quot; }, { &quot;n&quot;, &quot;ñń&quot; }, { &quot;o&quot;, &quot;òóôõöøőð&quot; }, { &quot;r&quot;, &quot;ř&quot; }, { &quot;s&quot;, &quot;śşšŝ&quot; }, { &quot;ss&quot;, &quot;ß&quot; }, { &quot;th&quot;, &quot;Þ&quot; }, { &quot;u&quot;, &quot;ùúûüŭů&quot; }, { &quot;y&quot;, &quot;ýÿ&quot; }, { &quot;z&quot;, &quot;żźž&quot; } }; foreach(var mapping in mappings) { if (mapping.Value.Contains(s)) return mapping.Key; } return string.Empty; } </code></pre>
4,490
<p>I created a view on a machine using the <em>substring</em> function from Firebird, and it worked. When I copied the database to a different machine, the view was broken. This is the way I used it:</p> <pre><code>SELECT SUBSTRING(field FROM 5 FOR 15) FROM table; </code></pre> <p>And this is the output on the machine that does not accept the function:</p> <pre><code>token unknown: FROM </code></pre> <p>Both computers have this configuration:</p> <ul> <li><em>IB Expert</em> version 2.5.0.42 to run the queries and deal with the database.</li> <li><em>Firebird</em> version 1.5 as server to database.</li> <li><em>BDE Administration</em> version 5.01 installed, with <em>Interbase</em> 4.0 drivers.</li> </ul> <p>Any ideas about why it's behaving differently on these machines?</p>
<ol> <li><p>Make sure Firebird engine is 1.5 and there's no InterBase server running on this same box on the port you expected Firebird 1.5.</p> </li> <li><p>Make sure you don't have any UDF called 'substring' registered inside this DB so that Firebird is expecting different parameters.</p> </li> </ol>
<p>Different engine versions?</p> <p>Have you tried naming that expression in the result?</p> <pre><code>SELECT SUBSTRING(field FROM 5 FOR 15) AS x FROM table; </code></pre>
2,713
<p>In C++, I'm trying to catch all types of exceptions in one catch (like <code>catch(Exception)</code> in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?</p>
<pre><code>catch (...) { // Handle exceptions not covered. } </code></pre> <p>Important considerations:</p> <ul> <li>A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.</li> <li>catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.</li> <li>Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII pattern</a> if you choose this route.</li> </ul>
<p>If I recall correctly (it's been a while since I've looked at C++), I think the following should do the trick</p> <pre><code>try { // some code } catch(...) { // catch anything } </code></pre> <p>and a quick google(<a href="http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html" rel="nofollow noreferrer">http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html</a>) seems to prove me correct.</p>
7,969
<p>I noticed that Google maps is providing directions in my local language (hungarian) when I am using google chrome, but English language directions when I am using it from IE. </p> <p>I would like to know how chrome figures this out and how can I write code that is always returning directions on the user's language. </p>
<p><code>HTTP</code>requests` include an <strong>Accept-Language header</strong> which is set according to your locale preferences on most OS/browser combinations. Google uses a combination of that, the local domain you use (eg 'google.it', 'google.hu') and any preferences you set with the Preferences link in the home page to assign a language to your pages.</p> <p>It's likely that IE is misrepresenting your locale to Google Maps, whereas Chrome has correctly guessed it. You can change IE's locale by changing your national settings in Control Panel, while Chrome's locale can be changed in (wrench menu) > Preferences.</p>
<p>I could be way off but I think it's fairly safe to assume that google, is using gears.</p>
9,261
<p>I need to implement a Diff algorithm in VB.NET to find the changes between two different versions of a piece of text. I've had a scout around the web and have found a couple of different algorithms.</p> <p>Does anybody here know of a 'best' algorithm that I could implement?</p>
<p>Well I've used the c# version on codeproject and its really good for what I wanted...</p> <p><a href="http://www.codeproject.com/KB/recipes/diffengine.aspx" rel="noreferrer">http://www.codeproject.com/KB/recipes/diffengine.aspx</a></p> <p>You can probably get this translated into VB.net via an <a href="http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx" rel="noreferrer">online converter</a> if you can't do it yourself...</p>
<p>I don't know for sure if it's the best diff algorithms but you might want to check out those links that talks about SOCT4 and SOCT6</p> <p><a href="http://dev.libresource.org/home/doc/so6-user-manual/concepts" rel="nofollow noreferrer">http://dev.libresource.org/home/doc/so6-user-manual/concepts</a></p> <p>and also:<br> <a href="http://www.loria.fr/~molli/pmwiki/uploads/Main/so6group03.pdf" rel="nofollow noreferrer">http://www.loria.fr/~molli/pmwiki/uploads/Main/so6group03.pdf</a> <a href="http://www.loria.fr/~molli/pmwiki/uploads/Main/diffalgo.pdf" rel="nofollow noreferrer">http://www.loria.fr/~molli/pmwiki/uploads/Main/diffalgo.pdf</a></p>
2,530
<p>I wrote a simple web service in C# using SharpDevelop (which I just got and I love).</p> <p>The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)</p> <p>But I get this error when I try to load the service now.</p> <pre> Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'. Source Error: Line 1: &lt;%@ WebService Class="flightinfo.Soap,flightinfo" %&gt; </pre> <p>I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.</p> <p>Any ideas?</p>
<p>In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between <code>Namespace Z</code> and <code>End Namespace</code> will be in the X.Y.Z namespace. In C# you have to provide the full namespace name, regardless of the default namespace of the project. So if the C# project had the default namespace X.Y, the CS files would still include the <code>namespace X.Y</code> declaration. After converting to VB, if both the default namespace and the namespace declarations in the files stay the same you end up with classes in the X.Y.X.Y namespace. So in your case, the Soap class is now in the flightinfo.flightinfo namespace. Thus there are three possible solutions:</p> <ul> <li><p>change the asmx file to</p> </li> <li><p>remove the default namespace from the project</p></li> <li>remove the namespace declarations from the vb files</li> </ul>
<pre><code>&lt;%@ WebService Class="flightinfo.Soap,flightinfo" %&gt; </code></pre> <p>What is the name of your class?</p>
8,490
<p>I'm trying to call an Antlr task in my Ant build.xml as follows:</p> <pre><code>&lt;path id="classpath.build"&gt; &lt;fileset dir="${dir.lib.build}" includes="**/*.jar" /&gt; &lt;/path&gt; ... &lt;target name="generate-lexer" depends="init"&gt; &lt;antlr target="${file.antlr.lexer}"&gt; &lt;classpath refid="classpath.build"/&gt; &lt;/antlr&gt; &lt;/target&gt; </code></pre> <p>But Ant can't find the task definition. I've put all of the following in that <code>dir.lib.build</code>:</p> <ul> <li>antlr-3.1.jar</li> <li>antlr-2.7.7.jar</li> <li>antlr-runtime-3.1.jar</li> <li>stringtemplate-3.2.jar</li> </ul> <p>But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)</p>
<p>The current Antlr-task jar is available at <a href="http://www.antlr.org/share/1169924912745/antlr3-task.zip" rel="nofollow noreferrer">http://www.antlr.org/share/1169924912745/antlr3-task.zip</a></p> <p>It can be found on the <a href="http://antlr.org" rel="nofollow noreferrer">antlr.org</a> website under the "File Sharing" heading.</p>
<p>On Ubuntu this should make it available:</p> <p><code>sudo apt-get install ant-optional</code></p>
4,512
<p>How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.</p> <p><code>tf get</code> only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work.</p>
<p>TFS has a <a href="http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx" rel="nofollow noreferrer">.Net SDK</a> that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:</p> <pre><code>TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("MyServer"); VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer)); WorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces("MyWorkSpaceName", "MyLoginName", "MyComputer"); myWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll); </code></pre>
<p>I know you mentioned batch files, but let me throw something else out for you.</p> <p>I'm going to guess that you are using the 2005 version of TFS. 2008 has all of the scheduling stuff built in. </p> <p>However, you could also use <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl.net</a> to do scheduled builds for you. I've used both TFS 2008 and CruiseControl and they both seem to work just fine.</p>
5,439
<p>Suppose I have the following CSS rule in my page:</p> <pre class="lang-css prettyprint-override"><code>body { font-family: Calibri, Trebuchet MS, Helvetica, sans-serif; } </code></pre> <p>How could I detect which one of the defined fonts were used in the user's browser?</p> <p>For people wondering why I want to do this is because the font I'm detecting contains glyphs that are <em>not</em> available in other fonts. If the user does <em>not</em> have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).</p> <p>Currently, I am displaying the download font link for all users. I want to only display this for people who do <em>not</em> have the correct font installed.</p>
<p>I've seen it done in a kind of iffy, but pretty reliable way. Basically, an element is set to use a specific font and a string is set to that element. If the font set for the element does not exist, it takes the font of the parent element. So, what they do is measure the width of the rendered string. If it matches what they expected for the desired font as opposed to the derived font, it's present. This won't work for monospaced fonts.</p> <p>Here's where it came from: <a href="http://ajaxian.com/archives/javascriptcss-font-detector" rel="noreferrer">Javascript/CSS Font Detector (ajaxian.com; 12 Mar 2007)</a></p>
<p>You can use this website :</p> <p><a href="http://website-font-analyzer.com/" rel="nofollow noreferrer">http://website-font-analyzer.com/</a></p> <p>It does exactly what you want...</p>
2,328
<p>I'm trying to get good-quality thin wall prints with PLA on my Creality CR10s Pro V2 using Cura. After hours of calibration and testing, I'm getting quite good results. However, there is one issue I can't figure out. It seems that I'm getting uneven extrusion and blobs when the printer deaccelerates or accelerates. This issue causes problems with rounded corners on my test prints (see photos). In Cura, there is no retraction or anything in the arc, just accelerations. I have experimented with acceleration and jerk without success. I also tried to decrease the print speed from 50 mm/s to 20 mm/s, and it seems to have a minor positive effect. Anyone got any ideas on what values I need to change? Can this be a mechanical problem?</p> <h3>General print settings:</h3> <ul> <li>Temp: 210 °C</li> <li>Layer: 0.2 mm</li> <li>Infill: 0 %</li> <li>Retraction distance: 3 mm</li> <li>Retraction speed: 60 mm/s</li> <li>Cooling: 80 %</li> <li>Flow: 102.5 %</li> <li>Acceleration: 500 mm/s</li> <li>Jerk: 20 mm/s (Tried values from 5 to 20)</li> </ul> <h3>Printed at 50 mm/s:</h3> <p><a href="https://i.stack.imgur.com/OaIEh.jpg" rel="nofollow noreferrer" title="Printed model with blobs printing errors"><img src="https://i.stack.imgur.com/OaIEh.jpg" alt="Printed model with blobs printing errors" title="Printed model with blobs printing errors" /></a></p> <h3>Printed at 20 mm/s:</h3> <p><a href="https://i.stack.imgur.com/lNsIp.jpg" rel="nofollow noreferrer" title="Printed model that has been printed slower but still has blobs printing errors"><img src="https://i.stack.imgur.com/lNsIp.jpg" alt="Printed model that has been printed slower but still has blobs printing errors" title="Printed model that has been printed slower but still has blobs printing errors" /></a></p> <h3>Cura:</h3> <p><a href="https://i.stack.imgur.com/gFj1J.jpg" rel="nofollow noreferrer" title="Screenshot of the rendered model in Cura"><img src="https://i.stack.imgur.com/gFj1J.jpg" alt="Screenshot of the rendered model in Cura" title="Screenshot of the rendered model in Cura" /></a></p>
<p>Look at the gcode for those curves either manually in a text editor, or with a gcode analyzer tool (e.g. <a href="https://gcode.ws" rel="nofollow noreferrer">gcode.ws</a>) and see if there's anything strange about them. Cura is notorious for numeric instability problems with high resolution curves, where it will end up generating a few tiny moves (on the order of 0.005 mm) here and there that get truncated to zero motion on one axis and nonzero on the other (due to fixed rounding to 3 decimal places). To the printer firmware's motion planner, these look like sharp corners (because the angle changed severely from the last move), forcing it decelerate and re-accelerate.</p> <p>The right fix for this is fixing Cura's numerical precision flaws. <a href="https://github.com/Piezoid/CuraEngine" rel="nofollow noreferrer">@piezoid</a> has a WIP branch doing this that might eventually push upstream to improve, but I wouldn't hold my breath. Short of that, there are a couple good workarounds:</p> <ul> <li><p>Check the &quot;Maximum Resolution&quot; and &quot;Maximum Deviation&quot; settings in Cura. You might have to unhide them if they're hidden. The defaults on modern Cura versions are 0.5 and 0.025 which tend to avoid the problem well, but older versions had bad values. (And of course, make sure you're using a recent version.)</p> </li> <li><p>Lowering the resolution (having it use a coarser triangle mesh) exported from your CAD software tends to avoid the problem.</p> </li> <li><p>Some people have reported success with the <a href="https://marketplace.ultimaker.com/app/cura/plugins/fieldofview/ArcWelderPlugin" rel="nofollow noreferrer">Arc Welder plugin</a>, but I'm not sure this is a good idea, and it depends on your printer having firmware that accepts the arc motion commands.</p> </li> </ul>
<p>If you haven't already, try rotating the object about the Z-axis to give a different orientation with respect to X and Y. May not correct the problem but if the effect changes it may shed some light on the cause.</p>
2,101
<p>Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?</p> <p>I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).</p> <p>Any tips or resources would be appreciated.</p> <p><strong>Edit</strong>: thanks to everyone, <a href="https://stackoverflow.com/users/3655/aardvark">Aardvark</a>'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.</p> <pre><code>using Microsoft.Office.Interop.Word; using Microsoft.Vbe.Interop; ... public List&lt;string&gt; GetMacrosFromDoc() { Document doc = GetWordDoc(@"C:\Temp\test.docm"); List&lt;string&gt; macros = new List&lt;string&gt;(); VBProject prj; CodeModule code; string composedFile; prj = doc.VBProject; foreach (VBComponent comp in prj.VBComponents) { code = comp.CodeModule; // Put the name of the code module at the top composedFile = comp.Name + Environment.NewLine; // Loop through the (1-indexed) lines for (int i = 0; i &lt; code.CountOfLines; i++) { composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine; } // Add the macro to the list macros.Add(composedFile); } CloseDoc(doc); return macros; } </code></pre>
<p>You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with.</p> <p>Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides.</p> <p>This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky.</p> <p>I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? </p> <pre><code>Sub GetCode() Dim prj As VBProject Dim comp As VBComponent Dim code As CodeModule Dim composedFile As String Dim i As Integer Set prj = ThisDocument.VBProject For Each comp In prj.VBComponents Set code = comp.CodeModule composedFile = comp.Name &amp; vbNewLine For i = 1 To code.CountOfLines composedFile = composedFile &amp; code.Lines(i, 1) &amp; vbNewLine Next MsgBox composedFile Next End Sub </code></pre>
<p>You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with.</p> <p>Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides.</p> <p>This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky.</p> <p>I also wonder what the docm file format is now - XML like the docx? Would that be a better approach? </p> <pre><code>Sub GetCode() Dim prj As VBProject Dim comp As VBComponent Dim code As CodeModule Dim composedFile As String Dim i As Integer Set prj = ThisDocument.VBProject For Each comp In prj.VBComponents Set code = comp.CodeModule composedFile = comp.Name &amp; vbNewLine For i = 1 To code.CountOfLines composedFile = composedFile &amp; code.Lines(i, 1) &amp; vbNewLine Next MsgBox composedFile Next End Sub </code></pre>
7,233
<p>I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.</p> <p>Does anyone know the best way to do this using the WiX framework.</p>
<p>Wix has out-of-the-box support for creating event log sources.</p> <p>Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :</p> <pre><code>&lt;Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"&gt; &lt;Component ...&gt; ... &lt;util:EventSource Log="Application" Name="*source name*" EventMessageFile="*path to message file*"/&gt; ... &lt;/Component&gt; </code></pre> <p>If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.</p>
<p>Just to save people some time - if you are trying to use the Application log and the .NET messages you can cut paste the below code:</p> <pre><code>&lt;Util:EventSource xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension" Name="ROOT Builder" Log="Application" EventMessageFile="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll" /&gt; </code></pre> <p>NOTE: the path above is now correct..</p>
8,289
<p>Although perhaps a bizare thing to want to do, I need to create an Array in .Net with a lower bound > 0. This at first seems to be possible, using:</p> <pre><code>Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9}); </code></pre> <p>Produces the desired results (an array of objects with a lower bound set to 9). However the created array instance can no longer be passed to other methods expecting <code>Object[]</code> giving me an error saying that:</p> <p><code>System.Object[*]</code> can not be cast into a <code>System.Object[]</code>. What is this difference in array types and how can I overcome this?</p> <p>Edit: test code = </p> <pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9}); Object[] y = (Object[])x; </code></pre> <p>Which fails with: "Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'."</p> <p>I would also like to note that this approach <strong>DOES</strong> work when using multiple dimensions:</p> <pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9}); Object[,] y = (Object[,])x; </code></pre> <p>Which works fine.</p>
<p>The reason why you can't cast from one to the other is that this is evil.</p> <p>Lets say you create an array of object[5..9] and you pass it to a function F as an object[].</p> <p>How would the function knows that this is a 5..9 ? F is expecting a general array but it's getting a constrained one. You could say it's possible for it to know, but this is still unexpected and people don't want to make all sort of boundary checks everytime they want to use a simple array.</p> <p>An array is the simplest structure in programming, making it too complicated makes it unsusable. You probably need another structure.</p> <p>What you chould do is a class that is a constrained collection that mimics the behaviour you want. That way, all users of that class will know what to expect.</p> <pre><code>class ConstrainedArray&lt;T&gt; : IEnumerable&lt;T&gt; where T : new() { public ConstrainedArray(int min, int max) { array = new T[max - min]; } public T this [int index] { get { return array[index - Min]; } set { array[index - Min] = value; } } public int Min {get; private set;} public int Max {get; private set;} T[] array; public IEnumerator&lt;T&gt; GetEnumerator() { return array.GetEnumarator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return array.GetEnumarator(); } } </code></pre>
<p>Know it's old question, but to fully explain it.</p> <p>If type (in this case a single-dimension array with lower bound > 0) can't be created by typed code, simply reflected type instance can't be consumed by typed code then.</p> <p>What you have noticed is already in documentation:</p> <p><a href="https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names</a></p> <blockquote> <p>Note that from a runtime point of view, MyArray[] != MyArray[*], but for multidimensional arrays, the two notations are equivalent. That is, Type.GetType("MyArray [,]") == Type.GetType("MyArray[*,*]") evaluates to true.</p> </blockquote> <p>In c#/vb/... you can keep that reflected array in object, pass around as object, and use only reflection to access it's items. </p> <p>-</p> <p>Now you ask "why is there LowerBound at all?", well COM object aren't .NET, it could be written in old VB6 that actually had array object that has LowerBound set to 1 (or anything VB6 had such freedom or curse, depends whom you ask). To access first element of such object you would actually need to use 'comObject(1)' instead of 'comObject(0)'. So the reason to check lower bound is when you are performing enumeration of such object to know where to start enumeration, since element functions in COM object expects first element to be of LowerBound value, and not Zero (0), it was reasonable to support same logic on such instances. Imagine your get element value of first element at 0, and use some Com object to pass such element instance with index value of 1 or even with index value of 2001 to a method, code would be very confusing.</p> <p>To put it simply: it's mostly for legacy support only!</p>
8,040
<p>I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first?</p> <p>Is there some kind of hash function that can take identical input, but in any order, and still produce the same result?</p>
<p>The easiest way would seem to be to hash each line on the way in, storing the hash and the original data, and then compare each new hash with your collection of existing hashes. If you get a positive, you could compare the actual data, to make sure it's not a false positive - though this would be extremely rare, you could go with a quicker hash algorithm, like MD5 or CRC (instead of something like SHA, which is slower but less likely to collide), just so it's quick, and then compare the actual data when you get a hit.</p>
<p>So you have input like</p> <pre><code>A B C D D E F G C B A D </code></pre> <p>and you need to detect that the first and third lines are identical?</p>
8,972
<p>What CSS should I use to make a cell's border appear even if the cell is empty?</p> <p>IE 7 specifically.</p>
<p>If I recall, the cell dosn't exist in some IE's unless it's filled with something...</p> <p>If you can put a <code>&amp;nbsp;</code> (non-breaking space) to fill the void, that will usually work. Or do you require a pure CSS solution?</p> <p>Apparently, IE8 shows the cells by default, and you have to hide it with <code>empty-cells:hide</code> But it doesn't work at all in IE7 (which hides by default).</p>
<p>"IE" isn't a useful term in this context anymore now that IE8 is out.</p> <p>IE7 always does "empty-cells:show" (or so I'm told ... Vista). IE8 in any of its "Quirks" or "IE7 Standards" modes always does "empty-cells:hide". IE8 in "Standards" mode defaults to "empty-cells:show" and supports the attribute via CSS.</p> <p>As far as I know, every other browser has correctly supported this for several years (I know it was added in Firefox 2).</p>
8,119
<p>I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota.</p> <pre><code>DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); </code></pre> <p>No matter what approach I tried (like <code>SecureString</code>), I am easily able to see the password (<strong>m_pwd</strong>) either using Reflector or using strings tab of Process Explorer for the executable.</p> <p>I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account.</p> <p>Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers?</p> <p>Hashing is not possible since I need to know the exact password (not just the hash for matching purpose). Encryption/Decryption mechanisms are not working since they are machine dependent.</p>
<p>The sanctified method is to use CryptoAPI and the Data Protection APIs.</p> <p>To encrypt, use something like this (C++):</p> <pre><code>DATA_BLOB blobIn, blobOut; blobIn.pbData=(BYTE*)data; blobIn.cbData=wcslen(data)*sizeof(WCHAR); CryptProtectData(&amp;blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &amp;blobOut); _encrypted=blobOut.pbData; _length=blobOut.cbData; </code></pre> <p>Decryption is the opposite:</p> <pre><code>DATA_BLOB blobIn, blobOut; blobIn.pbData=const_cast&lt;BYTE*&gt;(data); blobIn.cbData=length; CryptUnprotectData(&amp;blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &amp;blobOut); std::wstring _decrypted; _decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); </code></pre> <p>If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.</p>
<p>If you store it as a secure string and save the secure string to a file (possibly using <a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx" rel="nofollow noreferrer">Isolated Storage</a>, the only time you will have a plain text password is when you decrypt it to create your mbstore. Unfortunately, the constructor does not take a SecureString or a Credential object.</p>
6,212
<p>What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc.</p> <p>Some info on the DB:</p> <ul> <li>Needs to have the capacity to grow by thousands of records per week</li> <li>50-60 Tables</li> <li>Main revisioned tables may have several million records each</li> <li>Reasonable amount of foreign keys and indexes set</li> <li>Using PostgreSQL 8.x</li> </ul>
<p>In the past I have used triggers to construct db update/insert/delete logging. </p> <p>You could insert a record each time one of the above actions is done on a specific table into a logging table that keeps track of the action, what db user did it, timestamp, table it was performed on, and previous value. </p> <p>There is probably a better answer though as this would require you to cache the value before the actual delete or update was performed I think. But you could use this to do rollbacks. </p>
<p>The only problem with using Triggers is that it adds to performance overhead of any insert/update/delete. For higher scalability and performance, you would like to keep the database transaction to a minimum. Auditing via triggers increase the time required to do the transaction and depending on the volume may cause performance issues. </p> <p>another way is to explore if the database provides any way of mining the "Redo" logs as is the case in Oracle. Redo logs is what the database uses to recreate the data in case it fails and has to recover. </p>
4,363
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p> <p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p> <p>i.e.</p> <pre><code> >>> class Foo(object): def __eq__(self, other): return True >>> f = Foo() >>> f == None True >>> f is None False </code></pre>
<pre><code>a is b # returns true if they a and b are true alias a == b # returns true if they are true alias or they have values that are deemed equivalence a = [1,3,4] b = a[:] #creating copy of list a is b # if gives false False a == b # gives true True </code></pre>
4,616
<p>I have an Ender 3 with a removeable build surface. The build surface backing has become warped - the center is at least 0.3 mm higher than the corners. I'm not sure what the material of this plate is - it's the part behind the BuildTak-clone surface that sits on the aluminum heat bed and is clipped to it. This makes it impossible to level the entire bed, and annoyingly tedious to level it enough just to use the center, since the paper method doesn't work at the corners. Can this be fixed, or do I need to source a replacement for it?</p>
<p>I measured mine with a thread gauge and it says the pitch is <strong>0.7 mm</strong>.</p> <p>So, as the stock adjustment wheels have 14 bumps around their circumference, turning by one of those is an adjustment of exactly 0.05 mm (assuming no backlash).</p> <p>I can't speak for anyone else's, but due to the availability of replacement height adjustment wheels which don't specify alternative thread pitches, I <em>guess</em> that's the only one in use. I encourage you to verify my finding before relying on it.</p>
<p>I don't know what the value is, but there are a few ways to find out. It is very hard to measure this with a caliper, but it can be done, mark the upper and bottom of e.g. 10 windings and measure this with a caliper. Alternatively measure how much the screw drops after 10 full turns. </p> <p>There are special tools that give you the answer directly, they cost a few Euros/bucks but can be very handy; a thread gauge, just place the 0.5&nbsp;mm and the 0.7&nbsp;mm beside the screw and you will instantly see which is the correct one.</p> <p><a href="https://i.stack.imgur.com/UYqFm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UYqFm.jpg" alt="enter image description here"></a></p> <p><em>I bought mine at a typical Chinese vendor site.</em></p>
1,571
<p>I've got an MDI application written in Delphi 2006 which runs XP with the default theme. </p> <p>Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? </p> <p>I've tried setting the <code>BorderStyle</code> of the <code>MDIChildren</code> to <code>bsSizeToolWin</code> but they are still rendered as normal Forms.</p>
<p>All your need - overload procedure CreateWindowHandle, like this:</p> <pre><code>unit CHILDWIN; interface uses Windows, Classes, Graphics, Forms, Controls, StdCtrls; type TMDIChild = class(TForm) private { Private declarations } public { Public declarations } procedure CreateWindowHandle(const Params: TCreateParams); override; end; implementation {$R *.dfm} procedure TMDIChild.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); end; end. </code></pre>
<p>I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the VCL (and perhaps also by the Windows API?). For example, don't try hiding an MDI child (you'll get an exception if you try, and you'll have to jump through a couple of API hoops to work around that), or changing the way an MDI child's main menu is merged with the host form's.</p> <p>Given these limitations, perhaps you should reconsider why you'd like to have special title bars in the first place? I guess there are also good reasons why this MDI stuff is standardized --- your users might appreciate it :)</p> <p>(PS: nice to see a Delphi question around here!)</p>
3,022
<p>I'm downloading a web page (tag soup HTML) with XMLHttpRequest and I want to take the output and turn it into a DOM object that I can then run XPATH queries on. How do I convert from a string into DOM object?</p> <p>It appears that the general solution is to create a hidden iframe and throw the contents of the string into that. There has been <a href="http://starkravingfinkle.org/blog/2007/03/how-to-parse-html-in-mozilla/" rel="nofollow noreferrer">talk</a> of updating <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMParser" rel="nofollow noreferrer">DOMParser</a> to support text/html but as of Firefox 3.0.1 you still get an <code>NS_ERROR_NOT_IMPLEMENTED</code> if you try.</p> <p>Is there any option besides using the hidden iframe trick? And if not, what is the best way to do the iframe trick so that your code works outside the context of any currently open tabs (so that closing tabs won't screw up the code, etc)?</p> <p><a href="http://mxr.mozilla.org/mozilla/source/browser/components/microsummaries/src/nsMicrosummaryService.js#2090" rel="nofollow noreferrer">This</a> is an example of why I'm looking for a solution other than the iframe hack, if I have to write <em>all</em> that code to have a robust solution, then I'd rather keep looking for something else.</p>
<p>Ajaxian actually had a <a href="http://ajaxian.com/archives/introducing-html-into-an-iframe-and-getting-it-back" rel="noreferrer">post on inserting / retrieving html from an iframe</a> today. You can probably use the js snippet they have posted there.</p> <p>As for handling closing of a browser / tab, you can attach to the onbeforeunload (<a href="http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx</a>) event and do whatever you need to do.</p>
<p>So you want to download a webpage as an XML object using javascript, but you don't want to use a webpage? Since you have no control over what the user will do (closing tabs or windows or whatnot) you would need to do this in like a OSX Dashboard widget or some separate application. A Firefox extension would also work, unless you have to worry about the user closing the browser.</p>
2,592
<p>So I am trying to fix a custom built 3D printer for my institute and am running into a problem I can't wrap my head around.</p> <p>So the limit switches for Y-axis and Z-Axis work just fine, but the X-Axis does not. </p> <p>All three switches are Makerbot (3-pin), and all three light up the LED when they get pressed. However the X-axis does not get recognized by Marlin. When I diagnose with <code>M119</code> command it does not show as triggered even though the LED is on. All the other ones do.</p> <p>All three switches are connected to min (X-min, Y-min, and Z-min).</p> <p>Could this be a firmware problem? Or perhaps my RAMPS 1.4 has burned out the X-axis signaling? (I doubt this because the LED on the switch still turns on).</p> <p>Let me know if you need any more info to diagnose the problem.</p> <p><em>P.S. I have also replaced the X-Axis limit switch with a brand new one and the same result happens: LED turns on upon activation but it doesn't get recognized by the machine.</em></p>
<p>Considering you're having issues with the board, and the limit switches appear to be registering, but the board isn't doing anything about it, a first good step would be to update the firmware to 1.1.9 as @0scar states. If the update in the firmware doesn't do the trick, then move on to doing as he suggests with changing the Xmax/min stuff around. This just seems like a good first logical step to getting it fixed.</p>
<p>To rule out problem with the switches itself, you can change the Z-min and swap it with the Y- or Z-min. Once you found out that you get the same issues you know that your X endstop module is working (unless they both are faulty, but the odds are small for that), but the signal change is not registered by the board. This could be a faulty port/pin of the X-min port / attached microprocessor pin. What you could do to try to diagnose that is using the X-max header on the board. In order to use that header for X-min, you need to change some code in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/pins_RAMPS.h" rel="nofollow noreferrer">pins_RAMPS.h</a>, change:</p> <pre> // // Limit Switches // #define X_MIN_PIN 3 #ifndef X_MAX_PIN #define X_MAX_PIN 2 #endif </pre> <p>to:</p> <pre> // // Limit Switches // #define X_MIN_PIN 2 #ifndef X_MAX_PIN #define X_MAX_PIN 3 #endif </pre> <p>Recompile and upload. Please use the latest sources, 1.1.9, 1.1.0 is very old.</p>
1,153
<p>People,</p> <p>We have 4 or 5 utilities that work in conjunction with our application. These utilities are either .bat files, or VB apps, PowerBuilder, etc. I am trying to manage these utils in source control, and am trying to figure out a better way to assign versions to them. Right now, the developers use the version control's meta-data -- specifically label -- to store the version number of the tool.</p> <p>My goal is to have individual InstallShield packages for each utility, and an easy means to manage and assign version numbers to these packages.</p> <p>Would you recommend a separate .ini file with the info, or store the info in InstallShield .ism file itself, or just use the meta-data info from version control tool?</p> <hr> <p><strong>UPDATE:</strong> </p> <p>I like the idea Orion. I have one concern though. The script that increments the version number... it can not be intelligent enough to increment Major number etc. right. e.g. if one of the utils has version 1.2.3 and we are at a point where the new version is 2.0.0. The script may not be able to handle this. </p> <p>I think this has to do a lot with our branching techniques -- we don't have any. The folks thought since the utils are so small, the source may not need branches.</p>
<p>PowerBuilder in particular has a nice trick you can do to incorporate the build number from an ini file into the compiled application.</p> <p>Details here: <a href="http://www.pbdr.com/pbtips/ex/autorev.htm" rel="nofollow noreferrer">http://www.pbdr.com/pbtips/ex/autorev.htm</a></p> <p>We have ini file inside source control that stores the build number and its value is used in our build scripts to determine what label to apply to the source tree after a successful build. Works very nicely for our needs. When we branch, we do have to manually kick the file to increment the proper number though.</p>
<p>I managed our build system at my last job, which seemed to have some parallels to what you're asking.</p> <p>There were ~30 C++ projects which needed compiling, and various .NET/Java things, and the odd perl script.</p> <p>This was all built on our build machine using NAnt - If I were doing it today I'd use <a href="http://martinfowler.com/articles/rake.html" rel="nofollow noreferrer">rake</a>, but the idea is the same.</p> <p>We basically had an auto-incrementing build number which was stored in a version.txt file in the root of the repository.</p> <p>Each time we did a build (automatically done each night, or also on-demand if neccessary) the script would increment this number and check the file back into source control.</p> <p>All the other apps referenced this file for their version number, or for things which didn't support working like this, the script would set environment variables or perform other workarounds</p> <ul> <li>I'm pretty sure that our installshield programs referenced an environment variable for their version number, but we deprecated them in favour of <a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">wix</a> as installshield really did suck</li> <li>in the case of visual studio, grep/replace the number within the .csproj files, and check them back in</li> </ul> <p>Hope this gives you some ideas</p>
3,857
<p>After changing the output directory of a visual studio project it started to fail to build with an error very much like: </p> <pre><code>C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. </code></pre> <p>I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?</p>
<p>If you are having this problem while building your VS.NET project in Release mode here is the solution:</p> <p>Go to the project properties and click on the Build tab and set the value of the "Generate Serialization Assembly" dropdown to "Off".</p> <p>Sgen.exe is "The XML Serializer Generator creates an XML serialization assembly for types in a specified assembly in order to improve the startup performance of a XmlSerializer when it serializes or deserializes objects of the specified types." (<a href="https://msdn.microsoft.com/en-us/library/bk3w6240%28v=vs.110%29.aspx" rel="noreferrer">MSDN</a>)</p>
<p>I've not seen this particular problem, but recently for us a "C1001: An internal error has occurred in the compiler" type crash from cl.exe was fixed after installing some random and unrelated (or so we thought) Windows security updates.</p> <p>We knew the code didn't crash the compiler on other machines using the same version and service pack level of Visual Studio, but we were really clutching at straws when we tried the Windows security updates.</p>
2,834
<p>I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.</p> <p>What can I do to resolve this?</p>
<p>If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:</p> <pre><code>&lt;asp:Label runat="server" id="Label1" style="display: none;" /&gt; </code></pre> <p>Then, you could make it visible on the client side with:</p> <pre><code>document.getElementById('Label1').style.display = 'inherit'; </code></pre> <p>You could make it hidden again with:</p> <pre><code>document.getElementById('Label1').style.display = 'none'; </code></pre> <p>Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ.</p>
<p>If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.</p>
2,937
<p>I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.</p> <p>(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )</p>
<p>The previous answers seem either overly complicated, and/or not particularly suited to a batch file.</p> <p>This simple one liner should place the desired drive letter in variable myDrive. Obviously change "My Label" to your actual label.</p> <pre><code>for /f %%D in ('wmic volume get DriveLetter^, Label ^| find "My Label"') do set myDrive=%%D </code></pre> <p>If run from the command line (not in a batch file), then %%D must be changed to %D in both places.</p> <p>Once the variable is set, you can refer to the drive using <code>%myDrive%</code>. For example</p> <pre><code>dir %myDrive%\someFolder </code></pre>
<p>You can use the WMI query language for that. Take a look at <a href="http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa394592(VS.85).aspx</a> for examples. The information you are looking for is available e.g. through the property VolumeName of the Win32_LogicalDisk class, <a href="http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa394173(VS.85).aspx</a></p> <p><code>SELECT * FROM Win32_LogicalDisk WHERE VolumeName="MyLabel"</code></p>
7,014
<p>[We have a Windows Forms database front-end application that, among other things, can be used as a CMS; clients create the structure, fill it, and then use a ASP.NET WebForms-based site to present the results to publicly on the Web. For added flexibility, they are sometimes forced to input actual HTML markup right into a text field, which then ends up as a varchar in the database. This works, but it's far from user-friendly.]</p> <p>As such… some clients want a WYSIWYG editor for HTML. I'd like to convince them that they'd benefit from using simpler language (namely, Markdown). Ideally, what I'd like to have is a WYSIWYG editor for that. They don't need tables, or anything sophisticated like that.</p> <p>A cursory search reveals <a href="http://aspnetresources.com/blog/markdown_announced.aspx" rel="noreferrer">a .NET Markdown to HTML converter</a>, and then we have <a href="http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx" rel="noreferrer">a Windows Forms-based text editor that outputs HTML</a>, but apparently nothing that brings the two together. As a result, we'd still have our varchars with markup in there, but at least it would be both quite human-readable and still easily parseable.</p> <p>Would this — a WYSIWYG editor that outputs Markdown, which is then later on parsed into HTML in ASP.NET — be feasible? Any alternative suggestions?</p>
<p>I think the best approach for this is to combine </p> <ol> <li><a href="https://stackoverflow.com/q/460483/1366033">Converting Markdown to HTML</a> &amp;</li> <li><a href="https://stackoverflow.com/a/12724381/1366033">Displaying HTML in WinForms</a></li> </ol> <p>The most up to date Markdown Library seems to be <a href="https://github.com/lunet-io/markdig" rel="noreferrer"><strong>markdig</strong></a> which you can install <a href="https://www.nuget.org/packages/Markdig/" rel="noreferrer">via nuget</a></p> <p><a href="https://i.stack.imgur.com/Gl8UV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gl8UV.png" alt="Nuget &gt; Markdig"></a></p> <p>A simple implementation might be to:</p> <ol> <li>Add a <code>SplitContainer</code> to a <code>Form</code> control, set <code>Dock = Fill</code></li> <li>Add a <code>TextBox</code>, set <code>Dock = Fill</code> and set to <code>Multiline = True</code></li> <li>Add a <code>WebBrowser</code>, set <code>Dock = Fill</code></li> </ol> <p>Then handle the <code>TextChanged</code> event, parse the text into html and set to <code>DocumentText</code> like this:</p> <pre class="lang-cs prettyprint-override"><code>private void textBox1_TextChanged(object sender, EventArgs e) { var md = textBox1.Text; var html = Markdig.Markdown.ToHtml(md); webBrowser1.DocumentText = html; } </code></pre> <p>Here's a recorded demo:</p> <p><a href="https://i.stack.imgur.com/XcOsX.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/XcOsX.gif" alt="Demo screen share"></a></p>
<p>Can't you just use the same control I'm Stack Overflow uses (that we're all typing into)---WMD, and just store the Markdown in the VARCHAR. Then use the .NET Markdown to HTML converter, as you mentioned, to display the HTML as needed. Jeff talks about this in more detail in a StackOverflow podcast (don't know the episode number).</p>
5,077
<p>For various reasons calling <code>System.exit</code> is frowned upon when writing <strong>Java Applications</strong>, so how can I notify the calling process that not everything is going according to plan?</p> <p><strong>Edit:</strong> The 1 is a <code>standin</code> for any non-zero exit code.</p>
<p>The use of <code>System.exit</code> is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the <code>System.exit</code> could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.</p> <p>If the java application is really meant to be run as a standalone application, there is nothing wrong with using <code>System.exit</code>. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.</p>
<p>It's frowned upon for <em>normal</em> exits. If "not everything is going according to plan", then System.exit is fine.</p> <p>Update: I should add that I assume your '1' has meaning that is documented somewhere.</p>
5,279
<p>What are the real overhang limits? I see a lot online about 45 %, then up to 60 %, but I'm routinely doing them at up to 90 % for &quot;shortish&quot; distances and 80%+ for several centimeters at a time. I haven't tried to see how far I can do it, since I don't have filament to waste on that sort of thing.</p> <p>It's making me wonder how believable all the YouTube and website experts are. Same thing with stringing, they all talk about it on Ender 3's but this print has been going for 25 hours and has maybe two tiny strings.</p> <p>This is the second time I've printed this same STL with no supports.</p> <ul> <li>0.2 mm layer height</li> <li>Ender 3 Pro</li> <li>Generic PLA</li> </ul> <p><a href="https://i.stack.imgur.com/IqHWF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IqHWF.jpg" alt="Overhang" /></a></p>
<p>It is very difficult to determine a definitive number/value for the overhang angle, this is very dependent on the temperature, speed, material, nr. of walls amount of cooling fan percentage and the effectivity of the fan duct and your object geometry. Probably more settings are applicable.</p> <p>You could find out what the specific values for you printer and your settings are by printing an overhang test, e.g. like <a href="https://www.thingiverse.com/thing:2656594" rel="nofollow noreferrer">this one</a>:</p> <p><a href="https://i.stack.imgur.com/Xcypr.png" rel="nofollow noreferrer" title="All In One 3D Printer test"><img src="https://i.stack.imgur.com/Xcypr.png" alt="All In One 3D Printer test" title="All In One 3D Printer test" /></a></p> <p>Such a test will give you definitive answers on the overhang angle for your specific slicer settings and machine capabilities.</p>
<p>From my limited experience there is very little in the way of overhangs that won't print for a short distance. Depending what you're printing and what it's end use will be.</p> <p>In this case it needs to be robust enough for daily use holding napkins and toothpicks and cutlery at a restaurant.</p> <p>The model in the question printed for about 3 centimeters well over the threshold as shown in the picture and will print a bit more before joining the rest of the arm.</p> <p>The overhang tests available online are in my opinion a waste of time. It would be very bad design to print something like them because if it's not joining anything it would be too fragile to be any use. Dropping it off a table accidently or breathing too hard near it might result in it snapping.</p> <p>So if the distance is short anything up to about 80 - 85 % is possible. What happens is that the leading edge bends upwards a little bit after it prints. Then the next layer heats it soft and pushes it down and deposits on top of it (which then warps upwards) until it eventually reaches the join where the final warp is pushed down and joins nicely.</p> <p>You can do all the fancy tests you want, but this is how it actually works in practice.</p> <p>I find that post processing afterwards is minimal, less than if I'd used supports. <a href="https://i.stack.imgur.com/rO8hB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rO8hB.jpg" alt="Overhang after 1 hour" /></a></p>
2,127
<p>I am considering log-shipping of <a href="http://www.postgresql.org/docs/8.2/static/runtime-config-wal.html" rel="noreferrer">Write Ahead Logs (WAL)</a> in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, <strong>is there a way to prevent any activity on one table from being recorded in the WALs?</strong></p>
<p>Unfortunately, I don't believe there is. The WAL logging operates on the page level, which is much lower than the table level and doesn't even know which page holds data from which table. In fact, the WAL files don't even know which pages belong to which <em>database</em>.</p> <p>You might consider moving your high activity table to a completely different instance of PostgreSQL. This seems drastic, but I can't think of another way off the top of my head to avoid having that activity show up in your WAL files.</p>
<p>I'd consider <a href="http://www.danga.com/memcached/" rel="nofollow noreferrer">memcached</a> for use-cases like this. You can even spread the load over a bunch of cheap machines too.</p>
5,903
<p>How do I get the id of my Java process? </p> <p>I know there are several platform-dependent hacks, but I would prefer a more generic solution.</p>
<p>There exists no platform-independent way that can be guaranteed to work in all jvm implementations. <code>ManagementFactory.getRuntimeMXBean().getName()</code> looks like the best (closest) solution, and typically includes the PID. It's short, and <em>probably</em> works in every implementation in wide use.</p> <p>On linux+windows it returns a value like <code>&quot;12345@hostname&quot;</code> (<code>12345</code> being the process id). Beware though that <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getName%28%29" rel="noreferrer">according to the docs</a>, there are no guarantees about this value:</p> <blockquote> <p>Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.</p> </blockquote> <p><strong>In Java 9</strong> the new <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html" rel="noreferrer">process API</a> can be used:</p> <pre><code>long pid = ProcessHandle.current().pid(); </code></pre>
<p>This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux</p> <pre><code>netstat -tupln | grep portNumber </code></pre>
5,642
<p>I'm trying to design a camera handle, which will be around 8" long and will have a brass camera thread insert in the end, where the camera will be mounted. (That way, I don't have to screw the camera thread into plastic which will wear out faster.)</p> <p>If I print the handle normally, the end of the handle won't be solid so I can't solidly put that brass fitting in. If I set the fill in Cura to 100%, the print will take a very long time and will be unnecessarily solid. I only need a centimeter or two at the end to be solid.</p> <p>Is there a way to get one particular wall in Cura to be very thick (1-2cm) without affecting the other walls? Is there some other way to get a solid chunk in the end of the part?</p>
<p>I think you are approaching this wrong. Sounds like you need to design it to have a hollow wall. That said to answer your question no you cannot have your slicer modify prints like that. But it bears mentioning you can set all shells to what ever you want have have a very sparse infill. To you can set vertical shells to 3 or so. Top to 3 bottom to 2 and infill to 7-15% so it will be 93% hollow not counting the 3 layers of solid skin. </p> <p>Post pics of your design. Or let me know what else I can add. Check out my answer to this <a href="https://3dprinting.stackexchange.com/questions/3198/reducing-amount-of-material/3206#3206">other stack overflow question</a></p>
<p>I believe the solution is to use more walls in Cura.</p> <p>Here is a 50mm cylinder with a 20mm hole. I specified 10 walls in Cura.</p> <p>This should give extra plastic for the screw to bit into, but not take all day to print!</p> <p><a href="https://i.stack.imgur.com/cItxw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cItxw.png" alt="enter image description here"></a></p>
464
<p>I had filament on my 3D45 coming out of threads on the nozzle.</p> <p>To fix this I removed the nozzle to find the PTFE Liner in really bad shape. It looked crushed and deformed. Now the tough part, how do I replace the PTFE Liner. You can't seem to buy the liner and getting a replacement nozzle assembly from Dremel takes weeks. Can anybody help me figure this out please, I really would like to get back to printing!!</p>
<p>The initial problem you had with filament coming out of the threads at the nozzle is caused by improper seating of the heat break to the nozzle. In a &quot;from the ground up&quot; installation, you'd have an empty heat block, containing your heater core and your thermistor. Threaded into the &quot;bottom&quot; of the block is the nozzle, just a turn shy of being flush with the heat block. The heat break is the thin threaded segment extending from the heavily finned heat sink.</p> <p>The heat sink/heat break combination is threaded into the heat block until it contacts the nozzle, at which time, the nozzle is snugged into place securely. This keeps continuous the filament path from the heat break to the nozzle. Somewhere in time, a gap opened between the two.</p> <p>When you have assembled everything (including the PTFE liner), you'll want to heat the extruder assembly to about 250 °C and re-snug the nozzle to the heat block and heat break. Hold securely the heater block, as you do not want to apply force that will snap or otherwise damage the fragile heat break. Use a wrench that fits the heater block without contacting the wiring. Use a wrench that will keep your fingers safe, as the heat block will be hot.</p> <p>Stepping back in time a bit, when you remove the assembly, you should be able to determine the necessary length for the PTFE tube. I checked the manual for your printer and it is lacking in detail for this information. The diameters you've specified are standard and you should be able to locate a suitable substitute from many online sources. Amazon, Matterhackers, eBay, etc.</p> <p>Examine the heat break tubing. The diameter should not be so small as to allow you to push the PTFE tubing in from the heater block side, unless you have an unusually manufactured product. Dremel may have decided to create a new bit of engineering, but I'd expect not.</p> <p>You'll purchase more PTFE than required and examination of the upper portion of the heat sink should give you a clue how much to use. When the cover of the extruder assembly is removed, is there a guide for the filament to make it easier to push through the PTFE tubing? If so, the length of the PTFE is from the bottom of the guide to the bottom of the bore of the heat sink/heat break assembly.</p> <p>Photos of the upper entry to the heat sink/heat break, with the cover removed, would be useful, but you may have sufficient resources in hand to resolve your problem, once you replace the nozzle and purchase PTFE tubing of the correct size.</p>
<p>Capricorn sells 3x2mm ptfe heat break tube. Havnt used it long enough to know if it will hold up to its claims of withstanding temps up to 275c and beyond for any length of time; but I do know the generic ptfe I had in it before lived up to its reputation of going funny at 240c even though they sell it as rated for 250c. But capricorn has a good reputation in general it seems; and I can already testify that the reduction in friction in my bowden tube certainly did live up to the hype, so id recommend giving them a try.</p>
1,707
<p>Current main problem is that at various points during a print, one layer doesn’t attach well to the layer below it. That is what appears to be causing the artifacts in the second picture below, but the picture may not show it clearly.</p> <h2>Background</h2> <p>I have a Makerbot Replicator 5th generation printer. This is the one that is very locked down. As far as I know it can only use the slicer it comes with, Makerbot print, but I'd be happy to be told otherwise. It only prints in PLA and @Trish gave some good advice on drying out the filament. I've also leveled the print bed. Prints have improved from where they couldn't even finish to now where they just aren't very good quality.</p> <p>The issue I'm having now seems to be primarily that one build layer sometimes doesn't stick to the one below it very well. Then they peel up and the nozzle pulls them and re-melts them into a blob. I've attached two pictures. It's worse in the first one, then I lowered the first model layer fan setting from 50% to 45% and it improved and I was able to get the print in the second picture.</p> <p>Any help on what settings I can change would be great. Is this because it is underextruding? I think I'm stuck with whatever setting options are available in the Makerbot.print software.</p> <p><a href="https://i.stack.imgur.com/wJZOS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wJZOS.jpg" alt="First" /></a> <a href="https://i.stack.imgur.com/Htl1j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Htl1j.jpg" alt="Second" /></a></p> <h2>Print settings</h2> <p>The default print temp for this printer is 215. This is at 210 degrees, but those blobs aren't actually burned they are a mix of the previous red filament that was on the outside of the nozzle. The travel speed is 150 mm/s, First model layer print speed is 30mm/s, Raft to model shell vertical offset is 0.26mm, Raft to model vertical offset is 0.33mm (I can't tell what the different between those is), z-offset is 0 (default), Layer height is 0.14mm. In the second picture the print was attached but separated easily from the raft.</p> <p>A couple more settings that might matter is the Print speed: Outlines is 20mm/s, and the Print Speed: Infill is 90mm/s</p> <h2>Update 3/15/19</h2> <p>I made several of the changes suggested including lowering the temperature, leveling the bed, adjusting the Z-offset, and lowering the infill speed. I also continued to dry the filament in a dry box with a lot of desicant that I dry periodically. The desicant seemed to make much more difference than drying the filament at 50C for a couple hours. Print quality has improved a lot, but isn't great. I'm coming to the conclusion that the filament has been damaged by poor storage. It has been left in a drawer in a humid, hot room over the past summer or more.</p> <p>I'm still using a raft because prints fail completely without it and work reasonably well with one so I have no problem using a raft. Now most of my problem is blobs of filament that I think are running down the nozzle from the heater core. I may have to take some timelapse video to figure that part out. I'm also having some stringing which may be a filament quality issue and some layer shifting.</p>
<p>Your printer is improperly leveled with respect to the distance of the nozzle to the bed. This, and a high raft to print part distance, causes consecutive layers to not adhere well. </p> <p>PLA should not need that high temperatures to print nor does it need a raft. Rafts are interesting when printing filaments that have high shrinkage. Furthermore, a 90 mm/s infill speed is pretty high, and do not use the part cooling fan for the first few layers (if you cool too much it can curl up).</p> <p>You need to re-level the bed and make sure that the nozzle to build plate distance is the thickness of a sheet of A4 paper when <code>Z = 0</code>.</p>
<p>Reading your print settings, I noticed some oddities:</p> <ul> <li>215 °C</li> <li>raft</li> </ul> <p>These are settings one does not expect for PLA but seem reasonable for ABS. The 215 °C could be reasonable if</p> <ul> <li>the melt zone is extremely short and partially insulated (Makerbot Mk 10 style)</li> <li>the PLA is a blend with a particularly high melting temperature</li> </ul> <p>Common PLA is printed with</p> <ul> <li>190-200°C nozzle temperature in most e3d-v6 derivates and &quot;Mk 8&quot;<sup>*</sup></li> <li>60 °C bed temperature, when available</li> <li>no raft but possibly a brim to aid in getting a spatula under the print</li> <li>cleaning the build platform of residual fingerprints with Isopropyic alcohol or acetone is always adviseable</li> <li>a glass or metal print surface might get better adhesion from priming it with: <ul> <li>PVA-Gluestick/3dLac/Hairspray</li> <li>a fresh painters tape, but you <strong>need</strong> to re-level to include it!</li> </ul> </li> <li>a BuildTak (or clone) surface does <em>not</em> need additional settings</li> </ul> <p><sup>* As far as I know, that Mk 8 does not reference which manufacturer designed this thing, which makes it a kinda nonsensical naming. Mk 8 is short for Mark 8, so by definition the 8th iteration of a specific product.</sup></p>
1,144
<p>I am wondering if making an hermetic box is feasible using 3D printer. The box would be a cube with a front face removable, with screw and sealing joint to close it.<br> I searched for different materials, however, none talks about hermiticity. (However, I found a product that seems to improve water resistance of 3D printed items <a href="http://www.nanovia-technologies.com/...mperm-f10-ft-tds.pdf" rel="noreferrer">here</a>, which might be a starting point) </p> <p>Does anyone have experienced to make hermetic things ? I am specially interested in carbon fiber reinforced materials.</p>
<p>A few thoughts that might help...</p> <p><strong>Material:</strong></p> <ul> <li>ABS can be vapor smoothed with Acetone which results in the layers sort of "melting" together to form a smoother, and less porous surface.</li> <li>Other plastics can be smoothed with compatible solvents, but I've not tried solvent smoothing with anything other than ABS. Be careful if you try.</li> </ul> <p><strong>Print Method:</strong></p> <ul> <li>Consider slightly higher print temps to increase layer adhesion. You'll likely have to compensate with extra retraction to avoid excessive stringing.</li> <li>Consider more perimeter layers and more top/bottom layers.</li> <li>The CF materials are stiffened with chopped CF strands...I think it's a stretch to call them "reinforced" unless you happen to have a Markforged printer or similar.</li> </ul> <p><strong>Sealants:</strong> This is probably your best bet.</p> <ul> <li>Epoxy: Generally considered effective for producing hermetically sealed containers. Dip or brush on. Mind your VOC's and pay attention to working time.</li> <li>Plasti-dip or similar sealants: These may be good enough for your application and result in a rubbery coating over your part. Good for water sealing, and may be close enough to hermetically sealed for your needs.</li> </ul> <p><strong>Design:</strong></p> <ul> <li>To mechanically seal the opening, there are many options depending on your requirements. O-rings, gaskets, etc. If you use a rubberized dip, you may be able to skip the gasket. You could install a few threaded inserts around the perimeter of the opening, put in the screws, then dip. After drying, you slice around the screw and remove it (this just keeps the coating out of your threads) Dip the cover as well. Then when you screw on the cover, it will provide a water-tight seal. To help make a good seal, apply a silicone grease to the mating surface.</li> </ul> <p>I hope this helps. :-)</p>
<p>I believe this can be achieved using o-rings. That's what they use for scuba diving lights. The component doesn't need to be circular, but the o-ring needs to be slightly smaller than the component so that it is held in place via tension. Additionally, you'll want to create a groove for the o-ring to set it in and make sure that the o-ring protrudes slightly so that it applies pressure and creates a tiny amount of friction when it's coupled with its counterpart. Apply some type of lubricant to prevent the o-ring from sliding out of place and to keep it from drying out and cracking. </p>
392
<p>I'm trying to implement something like this:</p> <pre><code>&lt;div&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Port name&lt;/td&gt; &lt;td&gt;Current port version&lt;/td&gt; &lt;td&gt;New port version&lt;/td&gt; &lt;td&gt;Update&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;% foreach (var ip in Ports) { %&gt; &lt;tr&gt; &lt;td&gt; &lt;%= ip.PortName %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.CurrentVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.NewVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="&lt;% ip.PortName %&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>The button's <code>CommandArgument</code> property is where my code complains about not being able to resolve symbol <code>ip</code>. Is there any way to do what I'm trying to do? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction. </p> <p>You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action.</p>
<p>I think you have to enclose your block in Form tags ans runat=server.</p>
3,767
<p>I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.</p> <p>What is the easiest way to get the base 10 logarithm of a Fixnum?</p>
<p>There is </p> <pre><code>Math::log10 (n) </code></pre> <p>And there is also a property of logarithms that <code>logx(y) = log(y)/log(x)</code></p>
<p><a href="http://www.ruby-doc.org/core-1.8.7/classes/Math.html#M001197" rel="nofollow noreferrer">Math.log10</a>(numeric) => float returns base 10 log</p>
7,447
<p>I recently bought a Creality Ender 3 V2. I have heard that it is best to use a raft when printing. I have tried to use a raft a few different times using PLA, with different settings each time. When I try to peel the raft off of the print, it will snap around the bottom of the print. Are there any recommended slicer settings or printer tips to help this?</p>
<blockquote> <p>I have heard that it is best to use a raft</p> </blockquote> <p>Actually, it is not best to use a raft, a raft is an aid that can best be used in special cases, e.g. for filaments that shrink reasonably (PLA is not such a filament).</p> <p>A raft always caused a rough bottom of your print and is frequently difficult to remove. A raft is an aid for adhesion if your print object geometry or choice of filament requires you to use it, but as far as printing PLA, a raft is generally not needed. You need to spend some time to level the bed properly and dial in the best nozzle to bed distance (the thickness of a sheet of plain printing paper like A4 or US Letter will work fine).</p> <p>There are usually options available in slicer software to control the distance between the raft and the first layer of the print object. It is also reported that inserting a wait time to solidify/cool the raft is beneficial for creating less strong bonds between the raft and the print object.</p>
<p>Rafts fuse with models because the filament gets overheated. To avoid this, keep the temperature in the room between between 23 and 28 °C. Malfunctioning extruder fans, a heater &amp; thermocouple, extruder printed circuit board (PCB), extruder cable, and motherboard can be also to blame.</p>
2,161
<p>Compare</p> <pre><code>String.Format("Hello {0}", "World"); </code></pre> <p>with</p> <pre><code>"Hello {0}".Format("World"); </code></pre> <p>Why did the .Net designers choose a static method over an instance method? What do you think?</p>
<blockquote> <p>Because the Format method has nothing to do with a string's current value.</p> </blockquote> <p>That's true for <em>all</em> string methods because .NET strings are immutable.</p> <blockquote> <p>If it was non-static, you would need a string to begin with.</p> </blockquote> <p>It does: the format string.</p> <p>I believe this is just another example of the many design flaws in the .NET platform (and I don't mean this as a flame; I still find the .NET framework superior to most other frameworks).</p>
<p><code>String.Format</code> takes at least one String and returns a different String. It doesn't need to modify the format string in order to return another string, so it makes little sense to do that (ignoring your formatting of it). On the other hand, it wouldn't be that much of a stretch to make <code>String.Format</code> be a member function, except I don't think C# allows for const member functions like C++ does. [Please correct me and this post if it does.]</p>
4,324
<p>I would like to monitor the following system information in Java:</p> <ul> <li>Current CPU usage** (percent)</li> <li>Available memory* (free/total)</li> <li><p>Available disk space (free/total)</p> <p>*Note that I mean overall memory available to the whole system, not just the JVM.</p></li> </ul> <p>I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution.</p> <p>If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself).</p> <p>Any suggestions are much appreciated.</p> <p>To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es).</p> <p>The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future.</p> <p>For my current needs, I'm leaning towards the following:</p> <ul> <li>For CPU usage, <code>OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors()</code> (load average per cpu)</li> <li>For memory, <code>OperatingSystemMXBean.getTotalPhysicalMemorySize()</code> and <code>OperatingSystemMXBean.getFreePhysicalMemorySize()</code></li> <li>For disk space, <code>File.getTotalSpace()</code> and <code>File.getUsableSpace()</code></li> </ul> <p>Limitations:</p> <p>The <code>getSystemLoadAverage()</code> and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that <code>getSystemLoadAverage()</code> returns -1 on Windows).</p> <p>Although originally licensed under GPL, it <a href="http://forums.hyperic.com/jiveforums/thread.jspa?threadID=11426&amp;tstart=0" rel="noreferrer">has been changed</a> to <a href="http://support.hyperic.com/display/SIGAR/Home#Home-license" rel="noreferrer">Apache 2.0</a>, which can generally be used for closed source, commercial products.</p>
<p>Along the lines of what I mentioned <a href="https://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information#25583">in this post</a>. I recommend you use the <a href="https://github.com/hyperic/sigar" rel="noreferrer">SIGAR API</a>. I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a <strike>GPL 2</strike> Apache 2.0 license. Check it out. I have a feeling it will meet your needs.</p> <p>Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc.</p>
<pre><code> OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class); System.out.println((osBean.getCpuLoad() * 100) + &quot;%&quot;); </code></pre> <p>import <code>com.sun.management.OperatingSystemMXBean</code></p> <p>It only starts working after the second call so save the osBean and put it in a loop</p>
6,937
<p>I've been curious about the various UV/Laser printers in (or coming into) market that use liquid resin. I've seen the samples of the <a href="https://fslaser.com/Products/View/1" rel="noreferrer">Pegasus Touch</a>, <a href="http://formlabs.com/products/materials/" rel="noreferrer">Form1</a>, and the <a href="http://carbon3d.com/" rel="noreferrer">Carbon3D</a> as examples. I like the specifications of the quality that machines can put out. However, in my experience with FDM printing, there almost always seems to be something not quite right about the print.</p> <p>So, what are some major maintenance considerations for these types of 3D printing? Also, specifically, are supports and overhangs as much an issue in these types of printers as with FDM/FFF?</p> <p>Here are some things I consider major maintenance considerations in FDM:</p> <ul> <li>Extruder Clogging</li> <li>Build platform conditions (i.e. levelness, clean, type of tape, bubbles in tape)</li> <li>Variances in material quality (i.e. diameter, purity, physical conditions)</li> <li>Mechanics of the machine (i.e. belts, rods, gear teeth, etc.)</li> <li>Build environment (i.e. ensuring steady temperature in the build environment, minimize draft)</li> </ul> <p><sub>I'm not necessarily looking for printer recommendations, more so technical insight on the technology.</sub></p>
<p>Taken in order your questions:</p> <p>Maintenance for a resin printer means keeping the vat or tray clean, using appropriate methods to remove the unused resin (or leaving it in the vat per manufacturer's directions). Cleaning the tray should be done also per manufacturer's spec, although each printer's user forum may provide better or more effective options.</p> <p>The Pegasus Touch has a caution regarding dripping resin on the mirrors, so there's operational care considerations for these types of printers.</p> <p>There is a build platform for these printers. The flatness and level are as critical or more so for resin printers, as the resolution can be astonishingly high. If any portion of a print does not bond to the platform, that entire print will have a failed section, creating an entirely failed print. Gravity is not particularly helpful in that respect, at least with the Pegasus Touch.</p> <p>The release medium varies from device to device. The Pegasus Touch originally used PDMS (silicon release compound) and now uses what's called a SuperVat. The plastic material in the SuperVat is purported to provide better release and fewer failures, along with increased lifespan. PDMS becomes cloudy from repeated printing in the same location and can be torn away from the vat if the print does not properly release.</p> <p>I've become aware of a product from Australia that has had good reports from use in a B9 Creator resin printer. The report indicates that it releases the model quite easily and barely turns cloudy. I have an order pending for this material, as I am hopeful it will perform as described.</p> <p>The mechanics are also varied. One expects a system to raise and lower the build platform and to direct the laser or illumination system (DLP), but generally, this type of printer is somewhat simpler mechanically.</p> <p>Because I live in a hot humid climate, my Pegasus Touch remains in the box, and my brain is about to explode with what I've learned of using it. Environmental conditions are likely to vary with different machines. I've seen references that 70 degrees F is too cold, others that say 70-75 degrees F is just fine, anything higher is too hot. Another user says that 65 degrees is good. The type of resin also becomes an important factor for environmental conditions.</p> <p>The laser will create heat in the resin, so I'm inclined to believe that cooler is better. Different colors require different durations of laser light, somewhat akin to various plastics having different temperatures.</p> <p>supports and overhangs are important considerations in an SLA or DLP printer, just as they are in FDM.</p> <p>Expect also that many of the resin printers require that the user purchase only the product provided by the manufacturer. This isn't necessarily a negative as most of the resin sources are priced similarly.</p> <p>If I've missed any part of your question, let me know.</p>
<p>Despite how many vendors make it appear, resin-curing SLA/DLP printers are industrial or commercial tools that are really not suitable for home desktop use. Here are the major downsides:</p> <ul> <li>Significantly more expensive to operate than FDM printers, in most cases. </li> <li>The resin is seriously toxic until fully cured. Fumes can be an issue for users handling raw resin, and you should NEVER put a photopolymer print into a chemically-sensitive environment like an aquarium or children's toy. </li> <li>Prints require messy post-processing to rinse off excess resin (usually with rubbing alcohol) and additional UV light exposure to finish hardening the photopolymer. The used alcohol/resin rinse mix is basically hazmat waste. </li> <li>In bottom-up printers, the window in the print vat is typically a consumable. Some printers require replacing the vat ($$) after every liter or two of cured resin. (Technology is advancing rapidly here though.)</li> <li>The peel mechanism in bottom-up printers is often a major source of print flaws, due to the need to rock/tilt/slide the print to free it from the vat window.</li> <li>In top-down printers, you have to pay a large up-front consumables cost to initially fill the resin tank. (There are workarounds here like floating a layer of resin on brine, but these have their own technical issues.)</li> <li>If you leave the resin in the printer for an extended period, you'll probably find a hardened layer on the surface from stray light exposure and have to clean out or replace the vat.</li> <li>Resin vats/tanks need to be kept clean and free of cured resin debris from failed prints or stray light. </li> <li>Every combination of resin chemistry, printer light source, and printer optics requires specific tuning to dial in the photopolymer curing behavior. This means it's somewhat difficult to change resin brands, and you may effectively be locked into the printer manufacturer's resin. Many light sources will change in intensity or develop dim regions over time as they age, which will either harm print quality, require period recalibration, or require frequent light source replacement. </li> <li>There is a limited number of options for print materials. Technology here is advancing rapidly, but for the most part, SLA/DLP prints are non-load-bearing models with a limited range of color options. </li> </ul> <p>These are some pretty significant "user experience" downsides compared to a consumer desktop FDM printer. It's more hazard, more work, and more cost than FDM. SLA/DLP is primarily advantageous where high resolution or high print speeds are required. </p>
229
<p>I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code:</p> <p>GlobalVar.property = 11;</p> <p>(assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?</p>
<p>The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually <strong>read</strong> this value back again?</p> <p>The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the <strong>use</strong> of the variable, so here's a trivialish example in neutral C-like syntax:</p> <pre><code>int x = 0, y = 0; //thread A does: x = 1; y = 2; if (y == 2) print(x); //thread B does, at the same time: if (y == 2) print(x); </code></pre> <p>Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order.</p> <p>This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors.</p> <p>If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not.</p>
<p>If the operation is atomic, you <em>should</em> be able to get by just fine. But I wouldn't do that in practice. It is better just to acquire a lock on the object and write the value.</p>
9,769
<p>I am working on an application for college music majors. A feature i am considering is slowing down music playback without changing its pitch. I have seen this done in commercial software, but cannot find any libraries or open source apps that do anything like this. </p> <ol> <li>Are there libraries out there?</li> <li>How could this be done from scratch from various file formats?</li> </ol> <p>Note: I am working in java but am not oppossed to changing languages. </p>
<p>Timestretching is quite hard. The more you slow down or speed up the sound the more artifacts you get. If you want to know what they sound like listen to "The Rockafeller Skank" by Fat Boy Slim. There are a lot of ways to do it that all have their own strengths and weaknesses. The math can get really complex. That's why there are so many proprietary algorithms.</p> <p>This page explains things a bit clearer than I can and links to the Dirac library. <a href="http://www.dspdimension.com/admin/time-pitch-overview/" rel="nofollow noreferrer">http://www.dspdimension.com/admin/time-pitch-overview/</a></p> <p>I found this link for java code to do pitch shifting/timestretching <a href="http://web.archive.org/web/20081103052639/http://www.adetorres.com/keychanger/KeyChangerReadme.html" rel="nofollow noreferrer">http://www.adetorres.com/keychanger/KeyChangerReadme.html</a></p>
<p>audacity does it out of the box and it's free. THere are several plug ins for mp3 players as well that are free. Apparently it's pretty easy to do with an mp3 since it's already coded in the frequency domain.</p>
8,470
<p>I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>
<p>Another option is to consider looking at the <a href="http://www.jcraft.com/jsch/" rel="noreferrer" title="JSch library">JSch library</a>. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.</p> <p>It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.</p> <p>Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)</p> <pre><code>JSch jsch = new JSch(); String knownHostsFilename = "/home/username/.ssh/known_hosts"; jsch.setKnownHosts( knownHostsFilename ); Session session = jsch.getSession( "remote-username", "remote-host" ); { // "interactive" version // can selectively update specified known_hosts file // need to implement UserInfo interface // MyUserInfo is a swing implementation provided in // examples/Sftp.java in the JSch dist UserInfo ui = new MyUserInfo(); session.setUserInfo(ui); // OR non-interactive version. Relies in host key being in known-hosts file session.setPassword( "remote-password" ); } session.connect(); Channel channel = session.openChannel( "sftp" ); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.get("remote-file", "local-file" ); // OR InputStream in = sftpChannel.get( "remote-file" ); // process inputstream as needed sftpChannel.exit(); session.disconnect(); </code></pre>
<p>The best solution I've found is <a href="http://www.lag.net/paramiko/" rel="nofollow noreferrer">Paramiko</a>. There's a Java version.</p>
3,542
<p>I have an Ender 3 pro. In my country electricity outage is an issue, though it comes back pretty instantaneously, when I hit the resume button on the Ender 3 pro after heating the hot end and the bed when the hot end lifts the Y-axis or X-axis shifts a little bit, I do not understand why as when there is no power outage the prints are just flawless.</p> <p>I have also tried tightening everything but feels like the motors are having their own fun tilting an extra step for no reason. I have thrown away many prints because of this problem as I work in robotics and prototyping is a necessary thing for me and so is the accuracy.</p>
<p>Not sure on your exact firmware, but it could be that it is using a <a href="https://marlinfw.org/docs/gcode/M413.html" rel="nofollow noreferrer">M413 power loss recovery</a> rather than a power loss interrupt pin. Possible you might be able to change this with your current firmware, but worst case you could install a new controller that does support this power loss interrupt pin.</p> <p>Depending on the frequency and duration of your power outages it may be worth getting an uninterruptible power supply (UPS). With the heat bed off <a href="https://rads.stackoverflow.com/amzn/click/com/B000FBK3QK" rel="nofollow noreferrer" rel="nofollow noreferrer">this UPS</a> would run a full print easily. It would even handle a heat bed for shorter outages.</p> <p>Where you work in robotics, you are probably electrically savvy enough to set your printer up on <a href="https://youtu.be/5uUb-VnTzlU?t=625" rel="nofollow noreferrer">direct DC battery power</a>, which would be cheaper than a UPS of equivalent energy storage. If you need help going that route just post over on electrical engineering stack exchange with the power supply info.</p>
<p>you'll need a UPS with EMI filter. I had this same issue and I opt to a regular desktop UPS and the problem was still there. So, I connected a EMI filter and it worked.</p>
2,095
<p>I've asked a question before on the extruder gear clicking on my CR-10, but I'm certain its because of the nozzle getting clogged for some reason. I'm using a standard 0.4&nbsp;mm nozzle with white PLA and randomly during the print the extruder gear starts clicking on the fast parts and then under extrudes the rest of the print, eventually the hobbed gear digs away at the filament and doesn't grip anymore. Why would the nozzle keep getting clogged? Could it be because the filament isn't high enough quality and is leaving particles in the nozzle? </p> <p><a href="https://i.stack.imgur.com/j83BN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j83BN.jpg" alt="enter image description here"></a></p> <p>Additionally, when I performed a cold pull after breaking up the blockage on the inside, the filament came out like a thin film even though it was purging fine before I cooled it down. Why?</p> <p><a href="https://i.stack.imgur.com/PwXZl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PwXZl.jpg" alt="enter image description here"></a></p> <ul> <li>190&nbsp;&deg;C nozzle temperature (tried printing at 210&nbsp;&deg;C and the filament burned)</li> <li>50&nbsp;&deg;C bed temperature</li> <li>60&nbsp;mm/s speed, outline 50&nbsp;% - first layer being 30&nbsp;mm/s</li> <li>0.2&nbsp;mm layer height</li> </ul> <p>This starting happening after I returned to printing after a 6 month break, with the filament being stored in a cool and dry cupboard for around a year (the filament was on the cheaper side, but still highly recommended by SUNLU)</p>
<p>Turns out the filament was the problem, I tried printing a model with a high quality sample PLA filament I had and it printed perfectly; one of the cleanest prints I've had. Never skimp on filament.</p> <p><img src="https://i.stack.imgur.com/AT3cW.jpg" alt="enter image description here"></p>
<p>White PLA is usually some of the worst stuff to print with, generally avoid it. I would say. I myself are having a lot of problems with it as well.</p>
1,457
<p>In Windows, is there an easy way to tell if a folder has a subfile that has changed?</p> <p>I verified, and the last modified date on the folder does not get updated when a subfile changes.</p> <p>Is there a registry entry I can set that will modify this behavior?</p> <p>If it matters, I am using an NTFS volume. </p> <p>I would ultimately like to have this ability from a C++ program. </p> <p><strong>Scanning an entire directory recursively will not work for me because the folder is much too large.</strong></p> <p><strong>Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.</strong> </p> <p><strong>Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.</strong></p>
<p>This <a href="http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx" rel="nofollow noreferrer">article</a> should help. Basically, you create one or more notification object such as:</p> <pre> HANDLE dwChangeHandles[2]; dwChangeHandles[0] = FindFirstChangeNotification( lpDir, // directory to watch FALSE, // do not watch subtree FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes if (dwChangeHandles[0] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } // Watch the subtree for directory creation and deletion. dwChangeHandles[1] = FindFirstChangeNotification( lpDrive, // directory to watch TRUE, // watch the subtree FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes if (dwChangeHandles[1] == INVALID_HANDLE_VALUE) { printf("\n ERROR: FindFirstChangeNotification function failed.\n"); ExitProcess(GetLastError()); } </pre> <p>and then you wait for a notification:</p> <pre> while (TRUE) { // Wait for notification. printf("\nWaiting for notification...\n"); DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, INFINITE); switch (dwWaitStatus) { case WAIT_OBJECT_0: // A file was created, renamed, or deleted in the directory. // Restart the notification. if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_OBJECT_0 + 1: // Restart the notification. if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE ) { printf("\n ERROR: FindNextChangeNotification function failed.\n"); ExitProcess(GetLastError()); } break; case WAIT_TIMEOUT: // A time-out occurred. This would happen if some value other // than INFINITE is used in the Wait call and no changes occur. // In a single-threaded environment, you might not want an // INFINITE wait. printf("\nNo changes in the time-out period.\n"); break; default: printf("\n ERROR: Unhandled dwWaitStatus.\n"); ExitProcess(GetLastError()); break; } } } </pre>
<p>If you are not opposed to using .NET the <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="nofollow noreferrer">FileSystemWatcher</a> class will handle this for you fairly easily.</p>
8,071
<p>When you roll out changes to a live web site, how do you go about checking that the <em>live</em> system is working correctly? Which tools do you use? Who does it? Do you block access to the site for the testing period? What amount of downtime is acceptable?</p>
<p>I tend to do all of my testing in another environment (not the live one!). This allows me to push the updates to the live site knowing that the code should be working ok, and I just do sanity testing on the live data - make sure I didn't forget a file somewhere, or had something weird go wrong.</p> <p>So proper testing in a testing or staging environment, then just trivial sanity checking. No need for downtime.</p>
<p>Run your main server on a port other than 80. Stick a lightweight server (e.g. nginx) in front of it on port 80. When you update your site, start another instance on a new port. Test. When you are satisfied that it has been deployed correctly, edit your proxy config file, and restart it. In nginx's case, this results in zero downtime or failed requests, and can also provide performance improvements over the more typical Apache-only hosting option.</p> <p>Of course, this is no substitute for a proper staging server, it is merely a 'polite' way of performing the handover with limited resources.</p>
9,292
<p>I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. </p> <p>If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like:</p> <pre><code>Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). </code></pre> <p>I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again.</p> <p>The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: </p> <pre><code>timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); </code></pre> <p>Is there an easier way??</p>
<p>According to the <a href="http://java.sun.com/javase/6/docs/api/java/util/Timer.html" rel="noreferrer"><code>Timer</code></a> documentation, in Java 1.5 onwards, you should prefer the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html" rel="noreferrer"><code>ScheduledThreadPoolExecutor</code></a> instead. (You may like to create this executor using <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html" rel="noreferrer"><code>Executors</code></a><code>.newSingleThreadScheduledExecutor()</code> for ease of use; it creates something much like a <code>Timer</code>.)</p> <p>The cool thing is, when you schedule a task (by calling <code>schedule()</code>), it returns a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledFuture.html" rel="noreferrer"><code>ScheduledFuture</code></a> object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time.</p> <p>ETA: The <code>Timer</code> documentation linked to doesn't say anything about <code>ScheduledThreadPoolExecutor</code>, however the <a href="http://openjdk.java.net/" rel="noreferrer">OpenJDK</a> version had this to say:</p> <blockquote> <p>Java 5.0 introduced the <code>java.util.concurrent</code> package and one of the concurrency utilities therein is the <code>ScheduledThreadPoolExecutor</code> which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the <code>Timer</code>/<code>TimerTask</code> combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing <code>TimerTask</code> (just implement <code>Runnable</code>). Configuring <code>ScheduledThreadPoolExecutor</code> with one thread makes it equivalent to <code>Timer</code>.</p> </blockquote>
<p>Here is the example for Resetable Timer . Try to change it for your convinence...</p> <pre><code>package com.tps.ProjectTasks.TimeThread; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * Simple demo that uses java.util.Timer to schedule a task to execute * every 5 seconds and have a delay if you give any input in console. */ public class DateThreadSheduler extends Thread { Timer timer; BufferedReader br ; String data = null; Date dNow ; SimpleDateFormat ft; public DateThreadSheduler() { timer = new Timer(); timer.schedule(new RemindTask(), 0, 5*1000); br = new BufferedReader(new InputStreamReader(System.in)); start(); } public void run(){ while(true){ try { data =br.readLine(); if(data != null &amp;&amp; !data.trim().equals("") ){ timer.cancel(); timer = new Timer(); dNow = new Date( ); ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Modified Current Date ------&gt; " + ft.format(dNow)); timer.schedule(new RemindTask(), 5*1000 , 5*1000); } }catch (IOException e) { e.printStackTrace(); } } } public static void main(String args[]) { System.out.format("Printint the time and date was started...\n"); new DateThreadSheduler(); } } class RemindTask extends TimerTask { Date dNow ; SimpleDateFormat ft; public void run() { dNow = new Date(); ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); } } </code></pre> <p>This example prints the current date and time for every 5 seconds...But if you give any input in console the timer will be delayed to perform the given input task...</p>
5,193
<p>Im planning on building an enclosure for my CR-10S and am debating whether to use MDF walls lined with an insulation foam that reduces noise and keeps the heat in or going with double pane glass walls.</p> <p>My main concern is not necessarily keeping the enclosure hot as it is for noise reduction. Obviously the wood with insulation will give better sounds dampening, but I am wondering if anyone has tried both or at least heard a printer before and after with both and if the glass alone had a significant effect on the sounds reduction.</p>
<p>First you should check if the bed still works when applying 12V directly. You can then also check the voltage over the 12V output terminals to measure the power supply unit while it is powering the bed. It is unclear whether you measured the voltage of the PSU while it was powering a large load.</p> <p>It is also a good idea to get the external MOSFET board out of the equation (the less components you have, the less you need to troubleshoot).</p> <p>From the post can be concluded that you are using the so-called RAMPS EFB setup, e.g. in <a href="https://github.com/MarlinFirmware/Marlin/" rel="nofollow noreferrer">Marlin firmware</a> defined by constant <code>IS_RAMPS_EFB</code> in your firmware printer setup (Extruder on pin 10, fan on pin 9 and bed on pin 8).</p> <p>In the pin configuration file <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/pins_RAMPS.h" rel="nofollow noreferrer">pins_RAMPS.h</a> you can find the following lines:</p> <pre><code>#define FAN_PIN RAMPS_D9_PIN #define HEATER_BED_PIN RAMPS_D8_PIN </code></pre> <p>To change the pin layout, switch the values of the constants.</p>
<p>you can swap pins in Marlin firmware. When you download it from GitHub, there is a file called <a href="https://github.com/prusa3d/Prusa-Firmware/blob/MK3/Firmware/pins.h" rel="nofollow noreferrer">pins.h</a> (please be aware that this file is an example), and you can play with your setup to skip the broken mosfet.</p> <p><strong>Sometimes, it could be easier and faster to desolder and swap elements directly on the board - that depends on the skill set we have</strong></p>
931
<p>I'm using a CraftBot original to print PLA, but some of the filament has become stuck in the teeth of the <a href="https://craftunique.com/item/craftbot-extruder-gear" rel="nofollow">extruder gear</a> on its way into the hot end. I'm having issues with the gear becoming stuck and "clicking" instead of turning, and I suspect it is because of the clogged teeth. I haven't changed materials in a long time. I've cleared several print head clogs, but each time the gear gets back around to the one spot, it seems to get stuck again.</p> <p>Are there any good ways to clean this gear? I was thinking of putting it in a toaster oven and trying to melt the PLA off it, ideally without setting my house on fire in the process. Anyone have better ideas?</p>
<p>I mostly use a tooth brush for that kind of problem</p>
<p>If you are able to remove the gear, as I suspect you can, a useful tool is the file card. It resembles a flat hair brush but the bristles are short wire, very stiff. In traditional use, it removes metal shavings from conventional metal files. It will easily remove plastic from between the gear teeth. If you are unable to remove the gear, but can access a portion of the exposed teeth, a suitably named dental pick can remove slowly the clogged material.</p> <p>Cooking the gear may not cause a fire, but could carbonize the plastic onto the teeth, perhaps creating a greater problem.</p>
322
<p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p>
<p>This appears to work.</p> <pre><code>public string RenderControlToHtml(Control ControlToRender) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter stWriter = new System.IO.StringWriter(sb); System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter); ControlToRender.RenderControl(htmlWriter); return sb.ToString(); } </code></pre>
<p>If your control is a web user control, this is how you can get to the HTML it emits from another page or handler:</p> <pre><code>public void GetHtmlFromMySweetControl(HttpContext context) { HttpRequest httpRequest = context.Request; HttpResponse httpResponse = context.Response; string foo = httpRequest["foo"]; Page pageHolder = new Page(); string path = "~/usercontrols/MySweetControl.ascx"; MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path); ctrl.BindProducts(foo); pageHolder.Controls.Add(ctrl); StringWriter sw = new StringWriter(); context.Server.Execute(pageHolder, sw, false); httpResponse.Write(sw.ToString()); } </code></pre>
8,337
<p>I am having trouble with my Visual Studio 2005 IntelliSense for some time now.<br><br> It used to work fine, but for some reason the 'Updating IntelliSense...' does no longer seem to be able to complete for the solution I'm working on currenly- it simply gets stuck somewhere at about 3-bars of progress and blocks one of my precious CPUs for eternity.<br><br> Deleting the .ncb file of my solution and performing a full 'Clean' afterwards was no help. The 'Update' simply gets stuck again.<br><br> The project I'm working on is a fairly large C++ solution with 50+ projects, quite a few template classes (even more lately) and in general quite complex. I have no idea which impact this might have on the IntelliSense.<br><br> Visual Studio 2005 Service Pack 1 and all hotfixes which rely on it are <em>not</em> installed (we hade huge problems with this one, so we haven't migrated yet).<br><br> Any answer is very much appreciated on this one. Gives me the creeps.. <br><br> Cheers,<br> \Bjoern</p>
<p>I have found that the best fix for Intellisense in VS2005 is to install SP1, and then this hotfix: <a href="http://support.microsoft.com/kb/947315" rel="noreferrer">947315</a>. It has the added benefit of fixing most of the multi-core build issues.</p> <p>This hotfix also includes the ability to control Intellisense via Macros. More information <a href="http://blogs.msdn.com/vcblog/archive/2007/11/19/controlling-intellisense-through-macros.aspx" rel="noreferrer">here</a>.</p> <p>As for making SP1 more friendly for existing code, you might also check out this hotfix for template compilation: <a href="http://support.microsoft.com/kb/930198" rel="noreferrer">http://support.microsoft.com/kb/930198</a> </p>
<p>Intellsense is problematic. Very problematic. When it works, it's great, but more often than not it will cause more problems than it's worth. It will hang up, it will parse through files while you are trying to compile code and will generally make VC 2005 sometimes run like a dog. As a previous poster suggested, disable intellisense (and chose a potential alternative -- I also support VAX).</p> <p>Supposedly the hotfix and SP1 provided by MS will fix <em>some</em> intellisense problems, but not all. We have seen minimal help from these where I work. You are better off to disable it and rely on something else.</p> <p>My feeling is that the slowness comes from the size of the projects. Yours seems like it might fall into that case.</p>
9,511
<p>What is the best way to do per-user database connections in <code>Rails</code>? </p> <p>I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.</p>
<p>Put something like this in your application controller. I'm using the subdomain plus "_clientdb" to pick the name of the database. I have all the databases using the same username and password, so I can grab that from the db config file.</p> <p>Hope this helps!</p> <pre><code>class ApplicationController &lt; ActionController::Base before_filter :hijack_db def hijack_db db_name = request.subdomains.first + "_clientdb" # lets manually connect to the proper db ActiveRecord::Base.establish_connection( :adapter =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['adapter'], :host =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['host'], :username =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['username'], :password =&gt; ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['password'], :database =&gt; db_name ) end end </code></pre>
<p>Take a look at <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001397" rel="nofollow noreferrer">ActiveRecord::Base.establish_connection</a>. That's how you connect to a different database server. I can't be of much more help since I don't know how you recognize the user or map it to it's database, but I suppose a master database will have that info (and the connection info should be on the database.yml file).</p> <p>Best of luck.</p>
8,320
<p>What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class) Right now I can't think of any.</p>
<p>Because writing classes to be substitutably extended is <em>damn hard</em> and requires you to make accurate predictions of how future users will want to extend what you've written.</p> <p>Sealing your class forces them to use composition, which is much more robust.</p>
<p>Because you always want to be handed a reference to the class and not to a derived one for various reasons:<br> i. invariants that you have in some other part of your code<br> ii. security<br> etc</p> <p>Also, because it's a safe bet with regards to backward compatibility - you'll never be able to close that class for inheritance if it's release unsealed.</p> <p>Or maybe you didn't have enough time to test the interface that the class exposes to be sure that you can allow others to inherit from it.</p> <p>Or maybe there's no point (that you see now) in having a subclass. </p> <p>Or you don't want bug reports when people try to subclass and don't manage to get all the nitty-gritty details - cut support costs.</p>
4,426
<p>Each cell contains some text and a background color. So I have some cells that are blue and some that are red. What function do I use to count the number of red cells?</p> <p>I have tried <code>=COUNTIF(D3:D9,CELL("color",D3))</code> with no success (Where <code>D3</code> is red).</p>
<p>Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:</p> <p><a href="http://www.cpearson.com/excel/colors.aspx" rel="nofollow noreferrer">http://www.cpearson.com/excel/colors.aspx</a></p> <p>Example form the site:</p> <blockquote> <p>The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.</p> <p><code>=SUMCOLOR(B11:B17,B11:B17,3,FALSE)</code></p> </blockquote>
<p>Yes VBA is the way to go.</p> <p>But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.</p> <p>Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.</p> <p><a href="https://i.stack.imgur.com/YZOG2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YZOG2.png" alt="enter image description here"></a></p> <p>This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.</p>
7,259
<p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p> <p>On the Mac I am spawning <a href="http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html" rel="noreferrer">sips</a>. Is there something similarly simple I can do on Windows?</p>
<p>ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the <code>ps:alpha</code> delegate in ImageMagick, just adjusted to use JPEG as output):</p> <pre><code>gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT </code></pre> <p>where <code>$OUTPUT</code> and <code>$INPUT</code> are the output and input filenames. Adjust the <code>72x72</code> to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.)</p> <p>This is good for two reasons:</p> <ol> <li>You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions.</li> <li>ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step.</li> </ol> <p>Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the <code>-sDEVICE=jpeg</code> to <code>-sDEVICE=png16m</code>.</p>
<p>Is the PC likely to have Acrobat installed? I think Acrobat installs a shell extension so previews of the first page of a PDF document appear in Windows Explorer's thumbnail view. You can get thumbnails yourself via the IExtractImage COM API, which you'll need to wrap. <a href="http://www.vbaccelerator.com/home/net/code/libraries/shell_projects/Thumbnail_Extraction/article.asp" rel="noreferrer">VBAccelerator has an example in C#</a> that you could port to Python.</p>
2,293
<p>What's the easiest way to add a header and footer to a .Net PrintDocument object, either pragmatically or at design-time?</p> <p>Specifically I'm trying to print a 3rd party grid control (Infragistics GridEx v4.3), which takes a PrintDocument object and draws itself into it.</p> <p>The resulting page just contains the grid and it's contents - however I would like to add a header or title to identify the printed report, and possibly a footer to show who printed it, when, and ideally a page number and total pages.</p> <p>I'm using VB.Net 2.0.</p> <p>Thanks for your help!</p>
<p>The printdocument object fires the printpage event for each page to be printed. You can draw text/lines/etc into the print queue using the printpageeventargs event parameter: </p> <p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx</a></p> <p>Dim it WithEvents when you pass it to the grid, so you can handle the event. </p>
<p>The printdocument object fires the printpage event for each page to be printed. You can draw text/lines/etc into the print queue using the printpageeventargs event parameter: </p> <p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx</a></p> <p>Dim it WithEvents when you pass it to the grid, so you can handle the event. </p>
8,375
<p>What is the dependency inversion principle and why is it important?</p>
<p>Check this document out: <a href="https://drive.google.com/file/d/0BwhCYaYDn8EgMjdlMWIzNGUtZTQ0NC00ZjQ5LTkwYzQtZjRhMDRlNTQ3ZGMz/view" rel="noreferrer">The Dependency Inversion Principle</a>.</p> <p>It basically says:</p> <ul> <li>High level modules should not depend upon low-level modules. Both should depend upon abstractions.</li> <li>Abstractions should never depend upon details. Details should depend upon abstractions.</li> </ul> <p>As to why it is important, in short: changes are risky, and by depending on a concept instead of on an implementation, you reduce the need for change at call sites.</p> <p>Effectively, the DIP reduces coupling between different pieces of code. The idea is that although there are many ways of implementing, say, a logging facility, the way you would use it should be relatively stable in time. If you can extract an interface that represents the concept of logging, this interface should be much more stable in time than its implementation, and call sites should be much less affected by changes you could make while maintaining or extending that logging mechanism.</p> <p>By also making the implementation depend on an interface, you get the possibility to choose at run-time which implementation is better suited for your particular environment. Depending on the cases, this may be interesting too.</p>
<p>Dependency Inversion Principle (DIP) says that </p> <p>i) High level modules should not depend upon low-level modules. Both should depend upon abstractions.</p> <p>ii) Abstractions should never depend upon details. Details should depend upon abstractions.</p> <p>Example: </p> <pre><code> public interface ICustomer { string GetCustomerNameById(int id); } public class Customer : ICustomer { //ctor public Customer(){} public string GetCustomerNameById(int id) { return "Dummy Customer Name"; } } public class CustomerFactory { public static ICustomer GetCustomerData() { return new Customer(); } } public class CustomerBLL { ICustomer _customer; public CustomerBLL() { _customer = CustomerFactory.GetCustomerData(); } public string GetCustomerNameById(int id) { return _customer.GetCustomerNameById(id); } } public class Program { static void Main() { CustomerBLL customerBLL = new CustomerBLL(); int customerId = 25; string customerName = customerBLL.GetCustomerNameById(customerId); Console.WriteLine(customerName); Console.ReadKey(); } } </code></pre> <p>Note: Class should depend on abstractions like interface or abstract classes, not specific details (implementation of interface).</p>
8,803
<p>How can I figure out the size of a file, in bytes?</p> <pre><code>#include &lt;stdio.h&gt; unsigned int fsize(char* file){ //what goes here? } </code></pre>
<p>On Unix-like systems, you can use POSIX system calls: <a href="https://en.wikipedia.org/wiki/Stat_(system_call)" rel="noreferrer"><code>stat</code> on a path</a>, or <code>fstat</code> on an already-open file descriptor (POSIX <a href="https://man7.org/linux/man-pages/man3/fstat.3p.html" rel="noreferrer">man page</a>, Linux <a href="https://man7.org/linux/man-pages/man2/lstat.2.html" rel="noreferrer">man page</a>).<br /> (Get a file descriptor from <code>open(2)</code>, or <code>fileno(FILE*)</code> on a stdio stream).</p> <p>Based on NilObject's code:</p> <pre><code>#include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; off_t fsize(const char *filename) { struct stat st; if (stat(filename, &amp;st) == 0) return st.st_size; return -1; } </code></pre> <p>Changes:</p> <ul> <li>Made the filename argument a <code>const char</code>.</li> <li>Corrected the <code>struct stat</code> definition, which was missing the variable name.</li> <li>Returns <code>-1</code> on error instead of <code>0</code>, which would be ambiguous for an empty file. <code>off_t</code> is a signed type so this is possible.</li> </ul> <p>If you want <code>fsize()</code> to print a message on error, you can use this:</p> <pre><code>#include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; off_t fsize(const char *filename) { struct stat st; if (stat(filename, &amp;st) == 0) return st.st_size; fprintf(stderr, &quot;Cannot determine size of %s: %s\n&quot;, filename, strerror(errno)); return -1; } </code></pre> <p>On 32-bit systems you should compile this with the option <code>-D_FILE_OFFSET_BITS=64</code>, otherwise <code>off_t</code> will only hold values up to 2 GB. See the &quot;Using LFS&quot; section of <a href="http://www.suse.de/%7Eaj/linux_lfs.html" rel="noreferrer">Large File Support in Linux</a> for details.</p>
<p>You can open the file, go to 0 offset relative from the bottom of the file with </p> <pre><code>#define SEEKBOTTOM 2 fseek(handle, 0, SEEKBOTTOM) </code></pre> <p>the value returned from fseek is the size of the file.</p> <p>I didn't code in C for a long time, but I think it should work.</p>
2,971
<p>I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I <em>think</em> the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString.</p> <p>Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk?</p>
<p>In general you should define your threat model before worrying about more exotic attacks. In this case: are you worried that somebody shuts down the computer and does a forensic analysis of the harddrive? Application memory can also be swapped out, so the simple fact that <em>one</em> process has it in memory, makes it potentially possible for it to end in the swap file. What about hibernation? During hibernation the entire content of the memory is written to the harddisk (including the SecureString - and presumably the encryption key!). What if the attacker has access to the system <em>while it's running</em> and can search through the memory of applications?</p> <p>In general client side security is very tricky and unless you have dedicated hardware (like a TPM chip) it is almost impossible to get right. Two solutions would be:</p> <ul> <li>If you only need to test for equality between two strings (ie: is this string the same as the one I had earlier), store only a (salted) hash value of it.</li> <li>Make the user re-enter the information when it is needed a second time (not very convenient, but security and convenience are opposed to each other)</li> </ul>
<p>Unless your child process also understands how to work with SecureString I don't think there is a way to pass it directly. For example, the Process.Start() method has two overloads that take a SecureString so the risk of the actual string value being sniffed is minimized (it's still possible since somewhere along the the way the actual value has to be retrieved/unmarshalled).</p> <p>I think a lot of how to do this will depend on what the child process is and how it is being started.</p>
6,886
<p>Most 3&nbsp;mm (mostly are actually 2.85&nbsp;mm) filament extruders have some kind of gear reduction. Many 1.75&nbsp;mm extruders are direct-drive / ungeared but some do use gears. What kind of reduction ratios are suitable or optimal?</p>
<p>I'm not sure if it's possible, but on github is code for setting CuraEngine up. Maybe you'll find this link, <a href="https://github.com/Ultimaker/CuraEngine/blob/master/src/settings/settings.cpp" rel="nofollow noreferrer"> CuraEngine/src/settings/settings.cpp</a> helpful. </p> <p>The latest release has more speed customization. You can change first layer speed, outer shell speed, inner shell speed, infill speed, and top and bottom speed.</p> <p>You can cut objects, its just a little wonky. In the advanced tab there is a "cut off object at Z height" that you can use to cut objects in half.</p> <p>Theoretically, you can put all settings into a JSON formatted file. </p>
<p>I'm not sure if it's possible, but on github is code for setting CuraEngine up. Maybe you'll find this link, <a href="https://github.com/Ultimaker/CuraEngine/blob/master/src/settings/settings.cpp" rel="nofollow noreferrer"> CuraEngine/src/settings/settings.cpp</a> helpful. </p> <p>The latest release has more speed customization. You can change first layer speed, outer shell speed, inner shell speed, infill speed, and top and bottom speed.</p> <p>You can cut objects, its just a little wonky. In the advanced tab there is a "cut off object at Z height" that you can use to cut objects in half.</p> <p>Theoretically, you can put all settings into a JSON formatted file. </p>
214
<p>I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:</p> <blockquote> <p>The temperature at P1 is 35F.</p> <p>The temperature at P1 is 40F.</p> <p>The temperature at P3 is 35F.</p> <p>Logger stopped.</p> <p>Logger started.</p> <p>The temperature at P1 is 40F.</p> </blockquote> <p>and puts out something in the form of a printf():</p> <pre><code>&quot;The temperature at P%d is %dF.&quot;, Int1, Int2&quot; {(1,35), (1, 40), (3, 35), (1,40)} </code></pre> <p>The algorithm needs to be generic enough to recognize almost any data load in message groups.</p> <p>I tried searching for this kind of technology, but I don't even know the correct terms to search for.</p>
<p>I think you might be overlooking and missed fscanf() and sscanf(). Which are the opposite of fprintf() and sprintf().</p>
<p>@John: I think that the question relates to an algorithm that actually recognises patterns in log files and automatically "guesses" appropriate format strings and data for it. The <code>*scanf</code> family can't do that on its own, it can only be of help once the patterns have been recognised in the first place.</p>
3,121
<p>Why do we need to use:</p> <pre><code>extern "C" { #include &lt;foo.h&gt; } </code></pre> <p><strong>Specifically:</strong> </p> <ul> <li><p>When should we use it?</p></li> <li><p>What is happening at the compiler/linker level that requires us to use it? </p></li> <li><p>How in terms of compilation/linking does this solve the problems which require us to use it?</p></li> </ul>
<p>C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI', or 'Application Binary Interface', so the linker chokes up. This is preferable to passing C++ data to a function expecting C data.</p> <p>(To get into the really nitty-gritty, C++'s ABI generally 'mangles' the names of their functions/methods, so calling <code>printf()</code> without flagging the prototype as a C function, the C++ will actually generate code calling <code>_Zprintf</code>, plus extra crap at the end.)</p> <p>So: use <code>extern &quot;C&quot; {...}</code> when including a c header—it's that simple. Otherwise, you'll have a mismatch in compiled code, and the linker will choke. For most headers, however, you won't even need the <code>extern</code> because most system C headers will already account for the fact that they might be included by C++ code and already <code>extern &quot;C&quot;</code> their code.</p>
<p><strong>Decompile a <code>g++</code> generated binary to see what is going on</strong></p> <p>To understand why <code>extern</code> is necessary, the best thing to do is to understand what is going on in detail in the object files with an example:</p> <p>main.cpp</p> <pre><code>void f() {} void g(); extern "C" { void ef() {} void eg(); } /* Prevent g and eg from being optimized away. */ void h() { g(); eg(); } </code></pre> <p>Compile with GCC 4.8 Linux <a href="https://stackoverflow.com/questions/26294034/how-to-make-an-executable-elf-file-in-linux-using-a-hex-editor/30648229#30648229">ELF</a> output:</p> <pre><code>g++ -c main.cpp </code></pre> <p>Decompile the symbol table:</p> <pre><code>readelf -s main.o </code></pre> <p>The output contains:</p> <pre><code>Num: Value Size Type Bind Vis Ndx Name 8: 0000000000000000 6 FUNC GLOBAL DEFAULT 1 _Z1fv 9: 0000000000000006 6 FUNC GLOBAL DEFAULT 1 ef 10: 000000000000000c 16 FUNC GLOBAL DEFAULT 1 _Z1hv 11: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _Z1gv 12: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND eg </code></pre> <p><strong>Interpretation</strong></p> <p>We see that:</p> <ul> <li><p><code>ef</code> and <code>eg</code> were stored in symbols with the same name as in the code</p></li> <li><p>the other symbols were mangled. Let's unmangle them:</p> <pre><code>$ c++filt _Z1fv f() $ c++filt _Z1hv h() $ c++filt _Z1gv g() </code></pre></li> </ul> <p>Conclusion: both of the following symbol types were <em>not</em> mangled:</p> <ul> <li>defined</li> <li>declared but undefined (<code>Ndx = UND</code>), to be provided at link or run time from another object file</li> </ul> <p>So you will need <code>extern "C"</code> both when calling:</p> <ul> <li>C from C++: tell <code>g++</code> to expect unmangled symbols produced by <code>gcc</code></li> <li>C++ from C: tell <code>g++</code> to generate unmangled symbols for <code>gcc</code> to use</li> </ul> <p><strong>Things that do not work in extern C</strong></p> <p>It becomes obvious that any C++ feature that requires name mangling will not work inside <code>extern C</code>:</p> <pre><code>extern "C" { // Overloading. // error: declaration of C function ‘void f(int)’ conflicts with void f(); void f(int i); // Templates. // error: template with C linkage template &lt;class C&gt; void f(C i) { } } </code></pre> <p><strong>Minimal runnable C from C++ example</strong></p> <p>For the sake of completeness and for the newbs out there, see also: <a href="https://stackoverflow.com/questions/13694605/how-to-use-c-source-files-in-a-c-project/51912672#51912672">How to use C source files in a C++ project?</a></p> <p>Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.</p> <p>main.cpp</p> <pre><code>#include &lt;cassert&gt; #include "c.h" int main() { assert(f() == 1); } </code></pre> <p>c.h</p> <pre><code>#ifndef C_H #define C_H /* This ifdef allows the header to be used from both C and C++. */ #ifdef __cplusplus extern "C" { #endif int f(); #ifdef __cplusplus } #endif #endif </code></pre> <p>c.c</p> <pre><code>#include "c.h" int f(void) { return 1; } </code></pre> <p>Run:</p> <pre><code>g++ -c -o main.o -std=c++98 main.cpp gcc -c -o c.o -std=c89 c.c g++ -o main.out main.o c.o ./main.out </code></pre> <p>Without <code>extern "C"</code> the link fails with:</p> <pre><code>main.cpp:6: undefined reference to `f()' </code></pre> <p>because <code>g++</code> expects to find a mangled <code>f</code>, which <code>gcc</code> did not produce.</p> <p><a href="https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/c-from-cpp" rel="nofollow noreferrer">Example on GitHub</a>.</p> <p><strong>Minimal runnable C++ from C example</strong></p> <p>Calling C++ from is a bit harder: we have to manually create non-mangled versions of each function we want to expose.</p> <p>Here we illustrate how to expose C++ function overloads to C.</p> <p>main.c</p> <pre><code>#include &lt;assert.h&gt; #include "cpp.h" int main(void) { assert(f_int(1) == 2); assert(f_float(1.0) == 3); return 0; } </code></pre> <p>cpp.h</p> <pre><code>#ifndef CPP_H #define CPP_H #ifdef __cplusplus // C cannot see these overloaded prototypes, or else it would get confused. int f(int i); int f(float i); extern "C" { #endif int f_int(int i); int f_float(float i); #ifdef __cplusplus } #endif #endif </code></pre> <p>cpp.cpp</p> <pre><code>#include "cpp.h" int f(int i) { return i + 1; } int f(float i) { return i + 2; } int f_int(int i) { return f(i); } int f_float(float i) { return f(i); } </code></pre> <p>Run:</p> <pre><code>gcc -c -o main.o -std=c89 -Wextra main.c g++ -c -o cpp.o -std=c++98 cpp.cpp g++ -o main.out main.o cpp.o ./main.out </code></pre> <p>Without <code>extern "C"</code> it fails with:</p> <pre><code>main.c:6: undefined reference to `f_int' main.c:7: undefined reference to `f_float' </code></pre> <p>because <code>g++</code> generated mangled symbols which <code>gcc</code> cannot find.</p> <p><a href="https://github.com/cirosantilli/cpp-cheat/tree/bf5f48628d0b01ba6a3fcea6f1162b28539654c9/cpp-from-c" rel="nofollow noreferrer">Example on GitHub</a>.</p> <p>Tested in Ubuntu 18.04.</p>
9,345
<p>I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible. </p> <p>Any suggestions?</p>
<p><a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="nofollow noreferrer">JProfiler</a> is a really good one. It integrates with all the major IDEs and application servers.</p>
<p><a href="http://www.gurock.com/products/smartinspect/" rel="nofollow noreferrer">SmartInspect</a> is a profiler and logger. Not specific to memory, but you might want to take a look. It works with a variety of languages too, including Delphi, Java and .NET. Includes other more advanced features.</p> <p><img src="https://i.stack.imgur.com/S0Nug.png" alt="SmartInspect architecture"></p>
6,880
<p>How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.</p> <p>I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.</p> <p>On my client's desktops I have SOME shortcuts which point to <code>http://production_server</code> and <code>https://production_server</code> (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at <code>https://mirror_server</code> (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. </p> <p>Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).</p> <p>It's <a href="http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html" rel="noreferrer">very easy</a> <a href="http://bytes.com/forum/thread54801.html" rel="noreferrer">to find</a> <a href="http://support.jodohost.com/showthread.php?t=6678" rel="noreferrer">Apache solutions</a> for <a href="http://www.google.com/search?q=https+redirection&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a" rel="noreferrer">http->https redirection</a>, but for the life of me I can't do the opposite.</p> <p>Ideas?</p>
<p>This has not been tested but I think this should work using mod_rewrite</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} on RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} </code></pre>
<p>As far as I'm aware of a simple meta refresh also works without causing errors:</p> <pre><code>&lt;meta http-equiv="refresh" content="0;URL='http://www.yourdomain.com/path'"&gt; </code></pre>
2,980
<p>Prints are generally successful, but I always get a herringbone pattern on the top and bottom surfaces and striations on the sides. The herringbone is finer with finer print qualities, but it is always there. Ditto the sides. See photos.</p> <p>Always there, regardless of temperature (using a heat tower), speed (even very slow), quality in Cura, etc.</p> <p>Perhaps this is the best an Ender 3 Pro can do? If so, that's fine. I'm only trying to determine what this printer is capable of.</p> <p>(Perhaps I can improve the top surface with ironing, but that isn't my question.)</p> <p>Some things I've done with no effect: Run PLA spool from a drying cabinet; replaced extruder; reset Bowden tube; replaced nozzle; leveled bed numerous times.</p> <p>One thing I haven't tried yet (will soon): using a better grade of PLA.</p> <p><a href="https://i.stack.imgur.com/JvYbY.jpg" rel="nofollow noreferrer" title="Top herringbone"><img src="https://i.stack.imgur.com/JvYbY.jpg" alt="Top herringbone" title="Top herringbone" /></a></p> <p><a href="https://i.stack.imgur.com/SQY6r.jpg" rel="nofollow noreferrer" title="Side"><img src="https://i.stack.imgur.com/SQY6r.jpg" alt="Side" title="Side" /></a></p> <p>It's a heat tower, so the top surface was 190 °C. Speed was about 50-60 mm/s (don't remember exactly). With the belt tightened, the herringbone is much finer, but still there. The walls are much smoother, by still the layers are visible. I'm just not sure what to expect from this printer. Am I supposed to get surfaces that are perfectly smooth, or is some texture to be expected?</p>
<p>The top image looks as if the (top) layer(s) are <strong>under-extruding</strong>, the walls don't appear to be suffering from the same problem.</p> <p>The following image from a recent PETG print is typical for an FDM product. The deposited lines need to touch (actually, slightly overlapping, but the slicer will take care of that) each other:</p> <p><a href="https://i.stack.imgur.com/g83N2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g83N2.jpg" alt="enter image description here" /></a></p> <p>You will see texture (especially when there is a non uniform surface, e.g. with holes, and without an option as monotonic fill in Cura 4.11 or similar disabled), but the lines need to touch each other, you may not see the layer beneath.</p> <p>There are various reasons for this to happen, for instance: under-extruding because of speed or temperature issues or positioning accuracy. The walls seem to closely adhere, so this may find the cause in slicing parameters for the filling in of the layer.</p>
<p>With a replaced Bowden tube and better PLA, the herringbone is a little better, and the layering on the sides is more regular, but still there. So, based on this and photos from others here (especially @Oscar), I think the answer to my question is YES: These ARE normal surfaces from this printer.</p>
2,022
<p>For some reason I never see this done. Is there a reason why not? For instance I like _blah for private variables, and at least in Windows Forms controls are by default private member variables, but I can't remember ever seeing them named that way. In the case that I am creating/storing control objects in local variables within a member function, it is especially useful to have some visual distinction.</p>
<p>This might be counter-intuitive for some, but we use the dreaded Hungarian notation for UI elements.</p> <p>The logic is simple: for any given data object you may have two or more controls associated with it. For example, you have a control that indicates a birth date on a text box, you will have:</p> <ul> <li>the text box</li> <li>a label indicating that the text box is for birth dates</li> <li>a calendar control that will allow you to select a date</li> </ul> <p>For that, I would have lblBirthDate for the label, txtBirthDate for the text box, and calBirthDate for the calendar control.</p> <p>I am interested in hearing how others do this, however. :)</p>
<p>I use m_ for member variables, but I'm increasingly becoming tempted to just using lowerCamelCase like I do for method parameters and local variables. Public stuff is in UpperCamelCase.</p> <p>This seems to be more or less accepted convention across the .NET community.</p>
3,084
<p>Can you suggest some light weight fuzzy text search library?</p> <p>What I want to do is to allow users to find correct data for search terms with typos.</p> <p>I could use full-text search engines like Lucene, but I think it's an overkill.</p> <p><strong>Edit:</strong><br> To make question more clear here is a main scenario for that library:<br> I have a large list of strings. I want to be able to search in this list (something like MSVS' intellisense) but it should be possible to filter this list by string which is not present in it but close enough to some string which is in the list.<br> Example: </p> <ul> <li>Red</li> <li>Green</li> <li>Blue</li> </ul> <p>When I type 'Gren' or 'Geen' in a text box, I want to see 'Green' in the result set.</p> <p>Main language for indexed data will be English.</p> <p>I think that Lucene is to heavy for that task.</p> <p><strong>Update</strong>:</p> <p>I found one product matching my requirements. It's <a href="http://shuffletext.com/Highlight/" rel="noreferrer">ShuffleText</a>.<br> Do you know any alternatives?</p>
<p>Lucene is very scalable&mdash;which means its good for little applications too. You can create an index in memory very quickly if that's all you need.</p> <p>For fuzzy searching, you really need to decide what algorithm you'd like to use. With information retrieval, I use an <a href="http://en.wikipedia.org/wiki/N-gram#n-grams_for_approximate_matching" rel="nofollow noreferrer">n-gram</a> technique with Lucene successfully. But that's a special indexing technique, not a "library" in itself.</p> <p>Without knowing more about your application, it won't be easy to recommend a suitable library. How much data are you searching? What format is the data? How often is the data updated?</p>
<p>@aku - links to working soundex libraries are right there at the bottom of the page.</p> <p>As for Levenshtein distance, the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Wikipedia article on that</a> also has implementations listed at the bottom.</p>
6,339
<p>I've had a FTP server (Mac OS X, but not the server version) set up for a while where the users are virtual, i.e. they are not actual user accounts in the server's OS, but accounts handled by the FTP server software -- to the OS they all look like the <code>ftp</code> user account. I'd like to retire the FTP server software and go SFTP instead.</p> <p>Is there a way to set up SFTP/SSH so that I can create virtual users and at the same time sandbox them?</p> <p>The reason I want virtual users is because I add and remove accounts from time to time, and doing that with proper user accounts tend to get messy, and I don't know of a good way to sandbox them. There's always some files left and each user has their own user directory (with a lot of files only relevant if they would actually log on to the machine when sitting in front of it), which is quarantined when the account is removed, so you have to remove it by hand yourself, and so on.</p>
<p>The usual generic Unix answer to this is 'PAM'. If you want plain old OpenSSH SSHD to handle your SFTP, you need something plugged in to SSHD's PAM stack (/etc/pam.d/sshd) that does what you need and leaves out what you don't need. This might be a general-purpose directory server (probably LDAP) that maps all your virtual users to one home directory and gives them a restricted or scponly kind of shell.</p> <p>If you want to look at FTP servers that can also do FTP-ssl (which is not the same as SFTP), good ftp servers like Pure-ftpd or vsftp will do that. FTP-ssl servers have simpler virtual user support.</p> <p><a href="http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php" rel="nofollow noreferrer">http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php</a></p>
<p>If you're open to commercial products, VShell Server from Van Dyke Software is available on Unix/Linux/Windows, supports virtual users (multiple backends) with SSH and SFTP protocols:</p> <p><a href="http://www.vandyke.com/products/vshell/index.html" rel="nofollow">VShell Server</a></p>
6,023
<p>How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?</p> <p>i.e. something like:</p> <pre><code>If Typeof(foobar) = "CommandButton" Then ... </code></pre> <p><strong>/EDIT:</strong> to clarify, I need to check on Dynamically Typed objects. An example:</p> <pre><code>Dim y As Object Set y = CreateObject("SomeType") Debug.Print( &lt;The type name of&gt; y) </code></pre> <p>Where the output would be "CommandButton"</p>
<p>I think what you are looking for is TypeName rather than TypeOf.</p> <pre><code>If TypeName(foobar) = "CommandButton" Then DoSomething End If </code></pre> <p>Edit: What do you mean Dynamic Objects? Do you mean objects created with CreateObject(""), cause that should still work.</p> <p>Edit: </p> <pre><code>Private Sub Command1_Click() Dim oObject As Object Set oObject = CreateObject("Scripting.FileSystemObject") Debug.Print "Object Type: " &amp; TypeName(oObject) End Sub </code></pre> <p>Outputs</p> <p><code>Object Type: FileSystemObject</code></p>
<p>This should prove difficult, since in VB6 all objects are COM (<code>IDispatch</code>) things. Thus they are only an interface.</p> <p><code>TypeOf(object) is class</code> probably only does a COM get_interface call (I forgot the exact method name, sorry).</p>
7,540
<p>I'm trying to work out if I have an open relay on my server. How do I do that?</p> <p>I've tried <a href="http://www.abuse.net/relay.html" rel="nofollow noreferrer">http://www.abuse.net/relay.html</a></p> <p>and it reports:</p> <p>Hmmn, at first glance, host appeared to accept a message for relay. THIS MAY OR MAY NOT MEAN THAT IT'S AN OPEN RELAY. Some systems appear to accept relay mail, but then reject messages internally rather than delivering them, but you cannot tell at this point whether the message will be relayed or not.</p> <p>What further tests can I do to determine if the server has an open relay?</p>
<p>Eh? As your link tells you, register for the site and it will give you an address @abuse.net, valid for 24 hours. Enter that address into the testing form. If your abuse.net account receives the test email, you have an open relay.</p>
<p>This depends on your MTA and how you've configured it. Ultimately there is only one thing you must do to prevent relaying. Restrict relaying to authenticated users and/or restrict relaying to specific IPs. I prefer to restrict all IPs except localhost on my mail server and require authentication from everyone else.</p> <p>The common mistake is to allow more IPs than necessary. Imagine a user on a cable modem who decides to allow the roommate's laptop to relay with the statement 192.168.1.0/24 rather than the more specific 192.168.1.0/29. Now anyone else on the /24 can relay off the server.</p>
8,557
<p>I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:</p> <pre><code>void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = 1; (i &lt;= ArrayLength) &amp;&amp; flag; i++) { flag = 0; for (j = 0; j &lt; (ArrayLength -1); j++) { if (*pArray[j+1] &gt; *pArray[j]) // ascending order simply changes to &lt; { temp = &amp;pArray[j]; // swap elements pArray[j] = &amp;pArray[j+1]; pArray[j+1] = &amp;temp; flag = 1; // indicates that a swap occurred. } } } } </code></pre>
<p>You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped.</p> <p>See below:</p> <pre><code>void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = ArrayLength - 1; i &gt; 0 &amp;&amp; flag; i--) { flag = 0; for (j = 0; j &lt; i; j++) { if (*pArray[j] &gt; *pArray[j+1]) // ascending order simply changes to &lt; { temp = pArray[j]; // swap elements pArray[j] = pArray[j+1]; pArray[j+1] = temp; flag = 1; // indicates that a swap occurred. } } } } </code></pre> <p>Also, check out <a href="http://rant.blackapache.net/2008/08/14/sorting-algorithms-the-bubble-sort/" rel="nofollow noreferrer">this lovely blog post on Bubble Sorting</a> in case you're interested (sorry, shameless plug :)). Hope that helps you with your homework ;)</p> <hr> <p>Edit: Note the subtle "optimisation" where you count back from the array length and only increment up until 'i' in the inner loop. This saves you from needlessly reparsing items that have already been sorted.</p>
<p>To complete Brian Ensink's post, you'll find the STL full of surprises. For example, the std::sort algorithm:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; void printArray(const std::vector&lt;int *&gt; &amp; p_aInt) { for(std::vector&lt;int *&gt;::size_type i = 0, iMax = p_aInt.size(); i &lt; iMax; ++i) { std::cout &lt;&lt; "i[" &lt;&lt; static_cast&lt;int&gt;(i) &lt;&lt; "] = " &lt;&lt; reinterpret_cast&lt;unsigned int&gt;(p_aInt[i]) &lt;&lt; std::endl ; } std::cout &lt;&lt; std::endl ; } int main(int argc, char **argv) { int a = 1 ; int b = 2 ; int c = 3 ; int d = 4 ; int e = 5 ; std::vector&lt;int *&gt; aInt ; // We fill the vector with variables in an unordered way aInt.push_back(&amp;c) ; aInt.push_back(&amp;b) ; aInt.push_back(&amp;e) ; aInt.push_back(&amp;d) ; aInt.push_back(&amp;a) ; printArray(aInt) ; // We see the addresses are NOT ordered std::sort(aInt.begin(), aInt.end()) ; // DO THE SORTING printArray(aInt) ; // We see the addresses are ORDERED return EXIT_SUCCESS; } </code></pre> <p>The first printing of the array will show unordered addresses. The second, after the sort, will show ordered adresses. On my compiler, we have:</p> <pre><code>i[0] = 3216087168 i[1] = 3216087172 i[2] = 3216087160 i[3] = 3216087164 i[4] = 3216087176 i[0] = 3216087160 i[1] = 3216087164 i[2] = 3216087168 i[3] = 3216087172 i[4] = 3216087176 </code></pre> <p>Give STL's &lt;algorithm&gt; header a look <a href="http://www.cplusplus.com/reference/algorithm/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/algorithm/</a> You'll find a lot of utilities. Note that you have other implementation of containers that could suit you better (std::list? std::map?).</p>
3,798
<p>Is it possible to modify the title of the message box the confirm() function opens in JavaScript? </p> <p>I could create a modal popup box, but I would like to do this as minimalistic as possible. I would like to do something like this:</p> <pre><code>confirm("This is the content of the message box", "Modified title"); </code></pre> <p>The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this.</p>
<p>This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.</p> <p>There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code.</p>
<p>You can't unfortunately. The only way is to simulate this with a window.open call.</p>
6,558
<p>I got my ender 3 about a month ago, it was working fine. Tried a new brand, overture, this is when I started experiencing problems. First, I was clogging nozzles left and right, then I went back to hatchbox, and my layers are messed up... <a href="https://i.stack.imgur.com/TXuzX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TXuzX.jpg" alt="enter image description here"></a></p>
<p>I wonder if this problem is unrelated to your material or printer, and purely a matter of slicer breakage. Have you tried printing gcode files you created before the problem appeared? If you use Cura and upgraded it, you might have hit one of the bugs where it assumes by default you have 2.85 mm filament, even though your printer actually uses 1.75 mm. That will create underextrusion that has the whole printed object coming apart like an unravelling mummy. When I've seen it happen, it looks very similar to your picture.</p>
<p>Seems like in Movement without displaycement in x and y it seems to fit (neck-area). I also would check your belts. There may be a bit too much friction. Otherwise have you made some Testprints (calibration cube, boat)?</p> <p>Especially the base looks bad. But it is not a cylinder or?</p> <p>If you want, you may show us your 3dModell (rendered)</p>
1,458
<p>I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that <a href="http://developer.nvidia.com/object/fx_composer_home.html" rel="noreferrer">nVidia's FX Composer</a> is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started.</p> <p>What tutorials would you recommend?</p>
<p>Development of shaders in XNA (which obviously uses DirectX) requires knowledge of <a href="http://msdn.microsoft.com/en-us/library/bb509561(VS.85).aspx" rel="noreferrer">HLSL</a> or shader assembly. I'd recommend getting familiar with the former before diving into the latter.</p> <p>Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier.</p> <p>Next make an attempt to write your own HLSL which does what the <a href="http://www.computerhope.com/jargon/t/tandl.htm" rel="noreferrer">Fixed T&amp;L</a> pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff.</p> <p>As a next step you might want to simulate basic <a href="http://www.gamasutra.com/features/20030418/engel_pfv.htm" rel="noreferrer">sepcular lighting</a> in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well.</p> <p>When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic <a href="http://www.paulsprojects.net/tutorials/simplebump/simplebump.html" rel="noreferrer">bump</a> or <a href="http://www.bencloward.com/tutorials_normal_maps1.shtml" rel="noreferrer">normal maps</a>.</p> <p>When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for <a href="http://www.gpgpu.org/" rel="noreferrer">more</a> than it was originally intended.</p> <p>For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia <a href="http://developer.nvidia.com/object/gpu_gems_home.html" rel="noreferrer">here</a> and <a href="http://developer.nvidia.com/object/gpu_gems_2_home.html" rel="noreferrer">here</a>.</p> <p>Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's <a href="https://rads.stackoverflow.com/amzn/click/com/1556220413" rel="noreferrer" rel="nofollow noreferrer">1</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1556229887" rel="noreferrer" rel="nofollow noreferrer">2</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584503572" rel="noreferrer" rel="nofollow noreferrer">3</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584504250" rel="noreferrer" rel="nofollow noreferrer">4</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584504994" rel="noreferrer" rel="nofollow noreferrer">5</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/1584505443" rel="noreferrer" rel="nofollow noreferrer">6</a> already in print, and <a href="http://www.shaderx7.com/" rel="noreferrer">7</a> is coming soon.</p> <p>Good luck. If you get some shaders going, I'd love to see them :)</p>
<p>SAMS's <a href="https://rads.stackoverflow.com/amzn/click/com/0672329646" rel="nofollow noreferrer" rel="nofollow noreferrer">XNA Unleashed</a> by Chad Carter is a great starting point for XNA and assumes little knowledge of game development practices or hard maths before you start. It has two chapters on basic and advanced shaders.</p> <p>As a sidenote, keep an eye out on Google for WPF Shader tutorials, it now uses the same technology to allow customer shaders in WPF applications and tutorials for that I believe are largely compatible with XNA.</p>
2,861
<p><a href="https://3dprinting.stackexchange.com/questions/3586/adding-custom-m-codes-to-marlin">Adding custom M Codes to Marlin</a> doesn't work for Marlin 2.0</p> <p>How would one go about adding custom G codes or M Codes to Marlin 2.0? The Marlin_main.cpp file does not exist. </p> <p>In general for Marlin 2.0, things are organized better, but split into more files. </p>
<p>The code in 2.0.x is similar to the old branch 1.1.x, G-code is parsed in <a href="https://github.com/MarlinFirmware/Marlin/blob/2.0.x/Marlin/src/gcode/gcode.cpp" rel="nofollow noreferrer"><code>gcode.cpp</code></a>, specifically in <code>process_parsed_command</code>:</p> <pre><code>void GcodeSuite::process_parsed_command(const bool no_ok/*=false*/) </code></pre> <p>In the case statement the codes read from the G-code files are parsed (interpreted) and the appropriate method is called (e.g. <code>G28()</code> calls <a href="https://github.com/MarlinFirmware/Marlin/blob/2.0.x/Marlin/src/gcode/calibrate/G28.cpp" rel="nofollow noreferrer"><code>void GcodeSuite::G28()</code></a>)</p> <p>If you want to create your own codes, it could be an idea to start there. Also think of using a different letter and/or codes in the 10,000 range so that it will not collide with new implemented G-codes.</p>
<ol start="0"> <li>Choose a code in the &gt;10,000 in case new codes are added. But in this example I will choose 13</li> <li>Navigate to 'src' folder of Marlin</li> <li>Edit the file <code>gcode.cpp</code> around line 223 to have a new unused number. For example, this will create a new G code function for the label <code>G13</code>.</li> </ol> <pre><code> ... // Handle a known G, M, or T switch (parser.command_letter) { case 'G': switch (parser.codenum) { case 13: G13(); break; case 0: case 1: G0_G1( ... </code></pre> <ol start="3"> <li><p>On line 375 of <code>gcode.h</code> add: <code> static void G13();</code> to declare it.</p> </li> <li><p>In my case i was reading values from an analog system. So I went to <code>src/temperatures</code> and copied <code>M105.cpp</code> to be <code>G13.cpp</code>. Then inside the file I replaced <code>GcodeSuite::M105</code> to be <code>GcodeSuite::G13</code>. I am using this to take in the weight of something using a [scale][1] but for now I just want to test functionality so here is my test function:</p> </li> </ol> <pre><code> void GcodeSuite::G13() { SERIAL_ECHOPGM(MSG_OK); SERIAL_ECHOLNPGM(&quot;here is where weights are broadcast&quot;); } </code></pre> <p>And again this is the only part I changed in my new copy of M105.cpp (a new file named G13.cpp). There is still more stuff in the file than just these few lines.</p> <ol start="5"> <li><p>Upload to board</p> </li> <li><p>When going to octoprint and typing in <code>G13</code> I get:</p> </li> </ol> <pre><code> Send: G13 Recv: okhere is where weights are broadcast </code></pre> <p>A bit more work can be done to make it look nice, but this was the hard part. [1]: <a href="https://www.instructables.com/id/Arduino-Bathroom-Scale-With-50-Kg-Load-Cells-and-H/" rel="nofollow noreferrer">https://www.instructables.com/id/Arduino-Bathroom-Scale-With-50-Kg-Load-Cells-and-H/</a></p>
1,669
<p>One thing I never understood is the so-called <strong>Extrusion Multiplier (EM)</strong> or <strong>Flow</strong> setting in slicers like Simplify3D (S3D) or CURA.</p> <p>The description for this setting reads...</p> <ul> <li>S3D: <em>Multiplier for all extrusion movements (...)</em></li> <li>CURA: <em>The amount of material extruded is multiplied by this value. (...)</em></li> </ul> <p>I always believed that this parameter is just an ugly way to fix an underlying miscalculation or misconfiguration, because using it feels like doing a calculation, getting the wrong result and "correcting" it afterwards by a multiplier - <em>isn't that cheating</em>?</p> <hr> <p>But, recently I thought a bit harder about this setting, now I am not sure anymore. One of the main reasons is, that S3D suggests different values for the EM, depending on the type of plastics used, <strong>0.9 for PLA</strong> and <strong>1.0 for ABS</strong>.</p> <p>This somehow implies that there is a <em>physical property</em> that justifies the EM, but I cannot think of one because 1 m feeded would lead to 1 m extruded - no matter what kind of platics used, right?</p>
<p>No, the Flow rate or Extrusion multiplier is to compensate for different materials and temperature ranges.</p> <h2>Where does the factor come from?</h2> <p>Let's say we calibrated our nozzle for work at 200°C with PLA, so 100 mm extrusion are correct and want to print ABS. ABS behaves differently and we get bad prints. What is wrong? Well, they do behave differently in the heat, and print at different temperatures. One easily noticeable difference between the two is the heat expansion coefficient.</p> <p>Now, I had to scrounge through <a href="https://www.e3s-conferences.org/articles/e3sconf/pdf/2018/07/e3sconf_eenviro2018_01007.pdf" rel="noreferrer">research papers</a> and Material/Technical Data Sheets for PLA, so take that one with a grain of salt. But we can clearly compare the various plastics <a href="https://www.engineeringtoolbox.com/linear-expansion-coefficients-d_95.html" rel="noreferrer">heat expansion coefficients</a>:</p> <ul> <li>PLA: <span class="math-container">$41 \frac{\text{µm}}{\text{m K}}$</span> <sup><a href="https://www.sd3d.com/wp-content/uploads/2017/06/MaterialTDS-PLA_01.pdf" rel="noreferrer">a TDS</a></sup></li> <li>ABS: <span class="math-container">$72 \to 108 \frac{\text{µm}}{\text{m K}}$</span></li> <li>Polycarbonate: <span class="math-container">$65 \to 70 \frac{\text{µm}}{\text{m K}}$</span></li> <li>Polyamides (Nylons): <span class="math-container">$80 \to 110 \frac{\text{µm}}{\text{m K}}$</span></li> </ul> <p>Those are just three randomly picked plastics that clearly are printable. If we heat one meter of them by one Kelvin, they'd expand by that length (a couple micrometer). We heat the later three printing materials to about 200-240 K over the room temperature (~220-260 °C), so we'd expect these the materials to expand by the following ranges:</p> <ul> <li>PLA: 6.97 to 7.79 mm <sup>(1)</sup></li> <li>ABS: 14.4 to 25.92 mm <sup>(2)</sup></li> <li>Polycarbonate: 13 to 16.8 mm <sup>(2)</sup></li> <li>Polyamides (Nylons): 16 to 26.4 mm <sup>(2)</sup></li> </ul> <p><sup>1 - using 170 K and 190 K temperature difference for its normal print temperature range of ca 190 to 200 °C<br>2 - first: low expansion at 200 K increase, then high expansion at 240 K</sup></p> <p>You have calibrated your printer for <em>one</em> of these values somewhere in there. And now you get a different filament that has a different color and a different blend or even you swap from PLA to ABS or switch from one brand to another - the result is: you get a different heat expansion coefficient somewhere in that range and you have almost no chance to know it. The heat expansion coefficient, in the end, has an effect on the pressure in the nozzle and this the speed the material leaves the nozzle, which impacts die swell and so the overall printing behavior.</p> <p>Remember that heat expansion is not the only thing that is happening in the nozzle. Other big factors are for example the viscosity of the polymer at its printing temperature, its compressibility (which depends for example on chain length or embedded fillers), the geometry of the nozzle, the length of the melt zone... they all play a role in how exactly the print gets to come out.</p> <p>We can sum all those up under a general &quot;behavior in the nozzle&quot; tag, and as a result one gets vastly different flow/extrusion multipliers, like the 0.9 for PLA/1 for ABS in Simplify3D.</p> <h2>Other Factors?</h2> <p>There are also other factors that play a role.</p> <p>The distance between the extruder and the melt zone and how the filament behaves there are somewhat obvious: A ductile filament can bunch up some in a Bowden tube while in a direct drive there is much less space for that.</p> <p>The extruder can have an influence depending on the geometry of the drive gear and how much it <em>bites</em> into the filament. The depth of the deformation is again dependant on the hardness of the filament and the geometry of the teeth. <a href="https://3dprinting.stackexchange.com/a/8396/8884">Tollo</a> has a great explanation how this has an effect on the need to alter the extrusion multiplier.</p> <h2>gaining the factors</h2> <p>Most of these are determined by trial and error using a factor of 1 and dialing up manually until proper printing is achieved on the machine, then putting that factor back into the software.</p> <p>As a side note: Ultimaker Cura has (in its filament database) the ability to save flow rates into each different filament, but does initialize all with 100 % default.</p> <h2>TL;DR</h2> <p>It is a way to adjust to the relative difference between the behavior of filaments (using one of your filaments as the calibration) and <em>not</em> cheating.</p>
<p>The extrusion multiplier is just to compensate for amounts of flow. A material like PLA is very fluid when at 190-200C, so to extrude slightly less then 100% would reduce zits on the print, slightly increase tolerance, reduce stringing and also reduce risk of heatcreep. Materials like ABS and Nylon aren't as liquid when at temperature, so they don't require any alterations to the flow rate during printing. Flow rate can also be adjusted to improve first layers, although too much can cause "elephants foot", or too much first layer squish, similar to having your bed leveled too close.</p>
1,237
<p>I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes, but I'm pretty sure I'm still missing out on a lot of functionality which could make my life a lot easier. </p> <ul> <li>notify-extension: <a href="https://www.mercurial-scm.org/wiki/NotifyExtension" rel="nofollow noreferrer">https://www.mercurial-scm.org/wiki/NotifyExtension</a></li> </ul> <p>Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team? </p> <p>Please add links to non-standard parts you use and/or add the hook (or a description how to set it up), so others can easily use it. </p>
<p>I really enjoy what I did with my custom hook. I have it post a message to my campfire account (campfire is a group based app). It worked out really well. Because I had my clients in there and it could show him my progress.</p>
<p>Take a look at the hgweb stuff. You can set up RSS feeds and see all the revisions, et cetera.</p>
8,894
<p>In TFS whats the easiest way of linking a backlog item to a large number of other backlog items, without doing them one at a time?</p> <p>I do not have access to the underlying database so am unable to write a query to do it.</p>
<p>I'd stay away from the SQL Query. Instead, I'd either use the API or Web Services. Here's an example API call to retrieve and edit a work item:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb130323.aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/bb130323.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb130323.aspx</a></a></p> <p>You could modify that to add the links. Would be much safer, easier, and much more supported than going directly to the database.</p>
<p>Depends on your definition of easy, but you could write a SQL Update linking the backlog item(s) to the correct backlog items.</p> <p>(If there is no field in the backlog item to connect it to another backlog item, you would have to extend backlog item and the views showing them yourself)</p>
6,077
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
<p>You can add the catalog to the <code>XML_CATALOG_FILES</code> environment variable:</p> <pre><code>os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml' </code></pre> <p>See <a href="http://thread.gmane.org/gmane.comp.python.lxml.devel/5907" rel="noreferrer">this thread</a>. Note that entries in <code>XML_CATALOG_FILES</code> are space-separated URLs. You can use Python's <code>pathname2url</code> and <code>urljoin</code> (with <code>file:</code>) to generate the URL from a pathname.</p>
<p>It seems that lxml does not expose this libxml2 feature, grepping the source only turns up some #defines for the error handling:</p> <pre><code>C:\Dev&gt;grep -ir --include=*.px[id] catalog lxml-2.1.1/src | sed -r "s/\s+/ /g" lxml-2.1.1/src/lxml/dtd.pxi: catalog. lxml-2.1.1/src/lxml/xmlerror.pxd: XML_FROM_CATALOG = 20 # The Catalog module lxml-2.1.1/src/lxml/xmlerror.pxd: XML_WAR_CATALOG_PI = 93 # 93 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_MISSING_ATTR = 1650 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_ENTRY_BROKEN = 1651 # 1651 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_PREFER_VALUE = 1652 # 1652 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_NOT_CATALOG = 1653 # 1653 lxml-2.1.1/src/lxml/xmlerror.pxd: XML_CATALOG_RECURSION = 1654 # 1654 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG=20 lxml-2.1.1/src/lxml/xmlerror.pxi:WAR_CATALOG_PI=93 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_MISSING_ATTR=1650 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_ENTRY_BROKEN=1651 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_PREFER_VALUE=1652 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_NOT_CATALOG=1653 lxml-2.1.1/src/lxml/xmlerror.pxi:CATALOG_RECURSION=1654 </code></pre> <p>From the <a href="http://xmlsoft.org/catalog.html" rel="nofollow noreferrer">catalog implementation in libxml2 page</a> it seems possible that the 'transparent' handling through installation in /etc/xml/catalog may still work in lxml, but if you need more than that you can always abandon lxml and use the default python bindings, which do expose the catalog functions.</p>
3,362
<p>This is how I wanted to do it which would work in PHP 5.3.0+</p> <pre><code>&lt;?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo $classname::CONSTANT; // As of PHP 5.3.0 ?&gt; </code></pre> <p>But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?</p>
<p>You can accomplish this without using <a href="http://php.net/manual/en/function.eval.php" rel="nofollow noreferrer"><code>eval</code></a> in pre-5.3 code. Just use the <a href="http://php.net/manual/en/function.constant.php" rel="nofollow noreferrer"><code>constant</code></a> function:</p> <pre><code>&lt;?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo constant("$classname::CONSTANT"); ?&gt; </code></pre>
<p>If you absolutly need to access a constant like that, you can do this:</p> <pre><code>&lt;?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo eval( 'return '.$classname.'::CONSTANT;' ); ?&gt; </code></pre> <p>But, if i were you, I'd try not to use eval.</p>
2,735
<p>I am currently adding a fillet to the base of an object (the plane that's touching the bed) and I was curious if the radius of the filet contributed to any mis-prints. I've had luck so far but was wondering if the intensity of the radius had mattered.</p> <p>I am using the Ender3 Pro.</p> <hr /> <p><em>I may do some test prints and see for myself and provide an answer to share experience .</em></p>
<p>You can print a fillet without support as support material causes other issues like problems with removing supports and ugly scarring on you print. However, a fillet will cause an overhang when you slice the object</p> <p><a href="https://i.stack.imgur.com/mXpkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mXpkz.png" alt="enter image description here" /></a></p> <p>and may result into poor results as well, see e.g. this:</p> <p><a href="https://i.stack.imgur.com/hxKxd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxKxd.png" alt="enter image description here" /></a></p> <p>If your design allows it you should better use a chamfer than a fillet for the base of the print object.</p> <p>A chamfer prints better than a fillet because a fillet creates an overhang (see indicated area on the left part of the image below.</p> <p><a href="https://i.stack.imgur.com/fiFxU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fiFxU.png" alt="enter image description here" /></a> <em>Image from <a href="https://support.3dverkstan.se/article/38-designing-for-3d-printing#:%7E:text=It%27s%20important%20that%20you%20use,printer%20will%20handle%20very%20nicely." rel="nofollow noreferrer">3DVerkstan</a></em></p> <p>A chamfer, which normally is a 45° straight cut-off, doesn't create an overhang and, as such, prints better. If you still want a fillet, you could start with a chamfer of which you fillet the top, see the right part of the image above.</p> <p>A chamfer with the height of the first and second layer is generally a good idea to reduce the slightly over “squished” first layer issues that create a lip around the base of the part.</p>
<blockquote> <p>wondering if the intensity of the radius had mattered.</p> </blockquote> <p>Yes it does if it's an overhang.</p>
2,160
<p>I've upgraded my stepper drivers.</p> <p>I'm looking to understand why my stepper motors made noise in the first place.</p>
<p>Stepper motors contain two distinct sets of coils. The current in these coils is governed by your stepper motor driver.</p> <p><a href="https://i.stack.imgur.com/RaDxb.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RaDxb.gif" alt="Stepper motor diagram (WikiForU.com)"></a></p> <p>To move the motor in either direction, the coils are being driven one after another, and in different directions. Imagine this being a normal 3-phase AC motor, but instead of three phases, only two are used.</p> <p>A "full steps" (1/1 "microstepping") would mean switching one coil off and the other on - resulting in a jerky motion to the next position. Real stepper motors have multiple sets of those coils (rather than two like in the diagram) - usually 200 or 400, giving 1.8° or 0.9° of rotation per "full step".</p> <p>Such motion is usually not desired, since the immediate movement of the motor creates noise and vibration. If both coils are driven with less current (71% of the full current, the reciprocal of the square root of 2, so that the total force on the motor remains the same) during the switch from one current to the other, another position can be achieved - a "half step" between two full steps.</p> <p>This can be repeated for higher number of "microsteps", with 16 being the usual compromise.</p> <p>Optimal smoothness - and next to no noise - would be achieved by driving the stepper motor with pure sine waves. The closer a stepper driver can get to that pure sine wave, the lower the noise made by the stepper motor will be:</p> <p><a href="https://i.stack.imgur.com/GobdA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GobdA.jpg" alt="Microstepping plot (eeNewspower.com)"></a></p> <p>Some stepper motor drivers, most notably the TMC family of chips, can generate 256 microsteps internally, approximating a sine wave quite well.</p> <p>Other stepper motor drivers (like the LV8729) can also handle 128 microsteps, but they require the printer control board to send an individual step signal for each of those steps - which may limit speed because of the additional load on the board's MCU.</p>
<p>To make a stepper perform a step, block signals are send to energize the coils to position the rotor. Such a block signal causes abrupt motion and triggers harmonic frequencies. This is audible as stepper noise. If the block signal is smoothed, the motion is more fluent and less noise will be observed. A similar effect is achieved using micro-stepping. </p> <p>It could be that the new stepper drivers use more/less microsteps<sup>1)</sup> or a smoothed/block<sup>1)</sup> signal opposed to the previous drivers, hence less/more<sup>1)</sup> noise.</p> <hr> <p><sup>1)</sup><sub> The question does not state if the noise is reduced or increased, but noise reduction is most probable</sub></p>
1,388
<p>Take the following string as an example: </p> <p>"The quick brown fox" </p> <p>Right now the q in quick is at index 4 of the string (starting at 0) and the f in fox is at index 16. Now lets say the user enters some more text into this string.</p> <p>"The very quick dark brown fox"</p> <p>Now the q is at index 9 and the f is at index 26.</p> <p>What is the most efficient method of keeping track of the index of the original q in quick and f in fox no matter how many characters are added by the user?</p> <p>Language doesn't matter to me, this is more of a theory question than anything so use whatever language you want just try to keep it to generally popular and current languages.</p> <p>The sample string I gave is short but I'm hoping for a way that can efficiently handle any size string. So updating an array with the offset would work with a short string but will bog down with to many characters. </p> <p>Even though in the example I was looking for the index of unique characters in the string I also want to be able to track the index of the same character in different locations such as the o in brown and the o in fox. So searching is out of the question.</p> <p>I was hoping for the answer to be both time and memory efficient but if I had to choose just one I care more about performance speed.</p>
<p>Let's say that you have a string and some of its letters are <i>interesting</i>. To make things easier let's say that the letter at index 0 is always interesting and you never add something before it&mdash;a sentinel. Write down pairs of (interesting letter, distance to the previous interesting letter). If the string is "+the very Quick dark brown Fox" and you are interested in q from 'quick' and f from 'fox' then you would write: (+,0), (q,10), (f,17). (The sign + is the sentinel.)</p> <p>Now you put these in a balanced binary tree whose in-order traversal gives the sequence of letters in the order they appear in the string. You might now recognize the <a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=10&amp;url=http%3A%2F%2Ferikdemaine.org%2Fpapers%2FPartialSums_SODA2004%2Fpaper.ps&amp;ei=jyjrSMPCM4GmQO3FpLQM&amp;usg=AFQjCNGh-7I5N_BA1vpJTGLsmkgcxmOIxg&amp;sig2=AlYsMNNHPxrXNRImTYe9zQ" rel="nofollow noreferrer">partial sums problem</a>: You enhance the tree so that nodes contain (letter, distance, sum). The sum is the sum of all distances in the left subtree. (Therefore sum(x)=distance(left(x))+sum(left(x)).)</p> <p>You can now query and update this data structure in logarithmic time.</p> <p>To say that you added <em>n</em> characters to the left of character <em>c</em> you say distance(c)+=n an then go and update sum for all parents of <em>c</em>.</p> <p>To ask what is the index of <em>c</em> you compute sum(c)+sum(parent(c))+sum(parent(parent(c)))+...</p>
<p>The standard trick that usually helps in similar situations is to keep the characters of the string as leaves in a balanced binary tree. Additionally, internal nodes of the tree should keep sets of letters (if the alphabet is small and fixed, they could be bitmaps) that occur in the subtree rooted at a particular node.</p> <p>Inserting or deleting a letter into this structure only needs O(log(N)) operations (update the bitmaps on the path to root) and finding the first occurence of a letter also takes O(log(N)) operations - you descend from the root, going for the leftmost child whose bitmap contains the interesting letter.</p> <p>Edit: The internal nodes should also keep number of leaves in the represented subtree, for efficient computation of the letter's index.</p>
5,680
<p>I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio?</p> <p>Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries.</p>
<p>I've started using <a href="http://www.linqpad.net/" rel="noreferrer" title="Linq Pad">LinqPad</a>. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!</p>
<p>You can still install and use Query Analyzer from previous SQL Server versions.</p>
2,714
<p>I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.</p> <p>The html looks like this:</p> <pre><code>&lt;div onmouseover="jsHoverIn('1')" onmouseout="jsHoverOut('1')"&gt; &lt;div id="image1" /&gt; &lt;div id="text1" style="display: none;"&gt; &lt;p&gt;some content&lt;/p&gt; &lt;p&gt;some more content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And the javascript (It uses scriptaculous):</p> <pre><code>function jsHoverIn(id) { if(!visible[id]) { new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } }); visible[id] = true; } } function jsHoverOut (id) { var scope = Effect.Queues.get(id); scope.each(function(effect) { effect.cancel(); }); new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } }); new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } }); visible[id] = false; } </code></pre> <p>This seems really simple, but i just cant wrap my head around it.</p>
<p>I'd give the container div:</p> <pre><code>position: relative; </code></pre> <p>and add a third div in the container (should be the last child of the container) with:</p> <pre><code>position: absolute; top: 0; bottom: 0; left: 0; right: 0; </code></pre> <p>and catch the mouseover and mouseout events on this div instead.</p> <p>Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it.</p> <p><em>Edit:</em></p> <p>What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event.</p>
<p>This may not be the best solution but you could set a global boolean variable that would be accessible to both methods that would just specify if the last action was HoverIn or HoverOut. You could use this boolean variable to determine if the code should run or not. </p> <pre><code>if (bWasHoverIn){ ... } </code></pre>
7,226