instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I need to provide a window on an ASP.NET MVC web page where registered users of the site can group chat live.</p> <p>Can anyone recommend a component or control that can provide real-time group chat that I can embed on an ASP.NET MVC page?</p> <p>I am willing to use free or commercial components, as well as a web service.</p> <p>I looked into a few web 2.0 approaches, like:</p> <ul> <li>Campfire - problem is, it takes you to a separate site, and I can't embed the chat window (at least that's what they said when I contacted support)</li> <li>Meebo - requires that users have Meebo accounts (I think)</li> </ul> <p>What's unique here is that I need to enable site users to chat live with each other - not with a central support person (like LivePerson, or the Meebo widget).</p>
<p>All you really need is an action to post new messages to, an action to poll for updates, and a div to place the items.</p> <p>You can accomplish all of this pretty easily with ajax and those two actions on a ChatController in ASP.NET MVC.</p> <p>+1 for Campfire though, it's a really well polished tool.</p>
<p>There's an unofficial developer API for Campfire called <a href="http://opensoul.org/2006/12/8/tinder-campfire-api" rel="nofollow noreferrer">Tinder</a>.</p> <p>I saw that that 37 Signals was promoting it on their website <a href="http://www.campfirenow.com/?source=37s+home" rel="nofollow noreferrer">here</a>, so it's probably pretty good.</p>
39,935
<p>I have a property called "IsSecureConnection" that is part of my object's interface. This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly. </p> <p>Should I omit this property from the object's interface even though it is required by all of the implementations (though slightly different on occasion)?</p> <p>Thanks!</p>
<p>Just add the getter in the interface.</p> <pre><code>public interface Foo{ bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;} } </code></pre> <p>Interfaces specify the minimum an object must implement; it doesn't say what an object cannot do. For that, you need to look into creating base classes.</p>
<p>You need to evaluate the case. If it doesn't make sense to have it always be writeable, separate it into a second interface.</p> <pre><code>public interface IFoo { bool SecuredConnection{ get; } } public interface ISecurableOptionFoo: IFoo { bool SecuredConnection{ get; set; } } </code></pre>
29,694
<p>The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board. My question is if anyone has had issues working with Community Server, skinning it and extending it?<br /> I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff.</p> <p>edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it.</p> <p>another edit: Need to stick to .net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box.</p>
<p>I've done quite a few projects using Community Server. If you're okay with the out-of-the-box functionality, or you don't mind sticking to the version you start with, I think you'll be very happy.</p> <p>The times I've run into headaches using CS is when the client wants functionality CS does not provide, but also insists on keeping the ability to upgrade to the latest version whenever Telligent releases an update. You can mostly support that by making all of your changes either in a separate project or by only modifying aspx/ascx files (no codebehinds). Some kind of merge is going to be required though no matter how well you plan it out.</p>
<p>Have you had a look at the <a href="http://trac.sitecore.net/Blog" rel="nofollow noreferrer">Shared Source blog module</a> for Sitecore?</p>
2,736
<p>does anyone know is there a way to implement Windows Live ID authentication into your ASP.NET MVC site. There is some info about OpenID implementations and it uses some libraries. So is there a way to implement Live ID or it is not yet supported.</p> <p>Thank you</p>
<p>The same way you would with Memberships: <a href="http://www.eggheadcafe.com/tutorials/aspnet/48857836-0c72-4efb-9d29-fbcb8e17ef3a/integrate-windows-live-id.aspx" rel="nofollow noreferrer">http://www.eggheadcafe.com/tutorials/aspnet/48857836-0c72-4efb-9d29-fbcb8e17ef3a/integrate-windows-live-id.aspx</a></p>
<p>Newer information at </p> <p>It's pretty independent of mvc or webforms I think.</p> <p>Windows Live Messenger Connect Developer Guide <a href="http://msdn.microsoft.com/en-us/library/hh243641.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/hh243641.aspx</a></p>
48,773
<p>I'm trying to increase adhesion of the first layer (as well as to fill gaps for a more even surface) by squeezing more material against the bed. The obvious way of doing that in Cura is by increasing the "Initial Layer Flow", i.e. to make the printer push out slightly more material than it normally would.</p> <p>But then there is also a setting called "Initial Layer Width" and according to the the Cura Settings Guide (see image below), increasing line width will make the nozzle </p> <blockquote> <p>extrude more material and that material has to flow wider outward. This causes the nozzle to press the material harder on the build plate (...) Not only will the lines be wider ... but they will also be farther apart ... by the same factor, so it would not produce overextrusion</p> </blockquote> <p>This seems to imply that increasing the initial layer width will automatically <em>also</em> increase initial layer flow. If this is so, the question is: which setting is applied first? </p> <p>In any case, it seems that the two settings should not be applied together, if they manipulate the same variable (but I have not seen this recommendation anywhere). Which leads me to my may question: <strong>what is the difference between the two settings?</strong> More specifically (based on my above reasoning): <strong>what else does "Initial Layer Width" manipulate, apart from the flow rate in the first layer?</strong> Just the distance between the lines so that increasing the setting will lead to fewer lines?</p> <p><a href="https://i.stack.imgur.com/yzyn4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yzyn4.png" alt="enter image description here"></a></p>
<p>Cura option <code>Initial Layer Width</code> will cause lines to be further apart or closer together, based on the value you set with respect to the default. The required filament flow to produce these lines is calculated based on the width of the line and the overlap between lines (and layer height).</p> <p>The Cura option <code>Initial Layer Flow</code> adjusts flow for the current line width with a multiplier, this means that the distance between lines stays the same. I.e. with this parameter you can overextrude to push more material to the build plate. Note that for a well calibrated machine this is not necessary. My printers use the paper method to determine the initial <code>Z=0</code> for levelling and never use a wider initial line width or overextrusion of the first layer to get perfect filled mirror finish first layers on glass. However, if (paper) tape is used, the bed may be less flat and overextrusion might be beneficial for better adhesion.</p> <p>The options can be used together, the multiplier will act upon the calculated flow.</p>
<p>The typical consensus is that you increase the layer flow initially for better adhesion, though from my experience I <strong>decrease</strong> it!<br /> My first layer is printed at between 70-75 % layer flow, this gives the best adhesion and best visuals when printing with ASA or ABS.<br /> From layer 2 on I've 105 % layer flow.</p> <p>The reason is that my first layer is printed &quot;officially&quot; at 0.27mm but in reality, it's more like 0.05 mm thickness. That's manually finetuned while printing after a material change, basically, the thickness is adjusted for perfect grip on the build plate.<br /> When left at 100 % flow rate this will cause ripples or waves on the bottom, it's excess material that builds up along the printed lines.<br /> At 70 % the wrong initial distance is compensated (visually) while maintaining perfect adhesion.</p> <p>Conclusion: Fine-tune your printer and settings for each material used, a general answer is not possible. Especially true for difficult materials like ABS, ASS, or Nylon.<br /> The best is to watch the printer while it is printing and adapt the mechanical properties first, then fine tuning the flow rates.</p>
1,538
<p>First post here, so please forgive me for any silly mistakes.</p> <p>Recently the y-axis (I think, forward-backward) has started skipping forward when printing the first layer of my print. It prints the raft with no issues at all, sticks the bed nice and flat and the raft is perfect every time. </p> <p>Then it starts to print the actual item, but every time it starts to the print the back right corner the Y-Axis jumps or skips on the gears and makes a loud grinding noise. The amount it jumps varies on the print, but always jumps towards the front of the print. It doesn't matter on the size of the print or the position, it always jumps forward never back.</p> <p>The printer is a Makerbot Replikator clone, from eBay. The X &amp; Y moves the extruder. I have tried upgrading and downgrading the software (which uses Makerbot software) I am unsure if I can update the firmware.</p> <p>Any help much appreciated.</p> <p>UPDATE: Image has been attached of the failed part, excuse the colour, I use it for my test prints. This is orientation it printed on the bed. First 3 blocks printed fine, 4th one jumped It printed in the following order 1. top-left, 2. bottom left, 3. bottom right, 4. top right.</p> <p><a href="https://i.stack.imgur.com/bIkxe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bIkxe.jpg" alt="Failed 3D print part"></a></p>
<p>Layer shifting is a result of the use of open-loop control systems. This means that the printer just instructs the head to go to certain positions without checking that it actually did arrive at that position. If something happens along the path, like hitting some part of the print or the printer, the motors could loose steps or the belts may skip teeth without the printer knowing it, so it continues further without correcting this.</p> <p>There are a couple of causes for the skipping to occur. Usually it is a mechanical issue, but it can also be related to an electrical problem or a print settings problem (if e.g. your print speed it too high, the steppers could miss steps).</p> <p>Looking closely at the image, you will see that the infill of the first layer does not touch the outer lines. This could be a hint that your belts are not tight enough (mechanical issue). Too loose belts cause the stepper driving pulley to skip. Also check the pulley whether it is securely fastened so that the pulley is not slipping when subjected to an increased torque. The nozzle most probably hits the raft (ABS? as it curls up and detaches, you see some irregularities on the left of the bottom right product in your image). Do note that too tight belts are also not wanted as they stress the stepper by an increased torque load. If the issue is electronically related, you could thick of increasing the torque by increasing the current through the stepper (and driver). Too much current will overheat the stepper driver though, so make sure that these do not exceed their rated maximum and properly cool the stepper drivers.</p> <p>To solve your issues it is recommended to first try printing at lower speeds (this can be skipped if you already have low print speeds), then check the mechanical system of the printer, and finally, if this does not fix the problem, you could look into the electronics.</p>
<p>I'm guessing that the bed in the offending corner is farther away and your raft is curling and lifting off the bed in that corner, and your nozzle it hitting it. Try releveling your bed, paying particular close attention to that corner. In addition, work on bed adhesion in general. Clean the bed, make sure fan is off on first layer, and go slow on first layer, and use proper bed temp for the material. You can also try glue stick.</p>
1,116
<p>I have a little logging app (written in wxPython) that receives data from a bit of kit we're developing, and I want to display the text in a scrolling window. As it stands I'm using a wx.TextCtrl for the text display, but I'm having some issues with the scrolling behaviour.</p> <p>Basically, I'd like it so that if the scrollbar is at the bottom of the window (i.e. the end of the incoming data), adding more data should scroll the view onwards. If, however the view has been scrolled up a little (i.e. the user is looking at something interesting like an error message), the app should just add the text on the end without scrolling any more.</p> <p>I've got two problems at the moment:</p> <ol> <li>I can't work out how to retrieve the current scroll position (calls to GetScrollPos() don't seem to work - they just return 0).</li> <li>I can't work out how to retrieve the current range of the scroll bar (calls to GetScrollRange() just return 1).</li> </ol> <p>I've googled a bit and there seem to be a few hints that suggest GetScrollPos and GetScrollRange won't work for a wx.TextCtrl? Has anyone else had any experience in this area? Is there a nice easy way to solve the problem or am I going to have to roll my own wx.TextCtrl?</p>
<p>I just tested a simple example (checking <code>GetScrollPos(0)</code> and <code>GetScrollRange(0)</code> in <code>EVT_TEXT</code> event handler for <code>wx.TextCtrl</code>) and it works fine for me - they return index of currently shown line and total number of lines, respectively.</p> <p>Maybe the problem is your wxPython version? I used:</p> <pre><code>&gt;&gt;&gt; import wx &gt;&gt;&gt; wx.version() '2.8.9.1 (msw-unicode)' </code></pre>
<p>I just tested a simple example (checking <code>GetScrollPos(0)</code> and <code>GetScrollRange(0)</code> in <code>EVT_TEXT</code> event handler for <code>wx.TextCtrl</code>) and it works fine for me - they return index of currently shown line and total number of lines, respectively.</p> <p>Maybe the problem is your wxPython version? I used:</p> <pre><code>&gt;&gt;&gt; import wx &gt;&gt;&gt; wx.version() '2.8.9.1 (msw-unicode)' </code></pre>
18,604
<p>I'm in a new contract where they seem to have gone overboard with Agile, including hiring a consultant merely for facilitating Agile processes. Something he is instituting is a notion of "core hours" where we will all actually be in the same room together. Is this really what "core hours" constitutes? I ask because it's highly inconvenient to pick up my laptop and go to this shared location for half the day; I always thought "core hours" meant you were available, not necessarily in the same room, from 9:30 to 4, for instance.</p>
<p>Yes and no.</p> <p>Core hours are the period(s) when all team members commit to working on the project (and not doing administrative stuff or other projects). For many teams, this will imply being in the same room, but with proper planning and the necessary infrastructure, the team can work well from different locations.</p>
<p>I think what you have is an extension of the "core hours" where you are. The idea of being in the shared location is that ad-hoc meetings could occur as well as possibly being within earshot of various discussions so that you can jump in if it is something where you think your opinion or knowledge would be useful, e.g. why was this coded like that? or why do we have this requirement? kind of thing.</p>
39,384
<p>Something that has always bugged me is how unpredictable the <code>setTimeout()</code> method in Javascript is.</p> <p>In my experience, the timer is horribly inaccurate in a lot of situations. By inaccurate, I mean the actual delay time seems to vary by 250-500ms more or less. Although this isn't a huge amount of time, when using it to hide/show UI elements the time can be visibly noticeable.</p> <p>Are there any tricks that can be done to ensure that <code>setTimeout()</code> performs accurately (without resorting to an external API) or is this a lost cause?</p>
<blockquote> <p>Are there any tricks that can be done to ensure that <code>setTimeout()</code> performs accurately (without resorting to an external API) or is this a lost cause?</p> </blockquote> <p>No and no. You're not going to get anything close to a perfectly accurate timer with <code>setTimeout()</code> - browsers aren't set up for that. <strong>However</strong>, you don't need to rely on it for timing things either. Most animation libraries figured this out years ago: you set up a callback with <code>setTimeout()</code>, but determine what needs to be done based on the value of <code>(new Date()).milliseconds</code> (or equivalent). This allows you to take advantage of more reliable timer support in newer browsers, while still behaving appropriately on older browsers.</p> <p>It also allows you to <em>avoid using too many timers</em>! This is important: each timer is a callback. Each callback executes JS code. While JS code is executing, browser events - including other callbacks - are delayed or dropped. When the callback finishes, additional callbacks must compete with other browser events for a chance to execute. Therefore, one timer that handles all pending tasks for that interval will perform better than two timers with coinciding intervals, and (for short timeouts) better than two timers with overlapping timeouts!</p> <p>Summary: stop using <code>setTimeout()</code> to implement "one timer / one task" designs, and use the real-time clock to smooth out UI actions. </p>
<p>You could consider using the <a href="http://www.sitepoint.com/creating-accurate-timers-in-javascript/" rel="nofollow">html5 webaudio clock</a> which uses the system time for better accuracy</p>
23,819
<p><strong>Dup of <a href="https://stackoverflow.com/questions/330709/some-basic-php-questions#330829">Some Basic PHP Questions</a></strong></p> <p>Hello,</p> <p>I have a heap of tinyint fields in a mysql database I need to show with PHP. At the moment I am doing something like this:</p> <pre><code>if ($row['PAYPAL_ACCEPT'] == "1"){ $paypal = "Yes"; else $paypal = "No"; } </code></pre> <p>For each field, which is tedious and seems like there should be a better way, than using an if clause for each field. If there is, what is it?</p>
<p>Try if you want:</p> <pre><code>$paypal = $row['PAYPAL_ACCEPT'] ? 'YES' : 'NO'; </code></pre>
<p>You could write it shorter like:</p> <pre><code>$paypal = ($row['PAYPAL_ACCEPT']?'Yes':'No'); </code></pre>
46,439
<p>I am using jQuert .ajax function to call a page method. The site is using FormsAuthentication. So when an authentication ticket expires a call to the page method will obviously cause a redirect to the login page. </p> <p>Now, the geniuses that wrote the System.Web.Handlers.ScriptModule decided that if for some reason a REST style call to a page method or a web service method, from JavaScript causes a 302 Redirect, they're going to just simply turn the response into a 401 Unauthorized. This causes a browser to popup a login UI that is totally misleading, as the user tries to type in their username and password, which means nothing, because FormsAuthentication is used. Finally, when the user clicks Cancel, the 401 comes through to the error handler. </p> <p>So, the question is, how can one disable the browser's login UI prompt in any way? Some people on the web suggest to use a username and password in the XHR request, but it does not seem to work.</p>
<p>I think I worked around it. Ofcourse relying on internal MS AJAX related errors is not really nice, but this will do the trick for others faces with this problem.</p> <p>Basically what you do, is you set the <strong>X-MicrosoftAjax</strong> header to the value <strong>Delta=true</strong> (case is important here), the ScriptModule will interpret this as a normal redirect, and turn the response into a <strong>200</strong>, but will set the <strong>pageRedirect</strong> data string for any ScriptManager (MS-AJAX PageRequestManager) on the page to consume. The jQuery.ajax function will still see this as an error, so basically you can check for <strong>pageRedirect</strong> in responseText property of the XHR and hadle it accordingly. Like sending the user to the login page of something.</p> <pre><code> $.ajax({ type: "POST", url: postUrl + "/SomePageMethod", data: "{searchString:\"" + escape(searchString) + "\"}", contentType: "application/json; charset=utf-8", beforeSend: function(xhr) { xhr.setRequestHeader("X-MicrosoftAjax","Delta=true"); }, dataType: "json", success: onSuccess, error: onError }); function onError(xhr, e, textStatus) { var isAjaxRedirect = xhr.status == 200 &amp;&amp; xhr.responseText.match(/pageRedirect/); if (isAjaxRedirect == "pageRedirect") { // forms authentication ticket expired location.href = "a session timeout page, or a login page or whatever"; } } </code></pre>
<p>Both are great answers. But if your website is hosted in a shared server, you will probably not be able to change IIS settings, so the client side solution rocks. I have been facing the same problem, and this post saves me. My two cents to the solution: In jquery (at least in the latest versions) you can use a parameter called “header” to send this headers without using the “beforeSend” callback, and I think this can be a bit cleaner way for doing the same. You can also add other header info here:</p> <pre><code>$.ajax({ type: "POST", url: postUrl + "/SomePageMethod", data: "{searchString:\"" + escape(searchString) + "\"}", contentType: "application/json; charset=utf-8", headers: { "cache-control": "no-cache", "X-MicrosoftAjax" : "Delta=true" }, dataType: "json", success: onSuccess, error: onError }); </code></pre> <p>I didn’t know about this header “Delta=true”, and <a href="http://books.google.es/books?id=GkWTN3cVDRQC&amp;pg=PA165&amp;lpg=PA165&amp;dq=que%20es%20x-microsoftajax%20delta=true&amp;source=bl&amp;ots=F1YYQipM4u&amp;sig=Nm_VMJvDoPt0YSbp7mWpdG0HUWE&amp;hl=es&amp;sa=X&amp;ei=Et5IU9mILaPx0gX7lYHABA&amp;ved=0CI4BEOgBMAk#v=onepage&amp;q=que%20es%20x-microsoftajax%20delta=true&amp;f=false" rel="nofollow">after a bit research</a>, it seems to be a header to tell the server that the request you are doing is an asynchronous postback request.</p> <p>The AJAX call will return an HTTP Status 200 (instead of "Unauthorized" 401) in the “error” callback, meaning that the server request was successful in some way (although authentication fails). A bit strange, but is the way it works.</p> <p>Hope this helps.</p>
47,171
<p>I'm having trouble getting my MendelMax 2's heatbed <em>not</em> to heat up when I want to print without it. I don't get how multiple sources of control relate to each other (same with extrusion temperatures, actually):</p> <ul> <li><p>Slic3r (1.2.9) has settings under Filament Settings / Filament / Bed, for First layer and Other layers (and groups of settings can be saved).</p></li> <li><p>The pronterface GUI (Printrun-Mac-10Mar2014) has an "Options" panel where you can set "Bed temperature" (actually, two settings, one for PLA and one for ABS -- though I doubt the software can test which filament is loaded!)</p></li> <li><p>The pronterface GUI also has a menu/fill-in labelled "Bed", which works fine to adjust the bed when nothing is printing. The menu there lets you pick from a manually-entered value, "0 (off)", and (apparently) the settings for PLA and ABS from the options panel.</p></li> <li><p>Marlin's Configuration.h has settings for bed minimum and maximum temps (the non-zero minimum seems to be to prevent running the bed when the thermistor isn't working, to avoid unlimited overheating).</p></li> </ul> <p>I recently tried to print some PLA with no bed heat (using blue tape on the glass build plate). I sliced the model with bed heat off in Slic3r; changed the PLA bed temps in the printerface options panel to 0; and picked the PLA setting in the GUI main screen (and also tried setting "0 (off)" manually.</p> <p>When I started to print the object, the bed turned on and stayed on, maintaining 60C.</p> <p>I thought of just unplugging the heatbed, but then I expect the print would never start, since it would try to heat up the bed and never succeed.</p> <p>So how does the decision about which temperature setting to use, <em>really</em> get made? I have the same question about extruder temps, speeds, accelerations, and other things, too -- whose settings are really in charge?</p>
<p>3D printer get the temperature settings from g-code file. The firmware settings for min and max temperature are just safeguards.</p> <p>You should verify instructions within the g-code file. If you are not familiar with g-code, take a look to <a href="https://en.wikipedia.org/wiki/G-code" rel="noreferrer">wikipedia</a>. List of g-code instructions for marlin firmware is <a href="http://reprap.org/wiki/G-code" rel="noreferrer">here</a>.</p> <p>Instruction responsible for setting bed temperature are <a href="http://reprap.org/wiki/G-code#M190:_Wait_for_bed_temperature_to_reach_target_temp" rel="noreferrer">M190</a> and <a href="http://reprap.org/wiki/G-code#M140:_Set_Bed_Temperature_.28Fast.29" rel="noreferrer">M140</a>. Open your g-code file and search for lines containing them. If you delete these lines then the bed temperature will be not set during print. Additionally it means that it is set by your slicer. </p> <p>In <em>Slic3r</em> you should check <em>Printer settings</em> &rarr; <em>Custom G-code</em> &rarr; <em>Start G-code</em> if it contains one of mentioned instructions and possibly remove it.</p>
<p>Sli3er will control the bed temperature during a print. The options in Pronterface can be used to pre-heat the bed and hot end, or to adjust the temperature during a print. </p> <p>The slicer will put the temperatures you set in the filament tab settings into the gcode at the appropriate layers. As the printer reads these codes it will adjust the temperatures. If you manually change the temperature, it will stay at your adjustment until it encounters a line in the gcode file that tells it to change again. Usually this only happens at the start of a print, or at the transition from the first layer to the second layer. </p> <p>When you change the filament settings in Slic3r, they do not save automatically, so if you changed them, closed the program without saving your filament settings, and opened it later, the changes would be lost. </p> <p>The other place where temperature can be changed from is in the custom gcode settings, where you can specify operations to be performed at the start of the print, in between layers, or at the end of the print. Take a look there and make sure that there are no codes to change temperature in any of these fields.</p>
204
<p>I'm using start.jar and stop.jar to stop and start my jetty instance. I restart by calling stop.jar, then start.jar. The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.</p> <p>Sleeping for a longer period of time between stop and start is my current option.</p> <p>I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes. Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing. Another option might be to poll the log file, but that's pretty ugly.</p> <p>What's the best way of restarting jetty?</p> <p>Gilbert: The Ant task is definitely not a bad way of doing it. However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.</p>
<p>Can you write a shell script that does something like this after calling shutdown and before calling startup?</p> <pre> LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l ` while [$LISTEN_PORT -ne 0] ; do sleep 1 LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l ` done </pre>
<p>Did you try JFGI? Setting up Ant task that could do the work for you?</p> <p>This blog post details how to setup targets that can start and stop jetty for you. You could easily cobble together another target called 'jetty-restart' which depends on 'jetty-stop' and then calls 'jetty-start'.</p> <p><a href="http://ptrthomas.wordpress.com/2006/10/10/how-to-start-and-stop-jetty-from-ant/" rel="nofollow noreferrer">http://ptrthomas.wordpress.com/2006/10/10/how-to-start-and-stop-jetty-from-ant/</a></p>
12,907
<p>I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0_08. Note that this does not occur every time, but about 80% of the time:</p> <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke at java.util.TreeMap.compare(TreeMap.java:1093) at java.util.TreeMap.put(TreeMap.java:465) at java.util.TreeSet.add(TreeSet.java:210) at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364) at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300) at javax.swing.JComponent.setUI(JComponent.java:652) at javax.swing.JSplitPane.setUI(JSplitPane.java:350) at javax.swing.JSplitPane.updateUI(JSplitPane.java:378) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:332) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:287) ... </code></pre> <p>Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.</p> <p><strong>Edit #1</strong> See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.</p>
<p>After doing some Googling on bugs.sun.com, this looks like this might be a JDK bug that was only fixed in JDK 6.</p> <p>See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a></p>
<pre><code>java.lang.ClassCastException: javax.swing.KeyStroke cannot be cast to java.lang.Comparable.... </code></pre> <p>If you are getting above error after installing java 7 in dbviz then add Environment variabbles like: 'DBVIS_JAVA_HOME' as a 'Variable Name' and java path like for ex. "C:\SWDTOOLS\IBM\RAD85\runtimes\base_v7\java"</p>
13,911
<p>I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:</p> <pre><code>java CliMain arg1 arg2 </code></pre> <p>And another running GUI instance would perform an appropriate action.</p> <p>What is the easiest way of implementing something like this?</p>
<p>You could have the GUI application listen on a TCP port (on the <code>localhost</code> interface) and the CLI application would connect to it.</p> <p>One way to do this would be to use REST over HTTP.</p>
<p>Another way is through JMX. It gives you a lot of stuff "for free" (in the simple case you just implement a bean and register it -- very simple), and is particularly well suited to this task.</p>
30,955
<p>I need to deploy an application on the WAS ND 6.1 and do not know anything about it and cannot afford to go to training...</p>
<p>Getting started with WAS ND can be a bit overwhelming. The redbooks mentioned above to give you a good introduction, especially the first few chapters but they are often over 500 pages long. IBM also provides an educational assistant which is a presentation style overview and that may give a good point to start with. The link to the educational assistant is shown below:</p> <p><a href="http://publib.boulder.ibm.com/infocenter/ieduasst/v1r1m0/index.jsp" rel="nofollow noreferrer">http://publib.boulder.ibm.com/infocenter/ieduasst/v1r1m0/index.jsp</a></p>
<p>This course from IBM would also be excellent but a bit pricy!!!</p> <p><a href="http://www.redbooks.ibm.com/abstracts/sg247304.html?Open" rel="nofollow noreferrer">http://www.redbooks.ibm.com/abstracts/sg247304.html?Open</a></p>
9,053
<p>In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?</p>
<p>Convert from <code>String</code> to <code>byte[]</code>:</p> <pre><code>String s = &quot;some text here&quot;; byte[] b = s.getBytes(StandardCharsets.UTF_8); </code></pre> <p>Convert from <code>byte[]</code> to <code>String</code>:</p> <pre><code>byte[] b = {(byte) 99, (byte)97, (byte)116}; String s = new String(b, StandardCharsets.US_ASCII); </code></pre> <p>You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.</p>
<p>terribly late but i just encountered this issue and this is my fix:</p> <pre><code>private static String removeNonUtf8CompliantCharacters( final String inString ) { if (null == inString ) return null; byte[] byteArr = inString.getBytes(); for ( int i=0; i &lt; byteArr.length; i++ ) { byte ch= byteArr[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines if ( !( (ch &gt; 31 &amp;&amp; ch &lt; 253 ) || ch == '\t' || ch == '\n' || ch == '\r') ) { byteArr[i]=' '; } } return new String( byteArr ); } </code></pre>
11,451
<p>Im just starting a project and since this project is personal I was wondering what are the advantages of using Enterprise Library? We use the version 2 for several projects in the office but im not quite sure (aside of the good practices) of the advantages of it, especially in the database component. Any advice? Thanks</p>
<p>For the database application block, the main advantage is that it makes it easier to produce database-agnostic code. The developer interacts mainly with generic Database and DbCommand objects, rather than eg SqlConnection, SqlCommand, etc. Thus, switching to a different database (ie Oracle) becomes more feasible. Depending on your business needs, this could be a definite advantage. EntLib also gently prods the developer in the direction of using DbParameter for query parameters, which reduces the risk of SQL injection attacks.</p> <p>As another poster mentionned, the data app block is somewhat higher-level than the straight ADO.NET classes, so it tends to require fewer lines of code to do the same thing.</p> <p>From my point of view, the data, exception and logging blocks are the most useful. Exception and Logging together make it very easy to log exceptions (duh) to a number of places and in a number of formats. For example, they can put the entire exception log entry, including the stack trace, in the Windows event log making it relatively easy to diagnose a problem.</p> <p>One disadvantage of EntLib is that some app blocks place quite a bit of logic into configuration files. So your logic is more spread out; some of it is in code, some in config files. The upside is that the configuration can be modified post-build and even post-deployment.</p>
<p>The choice of not being able to use EF for me is bind by the constraints I have in my environment that requires the applications to process millions of transactions per hour. This is the volume of processing in Telco environment.</p> <p>Whether to use EF or not is entirely up to your environment and choice (as long as you know the limitations of the chosen technology). If your system does not require such high loads, I don't foresee you will have any problems in using EF.</p>
29,828
<p>Being a C# developer since version 1.0, F# has captured my free time for the past few weeks. Computers are now sold with 2, 4 .. Cores and multi-threading is not always simple to accomplish. </p> <p>At the moment I see that F# has great potential for complicated and or heavy workloads. Do you think that F# will (once RTM) become an important player in the Enterprise Software market?</p>
<p>I think regardless of whether F# becomes import for Enterprise Software being able to isolate pure functional portions of code in any language will be key to using the potential of multi-core computers. For instance Microsoft's Parallel Extensions for .NET are great, but there is still a lot of room to make mistakes by parallelizing code that can't execute in parallel. If the code is in the form of a pure functional language or a subset of your language that is purely functional, then you are assured that you can execute it in parallel. The trick is then figuring out the most efficient way to assign the work.</p> <p>The role that F# plays in this I would say would be more as a catalyst to get people's feet wet and start thinking in a more declarative way.</p>
<p>I think F# will always be a niche language, compared to VB/C#/Java, because it does require more of a mathematical or computer science background. However the very fact that it is a CLR language means that it will have much bigger exposure than earlier functional languages.</p> <p>I work in an investment bank and we are already using F# for some ad-hoc scripting purposes, we are pretty keen to see a released version of F# so that we can consider more formal integration into our systems (although they are likely to remain fundamentally C# based).</p>
13,096
<p>At my workplace we are using CVS as the version control system. Since we are using Windows mostly, TortoiseCVS and WinCVS serve as the GUI front-ends to CVS.</p> <p>Is there anything like those front-ends for one of the distributed VCS (bzr, hg, git)? I know we could use the command line but that is not an option.</p> <p>I've already tried Bazaar and was disappointed by TortoiseBzr.</p>
<p>Try <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a>. It has a <a href="http://tortoisehg.sourceforge.net/" rel="nofollow noreferrer">tortoise shell plugin</a> and <a href="http://www.vectrace.com/mercurialeclipse/" rel="nofollow noreferrer">integrates with Eclipse</a>.</p>
<p>I like bzr, but have not used the tortoise plugin; I believe Canonical are working on some front-ends for it as well. Oh, and of course there's an Eclipse plugin, so you can use your IDE as the GUI for it.</p>
35,737
<p>I am trying to get PHP working on my vista home machine but I am getting weird problems. First I had file permission problems for which I disabled Vista's UAC. Now I can't get the PHP interpreter working.</p> <p>I have made all the necessary changes following some tutorial but I still can't get it working.</p> <p>Tutorial was located here: <a href="http://www.tanguay.info/wamp/installPhp5.php5" rel="nofollow noreferrer">http://www.tanguay.info/wamp/installPhp5.php5</a></p>
<p>Try <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">XAMPP</a>. I use that at home on a Vista machine and it worked nicely after the install.</p>
<p>You can use FastCGI for IIS 7. I'm using this also and it works perfectly!!</p> <p><a href="http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis-70/" rel="nofollow noreferrer">FastCGI</a></p>
28,309
<p>I have a friend who is need of a web page. He does interior construction, and would like to have a gallery of his work. I'll probably go for a php host, and was thinking about the best way to implement the image gallery for him. I came up with:</p> <ul> <li>Use flickr to host the images. They can be tagged, added to sets, and I can use both the tag and set information to display "categories" for the gallery, as well as browsing. Flickr also has multi-upload tools so that a 20 photo job won't be a PITA to upload.</li> <li>How to best get at the api? Is there a good PHP library for flickr integration? Should I roll my own?</li> <li>API key - is this considered a commercial project? The web page is for his business, and he will be paying me to create the site...</li> <li>Is flickr the wrong tool for the job? It seems like a pretty good solution in my head, but is there something I'm missing? I haven't used their APIs at all.</li> </ul> <p>Thanks for any input!</p>
<p>It sounds like a difficult way to do things - have you considered <a href="http://gallery.menalto.com/" rel="nofollow noreferrer">Gallery</a> (No points on creativity for the name!).</p> <p>Unless you're really wanting to save on bandwidth, I think you'd get much better results from installing some pre-built gallery.</p>
<p>If you have any interest in Ruby on Rails, there is a screencast <a href="http://www.rubyonrails.org/screencasts" rel="nofollow noreferrer">here</a> that shows how to create a site similar to what you are describing in RoR.</p>
22,101
<p>I have Visual Studio setup with a VSTO word project, and when I hit run it runs fine.</p> <p>But, how do I setup a word document to use my code without having Visual Studio running?</p>
<p>RubyCocoa is not supported at all on the iPhone. There is no bridge support library, and I do not believe there is any ruby interpreter on the phone.</p> <p>You might be able to get it working in the simulator, it will not stop you from using OS X only libraries if you really try, but that still will not make it work on the iPhone.</p> <p>If you really want to use RubyCocoa on the iPhone you will need to build ruby as a static library and port the bridge to the phone, which is doable, but would probably be very difficult.</p>
<p>Howdy! Though I'm not familiar with how Ruby/Cocoa wraps foreign method calls- or with Objective C for that matter- the first place that would seem likely to disconnect under test is passing in a Ruby mock to the natively implemented controller. In the bowling tutorial, the ruby controller proxy is exposes its interface to the Cocoa bridge while in this implementation the proxy wraps an exposed Cocoa interface. There might be an issue, then, when substituting a ruby mock for a native field versus a ruby mock for a ruby field.</p> <p>The roll() test for the pins succeeds, though, so it's possible that messages are being passed correctly but arguments are mangled or dropped.</p> <p>This probably isn't much help, but it's an interesting problem. Good luck with the project!</p>
35,147
<p>I have two NSURLConnections. The second one depends on the content of the first, so handling the data received from the connection will be different for the two connections. </p> <p>I'm just picking up Objective-C and I would like to know what the proper way to implement the delegates is.</p> <p>Right now I'm using: </p> <pre><code>NSURL *url=[NSURL URLWithString:feedURL]; NSURLRequest *urlR=[[[NSURLRequest alloc] initWithURL:url] autorelease]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:urlR delegate:self]; </code></pre> <p>I don't want to use self as the delegate, how do I define two connections with different delegates?</p> <pre><code>NSURLConnection *c1 = [[NSURLConnection alloc] initWithRequest:url delegate:handle1]; NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:handle2]; </code></pre> <p>How would do i create handle1 and handle2 as implementations? Or interfaces? I don't really get how you would do this. </p> <p>Any help would be awesome.</p> <p>Thanks, Brian Gianforcaro</p>
<p><strong>Ben</strong>, while your info was helpful It didn't fully answer the question I asked. </p> <p>I finally figured out how to setup my own delegates, which was what I was really asking. </p> <p>I implemented it like so: </p> <pre><code>@interface DownloadDelegate : NSObject - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; @end @implementation DownloadDelegate - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { } @end </code></pre> <p>We use the delegate like so:</p> <pre><code>DownloadDelegate *dd = [DownloadDelegate alloc]; NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:dd]; </code></pre> <p>Hope that helps anybody in the same position, and thanks again <strong>Ben</strong> for your help. </p> <p>Thanks, </p> <p><strong>Brian Gianforcaro</strong></p>
<p>since the delegates are called asynchronously, they could call didfinishloading in random order. you can then use a state check to determine if the "other" download is done yet before continuing.</p> <p>i use 2 delegates:</p> <p>for instance (this is pseudo oc):</p> <pre><code>jsondelegate = [[JSonDelegate alloc]initWithCaller:self andSelector:@selector(jsonDone:)] otherdelegate = [[OtherDelegate] initWithCaller:self andSelector:@selector(otherDone:)] </code></pre> <p>when each delegate finishes, the delegate informs the caller, by calling the 2 done methods.</p> <p>each done method receives the url data, and saves its state to an ivar. then they check to see if the other ivar is set, and continue processing if they both are done.</p> <pre><code>if(self.jsonString &amp;&amp; self.otherData){ continueProcessing } </code></pre> <p>hope this helps.</p>
24,871
<p>I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and &quot;&quot; or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.</p> <p><strong>What do you use as the default initializer and why?</strong></p> <p><em>Edit: Based on the answers I futher my further thoughts</em></p> <ol> <li><p><strong>Avoiding error handling</strong> If the value shouldn't be null, why did it get set to <code>NULL</code> in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase?</p> </li> <li><p><strong>Avoiding null checks</strong> If you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them <code>NULL</code> safe? What happens if you constantly use <code>String.Empty</code> and a null happens to work it's way into your system, do you start adding <code>NULL</code> checks anyways?</p> </li> </ol> <p>I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of <code>null</code> in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use <code>String.Empty</code> rather than <code>NULL</code> to represent no value.</p> <blockquote> <h3>Related Questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/263191/in-c-should-i-use-stringempty-or-stringempty-or">In C#, should I use string.Empty or String.Empty or “” ?</a></li> <li><a href="https://stackoverflow.com/questions/151472/what-is-the-difference-between-stringempty-and">What is the difference between String.Empty and “”</a></li> <li><a href="https://stackoverflow.com/questions/167952/null-or-empty-string-to-represent-no-data-in-table-column">Null or empty string to represent no data in table column?</a></li> </ul> </blockquote>
<p>+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."</p> <p>So I'd answer your question like this:</p> <p><strong>empty</strong> when I want a valid default value that may or may not be changed, for example, a user's middle name.</p> <p><strong>NULL</strong> when it is an error if the ensuing code does not set the value explicitly.</p>
<p>Strings aren't value types, and never will be ;-)</p>
33,338
<p>Anyone have experience with algorithmic trading (like stocks)? Any good services to use to get quotes and to make trades?</p>
<p>I had a freelance project that used <a href="http://www.interactivebrokers.com/" rel="noreferrer">Interactive Brokers</a>, which provided both a proprietary API as well as a FIX-based one. The proprietary API is somewhat painful to use (and they probably can't change it much, for compatibility), but you can easily code a "translation layer" to make it much more pleasant. I haven't tried the FIX-based API, so no comments there.</p> <p>And yes, I reopened the question. I happen to think it's a fair question to ask.</p>
<p>I know <a href="http://www.tradestation.com/default_2.shtm" rel="nofollow noreferrer">TradeStation</a> is pretty popular. </p>
40,095
<p>In Cura, I can edit my .ini profile settings as needed, for example, when I change filament or models. It's annoying to have to edit the profile on another computer and update it on my Pi just to change the infill, etc. I've searched <a href="http://plugins.octoprint.org/" rel="noreferrer">http://plugins.octoprint.org/</a> and can't find any plugins that do this.</p>
<p>As far as I know, this is currently not possible.</p>
<p>There is an import function. <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura" rel="nofollow">https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura</a></p> <p>Btw. now in Cura 2.1 you'll also need to reimport your .ini.</p> <p>Regards :)</p>
162
<p>I have run in to a bit of a problem and I have done a bit of digging, but struggling to come up with a conclusive answer/fix.</p> <p>Basically, I have some javascript (created by a 3rd party) that does some whizzbang stuff to page elements to make them look pretty. The code works great on single pages (i.e. no master), however, when I try and apply the effects to a content page within a master, it does not work.</p> <p>In short I have a master page which contains the main script reference. All pages will use the script, but the parameters passed to it will differ for the content pages.</p> <p><strong>Master Page Script Reference</strong></p> <pre><code>&lt;script src=&quot;scripts.js&quot; language=&quot;javascript&quot; type=&quot;text/javascript&quot; /&gt; </code></pre> <p><strong>Single Page</strong></p> <pre><code>&lt;script&gt; MakePretty(&quot;elementID&quot;); &lt;/script&gt; </code></pre> <p>As you can see, I need the reference in each page (hence it being in the master) but the actual elements I want to &quot;MakePretty&quot; will change dependant on content.</p> <p><strong>Content Pages</strong></p> <p>Now, due to the content page not having a <code>&lt;head&gt;</code> element, I have been using the following code to add it to the master pages <code>&lt;head&gt;</code> element:</p> <pre><code>HtmlGenericControl ctl = new HtmlGenericControl(&quot;script&quot;); ctl.Attributes.Add(&quot;language&quot;, &quot;javascript&quot;); ctl.InnerHtml = @&quot;MakePretty(&quot;&quot;elementID&quot;&quot;)&quot;; Master.Page.Header.Controls.Add(ctl); </code></pre> <p>Now, this <strong>fails to work</strong>. However, if I replace with something simple like <code>alert(&quot;HI!&quot;)</code>, all works fine. So the code is being added OK, it just doesn't seem to always execute depending on what it is doing..</p> <p>Now, having done some digging, I have learned that th content page's <code>Load</code> event is raised before the master pages, which may be having an effect, however, I thought the javascript on the page was all loaded/run at once?</p> <p>Forgive me if this is a stupid question, but I am still relatively new to using javascript, especially in the master pages scenario.</p> <p><strong>How can I get content pages to call javascript code which is referenced in the Master page?</strong></p> <p>Thanks for any/all help on this guys, you will really be helping me out with this work problem.</p> <h2>NOTES:</h2> <ul> <li><code>RegisterStartupScript</code> and the like does not seem to work at any level..</li> <li>The control ID's are being set fine, even in the MasterPage environment and are rendering as expected.</li> </ul> <hr /> <p>Apologies if any of this is unclear, I am real tired so if need be please comment if a re-word/clarification is required.</p>
<p>Put a ContentPlaceHolder in the head section of the master page, then add a asp:Content control on the content page referring to the placeholder and put your script in that control. You can customize it for each page this way.</p> <p>Also, the reference by ID may not be working because when you use Master Pages, the control IDs on the page are automatically created based on the container structure. So instead of "elementID" as expected, it may be outputting "ctl00_MainContentPlaceHolder_elementID" View your source or use firebug to inspect your form elements to see what the IDs outputted are.</p>
<p>Once you use Master Pages, the ids of controls on the client side aren't what you think they are. You should use Control.ClientID when you generate the script.</p>
21,224
<p>Is there any free java library which I can use to convert string in one encoding to other encoding, something like <a href="https://en.wikipedia.org/wiki/Iconv" rel="nofollow noreferrer"><code>iconv</code></a>? I'm using Java version 1.3.</p>
<p>You don't need a library beyond the standard one - just use <a href="https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html" rel="nofollow noreferrer">Charset</a>. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)</p> <p>EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String%28byte%5B%5D%2C%20java.nio.charset.Charset%29" rel="nofollow noreferrer">new String(bytes, charset)</a> and <a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes%28java.nio.charset.Charset%29" rel="nofollow noreferrer">String.getBytes(charset)</a>.</p> <p>See "<a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow noreferrer">URL Encoding (or: 'What are those "<code>%20</code>" codes in URLs?')</a>".</p>
<p>It is a whole lot easier if you think of unicode as a character set (which it actually is - it is very basically the numbered set of all known characters). You can encode it as UTF-8 (1-3 bytes per character depending) or maybe UTF-16 (2 bytes per character or 4 bytes using surrogate pairs).</p> <p>Back in the mist of time Java used to use UCS-2 to encode the unicode character set. This could only handle 2 bytes per character and is now obsolete. It was a fairly obvious hack to add surrogate pairs and move up to UTF-16.</p> <p>A lot of people think they should have used UTF-8 in the first place. When Java was originally written unicode had far more than 65535 characters anyway...</p>
28,348
<p>I'm trying to figure out the best lower-budget home office development hardware setup. My laptop is aging.</p> <p>My latest idea is that I would like a very powerful desktop paired with a less-powerful laptop. The idea being that the desktop would do the heavy lifting while the laptop would allow me to work untethered (but within range of the wireless network, of course.)</p> <p>Is such a thing possible, or am I dreaming? </p> <p>(I develop .Net applications - mostly Asp.Net)</p> <p>Thanks for ideas!</p>
<p>You can do that with an RDP / Terminal Services client or VNC. You could also run multiple virtual machines on the beefy server (making it look like a poor man's datacentre / set of less powerful servers). </p> <p>Another benefit is that you can do some testing with the laptop as the browser client and the desktop as server - this can sometimes show up issues that you won't see with testing on localhost (especially if your network goes down in the middle of it).</p>
<p>This is exactly how my current setup is, and it works nicely. I'd still get a couple of 20"+ monitors, as the laptop can be a little restricting for long usage.</p>
49,270
<p>Is there some way to determine what file currently is being rendered by Rails (2.2) in a helper method. An example result would be "/sessions/new.html.erb" or something similar.</p> <p>I am trying to write a helper function that does something based on the file name that is being rendered, so I need a reliable way to obtain this information. Is there an official way to get this information?</p>
<p>It's never a good idea to use <code>DoCmd.RunSQL</code> as it generates a prompt (which you have to turn off if you don't want it), and it completes the updates even if errors occur, and doesn't report the errors. Much better is to replace it with a function that executes the same SQL:</p> <pre><code>Public Function SQLRun(strSQL As String) As Boolean On Error GoTo errHandler CurrentDB.Execute strSQL, dbFailOnError SQLRun= True exitRoutine: Exit Function errHandler: MsgBox err.Number &amp; ": " &amp; err.Description, vbExclamation, "Error in SQLRun()" Resume exitRoutine End Function </code></pre> <p>Once you've placed this in a public module, you can easily do a global search and replace for <code>DoCmd.RunSQL</code> to replace it with <code>SQLRun</code>.</p> <p>EDIT: Another version of this function that returns the number of records affected is <a href="https://stackoverflow.com/questions/343396/acess-vba-to-get-value-from-update-query-prompt/348453#348453">here</a>.</p>
<p>I don't see any way at this time to get the information after the update query has run unless you have another distinguishing field (maybe an updated date field). Why not run a select query for it and run a report off of that data, THEN run the update query to change the values for 'bonus'.</p> <p>Let me know if this helps! JFV</p>
43,284
<p>My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look</p> <p><a href="http://img114.imageshack.us/img114/9683/frameow2.jpg" rel="nofollow noreferrer">Image</a></p> <p>Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?</p> <p>I also would like to set the size of those buttons so they are not so huge (<code>BorderLayout</code> is being used for the buttons and TextField)</p>
<p>If you want the two checkerboards to stay the same size, then you'll need to have them each contained in their own <code>JPanel</code>. Set each of those parent JPanel's to have a layout type of <code>GridBagLayout</code>. Set the preferedSize for each checkerboard component and then add them to their respective containers. GridBagLayout should by default lay each board out in the center of the parent JPanel. So as the window is resized, the JPanel parent area will get larger or smaller, but the checkerboard components inside will remain the same size.</p> <p>Alternatively, you could have your blue squares scale to the right size as the window is resized by having each checkboard square be a <code>JPanel</code> with a <code>BorderLayout</code> layout manager and adding the <code>JLabel</code> (with a blue background color) to its <code>BorderLayout.CENTER</code> location.</p> <p>As for your buttons, try something like this:</p> <pre><code>JPanel theButtonPanel = new JPanel(new BorderLayout()); JButton button1 = new JButton("Fire"); JButton button2 = new JButton("Pass"); JButton button3 = new JButton("Forfiet"); JPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8)); innerButtonContainer.add(button1); innerButtonContainer.add(button2); innerButtonContainer.add(button3); theButtonPanel.add(innterButtonContainer); </code></pre> <p>Lastly, consider using a design tool for your Swing user interface. Netbeans has an <strong>excellent UI</strong> designer built into it. Download Netbeans <a href="http://www.netbeans.org/downloads/index.html" rel="nofollow noreferrer">here</a>.</p>
<p>I have had success solving problems like these using <code>TableLayout</code> which is a third party layout manager. You will need to download it and read the tutorial but the key would be to set the justification to CENTER when adding the JButtons to their positions in the layout.</p>
40,863
<p>So I was thinking about creating a dynamic sql question, meaning that i want the amount of parameters to be dynamic.</p> <p>Having looked at this: <a href="https://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause#337725">Parameterize an SQL IN clause</a> i was thinking that using like '%x%' is SLOW and not good.</p> <p>What i actually would like to do is using the IN keyword and have it somewhat like this:</p> <p>select UserId from NameTable where Name IN (@List_of_names)</p> <p>Where the @List_of_names could contain i.e. </p> <ul> <li>Filip Ekberg</li> <li>Filip</li> <li>Ekberg Filip</li> <li>Ekberg</li> <li>Johan Ekberg</li> <li>Johan</li> </ul> <p>( my second name is johan, thats why it's in there ,) )</p> <p>So all these should match up with Johan Filip Ekberg.</p> <p>I want to be using either LINQ to SQL or LINQ to SQL ( Stored Procedure ) using C#.</p> <p>Suggestions and thoughts please!</p> <p>----------------- Clearification of scenario and tables -------------------------</p> <p>Imagine i have the following: A table with Users, A table with Names and a Table that connects the Names to a certain user.</p> <p>So by having</p> <pre><code>[User Table] User ID Full Name 1 Johan Filip Ekberg 2 Anders Ekberg [Names] Name ID Name 1 Filip 2 Ekberg 3 Johan 4 Anders [Connect Names] Name ID User ID 1 1 2 1 3 1 2 4 2 2 </code></pre> <p>So if i want to look for: Ekberg</p> <p>The return should be:</p> <ul> <li>Johan Filip Ekberg</li> <li>Anders Ekberg</li> </ul> <p>If i want to search for Johan Ekberg</p> <ul> <li>Johan Filip Ekberg</li> </ul> <p>If i want to search for Anders</p> <ul> <li>Anders Ekberg</li> </ul> <p>The amount of "search names" can be infinite, if i have the name: Johan Anders Carl Filip Ekberg ( This is just 1 person with many names ) and i just pass "Carl Filip" in, i want to find that User.</p> <p>Does this make everything clearer?</p>
<p>It looks like SQL 2008 is an option, so passing a table parameter is probably your best bet. Another possible solution for those who can't move to 2008 yet, is to write a table-valued UDF that generates a table from a delimited string. Then you can do something like this:</p> <pre><code>SELECT DISTINCT CN.user_id FROM dbo.Names N INNER JOIN dbo.Connect_Names CN ON CN.name_id = N.name_id INNER JOIN dbo.GetTableFromNameList(@names) T ON T.name = N.name </code></pre> <p>This will give you user IDs where ANY of the passed names match ANY of the user's names. If you want to change it so that it only gives a match when ALL of the passed names match one of the user's names then you could do something like this:</p> <pre><code>SELECT CN.user_id FROM dbo.Names N INNER JOIN dbo.Connect_Names CN ON CN.name_id = N.name_id INNER JOIN dbo.GetTableFromNameList(@names) T ON T.name = N.name GROUP BY CN.user_id HAVING COUNT(*) = (SELECT COUNT(*) FROM dbo.GetTableFromNameList(@names)) </code></pre> <p>I haven't tested that second query, so you may need to fiddle with it. Also, you might want to create a local table and fill it with the function so that you don't have to run the function multiple times.</p> <p>I can post my own version of the string to table function if you need it. Also, if you want to use LIKE rather than exact matches, you can do that.</p>
<p>I hear that SQL Server 2008 has a feature called Table Parameters, so you can pass a Table as a parameter to a Function or Stored Procedure.</p> <p>Until then, you could use the classic:</p> <pre><code>SELECT UserId FROM NameTable WHERE CHARINDEX( '|' + Name + '|', '|Filip Ekberg|Filip|Ekberg Filip|') &gt; 0 </code></pre> <p>This means that column name can be any of the values you have in the list.</p> <p>You can also pass an XML parameter into the stored procedure and then use it as a table in your code, via the OPENXML command.</p>
44,257
<p>I've been working with JSF for some time, and been using the Apache-Trinidad tags. I like developing using this a lot but I keep hearing great things about facelets. Is anyone out there using it, and what exactly does it get you? </p> <p>I've looked at the facelets site (<a href="https://facelets.dev.java.net/" rel="nofollow noreferrer">https://facelets.dev.java.net/</a>), but it doesn't do a very good job explaining the advantages or any tutorials about facelets. I looked on google, but everything seems to be from 2005 or 2006, surely there's been a lot of changes since then. </p> <p>Anyone want to chime in with their opinion of facelets or point me to some good resources?</p>
<p>Facelets haven't really changed. It's a very simple templating engine that runs as a JSF view handler and replaces jsp.</p> <p>The old resources are still valid.</p> <ul> <li>Uses xml for templates.</li> <li>You can use EL anywhere.</li> <li>Very few tags.</li> <li>Very simple</li> <li>...</li> </ul> <p>In my humble opinion, it is a much better approach to create the interface than JSPs.</p>
<p>I've just started working with facelets as well, and so far the best resource I've found is the book "The Definitive Guide to Apache MyFaces and Facelets" from Apress. While it's likely you won't need the other chapters, since you've worked with Trinadad tags already, I've found the examples they use to explain facelets give a good concrete foundation. I'm constantly refering to the text to pull out bits of code.</p> <p>PS Here's the link from <a href="http://books.google.com/books?id=FPxif81mgYoC&amp;printsec=frontcover&amp;dq=myfaces+and+facelets&amp;cd=1#v=onepage&amp;q&amp;f=false" rel="nofollow noreferrer">Google Books</a>, it'll at least give you a taste of what's inside.</p>
41,499
<p>I'm experimenting with the iPhone SDK and doing some TDD ala Dr. Nic's rbiPhoneTest project. I'm wondering how many, if any, have been successful using this or any other testing framework for iPhone/Cocoa? More important, I'd like to know how to best assert a proprietary binary request/response protocol. The idea is to send a binary request over the network and receive a binary response. Requests and responses are created using byte and'ing and or'ing. I'm using the golden copy pattern to test my request. Here's what I have so far. Don't laugh as I'm new to btoh Objective C and Ruby:</p> <pre><code>require File.dirname(__FILE__) + '/test_helper' require 'fileutils' require 'io' require "MyModel.bundle" OSX::ns_import :MyModel module MyTestExtensions def is_absolute_path(path) return /^\/.*/.match(path) end def parent_directory(file) dir = file if(! is_absolute_path(dir)) dir = File.expand_path(dir) end dir = File.dirname(dir) assert is_absolute_path(dir), "Expecting an absolute path with #{dir}" return dir end def assert_NSData_contains_bytes_from_file(file, data) assert_not_nil data, "Data should not be nil." assert data.bytes, "data should have bytes" data.length.times { |i| expected = file.getc assert_not_nil expected, "Expected only #{i} bytes. Actual data contains more." actual = data.bytes.int8_at(i) assert_equal expected, actual, "Bytes should be equal at offset #{i} expected #{expected.chr} but was #{actual.chr}" } expected = file.getc raise AssertionFailedError, "Expecting #{expected.chr} at offset #{data.length}" unless expected == nil end end class TestMyModel &lt; Test::Unit::TestCase include OSX include MyTestExtensions def this_files_dir return parent_directory(__FILE__) end def setup @expectedReq = File.new("#{this_files_dir}/ExpectedMyReq") # @expectedReq = File.new("#{this_files_dir}/hello.txt") assert File.exist?("#{this_files_dir}/ExpectedMyReq"), "The file [#{@expectedReq.path}] should exist." end def test_my_model_class_exists MyModel end def test_can_init_instance assert MyModel.instancesRespondToSelector(:init), "MyModel Should define :init" end def test_my_model_can_request_my_data myModel = MyModel.alloc.init data = myModel.requestMyData 'Some query text' assert_NSData_contains_bytes_from_file @expectedReq, data end end </code></pre>
<p>I don’t know much about Ruby or binary protocols, but if You’re interested in unit testing on iPhone, You might want to check out the <a href="http://code.google.com/p/google-toolbox-for-mac/" rel="nofollow noreferrer">Google Toolbox for Mac</a>. I am having great success testing my OpenGL ES application with it.</p>
<p>Cliff, long term you're best investing time in pure ObjC TDD tools. I have used my own rbiphonetest lib in fmdb-migration-manager successfully, but its usefulness is probably limited to libraries etc. Even then there will undoubtly be enough 'works in Cocoa but fails in UIKit' scenarios to make rbiphonetest dubious to use. Hopefully one day RubyCocoa can be built against the Intel UIKit libraries and then it will be very useful and sturdy I think.</p>
23,795
<p>Are PHP variables passed by value or by reference?</p>
<p>It's by value according to the <a href="http://php.net/manual/en/functions.arguments.php" rel="noreferrer">PHP Documentation</a>.</p> <blockquote> <p>By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.</p> <p>To have an argument to a function always passed by reference, prepend an ampersand (<strong>&amp;</strong>) to the argument name in the function definition.</p> </blockquote> <pre><code>&lt;?php function add_some_extra(&amp;$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' ?&gt; </code></pre>
<p>Depends on the version, 4 is by value, 5 is by reference.</p>
2,331
<p>When using TFS with a tool outside of Visual Studio (Specifially ORMS), modifications to the project file to include a new file will not cause the file to be added to source control.</p> <p>Does anything exist that could potentially say "Warning: You are about to check in change to a project file which include a file which is not versioned"</p>
<p>Not quite, however you might want to download the <a href="http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx" rel="nofollow noreferrer">TFS Power Tools</a> and check out the command line utility tfpt.exe.</p> <p>The "tfpt online" and "tfpt treeclean" might be most useful to you when working outside of an integrated TFS client. tfpt online will look for files in your local directory that are not under version control, treeclean will show you files in your local directory that are not under version control so that you can remove then if they are not required.</p> <p>Good luck,</p> <p>Martin.</p>
<p>One gotcha I've found using tfpt online is that it doesn't always pick up changes unless you use the /diff switch. That one caused us all kinds of headaches with our automated build until I realised what was happening!</p>
43,085
<p>I have a form that has multiple fields, and for testing purposes is there a way I could print out the values entered in all the fields, without having to individually print each value.</p>
<p>You should be able to do a <code>var_dump($_REQUEST);</code></p> <p><a href="http://us2.php.net/manual/en/reserved.variables.request.php" rel="nofollow noreferrer">http://us2.php.net/manual/en/reserved.variables.request.php</a></p> <p><a href="http://us2.php.net/manual/en/function.var-dump.php" rel="nofollow noreferrer">http://us2.php.net/manual/en/function.var-dump.php</a></p>
<p>Very simply,</p> <pre><code>phpinfo(); </code></pre> <p>It includes a listing of all variables passed to PHP from a form, in an easy-to-read format.</p>
23,891
<p>My goal is to integrate testing into my development environment (as post-build step). I don't want to interfere with the DLLs that are generated in debug and release, so i plan to create new configurations for the project. But i don't want to compile every source file i have twice - once for the DLL, once for the test unit - I want to share the generated object files. How can I achieve this ?</p> <p>I am developping in c++ using Visual Studio 2005.</p>
<p>Compile the objs into a new lib project that is shared between the dll and your test project.</p>
<p>The compiler has an "intermediate" directory per configuration. If the .obj files in there are newer than the source files it compiles, it won't regenerate them.</p>
32,710
<p>Ok this is more of a computer science question, than a question based on a particular language, but is there a difference between a map operation and a foreach operation? Or are they simply different names for the same thing?</p>
<p>Different.</p> <p>foreach iterates over a list and <strong>performs</strong> some operation with side effects to each list member (such as saving each one to the database for example)</p> <p>map iterates over a list, <strong>transforms</strong> each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)</p>
<p>ForEach tries to apply a function such as writing to db etc on each element of the RDD without returning anything back.</p> <p>But the <code>map()</code> applies some function over the elements of rdd and returns the rdd. So when you run the below method it won't fail at line3 but while collecting the rdd after applying foreach it will fail and throw an error which says</p> <blockquote> <p>File &quot;&lt;stdin&gt;&quot;, line 5, in &lt;module&gt;</p> <p>AttributeError: 'NoneType' object has no attribute 'collect'</p> </blockquote> <pre><code>nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10]) num2 = nums.map(lambda x: x+2) print (&quot;num2&quot;,num2.collect()) num3 = nums.foreach(lambda x : x*x) print (&quot;num3&quot;,num3.collect()) </code></pre>
46,248
<p>I have been hearing that with unit testing we can catch most of the bugs in the code and I really believe that this is true. But my question is in large projects where each class is dependent on many other classes how do you go about unit testing the class ? Stubbing out every other class doesn't make much sense because of both complexity and the time required to write the stubs. What is your opinion about it?</p>
<p>Part of the advantage of using tests, is that it forces you to minimize dependencies thereby creating testable code. By minimizing dependencies you will increase maintainability and reusability of your code, both highly desirable traits. </p> <p>Since you are introducing tests into an existing code-base, you will no doubt encounter many hard-to-test situations which will require refactoring to test properly. This refactoring will increase the testability of your code, decreasing dependencies at the same time.</p> <p>The reason why its hard to retrofit code with tests is why many advocate following Test-Driven-Development. If you write your tests first and then write the code to pass the tests, your code will by default be much more testable and decoupled.</p>
<p>I'm not up to speed on the whole unit testing thing, but I would think that each unit should represent some sort of test. A test case should test some procedure. A procedure may not be confined to a single class.</p> <p>For instance, if your application can be broken down into atomic components, then a test case could exist for each component and for each applicable chain of transitions between components.</p>
45,065
<p>I'm working on a WPF application that sometimes exhibits odd problems and appears to <em>hang</em> in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below.</p> <p>My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page.</p> <p>I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it.</p> <p>EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows:</p> <pre><code>[Managed to Native Transition] </code></pre> <blockquote> <p>WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes<br> WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes<br> WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes<br> PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes<br> PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C# [Native to Managed Transition]<br> [Managed to Native Transition]<br> mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes<br> Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes<br> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes<br> mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes<br> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes </p> </blockquote>
<p>Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'ing any long running operations?</p> <p>Another thing to look at: When you break into your code, try looking at threads other than your main thread. One of them may be blocking the UI thread.</p>
<p>Hurrah,... it seems that the problem isn't related to borderless windows (at least in my case).</p> <p>There is a big performance hit when you set <code>AllowsTransparency</code> to true. So much of a hit it would seem, that the whole thing can hang the UI thread. Very strange behaviour. Could be related to <a href="http://support.microsoft.com/kb/937106" rel="nofollow noreferrer">this ticket</a></p>
12,977
<p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p> <p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
<p>Check your path by running:</p> <pre><code>'echo $PATH' </code></pre>
<p>I would suspect the permissions on the library. Can you do a strace or similar to find out the filenames it's looking for, and then check the permissions on them?</p>
9,402
<p>I would like to ask this in more of a general sense than anything, just for people to make note.</p> <p>I am printing out things for people and some files have some edges hanging out the side. I always worry, since it is printing in mid air, that it would screw up the print. But I was able to go, maybe 1mm(I am not to good with metric when it comes to guessing). My question is, how far at 90* from a wall can a printer pull off before it is necessary to have support? This would help me when slicing up files. </p>
<p>If I understand correctly, your question is specifically for <strong>overhangs at 90°</strong> (so an horizontal plane that has no support under it.</p> <p>The first to notice is that <strong>you can only pull this off if the extrusion happens perpendicular to the surface from which the overhang is coming off</strong> (the closest to 90° the better) as effectively what is happening is that you are building a cantilever structure as you extrude.</p> <p>If you think about it in terms of a <em>cantilever structure</em> you will quickly realise that the stiffer the structure, the furthest you can go without it drooping. The main parameters you can tweak to increase the stiffness are:</p> <ul> <li><strong>Cooling</strong>. The cooler the plastic, the stiffer it is, so crank the cooling part fan up to 100%!</li> <li><strong>Speed</strong>. Plastic need time to cool off, so the slower you print (within reasonable limits), the more time you will allow for plastic to cool under the fan. On my rig I seem to get the best result between 15 and 20mm/s, but your mileage may vary, obviously.</li> <li><strong>Layer height</strong>. The thicker the layer, the more weight it will bear before drooping, so higher layers work best. A slicer that is very convenient to use for prints that have a couple of overhangs like these is <a href="https://www.prusa3d.com/slic3r-prusa-edition/" rel="nofollow noreferrer">slic3r PE</a>, as you can vary the height of the layers at specific points in the print.</li> <li><strong>Material</strong>. Some materials are more rigid than others. PLA is probably the one that works best for overhangs. PETG and Nylon are somewhat more problematic, and flexible filaments are the ones being more difficult to use.</li> </ul> <p><strong>For bridges</strong> (unsupported filament extruded between two supported structures) the considerations are identical but for speed: in my experience having the <strong>speed not too low</strong> helps the nozzle keep tension in the extruded filament by "pulling" it and keeping it horizontal. But again: each printer, firmware and slicer is different, and you should experiment yourself to see what works for you.</p> <p>To sum this up: <strong>"how far you can go before needing support" is a question that cannot be answered with a fixed number</strong> as the answer depends from a lot of factors that vary from printer to printer and material to material. Without mentioning: how many defects you are happy to tolerate before calling the print a failure.</p>
<p>To add to what mac described, there are small detail effects which sometimes change the behaviour of an overhang (and not necessarily in a predictable manner).</p> <p>Concave overhangs might sag (rather than turn out like a bridge). Convex overhangs might pull tight. Cooling plastic tends to shrink,so might sag less.</p> <p>I'm often surprised how well overhangs turn out, but equally often see failures which I don't anticipate.</p>
803
<p>I have the following code that shows either a bug or a misunderstanding on my part.</p> <p>I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.</p> <p>Is this work as it should, or should I file a bug?</p> <pre> import java.io.*; import java.net.*; import java.util.*; public class OOS { public static void main(String[] args) throws Exception { Thread t1 = new Thread(new Runnable() { public void run() { try { ServerSocket ss = new ServerSocket(12344); Socket s= ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); List same = new ArrayList(); same.add(0); oos.writeObject(same); same.clear(); same.add(1); oos.writeObject(same); } catch(Exception e) { e.printStackTrace(); } } }); t1.start(); Socket s = new Socket("localhost", 12344); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); // outputs [0] as expected System.out.println(ois.readObject()); // outputs [0], but expected [1] System.out.println(ois.readObject()); System.exit(0); } } </pre>
<p>The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).</p> <p>See the reset() method if you want to reset the graph.</p>
<p>Max is correct, but you can also use:</p> <pre><code>public void writeUnshared(Object obj); </code></pre> <p>See comment below for caveat</p>
17,201
<p>I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream <strong>WITHOUT</strong> writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.</p> <p>Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as &quot;content&quot;</p> <p><strong>UPDATE:</strong></p> <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1" rel="nofollow noreferrer">API docs</a> how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.</p> <blockquote> <p>You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a &quot;pack://application&quot; URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.</p> </blockquote>
<p>There is a similar question <a href="https://stackoverflow.com/questions/44912480/c-sharp-wpf-how-to-load-a-fontfamily-from-a-byte-array">here</a>, which contains a supposed solution by converting a System.Drawing.FontFamily to a WPF font family, all in memory without any file IO:</p> <pre><code>public static void Load(MemoryStream stream) { byte[] streamData = new byte[stream.Length]; stream.Read(streamData, 0, streamData.Length); IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important. Marshal.Copy(streamData, 0, data, streamData.Length); PrivateFontCollection pfc = new PrivateFontCollection(); pfc.AddMemoryFont(data, streamData.Length); MemoryFonts.Add(pfc); // Your own collection of fonts here. Marshal.FreeCoTaskMem(data); // Very important. } public static System.Windows.Media.FontFamily LoadFont(int fontId) { if (!Exists(fontId)) { return null; } /* NOTE: This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection. */ return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name); } </code></pre> <p>This seems to use the <code>System.Drawing.PrivateFontCollection</code>(<a href="https://learn.microsoft.com/en-us/dotnet/api/system.drawing.text.privatefontcollection?view=dotnet-plat-ext-5.0" rel="nofollow noreferrer">^</a>) to add a <code>System.Drawing.Font</code> created from a <code>MemoryStream</code> and then use the <code>Families[0].Name</code> of that font to pass into the <code>System.Windows.Media.FontFamily</code> constructor. I assume the family name would then be a URI to the instance of that font in the PrivateFontCollection but you'd probably have to try it out.</p>
<p>The best approach I could think of, was to save the oldFont to a temp directory, and immediately load it using the newFont constructor that accepts a uri.</p>
6,616
<p>I have a simple table in SQL Server 2005, I wish to convert this to XML (using the "FOR XML" clause). I'm having trouble getting my XML to look like the required output.</p> <p>I've tried looking through various tutorials on the web, but I am struggling. Can someone help?</p> <p>The table I have looks like this</p> <pre><code>TYPE,GROUP,VALUE Books,Hardback,56 Books,Softcover,34 CDs,Singles,45 CDS,Multis,78 </code></pre> <p>The output style I need is:</p> <pre><code>&lt;data&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;variable name="TYPE"&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;row&gt; &lt;column&gt;GROUP&lt;/column&gt; &lt;column&gt;VALUE&lt;/column&gt; &lt;/row&gt; &lt;/variable&gt; &lt;/data&gt; </code></pre> <p><strong>Edit:</strong> As far as I can tell I require the multiple values. I'm generating XML for use with Xcelsius (<a href="http://xcelsius.files.wordpress.com/2008/05/xml_data_button.pdf" rel="nofollow noreferrer">Linking XML and Xcelsius</a>) so have no control over in the formatting of the XML. I can generate the XML using ASP as per the linked tutorial, but I was hoping to get it straight from SQL Server.</p> <p><strong>Edit 2:</strong> I was hoping for something elegant and tidy... but Godeke's example got the closest. Some fiddling with the SQL and I've come up with:</p> <pre><code>select "type" as '@name', "group" as 'row/column', null as 'row/tmp', "value" as 'row/column' from tableName for xml path('variable'), root('data') </code></pre> <p>Outputs almost in the exact way I wanted. The null/tmp line doesn't even output; it is just preventing the concatenation. Still the tag <code>&lt;variable name="TYPE"&gt;</code> repeats for each row, which I can't have.</p>
<p>As close as I can get is this:</p> <pre><code>select "type" as '@name', "group" as 'row/column1', "value" as 'row/column2' from tableName for xml path('variable'), root('data') </code></pre> <p>Naming two items the same ("column" and "column") isn't something I know how to do in one pass, but on the other hand it is an odd XML schema choice; normally elements have unique names if they contain distinct data. The obvious choice (name them both 'row/column') simply concatenates them in the output into one value.</p> <p>Also note that each returned row will be a "variable" element distinct from the others. To get the nesting without redundant records will require a subquery:</p> <pre><code>select distinct "type" as '@name' from Agent for xml path('variable'), root('data') </code></pre> <p>was my first thought, but the distinct prevents nesting.</p> <p>All this makes me think that to get the <em>exact</em> output you need you might have to use EXPLICIT mode. Perhaps my problem is for something like this I punt and use a DOMDocument in code :).</p>
<p><b>The script below produces the desired format </b></p> <blockquote> <br/>&lt;DATA&gt; <br/>&nbsp; &nbsp; &lt;VARIABLE TYPE="Books"&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE="Books"&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Hardback&lt;/GROUP&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;56&lt;/VALUE&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE="Books"&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Softcover&lt;/GROUP&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;34&lt;/VALUE&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt; <br/>&nbsp; &nbsp; &lt;/VARIABLE&gt; <br/>&nbsp; &nbsp; &lt;VARIABLE TYPE="CDs"&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE="CDs"&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Singles&lt;/GROUP&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;45&lt;/VALUE&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;row TYPE="CDS"&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;GROUP&gt;Multis&lt;/GROUP&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;VALUE&gt;78&lt;/VALUE&gt; <br/>&nbsp; &nbsp; &nbsp; &lt;/row&gt; <br/>&nbsp; &nbsp; &lt;/VARIABLE&gt; <br/>&lt;/DATA&gt; </blockquote> <p><b>Invoke</b></p> <blockquote> <code> <br/>DECLARE @tblItems table ( <br/>&nbsp; &nbsp; [TYPE] varchar(50) <br/>&nbsp; &nbsp; ,[GROUP] varchar(50) <br/>&nbsp; &nbsp; ,[VALUE] int <br/>) <br/> <br/>DECLARE @tblShredded table ( <br/>&nbsp; &nbsp; [TYPE] varchar(50) <br/>&nbsp; &nbsp; ,[XmlItem] xml <br/>) <br/> <br/>DECLARE @xmlGroupValueTuples xml <br/> <br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Hardback',56) <br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'Books','Softcover',34) <br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDs','Singles',45) <br/>insert into @tblItems([TYPE],[GROUP],[VALUE]) values( 'CDS','Multis',78) <br/> <br/>SET @xmlGroupValueTuples = <br/>&nbsp; ( <br/>&nbsp; &nbsp; SELECT <br/>&nbsp; &nbsp; &nbsp; "@TYPE" = [TYPE] <br/>&nbsp; &nbsp; &nbsp; ,[GROUP] <br/>&nbsp; &nbsp; &nbsp; ,[VALUE] <br/>&nbsp; &nbsp; FROM @tblItems <br/>&nbsp; &nbsp; FOR XML PATH('row'), root('Root') <br/>&nbsp; ) <br/> <br/>INSERT @tblShredded([TYPE], XmlItem) <br/>SELECT <br/>&nbsp; &nbsp; [TYPE] = XmlItem.value('./row[1]/@TYPE', 'varchar(50)') <br/>&nbsp; &nbsp; ,XmlItem <br/>FROM dbo.tvfShredGetOneColumnedTableOfXmlItems(@xmlGroupValueTuples) <br/> <br/> <br/>SELECT <br/>&nbsp; ( <br/>&nbsp; &nbsp; SELECT <br/>&nbsp; &nbsp; &nbsp; VARIABLE = <br/>&nbsp; &nbsp; &nbsp; &nbsp; ( <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "@TYPE" = t.[TYPE] <br/> <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ,( <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tInner.XmlItem.query('./child::*') <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FROM @tblShredded tInner <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; WHERE tInner.[TYPE] = t.[TYPE] <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FOR XML PATH(''), ELEMENTS, type <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FOR XML PATH('VARIABLE'),type <br/>&nbsp; &nbsp; &nbsp; &nbsp; ) <br/>&nbsp; ) <br/>FROM @tblShredded t <br/>GROUP BY <br/>&nbsp; &nbsp; t.[TYPE] <br/>FOR XML PATH(''), ROOT('DATA') </code> </blockquote> <p><b>where</b></p> <blockquote> <code> <br/>-- Example Inputs <br/>/* <br/>DECLARE @xmlListFormat xml <br/>SET @xmlListFormat = <br/>&nbsp; &nbsp; ' <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;XmlListRoot&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;004421UB7&lt;/Item&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;59020UH24&lt;/Item&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;Item&gt;542514NA8&lt;/Item&gt; <br/>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/XmlListRoot&gt; <br/>&nbsp; &nbsp; ' <br/>*/ <br/> <br/>-- ============================================= <br/>-- Author: 6eorge Jetson <br/>-- Create date: 01/22/3003 <br/>-- Description: Shreds an input XML list conforming to the expected list schema <br/>-- ============================================= <br/>CREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlListFormat xml) <br/>RETURNS <br/>@tblResults TABLE (XmlItem xml) <br/>AS <br/>BEGIN <br/> <br/>&nbsp; &nbsp; INSERT @tblResults <br/>&nbsp; &nbsp; SELECT <br/>&nbsp; &nbsp; &nbsp; &nbsp; tblShredded.colXmlItem.query('.') as XmlItem <br/>&nbsp; &nbsp; FROM <br/>&nbsp; &nbsp; &nbsp; &nbsp; @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem) <br/> <br/>&nbsp; &nbsp; RETURN <br/>END </code> </blockquote>
31,393
<p>I'm working with a datagrid and adapter that correspond with an MSAccess table through a stored query (named "UpdatePaid", 3 paramaters as shown below) like so:</p> <pre><code> OleDbCommand odc = new OleDbCommand("UpdatePaid", connection); OleDbParameter param; odc.CommandType = CommandType.StoredProcedure; param = odc.Parameters.Add("v_iid", OleDbType.Double); param.SourceColumn = "I"; param.SourceVersion = DataRowVersion.Original; param = odc.Parameters.Add("v_pd", OleDbType.Boolean); param.SourceColumn = "Paid"; param.SourceVersion = DataRowVersion.Current; param = odc.Parameters.Add("v_Projected", OleDbType.Currency); param.SourceColumn = "ProjectedCost"; param.SourceVersion = DataRowVersion.Current; odc.Prepare(); myAdapter.UpdateCommand = odc; ... myAdapter.Update(); </code></pre> <p>It works fine...but the really weird thing is that it <em>didn't</em> until I put in the <strong>odc.Prepare()</strong> call.<br><br>My question is thus: Do I need to do that all the time when working with OleDb stored procs/queries? Why? I also have another project coming up where I'll have to do the same thing with a SqlDbCommand... do I have to do it with those, too? </p>
<p>This is called, oddly enough, a prepared statement, and they're actually really nice. Basically what happens is you either create or get a sql statement (insert, delete, update) and instead of passing actual values, you pass "?" as a place holder. This is all well and good, except what we want is our values to get passed in instead of the "?". </p> <p>So we prepare the statement so instead of "?", we pass in parameters as you have above that are going to be the values that go in in place of the place holders.</p> <p>Preparing parses the string to find where parameters can replace the question marks so all you have to do is enter the parameter data and execute the command.</p> <p>Within oleDB, stored queries are prepared statements, so a prepare is required. I've not used stored queries with SqlDB, so I'd have to defer to the 2 answers previous.</p>
<p>I don't use it with SqlDbCommand. It seems as a bug to me that it's <em>required</em>. It should only be <em>nice to have</em> if you're going to call a procedure multiple times in a row. Maybe I'm wrong and there's a note in documentation about providers that love this call too much.</p>
18,790
<p>Say I have a list as follows:</p> <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> <p>Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.</p> <p>Cheers!</p>
<p>Not that i'm aware of. The traditional solution is to tag the first &amp; last items with class="first" &amp; class="last" so you can identify them.</p> <p>The CSS psudo-class <a href="http://www.w3.org/TR/CSS2/selector.html#first-child" rel="noreferrer">first-child</a> will get you the first item but not all browsers support it. CSS3 will have <a href="http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#last-child-pseudo" rel="noreferrer">last-child too</a> (this is currently supported by Firefox, Safari but not IE 6/7/beta 8)</p>
<p>The answer for this question should be updated! IE9 + Firefox (for a while back) + Chrome, Safari all support: <code>last-of-type</code> or <code>last-child</code> </p>
7,411
<p>I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done?</p> <p>I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area?</p>
<p>One way would be to have the Erlang core of the application be a daemon that the Cocoa front-end communicates with over a Unix-domain socket using some simple protocol you devise.</p> <p>The use of a Unix-domain socket means that the Erlang daemon could be launched on-demand by <code>launchd</code> and the Cocoa front-end could find the path to the socket to use via an environment variable. That makes the rendezvous between the app and the daemon trivial, and it also makes it straightforward to develop multiple front-ends (or possibly a framework that wraps communication with the daemon).</p> <p>The Mac OS X <code>launchd</code> system is really cool this way. If you specify that a job should be launched on-demand via a secure Unix-domain socket, <code>launchd</code> will actually create the socket itself with appropriate permissions, and advertise its location via the environment variable named in the job's property list. The job, when started, will actually be passed a file descriptor to the socket by <code>launchd</code> when it does a simple check-in.</p> <p>Ultimately this means that the entire process of the front-end opening the socket to communicate with the daemon, <code>launchd</code> launching the daemon, and the daemon responding to the communication can be secure, even if the front-end and the daemon run at different privilege levels.</p>
<p>Usually when creating Cocoa applications that front UNIX commands or other headless programs you use an <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTask_Class/Reference/Reference.html" rel="nofollow noreferrer"><code>NSTask</code></a>:</p> <blockquote> <p>Using the NSTask class, your program can run another program as a subprocess and can monitor that program’s execution. An NSTask object creates a separate executable entity; it differs from NSThread in that it does not share memory space with the process that creates it.</p> <p>A task operates within an environment defined by the current values for several items: the current directory, standard input, standard output, standard error, and the values of any environment variables. By default, an NSTask object inherits its environment from the process that launches it. If there are any values that should be different for the task, for example, if the current directory should change, you must change the value before you launch the task. A task’s environment cannot be changed while it is running.</p> </blockquote> <p>You can communicate with the backend process by way of <code>stdin</code>/<code>stdout</code>/<code>stderr</code>. Bascially <code>NSTask</code> is a high-level wrapper around <code>exec</code> (or <code>fork</code> or <code>system</code>, I always forget the difference).</p> <p>As I understand it you don't want the Erland program to be a background daemon that runs continuously, but if you do, go with <a href="https://stackoverflow.com/questions/37381/whats-a-good-way-to-write-a-cocoa-front-end-to-an-erlang-application#37408">@Chris's</a> suggestion.</p>
5,805
<p>Was looking to get peoples thoughts on keeping a Lucene index up to date as changes are made to the domain model objects of an application. </p> <p>The application in question is a Java/J2EE based web app that uses Hibernate. The way I currently have things working is that the Hibernate mapped model objects all implement a common "Indexable" interface that can return a set of key/value pairs that are recorded in Lucene. Whenever a CRUD operation is performed involving such an object I send it via JMS queue into a message driven bean that records in Lucene the primary key of the object and the key/value pairs returned from the index( ) method of the Indexable object that was provided. </p> <p>My main worries about this scheme is if the MDB gets behind and can't keep up with the indexing operations that are coming in or if some sort of error/exception stops an object from being index. The result is an out-of-date index for either a sort, or long, period of time. </p> <p>Basically I was just wondering what kind of strategies others had come up with for this sort of thing. Not necessarily looking for one correct answer but am imagining a list of "whiteboard" sort of ideas to get my brain thinking about alternatives.</p>
<p>Change the message: just provide the primary key and the current date, not the key/value pairs. Your mdb fetches the entity by primary key and calls index(). After indexing you set a value "updated" in your index to the message date. You update your index only if the message date is after the "updated" field of the index. This way you can't get behind because you always fetch the current key/value pairs first.</p> <p>As an alternative: have a look at <a href="http://www.compass-project.org" rel="nofollow noreferrer">http://www.compass-project.org</a>.</p>
<p>The accepted answer is 8 years old now and very out of date.</p> <p>The Compass Project is not maintained anymore since a long time, as its main developer moved on to create the excellent Elasticsearch.</p> <p>The modern answer to this is to use <a href="http://hibernate.org/search/" rel="nofollow noreferrer">Hibernate Search</a>, which incidentally can map to either a Lucene index directly or through Elasticsearch.</p>
5,905
<p>I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?</p>
<p>Just a few off the top of my head:</p> <ul> <li>Navigating around in memory-mapped files.</li> <li>Windows API calls where you have to over-allocate (like a LPBITMAPINFOHEADER).</li> <li>Any code where you're munging around in arbitrary memory (VirtualQuery() and the like).</li> <li>Just about any time you're using reinterpret_cast&lt;> on a pointer.</li> <li>Any time you use placement-new.</li> </ul> <p>The common thread here is "any situation in which you need to treat a piece of memory as something other than a resource over which you have allocation control".</p>
<p>Not that I would do it, but you need raw pointers to implement, say, a linked list or a graph. But it would be much smarter to use <code>std::list&lt;&gt;</code> or <code>boost::graph&lt;&gt;</code>.</p>
47,445
<p>I write a singleton c++ in the follow way:</p> <pre><code>class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL) m_pA = new A(); return m_pA; } A::~A() { FreeInstance() // Can I write this? are there any potential error? } void A::FreeInstance() { delete m_pA; m_pA = NULL; } </code></pre> <p>Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake.</p> <p>My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.<p> //----------------------------------------------------------- A new singleton, you are welcome to edit if you think there is any problem in the following sample:</p> <pre><code>class A { private: static A* m_pA; explicit A(); void A(const A&amp; a); void A(A &amp;a); const A&amp; operator=(const A&amp; a); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA == NULL){ static A self; m_pA = &amp;self; } return m_pA; } A::~A() { } </code></pre>
<p>Why does everybody want to return a singleton as a pointer?<br> Return it as a reference seems much more logical!</p> <p>You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.</p> <p>Use the static in a function method.<br> This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free. </p> <pre><code>class S { public: static S&amp; getInstance() { static S instance; return instance; } private: S() {} S(S const&amp;); // Don't Implement. void operator=(S const&amp;); // Don't implement }; </code></pre> <p>Note you also need to make the constructor private. Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).</p> <p>Also read:</p> <ul> <li><a href="https://stackoverflow.com/a/1008289/14065">https://stackoverflow.com/a/1008289/14065</a></li> <li><a href="https://stackoverflow.com/questions/86582/singleton-how-should-it-be-used">Singleton: How should it be used</a> </li> <li><a href="https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289">C++ Singleton design pattern</a></li> </ul> <p>To make sure you are using a singleton for the correct reasons.</p> <p>Though technically not thread safe in the general case see:<br> <a href="https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function">What is the lifetime of a static variable in a C++ function?</a></p> <p>GCC has an explicit patch to compensate for this:<br> <a href="http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html" rel="noreferrer">http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html</a></p>
<p>There is a great C++ library, ACE, based on patterns. There's a lot of documentation about different kind of patterns so look at their work: <a href="http://www.cs.wustl.edu/~schmidt/ACE.html" rel="nofollow noreferrer">http://www.cs.wustl.edu/~schmidt/ACE.html</a></p>
34,067
<p>I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs <code>&lt;BR/&gt;</code>, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted. </p> <p>I have found this <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="noreferrer">http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html</a>, but it is useless for my purpose. Also, I have found this <a href="http://msdn.microsoft.com/en-us/library/aa973813.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa973813.aspx</a> and tried to put inside a model binder but I couldn't make to work.</p>
<p>With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.:</p> <pre><code>[ValidateInput(false)] public ActionResult create() { // ...method body } </code></pre> <p>The ValidateInputAttribute is in System.Web.Mvc.</p> <p>But as others have said, you do then have to perform your own manual input validation or cleaning.</p> <p>Using MVC 3, you must also ensure this is in your Web.config: <code>&lt;system.web&gt;&lt;httpRuntime requestValidationMode="2.0" /&gt;&lt;/system.web&gt;</code></p>
<p>Put put ValidateRequest="false" to your aspx view declaration, but sanitize users input text inside your code, to avoid some xss attacks. </p>
30,959
<p>I'm using <code>ByteBuffers</code> and <code>FileChannels</code> to write binary data to a file. When doing that for big files or successively for multiple files, I get an <code>OutOfMemoryError</code> exception. I've read elsewhere that using <code>Bytebuffers</code> with NIO is broken and should be avoided. Does any of you already faced this kind of problem and found a solution to efficiently save large amounts of binary data in a file in java?</p> <p>Is the jvm option <code>-XX:MaxDirectMemorySize</code> the way to go?</p>
<p>I would say don't create a huge ByteBuffer that contains ALL of the data at once. Create a much smaller ByteBuffer, fill it with data, then write this data to the FileChannel. Then reset the ByteBuffer and continue until all the data is written.</p>
<p>The previous two responses seem pretty reasonable. As for whether the command line switch will work, it depends how quickly your memory usage hits the limit. If you don't have enough ram and virtual memory available to at least triple the memory available, then you will need to use one of the alternate suggestions given.</p>
4,830
<p>What resources do you know dedicated to software development in C for PIC microcontrollers?</p> <p>I would like to see some kind of framework that handles both IO (buttons for input and LCD for output) and application logic. You can think of it as a VERY simple OS. I understand that PIC's memory can be small for such frameworks so I think it could be a code generator that creates a specific code based on a config file. Then you add code fragments specific to your app. Have you seen something similar?</p>
<p>TinyOS (written in a dialect of C) has been ported to some of the PIC microcontrollers:</p> <ul> <li><a href="http://www.tinyos.net/" rel="nofollow noreferrer">http://www.tinyos.net</a></li> <li><a href="http://en.wikipedia.org/wiki/TinyOS" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/TinyOS</a></li> </ul> <p>But if all you want to do is is simple I/O then its way more sophisticated than you need and probably much easier just to write the code yourself than go through the learning curve.</p> <p>Otherise it possible to write fairly sophisticated logic using a PLC 'ladder logic' approach. There's one based on PIC microcontrollers at:</p> <ul> <li><a href="http://www.cq.cx/ladder.pl" rel="nofollow noreferrer">http://www.cq.cx/ladder.pl</a></li> </ul>
<p>Look into CCS C compiler (<a href="http://www.ccsinfo.com" rel="nofollow noreferrer">http://www.ccsinfo.com</a>). It has a nice comprehensive library for handling digital I/O, ADC, common bus communication. Tutorials and development boards available too.</p> <p>It has a remarkable peer-to-peer support forum <a href="http://www.ccsinfo.com/forum" rel="nofollow noreferrer">http://www.ccsinfo.com/forum</a> . If you are considering CCS C, make sure to check out this forum, because it will identify for you some of this IDE's idiosyncrasies.</p> <p>It's relatively inexpensive. I've been using it for years. It's been doing an adequate job.</p>
37,521
<p>I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program.</p> <p>Currently, I do something like this (top level, i.e. column 1):</p> <pre><code>$(info Generating build rules...) $(shell python collect_sources.py) include BuildRules.mk </code></pre> <p>But this does not stop make if <code>collect_sources.py</code> exits with a status code of 1. This also captures the standard output of <code>collect_sources.py</code> but does not print it out, so I have the feeling I'm looking in the wrong direction.</p> <p>If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell.</p> <p>Any suggestion?</p>
<p>There might be a better way, but I tried the following and it works:</p> <pre><code>$(if $(shell if your_command; then echo ok; fi), , $(error your_command failed)) </code></pre> <p>Here I did assume that <code>your_command</code> does not give any output, but it shouldn't be hard to work around such a situation.</p> <p>Edit: To make it work with the default Windows shell (and probably any decent shell) you could write <code>your_command &amp;&amp; echo ok</code> instead of the <code>if</code> within the <code>shell</code> function. I do not think this is possible for (older) DOS shells. For these you probably want to adapt <code>your_command</code> or write a wrapper script to print something on error (or success).</p>
<p>Make sure you're not invoking make/gmake with the -k option.</p>
27,876
<p>I first want to say <strong>thank you</strong> for taking the time to read this. I've been trying to print out some parts for another project of mine. These parts use up around 70% of the bed so they are fairly large, unlike the smaller trinkets and things I normally print.</p> <p>However, I have yet been able to print one of these larger parts without any layer shifting. The part I've been trying to print is a lid to the bottom of a case. It's square, with rounded corners, about 160mm x 160mm.</p> <p>It will print the first layer without shifting most of the time. However, upon starting the second layer it will almost have at least one layer shift. I have tried a number of things to remedy this, which I will list further down this post.</p> <p>The layer shifting seems to be unrelated to jerk, acceleration, bed shifting, and z offset at the very least. There is an audible clunk sound that can be heard when it does this. In the image I've linked, you can see the correct path of the print head through the green arrows. However, upon a layer shift, it follows the path of the red arrows. It never shifts during a direction change, only when it is following a straight path. It's almost as if one of the motors gives up for a second. I am aware the print is under extruded, this is one of my trials hoping it was merely the nozzle clipping against the print.</p> <p><a href="https://i.stack.imgur.com/ltqzA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ltqzA.jpg" alt="enter image description here" /></a></p> <p>Allow me to share with you my setup:</p> <ul> <li><p>I have an Ender 3 V2, with the stock mainboard, stock glass bed, and stock hotend.</p> </li> <li><p>I've replaced the extruder assembly with an all-metal one from Creality.</p> </li> <li><p>I have the stiffer bed springs. As well as the better PTFE tube fittings and Capricorn tubes.</p> </li> <li><p>I've put together a cooling pack on Thingiverse. <a href="https://www.thingiverse.com/thing:4644985" rel="nofollow noreferrer">https://www.thingiverse.com/thing:4644985</a> The mainboard and hotend fans were replaced with Noctua performance fans that I'll talk more about later.</p> </li> <li><p>The hotend assembly is a hero me gen 5 with dual 4010 fans and a BLTouch.</p> </li> <li><p>I'm using Smith3D's 5x5 high-speed firmware (Previously the 4x4 high speed).</p> </li> </ul> <hr /> <p>Now let me share my tried solutions.</p> <ul> <li><p>I firstly, disassembled the printer, checking all belt teeth and motor gears (which are pressed onto their shafts without a grub screw). Afterward, I readjusted all eccentric nuts to get the perfect amount of tension while maintaining smooth operation on both X and Y axes. I've used brake cleaner and dish soap to remove the grease on the Z-axis lead screw and replaced it with WD-40 dry lubricant.</p> </li> <li><p>Continuing, I've releveled the bed and checked all axis operation to ensure it was smooth and without any bumps, hitches, or anything of the sort.</p> </li> </ul> <ol> <li><p>I tightened all the frame screws, hotend screws, fan screws, grub screws. Nothing moves even a millimeter.</p> </li> <li><p>The belts were tensioned so that they can be strummed like a guitar string when I move either the hotend or bed to its end stop.</p> </li> <li><p>I checked my aftermarket fans to ensure they are working. The mainboard and hotend fan run nonstop at their optimal 12V. The PSU fan turns on and off as it needs to cool the PSU...</p> </li> <li><p>The cables are nicely managed in the mainboard compartment and I'm sure that the larger fans provide it plenty of airflow. Not to mention the printer was raised by the use of squash-ball feet.</p> </li> <li><p>I have slowed my print speed from 75mm/s to 60mm/s with this print. This means a 30mm/s inner/outer wall along with 60mm/s infill speed and 150mm/s travel speed. Acceleration and jerk are at their defaults: 500mm/s^2 and 10mm/s.</p> </li> <li><p>I've adjusted my Z offset so that it slightly under extrudes to prevent the filament from bunching up.</p> </li> <li><p>I've calibrated my e steps.</p> </li> <li><p>I've formatted the SD card and changed my firmware from Smith 3D's 4x4 high speed to 5x5 high speed.</p> </li> <li><p>I've updated Cura to the latest version 4.8 and ensured my hero me home offset is correct.</p> </li> <li><p>I've tried moving the model to different corners in Cura and ensured the software's jerk and acceleration control are disabled.</p> </li> <li><p>I've checked the bed movement with its clips, it doesn't move easily and both clips have very good tension.</p> </li> <li><p>I've checked the stepper driver voltages (I did not change them). E: 1.34V Z: 1.16V Y: 0.99V X: 1.15V.</p> </li> <li><p>I have Z hop enabled with a 0.2mm hop, no issues or noises when it moves across the print.</p> </li> <li><p>I've purchased a filament dry-box from SUNLU along with a new spool of SUNLU black filament. The dry box has Capricorn PTFE tubing that leads the filament straight into the extruder. There is very little friction inside the tube.</p> </li> <li><p>I've slightly tightened the tension on the extruder although I didn't have problems with it skipping.</p> </li> </ol> <hr /> <p>Again, I'd like to reiterate, nothing is loose on this printer, it doesn't skip when it rapidly changes directions, only when following either a straight or diagonal line. The printer movement is very smooth and near-silent with all of my modifications. It's frustrating to me that I can't solve this problem. I feel like the printer has a mind of its own. I have begun to suspect either the mainboard or something else hardware related is amiss. However, I have chosen not to mess with it until posting this. If you've read through this, <strong>I thank you for your patience and time reading it</strong>.</p> <hr /> <p>Any advice or possible causes to this problem are welcomed. I am at a complete loss and am desperate for a solution.</p>
<p>You mentioned a noticeable 'clunk' when it shifts, are you sure it isn't a physical obstruction? You said you checked that all axis run smoothly but are you sure you checked the full extents of the printable area?</p> <p>Watch carefully when the issue happens, are any of the cables getting snagged on the machine or surrounding workspace? Check under the bed in particular, I've noticed on my Ender 3 V2 the bed will sometimes bump into part of the base if the leveling screws are tightened too far.</p>
<p>Not sure if you're still actively working on this but my setup mirrors yours almost perfectly, I added an all metal extruder, Micro Swiss hotend, a BLTouch, yellow bed springs and Capricorn tube and got great results but needed more cooling so I changed to the Hero Me Gen 5 using 2 5015 blowers and a Noctua 40x20 fan with a buck converter set to 12 V and noticed I had shifting so I printed 35 mm standoffs and wired another Noctua fan, 80x25. It helped reduce shifting but still not perfect and I as well has combed through every possible issue.</p>
1,825
<p>I'm writing some JavaScript code that needs to fire the <code>click</code> event for a link. In Internet Explorer I can do this </p> <pre><code>var button = document.getElementById('myButton'); button.click(); </code></pre> <p>But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this </p> <pre><code>var button = document.getElementById('myButton'); window.location = button.href; </code></pre> <p>I feel like this is not the best way to do this. Is there a better way to trigger a <code>click</code> event? Preferably something that works regardless of the type of element or the browser.</p>
<p><a href="http://jehiah.cz/archive/firing-javascript-events-properly" rel="noreferrer">http://jehiah.cz/archive/firing-javascript-events-properly</a></p> <pre><code>function fireEvent(element,event) { if (document.createEvent) { // dispatch for firefox + others var evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); // event type,bubbling,cancelable return !element.dispatchEvent(evt); } else { // dispatch for IE var evt = document.createEventObject(); return element.fireEvent('on'+event,evt) } } </code></pre>
<p>Hey, I don't mean to dig up an old thread - but I was searching for an answer to this same problem as well, and found a function new to jQuery 1.3x (I was having a problem with Ajax Loaded content)</p> <p>Here's how I implemented it:</p> <p>HTML</p> <pre><code>&lt;a class="navlink" href="mypage.html"&gt;Online Estimate&lt;/a&gt; </code></pre> <p>LOADED SCRIPT</p> <pre><code>$(".pagelink").click(function(){ $(".navlink[href="+$(this).attr("href")+"]").trigger('click'); return false; }); </code></pre> <p>LOADED HTML</p> <pre><code>&lt;a class="pagelink" href="mypage.html"&gt;Online Estimate&lt;/a&gt; </code></pre> <p>The function is the 'Trigger Event'...<br/> More details on it here: <a href="http://docs.jquery.com/Events/trigger#eventdata" rel="nofollow noreferrer">http://docs.jquery.com/Events/trigger#eventdata</a></p>
17,344
<p>Is there any way to remove “save target as” from internet explorer’s right-click menu by using group policies or registry hacks? Failing that is there a simple programmatic way?</p>
<p>If you are trying to implement some kind of DRM scheme for websites - just dont. They never work and just annoy your users.</p>
<p>Why dont you try removing the right click altogether. Or if you need your own menu, you can create your own popup easily using div's. </p> <p>There is no way to modify the default menu and to disable a part of the menu as such. </p> <p>See how I disabled right click context menu here :</p> <p><a href="http://www.codeproject.com/tips/42554/Javascript-hack-to-disable-Right-Click-and-Text-Se.aspx" rel="nofollow noreferrer">http://www.codeproject.com/tips/42554/Javascript-hack-to-disable-Right-Click-and-Text-Se.aspx</a></p> <p>I hope this will help you. </p>
19,318
<p>I have a bash script which will be run on a Mac via ssh. The script requires a particular network drive to already be mounted. On the Mac, I mount this drive by opening a folder "JPLemme" on that drive in Finder. This mounts the drive until the Mac goes to sleep at night.</p> <p>Obviously, Finder isn't available via ssh, so I want to create an AppleScript that will simulate what I do through the GUI. I've tried:</p> <pre><code>tell application "Finder" activate open "JPLemme" end tell </code></pre> <p>I receive the following error:</p> <pre><code>execution error: Finder got an error: Can't get "JPLemme". (-1728) </code></pre> <p>I assume I'm missing something obvious, but Google has failed me. I would also be willing to entertain better solutions like mounting the drive directly; I've avoided that approach because I don't want the Mac to choke trying to mount the drive a second time after I've already mounted it in an unexpected way. (I don't really like Macs or AppleScript...)</p>
<p>Your network volume should have a domain attached to it of some kind. So, "JPLemme.domain.com". I use the following chunk of code to get onto a network volume that is password protected:</p> <pre><code> tell application "Finder" try set theServer to mount volume "smb://path/to/volume" as username "YourUserName" with password "YourPassword" --Please note here that this is a plain string without any built-in security. Use at your own risk. on error set VolumeCount to (get count of disks) repeat with x from 1 to VolumeCount set thisVolume to disk x if name of thisVolume is "JPLemme" then set theServer to thisVolume exit repeat end if end repeat end try end tell </code></pre> <p>You can clean it up as necessary, but that's the core of it. Good luck</p>
<p>At it's very core, all that is really needed is the following: </p> <pre><code>Tell Application "Finder" Mount Volume "smb://username:password@server/sub/directory" End Tell </code></pre> <p>But what is used will depend largely on network environment and errors returned.</p>
41,065
<p>I have a poorly designed database. One of the most important tables has 11,000+ entries. We would like to expand our system, and I am wondering if this table grew to 5x its size, would this be a problem? It's 15360 kB in size... if that matters.</p> <hr> <p>I'm using phpMyAdmin, the server is a Fedora Linux box (nothing fancy), The load is light. It stores just about everything our system uses.</p>
<p>What DBMS? What server? What load? What application?</p> <p>Besides: 11.000 records are nothing, really. Even in MS Access. :-)</p> <p>EDIT: So I assume you use a fairly recent MySQL with MyISAM tables. In theory, you can go ahead and fill the table into the millions of records. Depending on how you work with them (lots of joins / or not, lots of queries/updates/deletes / or not), you don't need to do anything special. Put a proper index on the table and you should be fine.</p>
<p>A bad foundation will be your most costly mistake. If the table is important, then you need to decide how important it is to fix it. The amount of rows in a table only affects the speed at which you can pull stuff out of it. But, if you've got a bad database design to start with, your hands will be tied at certain places down the road.</p>
21,629
<p>The following Code does not compile</p> <pre><code>Dim BasicGroups As String() = New String() {"Node1", "Node2"} Dim NodesToRemove = From Element In SchemaDoc.Root.&lt;Group&gt; _ Where Element.@Name not in BasicGroups For Each XNode In NodesToRemove XNode.Remove() Next </code></pre> <p>It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is <strong>Not</strong> listed in the BasicGroups StringArray.</p> <p><strong>What is the correct syntax for this task?</strong></p>
<p>You probably want to move the 'not' part. Eg (psuedo code)</p> <pre><code>where (not (list.Contains(foo)) </code></pre>
<p>Maybe you can try something like this</p> <p>mylistWithOutUndesirebleNodes = (from b in NodeLists.Cast() where (from c in NodesToDeleteList.Cast() where c.Attributes["atributo"].Value == b.Attributes["atributo"].Value select c).Count() == 0 select b).ToList();</p>
27,307
<p>Can anyone recommend a good Windows form component for displaying PDF documents and allowing users to add <em>real</em> annotation (by which I mean identical to that created by Adobe Reader). </p> <p>Update: I've tried the AxAcroPDF component which Abobe installs alongside Reader, but this doesn't support annotation. I basically want AxAcroPDF combined with Reader's "Comment &amp; Markup Toolbar". It seems that the <a href="http://www.foxitsoftware.com/pdf/sdk/activex/" rel="nofollow noreferrer">Foxit SDK ActiveX</a> supports this, so I'm going to try that. I just thought that there would be some more alternatives to choose from. </p>
<p>If anyone's interested, it looks like we'll end up using jPDFNotes, from <a href="http://www.qoppa.com" rel="nofollow noreferrer">Qoppa Software</a>.</p> <p>To quote from the web site:</p> <blockquote> <p>jPDFNotes is a Java™ bean that integrates into your application to display PDF documents and forms and allow your users to annotate the documents and fill the forms. After editing documents, the library can save them to a local file or the host application can override the save function to save the file to any location locally or on a network.</p> <p>jPDFNotes is built on top of Qoppa's proprietary PDF technology so your users do not have to install Acrobat Reader or any other third party software or drivers. jPDFNotes is 100% Java so it is completely platform independent and so can run on Windows, Linux, Unix, Mac OSX and any other platform that supports the Java runtime environment.</p> </blockquote> <p>It's not what we started looking for, but it seems to be exactly what we need. They seem a nice bunch of people too. </p>
<p>For editing the documents I have worked with <a href="http://www.syncfusion.com" rel="nofollow noreferrer">SyncFusions</a> Essential PDF and it worked quite well</p>
11,119
<p>I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:</p> <pre><code>&lt;rp:do-something runat="server" id="doSomething1" /&gt;</code></pre> <p>I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer" title="tagMapping Element">tagMapping element</a> doesn't quite match up for what I'd like to do.</p>
<p>XML, unlike HTML does not define entities (ie named references to UNICODE characters) so &amp;alpha; &amp;mdash; etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use &amp;lt; and &amp;amp; in XML</p> <p>If you want to create HTML, use an HtmlDocument instead.</p>
<p>You could also set the InnerText to <code>"Hello, I am text α – —"</code>, making the XmlDocument escape them automatically. I think.</p>
35,650
<p>I have a user control which is loaded in the page dynamically using the following code in Init of the Page.</p> <pre><code>Dim oCtl As Object oCtl = LoadControl("~/Controls/UserControl1.ascx") oCtl.Id = "UserControl11" PlaceHolder1.Controls.Clear() PlaceHolder1.Controls.Add(oCtl) </code></pre> <p>The user control also contains a button and I am unable to capture the button click within the user control. </p>
<p>You have to ensure that the control exists on the page prior to .NET entering the "Postback event handling" step of the page lifecycle. Since the control is added dynamically you have to ensure that on every post back you recreate that control so that it can find the control to fire the event.</p>
<p>You want to only load the control when not isPostBack</p>
11,825
<p>I've read that Silverlight 2.0 imposes by design an asynchronous model when communicating with the web server. I haven't had a chance to experiment with Silverlight, but I assume that it uses a thread-pool to manage threads like in the .NET Framework.<br /><br/> Now, since some browsers, most notably Internet Explorer, have an hard-coded limit of maximum two concurrent HTTP connections that can be made on the web server, what happens if I make a bunch of asynchronous requests from Silverlight?<br /><br /> Does Silverlight bypass this limitation in the web browser and open as many HTTP connections as there are threads available, or do the asynchronous requests queue up and wait for one of the two connections to become available?</p>
<p>In IE (haven't tested others) Silverlight is restricted to 2 connections at a time. </p> <p>The behavior in Silverlight is to simply not make the request. So if you make 5 Async web service requests right in a row, the first 2 will happen, the other three won't. No exception is thrown that i've seen... </p> <p>Fiddler is a big help here :)</p>
<p>Firstly the Machine.config file would not be used as the Silverlight control is sandboxed with its own version of the CoreCLR.</p> <p>I believe that the Silverlight control actually makes use of the underlying browser to make the asynchronous HTTP requests. This is most likely the case considering how the Silverlight control can't gain access to SOAP fault information as the SOAP specification requires that the server returns an HTTP 500 response code and the Silverlight control doesn't get that from the browser hosting the control.</p> <p>This post <a href="http://www.wilcob.com/Wilco/News/http-requests-in-silverlight.aspx" rel="nofollow noreferrer">here</a> serves to confirm this.</p> <p>As to the limit of concurrent HTTP connections, I believe IE5 and later limit the number of connections to the same site based on HTTP protocol version - HTTP/1.0 it limits to 4 connections and HTTP/1.1 to 3 connections. Most of the time the web server will limit the number of connections to 2 per client, queueing or discarding the remainder.</p>
28,346
<p>Just wondering if someone could help me with some msbuild scripts that I am trying to write. What I would like to do is copy all the files and sub folders from a folder to another folder using msbuild.</p> <pre><code>{ProjectName} |-----&gt;Source |-----&gt;Tools |-----&gt;Viewer |-----{about 5 sub dirs} </code></pre> <p>What I need to be able to do is copy all the files and sub folders from the tools folder into the debug folder for the application. This is the code that I have so far.</p> <pre><code>&lt;ItemGroup&gt; &lt;Viewer Include=&quot;..\$(ApplicationDirectory)\Tools\viewer\**\*.*&quot; /&gt; &lt;/ItemGroup&gt; &lt;Target Name=&quot;BeforeBuild&quot;&gt; &lt;Copy SourceFiles=&quot;@(Viewer)&quot; DestinationFolder=&quot;@(Viewer-&gt;'$(OutputPath)\\Tools')&quot; /&gt; &lt;/Target&gt; </code></pre> <p>The build script runs but doesn't copy any of the files or folders.</p> <p>Thanks</p>
<p>I was searching help on this too. It took me a while, but here is what I did that worked really well.</p> <pre><code>&lt;Target Name="AfterBuild"&gt; &lt;ItemGroup&gt; &lt;ANTLR Include="..\Data\antlrcs\**\*.*" /&gt; &lt;/ItemGroup&gt; &lt;Copy SourceFiles="@(ANTLR)" DestinationFolder="$(TargetDir)\%(RecursiveDir)" SkipUnchangedFiles="true" /&gt; &lt;/Target&gt; </code></pre> <p>This recursively copied the contents of the folder named <code>antlrcs</code> to the <code>$(TargetDir)</code>.</p>
<p>The best way to recursively copy files from one directory to another using MSBuild is using Copy task with SourceFiles and DestinationFiles as parameters. For example - To copy all files from build directory to back up directory will be</p> <pre><code>&lt;PropertyGroup&gt; &lt;BuildDirectory Condition="'$(BuildDirectory)' == ''"&gt;Build&lt;/BuildDirectory&gt; &lt;BackupDirectory Condition="'$(BackupDiretory)' == ''"&gt;Backup&lt;/BackupDirectory&gt; &lt;/PropertyGroup&gt; &lt;ItemGroup&gt; &lt;AllFiles Include="$(MSBuildProjectDirectory)/$(BuildDirectory)/**/*.*" /&gt; &lt;/ItemGroup&gt; &lt;Target Name="Backup"&gt; &lt;Exec Command="if not exist $(BackupDirectory) md $(BackupDirectory)" /&gt; &lt;Copy SourceFiles="@(AllFiles)" DestinationFiles="@(AllFiles-&gt; '$(MSBuildProjectDirectory)/$(BackupDirectory)/%(RecursiveDir)/%(Filename)% (Extension)')" /&gt; &lt;/Target&gt; </code></pre> <p>Now in above Copy command all source directories are traversed and files are copied to destination directory.</p>
14,505
<p>I am designing a web app and I intent to embed data on an xml island so that I can dynamically render it on an HTML table on the client-side based on options the users will select.</p> <p>I have the broad concepts, but I need pointers on how to use DOM in navigating my xml. And how to update my xml island possibly for posting back to the server?</p> <p>Please any links to online resources or a quick advice will be very appreciated.</p> <p>NB: I understand most of the dynamic HTML concepts and server and client side stuff, so don't shy being very technical in your response:)</p>
<p>In <em>W3C</em> HTML there are no XML data islands (unless you're referring to external XML file linked via frames loaded using Javascript), but you can re-use HTML elements and insert metadata in <code>class</code>, <code>title</code> (if you care about HTML4 validity), <code>data-*</code> (HTML5) or your custom attributes.</p> <p>For DOM navigation you've got <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614" rel="nofollow noreferrer">DOM Core</a>, like <code>element.childNodes</code>, <code>.nextSibling</code>, <code>.getAttribute()</code>, etc.</p> <p>DOM can be verbose and tedious to use (e.g. when looking for elements in DOM you have to be careful to skip text nodes), so there are JS libraries like jQuery and Prototype built on top of it that offer more convenient API.</p> <p>If you intend to a lot of DOM transformations, then Javascript API for <a href="https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript" rel="nofollow noreferrer">XPath</a> and <a href="https://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations" rel="nofollow noreferrer">XSLT processor</a> will be handy.</p>
<p>Ajax Patterns has some good examples for using data islands: <a href="http://ajaxpatterns.org/wiki/index.php?title=XML_Data_Island" rel="nofollow noreferrer">http://ajaxpatterns.org/wiki/index.php?title=XML_Data_Island</a></p>
38,476
<p>This question is simple. What function would I use in a PHP script to load data from a URL into a string?</p>
<p>CURL is usually a good solution: <a href="http://www.php.net/curl" rel="noreferrer">http://www.php.net/curl</a></p> <pre><code> // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // grab URL and pass it to the browser $html = curl_exec($ch); // close cURL resource, and free up system resources curl_close($ch); </code></pre>
<p>Check out <a href="http://sourceforge.net/projects/snoopy/" rel="nofollow noreferrer">Snoopy</a>, a PHP class that simulates a web browser:</p> <pre><code>include "Snoopy.class.php"; $snoopy = new Snoopy; $snoopy-&gt;fetchtext("http://www.example.com"); $html = $snoopy-&gt;results; </code></pre>
44,070
<p>I found this in an error log and am trying to work out how it's possible. It's not every day that a NullReferenceException turns up deep within the .net base classes!</p> <pre><code>1) Exception Information ********************************************* Exception Type: System.NullReferenceException Message: Object reference not set to an instance of an object. Data: System.Collections.ListDictionaryInternal TargetSite: Void Bind(System.Data.SqlClient.TdsParserStateObject) HelpLink: NULL Source: System.Data StackTrace Information ********************************************* at System.Data.SqlClient.SqlDataReader.Bind(TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult esult) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) at MyCode.Shared.Data.DataSocket.GetTable(String SPString) at &lt;rest of stack trace&gt; </code></pre> <p>The only thing I could come up with is there's a (slim) chance there were two threads executing the same method at the same time, and one cleared or modified the DataSet that is being passed to Fill(). So my question is really:</p> <ul> <li>how could this exception get thrown</li> <li>Could a multi-thread scenario cause this exception</li> <li>How can I be sure, eg is there a way i can step through the System.Data methods to replicate the problem?</li> </ul> <p>Incidentally, I've found a couple of other cases of this problem, one in <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/31f3e2d3-7e79-4a5e-8ac5-98a10479be41/" rel="noreferrer">this</a> thread and another in <a href="http://216.239.59.132/search?q=cache:IXoOnmhgFnAJ:www.hotel-ubytovani.com/5585-ubytovani-Hrabisin.htm+System.NullReferenceException+%22at+System.Data.SqlClient.SqlDataReader.Bind(TdsParserStateObject+stateObj)%22&amp;hl=en&amp;ct=clnk&amp;cd=2&amp;gl=uk&amp;client=firefox-a" rel="noreferrer">this</a> google cache of someone's page. Neither seems to be of any help though.</p> <p>The GetTable() method of mine that is being executed looks like this:</p> <pre><code>public DataTable GetTable(string SPString) { //Setup the data objects by calling helper prepareDataAdaptor(SPString,CommandType.Text); dataAdaptor.Fill(dataSet); dataAdaptor.SelectCommand.Connection.Close(); DataTable dt; //ensure we dispose okay using(dataSet) { if(dataSet.Tables.Count==0) { dataSet.Tables.Add(new DataTable("EmptyTable")); } dt=dataSet.Tables[0]; //because we are disposing we need to remove the table from the dataset dataSet.Tables.Clear(); } return dt; } private void prepareDataAdaptor(string SPString,CommandType Type) { checkForConnection(); dataSet=new DataSet(); dbCommand.CommandText=SPString; dbCommand.CommandTimeout = MySettings.CommandTimeout; dataAdaptor.SelectCommand=dbCommand; dataAdaptor.SelectCommand.CommandType=Type; dataAdaptor.SelectCommand.Connection=dbConnection; dataAdaptor.SelectCommand.Parameters.Clear(); } </code></pre> <p>dataAdaptor (sic) is an instance variable declared as an IDbDataAdapter populated with a SqlDataAdapter. dataSet is an instance variable of type DataSet.</p> <p>My theory goes that thread A runs through and gets partway into the SqlDataAdapter.Fill() method. Meanwhile thread B is also executing and does something that messes up thread A, like this line:</p> <pre><code>dataAdaptor.SelectCommand.Connection.Close(); </code></pre> <p>I can see that this code of mine isn't thread-safe but how can I be sure this is the problem that caused the above exception?</p> <p>many thanks for any suggestions!</p> <p>Rory</p> <p>EDIT: fixed case of lousy spelling. Didn't update it in the code as that's how it is.</p> <p>UPDATE: I agree there's several things wrong with this code that should be fixed, but my main interest is whether there's any way to verify that it is this threading issue that would have caused this error. Given my application it's slightly far-fetched but the only thing I can think of. Before I modify the code to generally make it better I'd like to be sure that I have found the cause of the exception so that I can be sure I've fixed it.</p> <p>Is there any way to step into the .net code for instance? I'm using VS 2005 / .net 2.0 but I think in VS 2008 you can view the .NET framework source? If that's the case could I create a 2-thread scenario and step through to recreate this problem? Or is there a way that doesn't require me installing VS 2008?</p>
<blockquote> <p>Could a multi-thread scenario cause this exception</p> </blockquote> <p>Instance methods of ADO.NET classes (e.g. SqlCommand) are generally not thread-safe. So if you are using such instances from multiple threads, you can expect problems such as the one you describe.</p>
<p>I'm guessing that disposing the dataset invalidates the table that it contains!</p> <p>BTW you don't need the dataset, you can fill a datatable directly - or call the other data adapter function which creates a datatable for you (Get, i think)</p> <p>and it's spelled "adapter" not "adaptor" ;-)</p>
47,933
<p>I'm making a simple Image Debugger Visualizer. Code is below. I'm not sure if i need to manually dispose of the Image instance? Because i'm making a windows Form window and the PictureBox inside that contains my dynamic image .. do i need to add some special code when the form is terminating, to dispose of this? </p> <p>here's the code..</p> <pre><code>using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Microsoft.VisualStudio.DebuggerVisualizers; using DebuggerVisualizers; [assembly: DebuggerVisualizer( typeof (ImageDebuggerVisualizer), typeof (VisualizerObjectSource), Target = typeof (Image), Description = "Image Visualizer")] namespace DebuggerVisualizers { public class ImageDebuggerVisualizer : DialogDebuggerVisualizer { protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { Image image = (Image) objectProvider.GetObject(); Form form = new Form { Text = ("Image Visualizer - " + image.HorizontalResolution + " " + image.VerticalResolution), Width = image.Width, Height = image.Height }; PictureBox pictureBox = new PictureBox {Image = image, SizeMode = PictureBoxSizeMode.AutoSize}; form.Controls.Add(pictureBox); form.ShowDialog(); } } } </code></pre> <p>thanks for any help :)</p>
<p>Change your Show method to this:</p> <pre><code>protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { Image image = (Image) objectProvider.GetObject(); using (Form form = new Form()) { PictureBox pictureBox = new PictureBox(); pictureBox.Image = image; form.Controls.Add(pictureBox); form.ShowDialog(); } } </code></pre> <p>The using(){} block will call Dispose on the form after it closes, which will dispose of everything on the form also.</p>
<p>I think you should dispose it. It should be quite easy, just add a using() at the first line of your method (around the Image image = ... line) and end it after the form.ShowDialog().</p> <p>I think it is safe to dispose the image, for if you want to change the visualized object you must call one of the TransferData/TranferObject/ReplaceDat/ReplaceObject methods to send it back.</p>
41,000
<p>Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like <em>http://mydomain/en/about</em> or <em>http://mydomain/de/about</em>. </p> <p>As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at <em>http://mydomain/</em> would be transferred to <em>http://mydomain/en/</em> for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie.</p> <p>I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that.</p> <p>Any ideas?</p>
<p>I don't believe a custom route handler is required for what you are doing.</p> <p>For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route.</p> <p>For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI.</p> <p>Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection.</p> <p>You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here.</p>
<p>You should be able to do this with ASP.NET MVC's default template, I'm doing something similar. Just build your routes as {language}/{controller}/{action}/{id}</p> <p>Just set a default route that goes to a controller that checks for the language cookie, and redirects the user based on that cookie.</p>
11,102
<p>I get a 2032 stream error from Flash in response to POST requests that return "201 Created" in IE (Firefox works fine). Since Flash doesn't provide access to the HTTP status I can't tell that it has actually succeeded. The request is being made with HTTPService.</p> <p>Any suggestions? Has anyone else seen this?</p> <p>Thanks, Alex</p>
<p>I found a way around this on my Flex on Rails application. I was seeing the same problem in IE - my development.log in Rails gave a 201 message, but this caused a fault coming back to Flex. I found a reference in a new book called <em>Flex On Rails</em> by Tony Hillerson and Daniel Wanja, on p. 31. It involves catching the 201 error and changing the header. Here's my ApplicationController file:</p> <pre><code> class ApplicationController &lt; ActionController::Base helper :all # include all helpers, all the time include AuthenticatedSystem before_filter :login_required after_filter :flex_error_handling def flex_error_handling response.headers['Status'] = interpret_status(200) if response.headers['Status'] == interpret_status(422) response.headers['Status'] = interpret_status(200) if response.headers['Status'] == interpret_status(201) end def rescue_action_in_public(exception) render_exception(exception) end def rescue_action_locally(exception) render_exception(exception) end rescue_from ActiveRecord::RecordNotFound, :with =&gt; :render_exception def render_exception(exception) render :text =&gt; "&lt;errors&gt;&lt;error&gt;#{exception}&lt;/error&gt;&lt;/errors&gt;", :status =&gt; 200 end end </code></pre> <p>The action of changing the 422 status message to 200 was part of Hillerman/Wanja's original suggestions to change the 2032 Stream Error into something more friendly, so that invalid record errors are sent back to the Flex UI. </p>
<p>Try using a debug proxy to take a peek at the traffic, I like <a href="http://www.charlesproxy.com/" rel="nofollow noreferrer">Charles</a>.</p>
46,250
<p>When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running</p> <pre><code>$&gt; do_something_intensive | less </code></pre> <p>and then exiting <em>less</em> used to return you immediately to a responsive shell, on a SuSE8 or former releases. when i'm trying that today, <em>do_something_intensive</em> is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ...</p> <p>Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ?</p> <p><em>edit</em> : further tests (using strace) reveal that "SIGPIPE" <em>is</em> generated, but that the program is not interrupted. A simple</p> <pre><code>#include &lt;stdio.h&gt; int main() { while(1) printf("dumb test\n"); exit(0); } </code></pre> <p>will go on with an endless</p> <pre><code>--- SIGPIPE (Broken pipe) @ 0 (0) --- write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe) </code></pre> <p>when <em>less</em> is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE</p> <p><em>edit again</em>: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4)</p>
<p>Well, if there is an attempt to write to a pipe after the reader has gone away, a SIGPIPE signal gets generated. The application has the ability to catch this signal, but if it doesn't, the process is killed.</p> <p>The SIGPIPE won't be generated until the calling process attempts to write, so if there's no more output, it won't be generated. </p>
<p>Thanks for your advices, the solution is getting closer...</p> <p>According to the manpage of tcsh, "non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent."</p> <p>Which suggest my <em>terminal</em> is actually the root of the problem ... if it ignored SIGPIPE, the shell itself will ignore SIGPIPE as well ... </p> <p><em>edit:</em> i have the definitive confirmation that the problem only arise with Eterm+tcsh and found a suspiciously missing signal(SIGPIPE,SIG_DFL) in Eterm source code. I think that close the case.</p>
12,861
<p>I am operating a laser sintering machine, using polyamide 2200 powder (with a grain size of approximately 50 micrometers). During a print, a lot of powder goes unsintered and can theoretically be reused. However, using purely recycled powder degrades print quality to an unacceptable level.</p> <p>Mixing a little used powder into a larger amount of fresh powder seems to work well though. What is the greatest ratio of used to fresh powder that still gives good results, and is there anything I can do (pre- postprocessing) to allow more powder to be reused?</p>
<p>You'll find generally that mixing 40% new polyamide with 60% recycled polyamide will result in a reasonable finish and part. You will obviously want to use all new for parts requiring the best possible finish and mechanical properties, but this mixture will be very difficult to tell apart from a fully new mixture part:</p> <p><a href="http://www.paramountind.com/pdfs/eos_pa2200_mds.pdf" rel="nofollow">http://www.paramountind.com/pdfs/eos_pa2200_mds.pdf</a></p> <p>This is more detailed research showing how used powder changes and how that affects print quality here:</p> <p><a href="http://www.emeraldinsight.com/doi/abs/10.1108/13552540910960299" rel="nofollow">http://www.emeraldinsight.com/doi/abs/10.1108/13552540910960299</a></p> <p>Searching for the research paper title may find a free source, but the linked resource does require a subscription or payment to that service.</p>
<p>You'll find generally that mixing 40% new polyamide with 60% recycled polyamide will result in a reasonable finish and part. You will obviously want to use all new for parts requiring the best possible finish and mechanical properties, but this mixture will be very difficult to tell apart from a fully new mixture part:</p> <p><a href="http://www.paramountind.com/pdfs/eos_pa2200_mds.pdf" rel="nofollow">http://www.paramountind.com/pdfs/eos_pa2200_mds.pdf</a></p> <p>This is more detailed research showing how used powder changes and how that affects print quality here:</p> <p><a href="http://www.emeraldinsight.com/doi/abs/10.1108/13552540910960299" rel="nofollow">http://www.emeraldinsight.com/doi/abs/10.1108/13552540910960299</a></p> <p>Searching for the research paper title may find a free source, but the linked resource does require a subscription or payment to that service.</p>
141
<p>I'm already familiar with the standard Java package naming convention of using a domain name to create a unique package name (i.e. package <code>com.stackoverflow.widgets</code>). However, I've never seen any recommendations for how to choose package names for personal projects. I assume because this is because this is really a matter of personal taste.</p> <p>So, how do you choose package names for personal projects that will never make it into production (you might be experimenting with a new framework in your spare time). Assuming you don't have a personal website whose domain you can use to create your package structure, what do (or would) you do? Do you have a logical system in place for generating new package names for hobby projects, or do you just use simple throw-away package names like <code>mypackage</code>?</p> <p>Since I'm just curious to see what different people's thoughts are on this, I've made this a community wiki.</p> <p>For me personally, I've never given it much thought, but I wanted to play around with <a href="http://wicket.apache.org/" rel="noreferrer">Wicket</a> tonight and it occurred to me that I don't have a clear idea of how I want to organize my hobby projects. A separate, distinct package naming convention for hobby projects (in my mind, at least) would serve as a good way to keep personal and work-related code clearly separate from each other.</p> <p>I was thinking of a simple hierarchal naming convention, to keep the source for my personal projects in a single root folder:</p> <ul> <li>Use <code>myprojects</code> as the root folder </li> <li>Append the project name </li> <li>Add any additional subpackage names</li> </ul> <p>So, my Wicket project would be in the package <code>myprojects.learningwicket</code> and unit tests would be in the package <code>myprojects.learningwicket.tests</code> (for example).</p>
<p>If you're just doing personal projects where nobody else will use the code, then you can make up a package name that you like. Don't make up something that starts with <code>com.</code> or <code>net.</code> or other top-level domain though, because that would imply that you own the domain name (ie. using <code>com.john</code> as your package name just because your name happens to be John is not a good idea).</p> <p>If you're going to give the code to anybody else, you should use a globally unique package name, which according to Java conventions means you should register and use a domain name.</p>
<p>I thought about asking this same question. So far i've used the prefix com.tehvan, even though i don't actually have a company.</p>
37,281
<p>What function will let us know whether a date in VBA is in DST or not?</p>
<p><b>For non-current dates (DST 2007+):</b></p> <p>First, you need a function to find the number of specific weekdays in a month:</p> <pre><code>Public Function NDow(Y As Integer, M As Integer, _ N As Integer, DOW As Integer) As Date ' Returns Date of Nth Day of the Week in Month NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _ (DOW + 1) Mod 8)) + ((N - 1) * 7)) End Function </code></pre> <p>Then, you can check for the DST day versus the following function calls:</p> <p>Fall: NDow(Year(newdate), 11, 1, 1)<br> Spring: NDow(Year(newdate), 3, 2, 1) </p> <p><b>For the current date:</b></p> <p>Call the Windows API function GetTimeZoneInformation, and it will return an enum (integer) with the status.</p> <p>I got the code for this from Chip Pearson's great Excel site.</p> <p><a href="http://www.cpearson.com/excel/MainPage.aspx" rel="nofollow noreferrer">Pearson's site</a></p>
<p>For anyone wondering how to account for daylight saving time in Europe (central europe time), I modified the script from <a href="http://www.cpearson.com/excel/DaylightSavings.htm" rel="nofollow noreferrer">Chip Pearson</a>. The last sunday of March (2 AM to 3 AM) and October (3 AM to 2 AM) are the days when the hour switching occurs.</p> <p>Following code is the click event of a button in Excel:</p> <pre><code>Dim dates As String dates = "A1:A20" For Each c In Worksheets("Sheet1").Range(dates).Cells If (IsDateWithinDST(c.Value)) Then c.Value = DateAdd("h", 1, c.Value) End If Next </code></pre> <p>The module containing the necessary methods are to be found <a href="https://github.com/pheemery2/EuropeanDST" rel="nofollow noreferrer">here</a>.</p> <p><a href="https://en.wikipedia.org/wiki/Summer_Time_in_Europe" rel="nofollow noreferrer">More info on DST in Europe.</a></p>
15,895
<p>I want to take an action in an Excel workbook macro after a period of inactivity (hide/protect some worksheets). What is the best/simplest way to achieve this?</p> <p>Í'm assuming I'll use <code>Application.OnTime</code> to periodically check if the user has been active. But what events should I handle to see if the user was "active" (i.e. has does something - anything - with the workbook)?</p> <p>Clarification: I want to detect <em>all</em> activity, not just changes. I.e. including mouse clicks, selecting, copying, navigating with the keyboard, changing worksheets, ...</p> <p>I'm assuming that when a UI event happens that represents user activity, I will set a variable thus:</p> <pre><code>LastActivityTime = Now </code></pre> <p>and the macro run by <code>Application.OnTime</code> will check this variable to see if the user has been active recently. Which events (other than <code>SheetChange</code>) would I need to handle to set this variable? I had kind of hoped there would be <code>KeyUp</code> and <code>MouseUp</code> events, these two would probably have been enough.</p> <p>Update: I have implemented this by handling <code>Workbook_SheetActivate</code>, <code>Workbook_SheetSelectionChange</code> and <code>Workbook_WindowActivate</code>. Realistically this is probably enough.</p>
<p>I have implemented this by handling Workbook_SheetActivate, Workbook_SheetSelectionChange and Workbook_WindowActivate. Realistically this is probably enough.</p>
<p>One simple way is to compare the content of the workbook with that of the last time you check. I believe combining this with Application.OnTime will solve your concern.</p>
20,555
<p>For example, given a type param method i'm looking for something like the part in bold</p> <blockquote> <p>void MyMethod&lt; T >() {<br> if ( <strong>typeof(T).Implements( <em>IMyInterface</em> )</strong> ) {</p> <pre><code> //Do something </code></pre> <p>else</p> <pre><code> //Do something else </code></pre> <p>}</p> </blockquote> <p>Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx" rel="noreferrer">Type.IsAssignableFrom</a></p> <pre><code>if(typeof(IMyInterface).IsAssignableFrom(typeof(T))) { // something } else { // something else } </code></pre>
<p>Ï've just tried using </p> <pre><code>if( typeof(T).Equals(typeof(IMyInterface) ) ... </code></pre> <p>And also works, but your answer seems more robust and was what I was looking for. Thanks!</p>
12,157
<p>I would like to display multiple colors (and potentially shapes and sizes) of data points in a Google Chart scatter chart. Does anyone have an example of how to do so?</p>
<p>I answered my own question after waiting SECONDS for an answer here :-)</p> <p>You can indeed have different colors for different data elements. For example:</p> <p><a href="http://chart.apis.google.com/chart?chs=300x200&amp;cht=s&amp;chd=t:1,2,3|6,5,4&amp;chds=1,3,0,10&amp;chxt=x,y&amp;chxl=0:|0|1|2|1:|0|10&amp;chm=d,ff0000,0,0,8,0|a,ff8080,0,1,42,0|c,ffff00,0,2,16,0" rel="nofollow noreferrer">http://chart.apis.google.com/chart?chs=300x200&amp;cht=s&amp;chd=t:1,2,3|6,5,4&amp;chds=1,3,0,10&amp;chxt=x,y&amp;chxl=0:|0|1|2|1:|0|10&amp;chm=d,ff0000,0,0,8,0|a,ff8080,0,1,42,0|c,ffff00,0,2,16,0</a></p> <p>It's the chm= that does the magic. I was trying to have multiple chm= statements. You need to have just one, but with multiple descriptions separated by vertical bars.</p>
<p>Here's another example: <a href="http://www.xefer.com/twitter/gruber" rel="nofollow noreferrer">twitter charts</a>. I'm hoping to do the same thing. Need to find out how to do the concentric circles.</p>
10,266
<p>I keep on hearing about concurrent programing every where. Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?</p>
<p>Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.</p> <p>Thread is short for "thread of execution". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread.</p> <p>In C++0x threads are started using the <code>std::thread</code> class:</p> <pre><code>void my_function() { // do stuff } std::thread my_thread(my_function); // run my_function in its own thread </code></pre> <p>The new C++0x standard also supports:</p> <ul> <li>atomic values and operations with the <code>std::atomic&lt;&gt;</code> class template,</li> <li>mutexes for data protection (<code>std::mutex</code>, <code>std::recursive_mutex</code>, etc.)</li> <li>lock classes for ease of managing lock lifetime (<code>std::lock_guard&lt;&gt;</code>, <code>std::unique_lock&lt;&gt;</code>)</li> <li><code>std::lock</code> and <code>std::try_lock</code> functions to manage acquiring multiple locks at the same time without risking deadlock</li> <li>condition variables to ease waiting for an event (<code>std::condition_variable</code>, <code>std::condition_variable_any</code>)</li> <li>futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic "how do I return a value from a thread" question.</li> <li>thread-safe initialization of local static objects</li> <li>the <code>thread_local</code> keyword to declare thread-local data</li> </ul> <p>I gave a more detailed overview of the new C++0x thread library in my article on devx.com: <a href="http://www.devx.com/SpecialReports/Article/38883" rel="noreferrer">Simpler Multithreading in C++0x</a></p> <p>I write about multithreading and concurrency in C++ on <a href="http://www.justsoftwaresolutions.co.uk/blog" rel="noreferrer">my blog</a>. I'm also writing a book on the topic: <a href="http://www.manning.com/williams" rel="noreferrer">C++ Concurrency in Action</a>.</p>
<p>This is the best article to understand concurrent programming: <a href="http://www.nondot.org/sabre/Mirrored/AdvProgLangDesign/finkel07.pdf" rel="nofollow">Concurrent Programming</a></p> <p>You will get the full picture of concurrent programming and C++ after reading it.</p> <p>As a quick summary, we can say that concurrent programming is to do multitasking. When a program gets blocked, it can do other things. Typically we get blocked while waiting for network connections and dealing with I/O. We can facilitate concurrent programming using <code>fork()</code> and thread libraries.</p>
26,922
<p>Perhaps not directly programming related, but definitely product / commercially related. And I can't find a dupe, so I thought I would ask.</p> <p>I have had a bit of trouble trying to figure out what best to say to people who have called and asked for advice. The Microsoft message is a bit worrying - basically, be worried, lock up everything and hold on tight. Some of the people I have directed towards that route have objected because of what it does to their browsing experience.</p> <p>The "go get Firefox" message seems to be going down a bit better. What is the real story and what is the best advice to give?</p> <p>How much actual risk does it pose between now and when MS patches it?</p> <p>Edit: here are the links that my community seem to be reading... <a href="http://voices.washingtonpost.com/securityfix/2008/12/microsoft_big_security_hole_in.html?nav=rss_blog" rel="nofollow noreferrer">WSJ</a> <a href="http://network.nationalpost.com/np/blogs/posted/archive/2008/12/16/gaping-security-hole-found-in-internet-explorer-browsing-software.aspx" rel="nofollow noreferrer">NP</a> <a href="http://news.bbc.co.uk/2/hi/technology/7784908.stm" rel="nofollow noreferrer">BBC</a></p>
<p><a href="http://www.google.com/chrome" rel="nofollow noreferrer">Switch</a> to <a href="http://www.mozilla.com/en-US/firefox/" rel="nofollow noreferrer">another</a> <a href="http://www.opera.com/" rel="nofollow noreferrer">browser</a>, <a href="http://www.apple.com/safari/" rel="nofollow noreferrer">already</a>.</p> <p><a href="http://www.google.com/chrome" rel="nofollow noreferrer">Chrome</a> and <a href="http://www.mozilla.com/en-US/firefox/" rel="nofollow noreferrer">Firefox</a> would be my first two choices. Firefox would probably be best for now, just because it has a longer history.</p> <p>The only way to prevent this on IE is to follow <a href="http://www.microsoft.com/technet/security/advisory/961051.mspx" rel="nofollow noreferrer">Microsoft's workaround procedures</a>, which will cause a huge headache for users.</p>
<p>Apart from switch browser, pay attention to the <a href="http://www.computerworld.com/action/article.do?command=viewArticleBasic&amp;articleId=9123612&amp;source=NLT_PM" rel="nofollow noreferrer">emergency patch</a> - get it installed.</p>
48,781
<p>I'm trying to find a simple way to change the colour of the text and background in <code>listview</code> and <code>treeview</code> controls in WTL or plain Win32 code.</p> <p>I really don't want to have to implement full owner drawing for these controls, simply change the colours used.</p> <p>I want to make sure that the images are still drawn with proper transparency.</p> <p>Any suggestions?</p>
<p>Have a look at the following macros:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb775063%28VS.85%29.aspx" rel="nofollow noreferrer">ListView_SetBkColor</a><br> <a href="http://msdn.microsoft.com/en-us/library/bb775116%28VS.85%29.aspx&gt;" rel="nofollow noreferrer">ListView_SetTextColor</a> </p> <p><a href="http://msdn.microsoft.com/en-us/library/bb760036%28VS.85%29.aspx" rel="nofollow noreferrer">TreeView_SetBkColor</a><br> <a href="http://msdn.microsoft.com/en-us/library/bb760131%28VS.85%29.aspx" rel="nofollow noreferrer">TreeView_SetTextColor</a></p>
<p>It's been a while since I've use the win32 API directly, but I believe that if you handle the WM_ERASEBACKGROUND message for your control, you can use FillRect() in your handler to paint the background using whatever color you like.</p>
6,742
<pre><code>$query = "SELECT * FROM `table`"; $results = mysql_query($query, $connection); </code></pre> <p>If 'table' has no rows. whats the easiest way to check for this.?</p>
<p>You could use <a href="http://php.net/mysql_num_rows" rel="noreferrer">mysql_num_rows($results)</a> to check if 0 rows were returned, or use this faster alternative:</p> <pre><code>$query = "SELECT COUNT(*) AS total FROM table"; $results = mysql_query($query, $connection); $values = mysql_fetch_assoc($results); $num_rows = $values['total']; </code></pre>
<p>If you loop through the results, you can have a counter and check that.</p> <pre><code>$x = 1; $query = mysql_query("SELECT * FROM table"); while($row = mysql_fetch_assoc($query)) { $x++; } if($x == 1) { //No rows } </code></pre>
26,356
<p>I'm about to start a new .net web project. Previsouly for my n-layer web apps i've used the "Microsoft Data Access Application Block" (sqlhelper.cs) for the data access, then an interface class to interface with the object classes. I'm aware this technique is a bit dated and was looking to use something a little more with the times.</p> <p>I've looked into LINQ to SQL for data access but was restricted by lacking the many to many relationship. The entity framework was a whole differnet approach that appears to have too larger learning curve.</p> <p>Would there be anything wrong with using the sqlhelper.cs class to handle my data access?</p>
<p>Not at all. It supports the creation of multi-tier layers which separates our data access from our logic. I usually have business and data classes in separate folders and include the SqlHelper class with my Data DALC class.</p> <p>I'm looking forward to the move towards LINQ and the use of generics. That's my next step and I think the the use of the SqlHelper promotes good coding practice in the meantime.</p> <p>I first started using it when I "borrowed" it from the Enterprise Library which was huge. Ditto for the Entity Framework which I have yet to come to grips with in the workplace. but all in good time :-)</p>
<p>You can get simple and good example of sql helper class on <a href="http://followprogrammers.blogspot.com/" rel="nofollow noreferrer">http://followprogrammers.blogspot.com/</a></p>
44,073
<p>I'm not good at programming and my trying to open one of my spreadsheet documents. Below in the basic login im using, I then request a list all my spreadsheet, which is returned in $feed.</p> <p>And now I'm worried I'm not on the right track with opening a document so I can read and write cells.</p> <pre><code>&lt;?php require_once '../library/Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata_Spreadsheets'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $user="username"; $pass="user password"; // login $service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME; $client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service); $spreadsheetService = new Zend_Gdata_Spreadsheets($client); $feed = $spreadsheetService-&gt;getSpreadsheetFeed(); print_r ($feed); ?&gt; </code></pre>
<p>I forgot which social network my id was with, and so I have Activ8ed a new. A bit like a cylon.</p> <blockquote> <p>I looked at the zend manual. I'm new to php so accessing Objects like $feed is still confusing. The Zend document needs to make better usage of http to expand the information present.</p> <p>ie. the quote from zend manual</p> <blockquote> <p>"Given the spreadsheet key from the of a Zend_Gdata_Spreadsheets_SpreadsheetEntry object you've already retrieved, you can fetch a feed containing a list of worksheets associated with that spreadsheet."</p> </blockquote> </blockquote> <p>$feed returns <a href="http://framework.zend.com/apidoc/core/Zend_Gdata/Spreadsheets/Zend_Gdata_Spreadsheets_SpreadsheetEntry.html" rel="nofollow noreferrer">Zend_Gdata_Spreadsheets_SpreadsheetEntry</a> object</p> <p>Ok so I've learned to display the files available with the code below.</p> <blockquote> <p>foreach ($feed->entries as $entry) {<br> echo $entry->title->text .' '. $entry->content->text . "\n"; }</p> </blockquote> <p>I think I'm starting to get it, but not sure what I should be reading.</p> <p><a href="http://framework.zend.com/apidoc/core/Zend_Gdata/Spreadsheets/Zend_Gdata_Spreadsheets.html" rel="nofollow noreferrer">http://framework.zend.com/apidoc/core/Zend_Gdata/Spreadsheets/Zend_Gdata_Spreadsheets.html</a> Is making more scene too. But it's missing links to <a href="http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_protocol.html#ListingSpreadsheets" rel="nofollow noreferrer">http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_protocol.html#ListingSpreadsheets</a> which is the structure on $feed, well a pointer to a segment of one.</p> <p>Trying more to Understanding how objects class's and functions are used in PHP. reading <a href="https://stackoverflow.com/questions/539677/class-variables-scope-resolution-operator-and-different-versions-of-php">Class variables, scope resolution operator and different versions of PHP</a></p> <p><a href="https://stackoverflow.com/questions/32145/is-this-a-reasonable-way-to-handle-getters-setters-in-a-php-class">Is this a reasonable way to handle getters/setters in a PHP class?</a></p> <p>Did I mention this, <a href="http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_protocol.html#ListingSpreadsheets" rel="nofollow noreferrer">http://code.google.com/apis/spreadsheets/docs/2.0/developers_guide_protocol.html#ListingSpreadsheets</a> </p> <p><a href="http://zendguru.wordpress.com/2009/04/17/zend-framework-select-statement-and-where-clause-examples/" rel="nofollow noreferrer">http://zendguru.wordpress.com/2009/04/17/zend-framework-select-statement-and-where-clause-examples/</a> </p>
<p>You're on the right track. Are you using the information found <a href="http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html" rel="nofollow noreferrer">http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html</a> ?</p> <p>Your code is getting a spreadsheet feed which lists all the available spreadsheets, which is an important step. You'll want to follow the link above to get a list-based feed or a cell-based feed.</p> <p>The documentation is pretty good I would recommend just reading through it all(yes it's long).</p>
40,266
<p>Say I have entities organized in a hierarchy with <code>Parent</code> being the root entity and <code>Child</code> being a subclass of <code>Parent</code>. I'd like to setup an <code>NSArrayController</code> to fetch only entities of <code>Parent</code>, but not <code>Child</code>.</p> <p>If you set the Entity Name of the array controller in Interface Builder to <code>Parent</code>, it fetches all <code>Parent</code> and <code>Child</code> entities. I originally tried setting the array controller's fetch predicate in Interface Builder to:</p> <pre><code>entity.name == "Parent" </code></pre> <p>This worked for an XML store, but when I switched to a SQLite store, it no longer worked. I get the following error:</p> <pre><code>keypath entity.name not found in entity &lt;NSSQLEntity xxx&gt; </code></pre> <p>As a work around, I am setting up a filter predicate (with the same <code>entity.name</code> predicate as above) in my <code>awakeFromNib</code> to filter only Parent entities. Apparently, that predicate is valid once the entities are in memory, but you can't use it in a SQL-backed fetch predicate.</p> <p>Is there a way to fetch only <code>Parent</code> entities, but not <code>Child</code> entities using a fetch predicate that works with a SQLite store? It seems wasteful to pull in entities that you're only going to ignore with the filter predicate.</p>
<p>Leopard introduced the <code>includesSubentities</code> property to NSFetchRequest for exactly this purpose. You'll have to subclass your NSObjectController or NSArrayController to provide the fetch request it will use via its <code>defaultFetchRequest</code> property, or to change the fetch request it uses by overriding its <code>-fetchWithRequest:...</code> method.</p>
<p>Leopard introduced the <code>includesSubentities</code> property to NSFetchRequest for exactly this purpose. You'll have to subclass your NSObjectController or NSArrayController to provide the fetch request it will use via its <code>defaultFetchRequest</code> property, or to change the fetch request it uses by overriding its <code>-fetchWithRequest:...</code> method.</p>
38,139
<p>I'm busy with an asignment where i have to make a graphical interface for a simple program. But i'm strugling with the layout.</p> <p>This is the idea:<br> <img src="https://i.stack.imgur.com/a3Xk7.png" alt="Layout Example" title="Layout Example"></p> <p>What is the easiest way to accomplish such a layout?</p> <p>And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?</p>
<p>Well considering how simple the layout is I would suggest you use a BorderLayout with NORTH set to the top section in a container and the JTable in the CENTER of the BorderLayout. For the Top it appears to be a simple BorderLayout again with NORTH as the Instruction: south as the black box (possibly in a container with a FlowLayout). The center of the top pane appears to be 2 Containers of GridLayouts with 2 rows and 2 columns, so put thos in another container with a GirdLayout.</p> <p>So in pseudo:</p> <pre><code>Container(BorderLayout) { @NORTH Container(BorderLayout) { @NORTH Label(Instruction); @CENTER Container(GridLayout(2,1)) { Container(GirdLayout(2,2)) { Label() TextField() Label() TextField() } Container(GirdLayout(2,2)) { Label() TextField() Label() TextField() } } @SOUTH Container(FlowLayout()) { JButton() //shaded thing? } } @CENTER { JTable } } </code></pre>
<p>I used to love Motif's XmForm for this sort of thing. In Java, I usually put Boxes inside of boxes. So I have a vertical box. First row of the box contains a JLabel for the Instruction. Second row contains something for the label/result stuff, possibly some sort of grid. Third row contains whatever that blacked out thing, Fourth row contains the JTable. Then I'd spend some time to try to figure out how to do the lable/result stuff. Then I'd probably end up saying "dammit", and doing it as a GridBagLayout.</p>
30,860
<p>I've created a DLL project in VS 2005 for native Win32/unmanaged C++, call it myProj.dll. It depends on a 3rd-party commercial DLL that in turn depends on msvcr90.dll (I assume it was built from a VS 2008 project). I'll call it thirdParty.dll.</p> <p>My DLL project builds just fine in VS2005. I've built a test app (again, VS 2005 Win32 C++) that links to myProj.lib. (As an aside, judging by the small size of the .lib, and by the fact that, at run-time, the app must locate myProj.dll, I'm guessing that the .lib is just a wrapper for a call to loadLibrary() that loads the actual DLL; is that close?)</p> <p>My problem is that, at run-time, the test app cannot locate msvcr90.dll (nor msvcp90.dll), the dependency on which stems from the thirdParty.dll.</p> <p>I've installed Microsoft's redist package, and so have all the std (9.0) C++ libraries in c:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_... . What's more, if I point the dependency walker at thirdParty.dll, it happily resolves the references to that location.</p> <p>But, if I point depends.exe at my test app (.exe) or myProj.dll, msvcr90.dll and msvcp90.dll are not found.</p> <p>I'm guessing there's something I need to configure in VS2005 so that the .exe or myProj.dll are aware of the location of the 9.0 versions of the std C++ libraries (presumably where the redist package installed them in C:\WINDOWS\WinSxS), but I can't seem to figure out what it is. Am I on the right track?</p> <p>I note that, if I simply copy the msvc*90.dll files to my app directory, then the dependency is resolved, but I get the run-time error about improper loading of std c++ DLLs, etc.</p> <p>Thanks immensely in advance.</p>
<p>This looks like a <em>"Side-by-Side Assemblies"</em> issue to me.</p> <p>From what I can tell, Microsoft in an attempt to stop the <em>DLL Hell</em> problems of past years has introduced a concept of <em>"Side-by-Side Assemblies".</em> </p> <p>In a nut shell it means that your application needs to tell <strong>Windows</strong> which version of the <strong>CRT</strong> it was designed to work with. When the application is installed Windows will make sure you application gets its own private copy of these DLL files.</p> <p>To make it all work you need to embed the application's DLL dependencies into the applications <strong>Manifest</strong> file and attaching it to the project using the <strong>Manifest Tool</strong>, <strong>Input and Output</strong> section of the application project settings.</p> <p>As an example here is the manifest I use for the <a href="http://www.zeusedit.com" rel="noreferrer">Zeus for Windows</a> IDE:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"&gt; &lt;assemblyIdentity name="Xidicone.Windows.Zeus for Windows" version="3.9.6.69" processorArchitecture="X86" type="win32" /&gt; &lt;description&gt;Zeus for Windows&lt;/description&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.VC80.CRT" version="8.0.50608.0" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*" /&gt; &lt;/dependentAssembly&gt; &lt;/dependency&gt; &lt;/assembly&gt; </code></pre> <p>Finally, if you plan to make an installer you will need to add the same versions of these DLL files to the application installer or alternatively have your installer run the Microsoft CRT redistributable installer.</p> <p>FWIW I only found out about this when a user reported that <a href="http://www.zeusedit.com" rel="noreferrer">Zeus</a> no longer ran on Windows XP because of a missing MSVCRT runtime DLL file, yet <a href="http://www.zeusedit.com" rel="noreferrer">Zeus</a> had been working fine for over 10 years without ever once having to ship with a MSVCRT runtime DLL file.</p>
<p>I would ask the third party dll people about this. </p>
43,070
<p>Is there a way to download older versions of Visual C++ Express? I'm particularly interested in Visual C++ 2005 Express (PRIOR SP1) and Visual C++ Toolkit 2003. I tried googling for them, but all the sites linked to microsoft.com, from where microsoft (for some reason) has taken them down.</p>
<p>If you want to link your application against the RTM (pre-SP1) version of the CRT (C runtime), you can apparently do that by <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/13efe532-8a62-4951-b636-39e4589e65a5/" rel="nofollow noreferrer">defining <code>_USE_RTM_VERSION</code></a> in your project or on the compiler command line.</p> <p>Also, <a href="http://msdn.microsoft.com/en-us/library/ms235291.aspx" rel="nofollow noreferrer">deploying the CRT as a private assembly</a> should still work with the SP1 version of the CRT. If that is what you have tried to do, posting more information about what went wrong might help you find a solution.</p>
<p>From my personal experience the software compiled with SP1 doesn't simply work, if the end user hasn't installed the redistributables. Without SP1 however it is possible to get the .exe working if you distribute it with the required .dlls.</p>
33,986
<p>I need the tool for graphical representing of work flow in a program (like electronic circuits are described with graphical representation). The representation has to be like the following: functions are boxes and arrows between boxes are "messages". Like this:</p> <p><a href="http://img372.imageshack.us/img372/8471/functionsqv0.png" rel="nofollow noreferrer">alt text http://img372.imageshack.us/img372/8471/functionsqv0.png</a></p> <p>This picture shows the following: (c (a) (b))<br> Where parameters of c() are named as d and e. On C it would be </p> <pre><code>void c( someType1 d, someType2 e ); someType1 a( void ); someType2 b( void ); .... c( a(), b() ); </code></pre> <p>So I think that I need the tool for manipulation and visual representation of s-expressions like these: </p> <pre><code>(a (b c d) e) </code></pre> <p>or </p> <pre><code>f(g(z(x,y))+5) </code></pre> <p>It is not about linked lists, it is about logical connections between functions.<br> The tool has only to generate the textual representation from graphical one.<br> Well, I've found a lot of stuff on the Wiki page about the "Visual programming" and "Graphical programming" and so on. Mostly all described tools are cool, but somewhat complicated. And the list is pretty long, so it would take a lot of time to test all of them. So I need an opinion of real, alive people.</p> <p>Requirements are:</p> <ul> <li>Free</li> <li>Simple</li> <li>Can export to at least one real language like XML or C++ or LISP or any other.</li> </ul> <p>And it would be really good if this tool were configurable.</p> <p>I like the FlowDesigner tool: it seems to be almost the thing I need, but it cannot export to any language... Alas.</p> <p><strong>UPD</strong>: The wiki page I mentioned: <a href="http://en.wikipedia.org/wiki/Graphical_programming" rel="nofollow noreferrer">Graphical Programming</a><br> <strong>UPD2</strong>: well, I decided to write my own tool...</p>
<p>What about using something like <a href="http://www.graphviz.org/" rel="nofollow noreferrer">Graphviz</a>?</p>
<p><a href="http://www.graphviz.org/" rel="nofollow noreferrer">http://www.graphviz.org/</a></p> <p>HTH</p>
43,398
<p>Since I'm running a 3D printing facility of an engineering school, students are always wondering how much infill percentage affects the stiffness of the part. I know that it is impossible to get a numerical solution for this question, but maybe there is an option to simulate in software an already sliced model. I haven't seen in any slicer an option to export as .stl or .step or any other format which can be accepted by simulation software. Has anyone seen or thought about something similar? </p>
<p>I don't believe that slicing engines create any sort of solid model that would be useful for CAD simulation. When a slicing engine slices a 3D model, it's goal is to spit out the preferred machine paths in G-Code (of some kind). However, I've read a few articles, done some tests, and heard through the grape vine that anywhere between 10%-35% is good enough for most applications. I once watched a webinar for understanding the new MakerWare interface that explained how they chose such settings. Although I can't find the clip directly, <a href="http://www.makerbot.com/resources/webinars" rel="nofollow">here</a> is the page for all of MakerBot's webinars. I think <a href="http://pages.makerbot.com/intro-makerbot-desktop-software-webinar.html?utm_source=leadgen&amp;utm_medium=resource-center&amp;utm_content=webinar&amp;utm_campaign=rc-intro-makerbot-desktop-webinar" rel="nofollow">this</a> webinar was the one I watched explaining a little bit about preferred infill percentages.</p> <p>From experience, anything over 35% doesn't yield much more strength from infill side of things. Beyond 35% and you're going to want to reconsider how you're orienting the print when you print it and what you're printing to utilize the grain structure for proper strength.</p> <p>However, infill percentage/patterns are not the only variable for creating strong parts. Infill is really just a way to save time and material. Here are some other ways to potentially increase strength:</p> <ul> <li>Increase your shell. Shell is the number of profile patterns per layer. Typically (in FDM/FFF), each shell is <strong>about</strong> the diameter of your extruder nozzle.</li> <li>Increase your floor/roof. Similar to shell, floor/roof refers to the number of layers that make up the "bottom" and "top" of the part with regard to the build plate.</li> <li>Print orientation. Pay attention to which areas of the part are susceptible to strain along the "grain" of the layers. Try to rotate your part on the build plate in a way that minimizes potential failure both in print and post-print use.</li> <li>Post process. Don't be afraid to do some post-processing to increase the strength. There are <a href="https://markforged.com/" rel="nofollow">some 3D printers on the market</a> that go as far as including Kevlar strands in the printing process to beef up their prints. However, it may be as simple as just coating the part in an epoxy with some basic finishing techniques. It's a bit more work, but it turns weak 3D printed parts into full production quality prints.</li> </ul> <p><strong>Update:</strong> Based on some of the comments, it sounds like your best bet might be to find a custom application that can either convert the g-code file into a solid model (try CAM software?), or create a plugin for your CAD software (I know Unigraphics NX and Solidworks allow for this) and essentially recreate your own slicing engine that takes your solid model and generates the same infill pattern dynamically inside.</p> <p>Perhaps look into the works of <a href="http://www.simlab-soft.com/index.aspx" rel="nofollow">Simlab</a> or similar which has a lot of 3D software plugins. I'm not promoting them and I don't work for them, this is just a reference of what to look for.</p>
<p>If you're an engineering class, you may very well print out big cubes of different infils and test them. </p>
266
<p>aspnet mvc has the HandleError filter that will return a view if an error occurs, but if an error occurs when calling a JsonResult Action how can I return a JSON object that represents an error?</p> <p>I don't want to wrap the code in each action method that returns a JsonResult in a try/catch to accomplish it, I'd rather do it by adding a 'HandleJsonError' attribute or using the existing HandleError attribute to the required action methods.</p>
<p>Take a look at the MVC implementation of HandleErrorAttribute. It returns a ViewResult. You could write your own version (HandleJsonErrorAttribute) that returns a JsonResult.</p>
<p>Maybe you could create your own Attribute and have a constructor value that takes an enum value of View or Json. Below is what Im using for a custom Authorization Attribute to demonstrate what I mean. This way when authentication fails on a json request it responds with a json error and the same with if it returns a View.</p> <pre><code> public enum ActionResultTypes { View, Json } public sealed class AuthorizationRequiredAttribute : ActionFilterAttribute, IAuthorizationFilter { public ActionResultTypes ActionResultType { get; set; } public AuthorizationRequiredAttribute(ActionResultTypes actionResultType) { this.ActionResultType = ActionResultType; } } //And used like [AuthorizationRequired(ActionResultTypes.View)] public ActionResult About() { } </code></pre>
13,515
<p>A colleague and I are discussing best practices regarding ordering method parameters. The goal is to establish a standard in our organization to improve readability and productivity by giving our methods common signatures. We are merely establishing guidelines for the recent grads we are hiring. </p> <p><strong>Example (userId is always passed in to audit the calls):</strong></p> <p>GetOrders(string userId, int customerId); GetOrders(string userId, int[] orderIds); GetCustomer(string userId, int customerId);</p> <p>My argument is the following:</p> <ol> <li>common arguments are left most.</li> <li>remaining arguments are based on importance</li> <li>optional (nullable) arguments last.</li> </ol> <p>His argument is essentially the opposite.</p> <p>I'm not asking for a right or wrong answer here, nor a discussion. I just want to see what standards exist already.</p> <p>Thanks!</p>
<p>I'd go with the ordering of input,output,optional.</p> <p>Optional should go at the end to me because most languages allow you to specify a default value for optional arguments to avoid having to include them. The provision of that is that they have to be the last argument(s) otherwise you can't drop them. </p> <p>That's assuming you can't have named arguments though. If you can have them, I'd always suggest using them for clarity and order becomes a moot point.</p>
<p>One idiom popular in C programming, is that the target goes first, so that in strcpy(A, B); is copying B to A (much like "A=B;" is copying B to A).</p>
25,619
<p>I'm on OS X 10.5.5 (though it does not matter much I guess)</p> <p>I have a set of text files with fancy characters like double backquotes, ellipsises ("...") in one character etc. </p> <p>I need to convert these files to good old plain 7-bit ASCII, preferably without losing character meaning (that is, convert those ellipses to three periods, backquotes to usual "s etc.).</p> <p>Please advise some smart command-line (bash) tool/script to do that.</p>
<p>The <a href="http://elinks.or.cz/" rel="nofollow noreferrer">Elinks</a> web browser will convert Unicode entities to their ASCII equivalents, giving things like "--" for "—" and "..." for "…", etc. There is a python module <a href="http://code.google.com/p/python-elinks/" rel="nofollow noreferrer">python-elinks</a> which uses the same conversion table, and it would be trivial to turn it into a shell filter, like this:</p> <pre><code>#!/usr/bin/env python import elinks import sys for line in sys.stdin: line = line.decode('utf-8') sys.stdout.write(line.encode('ASCII', 'elinks')) </code></pre>
<p>There was a question yesterday or the day before about file renaming, and I showed a Perl script <code>rename.pl</code> that would be usable for the task. The problem area is knowing how the odd characters are encoded, and devising the correct sequence of transliterations. I'd probably do it with an adaptation of that script that did all the mappings sequentially. Doing it one character at a time would be unduly fiddly.</p> <p>Question was: <a href="https://stackoverflow.com/questions/208181/how-to-rename-with-prefixsuffix">How to rename with prefix/suffix</a></p>
26,147
<p>I'm having a bit of a problem with converting the result of a MySQL query to a Java class when using SUM.</p> <p>When performing a simple SUM in MySQL</p> <pre><code>SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate'; </code></pre> <p>with <code>price</code> being an integer, it appears that the <code>SUM</code> sometimes returns a string and sometimes an integer, depending on the version of the JDBC driver.</p> <p>Apparently the server does tell the JDBC driver that the result of <code>SUM</code> is a string, and the JDBC driver sometimes 'conveniently' converts this to an integer. (see <a href="http://marc.info/?l=mysql-java&amp;m=116295785422117&amp;w=2" rel="nofollow noreferrer">Marc Matthews' explanation</a>).</p> <p>The Java code uses some <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/beans/BeanInfo.html" rel="nofollow noreferrer">BeanInfo</a> and <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/beans/Introspector.html" rel="nofollow noreferrer">Introspection</a> to automagically fill in a (list of) bean(s) with the result of a query. But this obviously can't work if the datatypes differ between servers where the application is deployed.</p> <p>I don't care wether I get a string or an integer, but I'd like to always have the same datatype, or at least know in advance which datatype I'll be getting. </p> <p>Is there some way to know which datatype will be returned by a MySQL <code>SUM</code> from within the Java code? Or does anyone know some better way to deal with this?</p>
<p>This is just a guess, but maybe casting to integer will force MySQL to always tell it is an integer.</p> <pre><code>SELECT CAST(SUM(price) AS SIGNED) FROM cakes WHERE ingredient = 'marshmallows'; </code></pre>
<p>I found <code>COALESCE(SUM(price),0)</code> good for always ensuring the field returned 0 if there was no result.</p> <p>See: <a href="http://lists.mysql.com/mysql/177427" rel="nofollow noreferrer">http://lists.mysql.com/mysql/177427</a></p>
41,845
<p>We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects.</p> <p>We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean its ok to drop them and the database will work as well as it did before without them, or have Red Gate missed a trick?</p>
<p>It is considered best practice to auto create and auto update statistics. Sql Server will create them if it needs them. You will often see the tuning wizard generate lots of these, and you will also see people advise that you update statistics as a part of your maintenance plan, but this is not necessary and might actually make things worse, just so long as auto create and auto update are enabled.</p>
<p>Statistics are too data-specific to be tooled. It would be potentially very inefficient to blindly re-create them on a data set.</p>
4,078
<p>I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?</p>
<p>I usually put separate folders at the root level, so I end up with a directory structure like this:</p> <pre><code>/system /css /js /img </code></pre> <p>Seems to work for me - when you use <code>site_url(url)</code>, the URL it generates is from the root, so you can use <code>site_url('css/file.css')</code> to generate URLs to your stylesheets etc.</p>
<p>I hate having so many directories at the root level, so I use /public and use htaccess to rewrite /scripts to /public/scripts and so on.</p>
21,514
<p>I'm terribly new to SQL, and cannot seem to get the desired information out, after trying a few different google searches, and reading through some SQL tutorials.</p> <p>I think it involves some sort of joins, but cannot get them straight.</p> <p>Given the following sample tables:</p> <p>Table 1(Activity This is updated every time a change is made to a task, could be manytimes per day):</p> <pre><code>ID Who What When 001 John Created 2008-10-01&lt;br&gt; 001 Bill Closed 2008-10-02&lt;br&gt; 001 John Updated 2008-10-03&lt;br&gt; 002 Bill Created 2008-10-04&lt;br&gt; 002 John Updated 2008-10-05&lt;br&gt; 002 Bill Closed 2008-10-06&lt;br&gt; </code></pre> <p>Table 2(Tasks - This is the main task tracking table):</p> <pre><code>ID Created Status 001 2008-10-01 Closed 002 2008-10-04 Closed </code></pre> <p>Table 3(Comments):</p> <pre><code>ID When Comment&lt;br 001 2008-10-01 "I'm creating a new task" 001 2008-10-02 "I have completed the task" 001 2008-10-03 "Nice job" 002 2008-10-04 "I'm creating a second task" 002 2008-10-05 "This task looks too easy" 002 2008-10-06 "I have completed this easy task" </code></pre> <p>What SQL (mySQL if it makes any difference) query would I use to find out who had done something on a task that had been closed?</p> <p>The results would be something like:</p> <pre><code>Who What ID When Comment Bill Updated 002 2008-10-03 "Nice job" </code></pre> <p>Meaning that Bill changed task 002 after it was closed, and added the comment "Nice Job"</p> <p>Any help would be much appreciated.</p> <p>Thanks in advance.</p>
<pre><code>SELECT a1.Who, a1.What, a1.ID, c.When, c.Comment FROM Activity AS a1 JOIN Activity AS a2 ON (a1.ID = a2.ID AND a1.When &gt; a2.When) JOIN Comments AS c ON (a1.ID = c.ID AND a.When = c.When); WHERE a2.What = 'Closed'; </code></pre> <p>I think you need some way to associate a row in Comments to the correct row in Activity. Right now if two people comment on a given Task on the same day, you don't know whose comment is whose. I'd recommend that you give each row in Activity a unique key, and then reference that from the Comments table.</p> <pre><code>CREATE TABLE Tasks ( Task_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Created DATE NOT NULL, Status VARCHAR(10) ) TYPE=InnoDB; CREATE TABLE Activity ( Activity_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Task_ID INT NOT NULL REFERENCES Tasks, Who VARCHAR(10) NOT NULL, What VARCHAR(10) NOT NULL, When DATE NOT NULL ) TYPE=InnoDB; CREATE TABLE Comments ( Comment_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Activity_ID INT NOT NULL REFERENCES Activity, Who VARCHAR(10) NOT NULL, When DATE NOT NULL, Comment VARCHAR(100) NOT NULL ) TYPE=InnoDB; </code></pre> <p>Then you can make associations so the query returns more accurate results:</p> <pre><code>SELECT c.Who, a1.What, a1.Task_ID, c.When, c.Comment FROM Activity AS a1 JOIN Activity AS a2 ON (a1.Task_ID = a2.Task_ID AND a1.When &gt; a2.When) JOIN Comments AS c ON (a1.Activity_ID = c.Activity_ID); WHERE a2.What = 'Closed'; </code></pre> <p>Make sure to use <code>TYPE=InnoDB</code> in MySQL because the default storage engine MyISAM doesn't support foreign key references.</p>
<p>Are you planning on joining the tables based on the date? So you will only have 1 change per day?</p>
28,607