instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am trying to use google search for my site:</p> <p><a href="http://www.houseofhawkins.com/search.php" rel="noreferrer">http://www.houseofhawkins.com/search.php</a></p> <p>It is not playing nice with some screen resolutions. Here is the code given from google:</p> <pre><code>&lt;div id="cse-search-results"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; var googleSearchIframeName = "cse-search-results"; var googleSearchFormName = "cse-search-box"; var googleSearchFrameWidth = 250; var googleSearchDomain = "www.google.com"; var googleSearchPath = "/cse"; &lt;/script&gt; &lt;script type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"&gt;&lt;/script&gt; </code></pre> <p>I changed the "googleSearchFrameWidth" down to 250 thinking that should be setting the width in px, (it was 600 to start with). But with smaller screens (1024 * 768) it sticks out the side of my divs.</p> <p>Am I doing something stupid?</p>
<p>I have three settings that you can tweak, a combination of which I hope will get you where you need to go:</p> <ol> <li><strong>googleSearchFrameWidth</strong> - Set this in the JavaScript to your desired width. This is the most obvious one and the one you've probably already tweaked.</li> <li><strong>Width of cse-search-results div</strong> - Use an inline style statement (e.g. <code>style ="width:500"</code>) to set the width of the div.</li> <li><strong>Set the IFrame Style</strong> - If you check, you'll probably notice that all of this content is being rendered from Google via an IFrame. This is a bit harder to tweak but doable. To do this, add a statement to the end of your stylesheet such as <code>#cse-search-results iframe { }</code>, including the actual iframe style within the brackets.</li> </ol> <p>I hope one of these or a combination of these proves to be the answer for you. When in doubt, use a DOM inspector such as the one available in Firebug to analyze the impact of your changes on the DOM. Hope this helps.</p>
<p>Google will not allow you to use a width smaller than 500px. Your best bet is to create a style for the iframe:</p> <pre><code>&lt;style&gt; #cse-search-results iframe {width: 200px; } &lt;/style&gt; </code></pre>
38,042
<p>Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.</p>
<pre><code>public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); } </code></pre>
<p>I think this is the fastest (download speed time with low latency) solution for download.</p> <pre><code>// WebClient vs HttpClient vs HttpWebRequest vs RestSharp // در نهایت به نظرم روش زیر سریعترین روشه HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url); Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; Request.Proxy = null; Request.Method = "GET"; using (WebResponse Response = Request.GetResponse()) { using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) { return Reader.ReadToEnd(); } } </code></pre>
4,584
<p>My new Ender 5 Plus' Bowden tube keeps popping out of its socket on the extruder mid-print, I've tried several times and it keeps doing it even though it's locked into place securely at the start every time. Is this a known issue? And how do I resolve it?</p> <p>I just got it so I doubt it's the coupler, I replaced it with a spare as my first solution, I did notice that it got almost stringy plastic around it whenever it gets popped out.... could that be indicative of what the problem is?</p>
<p>The coupler for the Bowden tube is probably worn out or the tube end has been scraped so that the coupler can't grab it or you have left out the clamp on the coupler.</p> <p>The coupler has a sleeve that when pressed down releases the Bowden tube. There is a C-shaped clip that should go between the top lip of the sleeve and the body of the coupler that prevents the sleeve from moving and should help hold the tube more firmly. Make sure this is installed.</p> <p>If the tube outside is visibly worn with scrape marks (this is rare), it might help to cut a few cm off the end so that a fresh section is gripped by the coupler. Be sure to cut the end flush so that there is no gap between the heat break and the Bowden tube or you will have other problems.</p> <p>Alternately (and this is more likely), the coupler itself is worn out, possibly with bent or broken-off teeth. If this is the case, you will need to replace the coupler.</p>
<p>OK well I feel silly, it turns out it wasn't fully pushed into place, I pushed it in feeling it lock and thought it was secure, when it actually wasn't, pushing it in till it feels locked up twice resulted in it being properly secured. (sorry if my description doesn't make a lot of sense, I'm not good at that kind of thing, so I'm trying my best.)</p>
2,066
<p>What tool is there for generating C# classes from NHibernate mappings files?</p>
<p>On the <a href="http://nhibernate.info/doc/nh/en/index.html#toolsetguide-s2" rel="nofollow noreferrer">NHibernate resources page</a> under 'Helpful tools', there are a few code generators listed: <a href="http://nhibernate.info/doc/nh/en/index.html#toolsetguide-s2" rel="nofollow noreferrer">http://nhibernate.info/doc/nh/en/index.html</a></p>
<p>I wrote a small one : <a href="http://www.codeplex.com/EntityGenerator" rel="nofollow noreferrer">http://www.codeplex.com/EntityGenerator</a></p> <p>Currently it's a small console application with a configuration file. Not very user friendly but it works and the templates are easily customizable.</p> <p>Still under heavy development, I'll update it when I have some time :)</p>
22,200
<p>When working with tables in Oracle, how do you know when you are setting up a good index versus a bad index?</p>
<p>This depends on what you mean by 'good' and 'bad'. Basically you need to realise that every index you add will increase performance on any search by that column (so adding an index to the 'lastname' column of a person table will increase performance on queries that have "where lastname = " in them) but decrease write performance across the whole table.</p> <p>The reason for this is when you add or update a row, it must add-to or update both the table itself and every index that row is a member of. So if you have five indexes on a table, each addition must write to six places - five indexes and the table - and an update may be touching up to six places in the worst case.</p> <p>Index creation is a balancing act then between query speed and write speed. In some cases, such as a datamart that is only loaded with data once a week in an overnight job but queried thousands of times daily, it makes a great deal of sense to overload with indexes and speed the queries up as much as possible. In the case of online transaction processing systems however, you want to try and find a balance between them.</p> <p>So in short, add indexes to columns that are used a lot in select queries, but try to avoid adding too many and so add the most-used columns first.</p> <p>After that its a matter of load testing to see how the performance reacts under production conditions, and a lot of tweaking to find an aceeptable balance.</p>
<p>A good index is something that you can rely on to be unique for a specific table row.</p> <p>One commonly used index scheme is the use of numbers which increment by 1 for each row in the table. Every row will end up having a different number index.</p>
10,459
<p>How do you properly ensure that a user isnt tampering with querystring values or action url values? For example, you might have a Delete Comment action on your CommentController which takes a CommentID. The action url might look like /Comments/Delete/3 to delete the comment with the id 3.</p> <p>Now obviously you dont want anyone to be able to delete comment 3. Normally on the owner of the comment or an admin has permission to do so. Ive seen this security enforced different ways and would like to know how some of you do it.</p> <p>Do you make multiple Database calls to retrieve the comment and check that the author of the comment matches the user invoking the delete action? </p> <p>Do you instead pass the CommentID and the UserID down to the stored procedure who does the delete and do a Delete where UserID and CommentID equal the values passed in? </p> <p>Is it better to encrypt the query string values? </p>
<p>You don't.</p> <p>It is a cardinal rule of programming, especially in this day and age, that <em>you never trust any input which comes from the user, the browser, the client, etc.</em></p> <p>It is also a cardinal rule of programming that you should probably not try to implement encryption and security yourself, unless you really know what you are doing. And even if you do know what you are doing, you will only remain one step ahead of the tard-crackers. The smart ones are still going to laugh at you.</p> <p>Do the extra query to ensure the logged-in user has the right set of permissions. That will make everyone's lives just that much simpler.</p>
<p>I've done funky things take the querystring, compress it, Base64 or just hex encode it, so that "commentid=4&amp;userid=12345" becomes "code=1a2b23de12769"</p> <p>It's basically "Security through obscurity" but it does make a lot of work for someone trying to hack the site.</p>
30,463
<p>My users use the site pretty equally 24/7. Is there a meme for build timing?</p> <p>International audience, single cluster of servers on eastern time, but gets hit well into the morning, by international clients.</p> <p>1 db, several web servers, so if no db, simple, whenever.</p> <p>But when the site has to come down, when would you, as a programmer be least mad to see SO be down for say 15 minutes.</p>
<p>If there's truly no good time from the users' perspective, then I'd suggest doing it when your team has the most time to recover from any build-related disaster.</p>
<p>Use a second site, and hotswap as needed.</p>
11,537
<p>I'm seeing some errors that would indicate a "connection leak". That is, connections that were not closed properly and the pool is running out. So, how do I go about instrumenting this to see exactly how many are open at a given time?</p>
<p>If you're using .net, there's the .net data provider for SQL server in PerfMon. You can look at NumberOfPooledConnections there</p> <p><a href="https://i.stack.imgur.com/oH5Cd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oH5Cd.png" alt="screenshot of perf monitor" /></a></p>
<p>you can use the profiler tool to trace all existing and opening and closing connections</p> <p>You can open profiler from enterprise manager</p>
12,204
<p>Basically I’ve heard that certain conditions will cause .NET to blow past the <code>finally</code> block. Does anyone know what those conditions are?</p>
<p>Two possibilities:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx" rel="noreferrer">StackOverflowException</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.executionengineexception.aspx" rel="noreferrer">ExecutionEngineException</a></li> </ul> <p>The finally block will not be executed when there's a <code>StackOverflowException</code> since there's no room on the stack to even execute any more code. It will also not be called when there's an <code>ExecutionEngineException</code>, which may arise from a call to <code>Environment.FailFast()</code>.</p>
<p>Neither code which follows a finally block, nor code in outer scopes, will execute without the finally block having been started first (an exception within the finally block may cause it to exit prematurely, in which case execution will jump out from the finalizer to an outer scope). If code prior to the finally block gets stuck in an endless loop or a method that never exits, or if the execution context is destroyed altogether, the finally block will not execute.</p> <p>Note that it is proper to rely upon finally blocks, unlike "Finalize" methods (or C# "destructors") which should not properly be relied upon.</p>
13,680
<p>A Visual Studio 2008 project in one solution needs to reference a WCF service in another VS 2008 solution on the same development machine. Does anybody have any suggestions on how best to accomplish this?</p>
<p>You could do a redirect to buy.php after saving to the session object, which then does a server redirect to check.php, it would mean when the user clicks back, they're going back to the GET request not the POST request</p>
<p>Yes - I agree with above. I ALWAYS do a <code>redir</code> away from the last post, so clicking back bounces them back without that error OR re-submissions. it also avoids complications. u can always tag the <code>redir</code> link page with a <code>?m</code> or <code>&amp;m</code> (i.e.: <code>page.php?m</code>) and have this at top of page: (use <code>elseif</code> there after) </p> <pre><code>if (isset($_GET['m'])) { echo 'order placed.'; } else { //... } </code></pre> <p>You can have it all on one page too. Just name the submit buttons <code>submit1</code>, <code>submit2</code>, like: (bear in mind if you use an image for submits, it becomes <code>$_POST['submit1_x']</code> :)</p> <pre><code>if (isset($_POST[submit1]) { //validate + save session data from form1 //display form 2 } else if(isset($_POST[submit2])) { //validate + save session data from form2 //display form 3 } else { //display first form //&lt;input type="submit" name="submit1" value="Continue"&gt; } </code></pre>
7,963
<p>I am trying to play the Asterisk system sound from a C# program with</p> <pre><code>System.Media.SystemSounds.Asterisk.Play(); </code></pre> <p>but no sound plays. My system does have a sound set up for Asterisk and other programs (not written by me) cause various system sounds to play.</p> <p>Can anyone suggest any possible reasons for this?</p>
<p>I had ignored this problem until today. Some googling revealed that this is quite a common problem and totally unrelated to the .NET Play calls.</p> <p>What happens is that while you can play/preview the sounds from the Control Panel Sounds and Audio Devices applet they do not play when programs trigger the sounds. It seems to be corruption caused by program installations. The fix is quite simple.</p> <p>The (Default) entry for HKEY_CURRENT_USER in the registry should be (value not set). If it is something else (mine was OfficeCompleted) delete the entry (right click and select delete) and it will be re-created as (value not set). The system sounds should then play.</p>
<p>I'm only 8 years late to the party, but I just had this issue on a Windows 7 tablet PC. The thing that fixed it? The classic <code>Restart</code>. </p> <p>Try restarting the device.</p>
44,713
<p>I am working with a wrapper class for <code>CFHTTPMessage</code>, which contains a <code>CFHTTPMessageRef</code> object to which is added the method (GET), the URL of the web application server, and a few custom headers containing the date and an authentication nonce.</p> <p>I'm having some problems getting the method and URL to return certain data. I think I've worked out the authentication nonce. </p> <p>I'd like to troubleshoot this by looking at the raw request going to the web application, and making sure everything is formatted properly. </p> <p>My question is: If I have a <code>CFHTTPMessageRef</code> object (e.g. <code>messageRef</code>), is there a way to log the raw HTTP request that comes out of this message?</p> <p>I've tried the following but I get a <code>EXC_BAD_ACCESS</code> signal when I try to access its bytes:</p> <pre><code>CFDataRef messageData = CFHTTPMessageCopyBody(messageRef); </code></pre> <p>Thanks for any advice.</p> <p>As an alternative, is it possible to use a packet sniffer on a switched network? I can run <code>ettercap</code> on a laptop device, but don't know how to sniff what my iPhone is doing on the local wireless network.</p>
<p>The following worked well:</p> <pre><code>NSData *d = (NSData *)CFHTTPMessageCopySerializedMessage(messageRef); NSLog(@"%@",[[[NSString alloc] initWithBytes:[d bytes] length:[d length] encoding:NSUTF8StringEncoding] autorelease]); </code></pre> <p>Hope this is helpful to others.</p>
<p>The only reason why you should be getting an EXC_BAD_ACCESS when accessing the bytes is if the messageData is NULL (no HTTP body) and you're dereferencing it.</p> <p>Point to remember: the HTTP body isn't the "raw request". It doesn't include the headers or the actual HTTP instruction (GET/POST/ETC). If you haven't actually set body content, it will be nil.</p> <p>It is possible (but less likely) that your CFHTTPMessageRef value isn't properly initialized. Check this in the debugger by setting a breakpoint on your CFHTTPMessageCopyBody line, going to the Debugger Console window, setting the text input cursor to the last line in this window and typing "po messageRef". It should give you a CFTypeID message if validly initialized.</p>
45,364
<p>I'm trying to find if there is a reliable way (using <a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a>) to find the ID of the next row to be inserted, <em>before it gets inserted</em>. I need to use the id for another insert statement, but don't have the option of instantly inserting and getting the next row.</p> <p>Is predicting the next id as simple as getting the last id and adding one? Is that a guarantee?</p> <p>Edit: A little more reasoning... I can't insert immediately because the insert may end up being canceled by the user. User will make some changes, SQL statements will be stored, and from there the user can either save (inserting all the rows at once), or cancel (not changing anything). In the case of a program crash, the desired functionality is that nothing gets changed.</p>
<p>Either scrapping or committing a series of database operations all at once is exactly what transactions are for. Query <code>BEGIN;</code> before the user starts fiddling and <code>COMMIT;</code> once he/she's done. You're guaranteed that either all the changes are applied (if you commit) or everything is scrapped (if you query <code>ROLLBACK;</code>, if the program crashes, power goes out, etc). Once you read from the db, you're also guaranteed that the data is good until the end of the transaction, so you can grab <code>MAX(id)</code> or whatever you want without worrying about race conditions.</p> <p><a href="http://www.sqlite.org/lang_transaction.html" rel="noreferrer">http://www.sqlite.org/lang_transaction.html</a></p>
<p>I think this can't be done because there is no way to be sure that nothing will get inserted between you asking and you inserting. (you might be able to lock the table to inserts but Yuck)</p> <p>BTW I've only used MySQL but I don't think that will make any difference)</p>
13,256
<p>On long Visual C++ builds, it would be really helpful to hear some sort of (optional) sounds for such build/compile results as:</p> <ul> <li>individual compile error</li> <li>file compile success/failure</li> <li>build success/failure</li> <li>batch build success/failure</li> </ul> <p>Does anyone know how to enable sounds for these kinds of build occurrences in Visual C++ (especially Visual C++ 2008 on Vista)?</p>
<p>CJM is almost right. </p> <p>In VC++ 9 (Visual Studio 2008) Go to Control Panel's Sounds applet (Control Panel/Hardware and Sounds/Sounds in Vista).</p> <p>Under the Sounds tab scroll to "Build Succeeded" under "Microsoft Visual Studio" and set a sound for this event. </p> <p>If you have (or had) multiple VS on this PC (I have 6.0, 2003, 2005, and 2008) there may be multiple entries with names like "Microsoft Developer" or blanks - which I assume work in the older versions. I often end-up setting the wrong ones. It seems you'll have to close VS 2008 and reopen for this to take effect.</p> <p>Someone mentioned this was broken/removed in VS 2005 - I noticed this as well.</p>
<p>In VS2005, the sound subsystem wasn't working correctly, not sure it was fixed in 2008. Using macros, you COULD play sounds, like different ones for builds that succeeded, and builds that failed, however the person that I knew that did them was constantly crashing due to the macros failing.</p>
16,330
<p>I just listened to the StackOverflow team's 17th podcast, and they talked so highly of <a href="http://www.asp.net/mvc/" rel="noreferrer">ASP.NET MVC</a> that I decided to check it out.</p> <p>But first, I want to be sure it's worth it. I already created a base web application (for other developers to build on) for a project that's starting in a few days and wanted to know, based on your experience, if I should take the time to learn the basics of MVC and re-create the base web application with this model.</p> <p>Are there really big pros that'd make it worthwhile?</p> <p>EDIT: It's not an existing project, it's a project about to start, so if I'm going to do it it should be now...</p> <hr> <p>I just found this</p> <blockquote> <p>It does not, however, use the existing post-back model for interactions back to the server. Instead, you'll route all end-user interactions to a Controller class instead - which helps ensure clean separation of concerns and testability (<strong>it also means no viewstate or page lifecycle with MVC based views</strong>).</p> </blockquote> <p>How would that work? No viewstate? No events?</p>
<p>If you are quite happy with WebForms today, then maybe ASP.NET MVC isn't for you.</p> <p>I have been frustrated with WebForms for a really long time. I'm definitely not alone here. The smart-client, stateful abstraction over the web breaks down severely in complex scenarios. I happen to love HTML, Javascript, and CSS. WebForms tries to hide that from me. It also has some really complex solutions to problems that are really not that complex. Webforms is also inherently difficult to test, and while you can use MVP, it's not a great solution for a web environment...(compared to MVC).</p> <p>MVC will appeal to you if... - you want more control over your HTML - want a seamless ajax experience like every other platform has - want testability through-and-through - want meaningful URLs - HATE dealing with postback &amp; viewstate issues</p> <p>And as for the framework being Preview 5, it is quite stable, the design is mostly there, and upgrading is not difficult. I started an app on Preview 1 and have upgraded within a few hours of the newest preview being available.</p>
<p>Is the fact that ASP.net MVC is only in 'Preview 5' be a cause for concern when looking into it? </p> <p>I know that StackOverflow was created using it, but is there a chance that Microsoft could implement significant changes to the framework before it is officially out of beta/alpha/preview release?</p>
4,993
<p>I try to print a stamp with flexible filaments. The problem I encounter is that the filament is flexible, but not soft. This leads to small differences in height to parts of the stamp not working.</p> <p>One solution would be to add a small 'cushion' to add some squishyness to the stamp. I designed the stamp and the 'cushion' but now the question arises: "Which infill will provide the best uniform squishyness (in one axis)?"</p> <p>I did a test with cubic infill of Cura, and although it becomes quite squishy, some parts are squishier than other parts of the block.</p> <p>TLDR; Trying to print a squishy cube, where in one axis all areas of the cube have the same squishyness.</p>
<p>As the rubber stamp needs to be soft in one axis for the whole area, you could use an infill that causes the same softness in all directions, but is sliced as such that the stamp experiences the same softness. Alternatively you can use the specific infill types for flexibility, but beware of the orientation:</p> <ul> <li>Concentric</li> <li>Cross</li> <li>Cross 3D </li> </ul> <p><strong>First</strong>, to get the same softness in each direction you need to use an infill pattern that has similar/uniform properties (<a href="https://en.wikipedia.org/wiki/Isotropy" rel="nofollow noreferrer">isotropic</a>) in all dimensions. </p> <p>It is suggested to look into the infill type called "<em>gyroid</em>" (see question <a href="/q/7037/">What are the advantages of gyroid infill?</a>). </p> <p><a href="https://ultimaker.com/en/products/52762-ultimaker-cura-36" rel="nofollow noreferrer">This type of infill</a> is described as:</p> <blockquote> <p>Gyroid infill is one of the strongest infill types for a given weight, has isotropic properties, and prints relatively fast with reduced material use and a fully connected part interior. </p> </blockquote> <p><strong>Second</strong>, since the stamp has relief, slicing the part may cause different infill height. You could look into <a href="/q/6522/">Different infill in the same part</a> to e.g. get a solid infill for under the relief to get a uniform infill for the "cushion".</p>
<p>Sinusoidal infill provides great squishiness in the infill direction, but you'll still have the problem that where the infill meets the perimeter wall, it'll be less squishy than where the perimeter wall isn't touching any infill. You can reduce this effect by using a stiffer filament for that wall (if you can print with multiple filaments), by adding more perimeters, and by reducing the gap between infills (i.e. increasing the infill density). You can even explicitly design an extra-thick wall on the face that takes the pressure (the engraved face of the stamp), and then a section behind that with the squishy infill.</p> <p>TBH, I'm not sure that flexible filament is really what you need for a stamp. Soft materials are commonly used for traditional stamp-making more because they're easy to etch than because the stamping works better that way. Print-making uses wooden or metal plates (the equivalent to the stamp) and produces better, more repeatable images than rubber stamps. When you're printing a stamp, you don't need to etch it, so the softness of rubber isn't an advantage for you. My outsider recommendation would be to try using a normal, rigid filament, and sand the surface to the smoothness you need. If you print with the stamp face on the bed, and your first-layer quality is really good on a smooth build plate, you can probably get better results without sanding.</p>
1,303
<p>I'm looking at <a href="http://www.sqlservercentral.com/articles/SQL+Server+2005/61765/" rel="nofollow noreferrer">this</a> as a baseline explanation of the SQL 2005 Enterprise partitioning. Is there a resource that goes deeper into fine points and considerations of this issue. Some more examples would be useful too.</p> <p>My main scenario is a time based partition system. With one partition that has the most accessed last X days. This partition will have to somehow slide (at least periodically) to keep it refereeing to the same amount of days.</p>
<p>I've found the <a href="http://technet.microsoft.com/en-us/library/ms130214(SQL.90).aspx" rel="nofollow noreferrer">SQL Server 2005 Books Online</a> normally has all the information I'm looking for.</p> <p>I found a good resource in the 05 BOL on SQL Server 2005 Partitioning: <a href="http://technet.microsoft.com/en-us/library/ms188706(SQL.90).aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/ms188706(SQL.90).aspx</a></p> <p>This link goes over designing partitioned tables and indexes: <a href="http://technet.microsoft.com/en-us/library/ms175533(SQL.90).aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/ms175533(SQL.90).aspx</a></p> <p>Here is a blog post that explains the sliding window case you posted: <a href="http://blogs.msdn.com/menzos/archive/2008/06/30/table-partitioning-sliding-window-case.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/menzos/archive/2008/06/30/table-partitioning-sliding-window-case.aspx</a></p>
<p>This site may help you:</p> <p><a href="http://highscalability.com/" rel="nofollow noreferrer">http://highscalability.com/</a></p> <p>specific tags:</p> <p><a href="http://highscalability.com/tags/shard" rel="nofollow noreferrer">http://highscalability.com/tags/shard</a></p> <p><a href="http://highscalability.com/tags/sharding" rel="nofollow noreferrer">http://highscalability.com/tags/sharding</a></p>
12,048
<h3>Background:</h3> <p>I have a module which declares a number of instance methods</p> <pre><code>module UsefulThings def get_file; ... def delete_file; ... def format_text(x); ... end </code></pre> <p>And I want to call some of these methods from within a class. How you normally do this in ruby is like this:</p> <pre><code>class UsefulWorker include UsefulThings def do_work format_text("abc") ... end end </code></pre> <h3>Problem</h3> <p><code>include UsefulThings</code> brings in <em>all</em> of the methods from <code>UsefulThings</code>. In this case I only want <code>format_text</code> and explicitly do not want <code>get_file</code> and <code>delete_file</code>.</p> <p>I can see several possible solutions to this: </p> <ol> <li>Somehow invoke the method directly on the module without including it anywhere <ul> <li>I don't know how/if this can be done. (Hence this question)</li> </ul></li> <li>Somehow include <code>Usefulthings</code> and only bring in some of it's methods <ul> <li>I also don't know how/if this can be done</li> </ul></li> <li>Create a proxy class, include <code>UsefulThings</code> in that, then delegate <code>format_text</code> to that proxy instance <ul> <li>This would work, but anonymous proxy classes are a hack. Yuck.</li> </ul></li> <li>Split up the module into 2 or more smaller modules <ul> <li>This would also work, and is probably the best solution I can think of, but I'd prefer to avoid it as I'd end up with a proliferation of dozens and dozens of modules - managing this would be burdensome</li> </ul></li> </ol> <p>Why are there lots of unrelated functions in a single module? It's <code>ApplicationHelper</code> from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive</p>
<p>If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as</p> <pre><code>module Mods def self.foo puts "Mods.foo(self)" end end </code></pre> <p>The module_function approach below will avoid breaking any classes which include all of Mods.</p> <pre><code>module Mods def foo puts "Mods.foo" end end class Includer include Mods end Includer.new.foo Mods.module_eval do module_function(:foo) public :foo end Includer.new.foo # this would break without public :foo above class Thing def bar Mods.foo end end Thing.new.bar </code></pre> <p>However, I'm curious why a set of unrelated functions are all contained within the same module in the first place? </p> <p><em>Edited</em> to show that includes still work if <code>public :foo</code> is called after <code>module_function :foo</code></p>
<p>This old question comes to me today when I am studing Ruby and found interesting so I want to answer with my new knowlege.</p> <p>Assume that you have the module</p> <pre class="lang-rb prettyprint-override"><code>module MyModule def say 'I say' end def cheer 'I cheer' end end </code></pre> <p>then with the class so call <code>Animal</code> I can take <code>cheer</code> method from MyModule as following</p> <pre class="lang-rb prettyprint-override"><code>class Animal define_method(:happy, MyModule.method(:cheer)) end </code></pre> <p>This is so called unbound method, so you can take a callable object and bind it to another place(s).</p> <p>From this point, you can use the method as usual, such as</p> <pre class="lang-rb prettyprint-override"><code>my_dog = Animal.new my_dog.happy # =&gt; &quot;I cheer&quot; </code></pre> <p>Hope this help as I also learned something new today.</p> <p>To learn further, you can use <code>irb</code> and take a look at Method object.</p>
41,740
<p>Where can I find the specifications for the various C# languages?</p> <p><em>(EDIT: it appears people voted down because you could 'google' this, however, my original intent was to put an answer with information not found on google. I've accepted the answer with the best google results, as they are relevant to people who haven't paid for VS)</em></p>
<p><a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="noreferrer">Microsoft's version</a> (probably what you want)</p> <p><a href="http://www.ecma-international.org/publications/standards/Ecma-334.htm" rel="noreferrer">The formal standardised versions</a> (via ECMA, created just so they could say it was "standardised" by some external body. Even though ECMA "standards" are effectively "Insert cash, vend standard").</p> <p><a href="http://www.ecma-international.org/publications/standards/Stnindex.htm" rel="noreferrer">Further ECMA standards</a></p>
<p>From : <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx</a></p> <p>In .doc format:</p> <p><a href="http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc" rel="nofollow noreferrer">http://download.microsoft.com/download/3/8/8/388e7205-bc10-4226-b2a8-75351c669b09/CSharp%20Language%20Specification.doc</a></p>
15,553
<p>It seems like there should be something shorter than this:</p> <pre><code>private string LoadFromFile(string path) { try { string fileContents; using(StreamReader rdr = File.OpenText(path)) { fileContents = rdr.ReadToEnd(); } return fileContents; } catch { throw; } } </code></pre>
<p>First of all, the title asks for "how to write the contents of strnig to a text file" but your code example is for "how to read the contents of a text file to a string.</p> <p>Answer to both questions:</p> <pre><code>using System.IO; ... string filename = "C:/example.txt"; string content = File.ReadAllText(filename); File.WriteAllText(filename, content); </code></pre> <p>See also ReadAllLines/WriteAllLines and ReadAllBytes/WriteAllBytes if instead of a string you want a string array or byte array.</p>
<p>File.ReadAllText() maybe?</p> <p>ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/4803f846-3d8a-de8a-18eb-32cfcd038f76.htm if you have VS2008's help installed.</p>
6,373
<p>Many 3D printers employ a GT2 band for the <em>y</em>-axis plate and the printhead in the <em>x</em>-axis carriage.</p> <p>However, there seems to be the obvious disadvantages of:</p> <ul> <li>stretching (and need for adjustment) and;</li> <li>possibly slight inaccuracy, or &quot;wobble&quot; (for want of a better word (as wobble is often used in describing <em>z</em>-axis deviations)), due to the elasticity of the band.</li> </ul> <p>Is there any particular reason why GT2 is used over a straight forward rack and pinion system?</p> <p><a href="https://i.stack.imgur.com/EUTlt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EUTlt.jpg" alt="Rack and pinion" /></a></p> <p>In particular, for the <em>y</em>-axis plate, as a rack would appear to me, be:</p> <ul> <li>easy to install;</li> <li>more accurate, and;</li> <li>require a lot less adjustment<sup>1</sup>.</li> </ul> <p>If the rack is made from aluminium, surely <em>weight</em> can not be a major factor... or can it?</p> <p>Is <em>cost</em> a factor? A pinion seems to cost around \$10-\$15 (650 B\$, here in BKK, Thailand), which is obviously more than a reel of GT2 and a couple of GT2 pulleys.</p> <p>Would the <em>rigidity</em> of the rack be less forgiving of an imperfectly aligned axis, something which the GT2 band and pulleys combination would not be so affected by?</p> <hr /> <h3>TL;DR</h3> <p>Which of these factors cause designers to use GT2 en lieu of a rack?</p> <ul> <li>Accuracy</li> <li>Weight</li> <li>Cost</li> <li>Maintenance</li> <li>Tolerence of non-square axes, manufacturing errors.</li> </ul> <hr /> <p><sup>1</sup> Maybe constant adjustment is not required on an everyday basis, but the tension would still need to be checked now and again, whereas a pinion would not have this requirement.</p>
<p>With a belt system, the belt engages roughly half the pulley. This, and the tension in the belt, ensures the belt always engages the pulley tightly. A belt and pulley system is thus relatively forgiving.</p> <p>With a rack and pinion system, only a few teeth engage at any given time. To avoid backlash and get the same kind of "tight" engagement, both the gear and the rack need to be made with very high precision. The carriage also needs to be very well constrained, because any wobble of the rack relative to the gear introduces backlash (or binding). Moreover, you also need to keep the rack and pinion well lubricated lest they wear out prematurely.</p> <p>Given that belt and pulley work well enough, I don't see why you'd need to move to rack and pinion. The main advantage of rack and pinion is that the rack isn't elastic. The maximum length of a belt system is limited by its elasticity, but given we aren't building meter-long 3D printers anyway, that advantage of rack and pinion does not apply.</p>
<p>The answer so others can understand is that it's cheap and simple to run with a belt. Much of the 3D printers these days either stem from the sintering systems that were developed years ago and things that rose out of the RepRap community where a Lead Screw that had the precision needed to do proper 3D printing at decent speeds was out of reach for most of the community.</p> <p>It's a bit of, &quot;we've always used belts,&quot; and then people come up with all sorts of stories to validate the dubious take to begin with.</p> <p>At one point in time (to be specific...around a couple of years BEFORE the question was asked here...) the costs of a lead/belt-screw system for anything other than a Z axis solution for a Cartesian or a Core-XY was prohibitive for a hobbyist or a system bought off shelf or build by them.</p> <p>It was too hard and expensive to get straight enough parts with precision to actually make anything other than small toy systems with those. We wouldn't get into racks as they were even MORE expensive. With the precisions we were previously working on and with in the community at the time this question was originally posed, it was something that only made sense for select solutions.</p> <p>As you scale larger (Hey, we're now professionally making HUGE parts with this stuff) it makes much, much more sense. For certain classes of manufacturing...it actually makes sense with certain filaments to make short run parts for almost ANYTHING, including things in the automotive space. At that juncture, prototyping, fixing &quot;impossible&quot; to repair situations on older cars, etc. makes some sense to get more precision or vastly larger size. Desireable becomes the ability to make printers with volumes up to 2 meters in size. Professional space? Maybe. But telling people that a pinion isn't making any sense? Heh...hardly. Same goes for lead/ball-screws. Several have made incredible printers fairly cheaply that can print seemingly impossible print runs (Hung at a 45 degree angle in mid air and print...) with some of this stuff. Is it cheaper? No. Does it make sense? Possibly. Especially if one wants to DIY a massive print volume printer (<em><strong>waves hand</strong></em>). I want a meter and a half cubed on a side print volume that I can enclose to crank out ASA prints of Smart body panels, for example... You're not getting that with belts- too stretchy, even with PU steel core belts.</p> <p>Frame it in from a relative cost perspective (It's only going to be about 25% more costly on a DIY or commercial product with a speed upside and precision that might make it WORTH that...but understand that an Ender 3 designed that way will run 350 dollars instead of the 200 or thereabouts it currently runs) and you're going to be more realistic and honest on the question's answer. Saying it isn't practical...even from when the post originated isn't being exactly forthright in this day and age- and disregards that a person MIGHT just be willing to spend the more money for the precision, etc.</p>
509
<p>I'm getting a syntax error (undefined line 1 test.js) in Firefox 3 when I run this code. The alert works properly (it displays 'work') but I have no idea why I am receiving the syntax error.</p> <p>jQuery code:</p> <pre><code>$.getJSON("json/test.js", function(data) { alert(data[0].test); }); </code></pre> <p>test.js:</p> <pre><code>[{"test": "work"}] </code></pre> <p>Any ideas? I'm working on this for a larger .js file but I've narrowed it down to this code. What's crazy is if I replace the local file with a remote path there is no syntax error (here's an example):</p> <p><a href="http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?" rel="noreferrer">http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&amp;tagmode=any&amp;format=json&amp;jsoncallback=?</a></p>
<p>I found a solution to kick that error</p> <pre><code>$.ajaxSetup({'beforeSend': function(xhr){ if (xhr.overrideMimeType) xhr.overrideMimeType("text/plain"); } }); </code></pre> <p>Now the explanation: In firefox 3 (and I asume only firefox THREE) every file that has the mime-type of "text/xml" is parsed and syntax-checked. If you start your JSON with an "[" it will raise an Syntax Error, if it starts with "{" it's an "Malformed Error" (my translation for "nicht wohlgeformt"). If I access my json-file from an local script - no server is included in this progress - I have to override the mime-type... Maybe you set your MIME-Type for that very file wrong...</p> <p>How ever, adding this little piece of code will save you from an error-message</p> <p><strong>Edit:</strong> In jquery 1.5.1 or higher, you can use the mimeType option to achieve the same effect. To set it as a default for all requests, use</p> <pre><code>$.ajaxSetup({ mimeType: "text/plain" }); </code></pre> <p>You can also use it with $.ajax directly, i.e., your calls translates to</p> <pre><code>$.ajax({ url: "json/test.js", dataType: "json", mimeType: "textPlain", success: function(data){ alert(data[0].test); } }); </code></pre>
<p>Try renaming "test.js" to "test.json", which is what <a href="http://en.wikipedia.org/wiki/JSON" rel="nofollow noreferrer">Wikipedia</a> says is the official extension for JSON files. Maybe it's being processed as Javascript at some point.</p>
43,502
<p>I have to give a general note to some huge Java project for which I have but little visibility and I was wondering if there were any guidelines for determining:</p> <ul> <li>what number of classes per package can be considered right, to low, or to high (this project has 3.89 classes per package, which seems a bit too small for me), </li> <li>number of methods per class? (this project has 6.54 methods per class...</li> <li>number of lines per method? (this project has about 7 lines per method (seems pretty good to me, maybe a bit low))</li> </ul> <p>I should note that this question is only dealing with volumetry. I have a bunch of reports from quality tools (checkstyle, jdepend, cpd, pmd, ncss) that give me more vision about code redundancy, classes usage, bugs, etc.</p>
<p>Steve McConnell in his book Code Complete recommends about 7 methods per class and no more lines in a method then can be viewed in a single screen without scrolling.</p> <p>I'm not sure about classes per package.</p> <p>I would highly recommend reading Code Complete for more information on such topics.</p>
<p>(note: tl;dr available at the very bottom for my real opinion)</p> <p>I'm not going to quote any big name and say that's the right answer because it's always very case dependant how you do all this stuff. For example the number of methods: If you're making a control software for modern HD LCD TV's remote controller which has about 40-50 buttons, how can you break that down into classes <strong>coherently</strong> so that you only have like, say, 7 methods per class?</p> <p>Personally I like to keep all the methods of one accessor level in one class which means some utility classes may end up having hundreds of methods but in my opinions it's easier to do something like <code>StringUtil.escapeXMLspecialCharacters(someString)</code> than <code>StringUtil.XML.escapeSpecialCharacters(someString)</code> or <code>XMLUtil.escapeSpecialCharacters(someString)</code>. While these all are seemingly OK solutions, the first one thrives (at least in my mind, that is!) because it's simple and very easy way to access that method: You don't have to think if the string you're handling contains XML or XHTML or JSON or whatever, you'll just pick one method from the general group of methods and that's it.</p> <p>Keeping on the previous TV remote analogy, lets assume you do split them to various classes anyway. If we allow ourselves to have 7 of such methods per class on average and manage to group the buttons on the remote to sensical groups like <code>MenuButtons</code>, <code>AdjustmentButtons</code> and 'NumberSelectorButtons', we end up with 8 or so classes. That's not a bad thing actually, but it gets slightly confusing easily especially if they're not divided to sensical groups with great care. Just imagine the rants around your TVRemotes'R'Us Inc. office: "Who says the power on/off button is a control button?" "Who's the joker who put volume +/- to menu buttons? PRE/CH <em>(the button which switches between current and previous channel and/or image source)</em> button isn't a number button!" "The guide button opens both tv guide AND navigational menu depending on context, what are we going to do with it!?"</p> <p>So as you can hopefully see from this example, using some arbitrary number to limit yourself could introduce some unneeded complexity and break the logical flow of the application.</p> <p>Before I throw in my last two cents, one thing about the number of lines per method: Think code as blocks. Each loop is a block, each conditional is a block and so on and so forth. What is the minimum amount of these blocks needed for a unit of code which has a single responsibility? That should be your limiter, not the desire to have "Seven everywhere." from number of classes in package, methods in classes and lines of code in methods.</p> <p>And here's the <strong>TL;DR</strong>:</p> <p>So, my real opinion is actually this: The number of classes in package should be fairly low. I've been lately starting to do the following but I'm not sure if I'll keep up to it:</p> <ul> <li>Package <code>foo</code> contains interfaces and other common classes for implementations.</li> <li>Package <code>foo.bar</code> contains implementation of said interfaces for function <code>bar</code></li> <li>Package <code>foo.baz</code> contains implementation of said interfaces for function <code>baz</code></li> </ul> <p>This usually means my whole structure has a coherent (and most likely low) number of classes and by reading the top level class interfaces (and their comments) I should be able to understand the other packages too.</p> <p>Methods per class: All which are needed as I explained above. If your class can't live without 170 methods, then let it have them. Refactoring is a virtue, not something that can be applied all the time.</p> <p>Lines per method: As low as possible, I usually end up with 10 to 25 lines per method and 25 is a bit high for me so I'd say 10 is a good balance point for that.</p>
40,295
<p>/dev/random and /dev/urandom use environmental noise to generate randomness. </p> <p>With a virtualised server there can be multiple instances of an Operating System on one hardware configuration. These operating systems will all be sourcing their randomness from the same environmental noise.</p> <p>Does this mean as a group the random number generators strength is reduced as all OS instances are basing their calculations of the same input? Or, is the environmental noise partitioned out so that sharing doesn't occur?</p> <p>If the latter is true, I can see this reducing the effectiveness of /dev/urandom because it reuses its internal pool and with less environmental input, reduces entropy.</p> <p>/dev/random should be ok because it blocks until enough noise is acquired... unless of course the OS instances are all sharing the input.</p> <p>So, the question: What is the impact of virtualisation on cryptographically strong random number generators, specifically those that use environmental noise?</p>
<p>I couldn't find any references quickly, but it would seem to me that the entropy is derived from the kernel data structures for the devices, not the actual devices themselves. Since these would be independent regardless of virtualization, I suspect the answer is not much.</p> <p>[EDIT] After peeking at the kernel source (actually patch history), it looks like Linux, at least, gathers entropy from keyboard presses, mouse activity, interrupt timing (but not all interrupts), and block device request finishing times. On a virtualized system, I suspect that mouse/keyboard events would be pretty low and thus not contribute to the entropy gathered. Presumably this would be offset by additional network I/O interrupt activity, but it's not clear. In this respect, I don't think it differs much from non-VM server.</p>
<p>Thanks. </p> <p>From what I understand that a system that relies on network I/O for entropy is susceptible to man in the middle attacks. I found the <a href="http://lwn.net/Articles/283103/" rel="nofollow noreferrer">follow article</a> that discusses appropriate sources of entropy. Their suggestion is to remove network I/O from the Linux kernel because of its susceptibility.</p> <p>I think that means that there is possibility for exploiting the common hardware in a virtualised environment. The chance is increased if network I/O is used. Otherwise it is low enough not to be of a concern for all but the most secure of applications. In such instances it probably safer to host your own application anyway.</p>
28,871
<p>I'm considering using Castle Windsor's Interceptors to cache data for helping scale an asp.net site.</p> <p>Does anyone have any thoughts/experience with doing this?</p> <p>Minor clarification: My intention was to use Windsor to intercept 'expensive' calls and delegate to MemCacheD or Velocity (or another distributed cache) for the caching itself.</p>
<p>I've been using caching decorators (not interceptors) with Windsor and they work great.</p> <p>Interceptors are good for this as well, see <a href="http://ayende.com/Blog/archive/2007/03/11/AOP-With-Windsor-Adding-Caching-to-IRepositoryT-based-on-Ts.aspx" rel="nofollow noreferrer">this</a> for example.</p>
<p>Windsor is great, but why use that for caching when you have several built in ways to cache data. Windsor has its foundation in other areas not necessarily caching. From the cache object to session to cookies. There are many ways to cache. More importantly in large applications you end up needing distributed caching. MS is working on a product for that and there are a couple good vendors out there that have products on the market. </p>
12,003
<p>Still struggling to understand what best practices are with respect to macros. I'm attempting to write a macro which defines packages on the fly.</p> <pre><code>(defmacro def-dynamic-package (name) `(defpackage ,(intern (string-upcase name) "KEYWORD") (:use :common-lisp))) </code></pre> <p>This works fine only for expressions such as:</p> <pre><code>(def-dynamic-package "helloworld") </code></pre> <p>But fails miserably for something like this:</p> <pre><code>(defun make-package-from-path (path) (def-dynamic-package (pathname-name path))) </code></pre> <p>or</p> <pre><code>(defun make-package-from-path (path) (let ((filename (pathname-path))) (def-dynamic-package filename))) </code></pre> <p>I understand how most basic macros work but how to implement this one escapes me.</p>
<p><strong>defpackage</strong> is a macro. As such, it's expanded at compile-time, not run-time. What you want is something that is called at run-time in order to make a new package. Therefore, <strong>defpackage</strong> can't do anything for you.</p> <p>Fortunately, there's also <strong><a href="http://www.lispworks.com/documentation/HyperSpec/Body/f_mk_pkg.htm#make-package" rel="noreferrer">make-package</a></strong>, which provides <strong>defpackage</strong>'s features as a function. Use it instead of <strong>defpackage</strong>.</p>
<p>Failure is to be expected here, because a macro is used when its argument should not be evaluated.</p> <p>In your first make-package-from-path, the def-dynamic-package will receive as argument a list that is EQUAL to the value of the following expression:</p> <pre><code>(list 'pathname-name 'path) </code></pre> <p>In your case, you only want a function:</p> <pre><code>(defun def-dynamic-package (name) (defpackage (string-upcase name) (:use :common-lisp))) </code></pre> <p>BTW, if you check the <a href="http://www.lispworks.com/documentation/HyperSpec/Front/index.htm" rel="nofollow noreferrer">CLHS</a>, you'll see that the first argument of <a href="http://www.lispworks.com/documentation/HyperSpec/Body/m_defpkg.htm" rel="nofollow noreferrer">defpackage</a> needn't be a symbol, but any <a href="http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_s.htm#string_designator" rel="nofollow noreferrer">string designator</a>.</p>
35,355
<p>Not sure if there is any Firefox add-on tool for checking JavaScript syntax, var declaration, or even pre-compiling available? </p> <p>I find out is very difficult to debug JavaScript in a web html page. I have to add some script there. When the scripts get very big or long, it stops working. Basically, there must be some bugs. It is very frustrating even the load event stop working. I do need some good tools to find out the bugs.</p> <p>I have tried FireBug. It is good but not enough. Maybe I don't know all its features. Anyway, I need any good suggestions. </p>
<p>This page may help you a bit as it also contains a screencast.</p> <p><a href="http://asymptomatic.net/2007/08/22/2643/debugging-javascript-in-firefox-with-firebug-and-breakpoints" rel="nofollow noreferrer">Debugging Javascript in Firefox with Firebug</a></p>
<p>Hi Gene: you could change one variable <strong>option.maxerr</strong> inside your <em>jslint.js</em> file into the number you want.</p> <p>The default value is 50, you could change it to 500 or 1000 to suite your taste.</p>
31,482
<p>Howdy... here on my local LAN, I have a Windows Server 2k8 box with SQL Server 2k8 installed. I can connect to the database engine using the SSMS tool on the server, but attempting to connect to the database engine from a remote machine (also on the same LAN), the connection fails with the usual generic message about not being able to contact the server. </p> <p>Before you offer the "usual" solutions, please let me say that I have already verified the instance name, verified that the instance is configured to allow remote connections, verified that the SQL Browser service is running, and verified that neither the Windows Firewall on the server nor on the client is getting in the way (tested with both completely disabled). I've even attempted to connect via the servers IP address on the LAN rather than it's Windows hostname. :) </p> <p>Does anyone know of any "uncommon" reasons (or even common ones that I failed to mention here) why I would be unable to connect to the database engine from a remote machine?</p> <p>Thanks.</p>
<p>In SQL Server Configuration Manager in Network Configuration-> Protocols enable TCP/IP or other protocols that you need. The default is: only Shared Memory. </p>
<p><a href="http://blogs.msdn.com/sql_protocols/archive/2006/09/30/SQL-Server-2005-Remote-Connectivity-Issue-TroubleShooting.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sql_protocols/archive/2006/09/30/SQL-Server-2005-Remote-Connectivity-Issue-TroubleShooting.aspx</a></p>
37,248
<p>I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later. When users upload files to my server, PHP tells me what filetype it is based on the extension. However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server. Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype?</p>
<p><a href="http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files" rel="noreferrer">Magic number</a>. If you can read first few bytes of a binary file you can know what kind of file it is. </p>
<p>On a unix system, capturing the output from the 'file' command should provide adequate info.</p>
22,400
<p>I have a C# module responsible for acquiring the list of network adapters that are "connected to the internet" on a windows Vista machine. The module uses the "<a href="http://msdn.microsoft.com/en-us/library/aa370803(VS.85).aspx" rel="nofollow noreferrer">Network List Manager API</a>" (or NLM API) to iterate over all network connections and returns all those for which the IsConnectedToInternet value is true.</p> <p>I received some suggestions for the implementation of this module in this <a href="https://stackoverflow.com/questions/38864/how-do-you-find-out-which-nic-is-connected-to-the-internet">SO question</a></p> <p>To test this module I've decided to write a helper that returns the list of internet connected interfaces based on another logic, so it would be a sort of a "reality check" for the original module's logic. Note that for the test helper I am willing to use detection methods that might be considered bad practice for production code (e.g. relying on some internet resource like "Google" to be available - in case it shuts down, blocked by our internal firewall etc. it's relatively easy to fix the test as opposed to a deployed product base).</p> <p>The alternative detection method I chose was to try to connect to "www.google.com:80" with a TcpClient. My problem: When I have more than one connected adapter (e.g. both wireless and LAN) the detection method fails for one of them with the error "A connect request was made on an already-connected socket".</p> <p>My question is three fold:</p> <ol> <li><p>How would you go about testing such a module in general? Do you support the idea of doing the same thing in a different way and comparing the results or is it an overkill and I should rely on the system's API? My main problem here, is that it's very hard to pre-configure the system so that I'll know what the expected results are in advance.</p></li> <li><p>What alternative logic would you suggest? One thing that was suggested in the aforementioned question was looking at the routing table - what about considering each adapter that has a routing entry with a destination of 0.0.0.0 as "connected to the internet"? Other suggestions?</p></li> <li><p>Do you understand why I get the "already-connected" error with the current test logic?</p></li> </ol>
<p>I can only answer your question about the unit test.</p> <p>The code you're testing is, in your own words, "a C# module responsible for acquiring the list of network adapters that are 'connected to the internet' on a windows Vista machine. The module uses the 'Network List Manager API' (or NLM API) to iterate over all network connections and returns all those for which the IsConnectedToInternet value is true."</p> <p>If I were writing this module, I would first use an interface for the NLM API, call it...NLMAPIService. Now, for the real code, create an Adapter that implements NLMAPIService and adapts the real NLM API. </p> <p>For testing, create a class FakeNLMAPI that implements NLMAPIService and has all of its data in-memory somewhere, or in an XML file, or whatever. Your module calls methods only on the NLMAPIService, so you don't have to change any "real" code depending on whether you're testing or not.</p> <p>Therefore, in your test setup method, you can instantiate FakeNLMAPI and pass it to your module, and in production, instantiate your NLM API Adapter.</p> <p>I'm going to assume that you can instantiate and modify the object that represents a network connection. If not, you can follow the same pattern for faking the actual network connection object.</p>
<p>UnitTests shouldn't access to external resources. To UnitTest your method, I would stub out the Network List Manager API. </p> <p>You still need an acceptance test layer. In that test environment you should replicate various configurations you expect to support in your environment, setup your own webhosts, routers, machine config. Acceptance testing should be done at the user experience level using a tool like Fitnesse.</p>
23,746
<p>Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?</p>
<p>I don't think there's a better person to answer this than <a href="https://ericlippert.com/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/" rel="noreferrer">Eric Lippert</a> (emphasis in the original): </p> <blockquote> <p>In C#, "volatile" means not only "make sure that the compiler and the jitter do not perform any code reordering or register caching optimizations on this variable". It also means "tell the processors to do whatever it is they need to do to ensure that I am reading the latest value, even if that means halting other processors and making them synchronize main memory with their caches".</p> <p>Actually, that last bit is a lie. The true semantics of volatile reads and writes are considerably more complex than I've outlined here; in fact <strong>they do not actually guarantee that every processor stops what it is doing</strong> and updates caches to/from main memory. Rather, <strong>they provide weaker guarantees about how memory accesses before and after reads and writes may be observed to be ordered with respect to each other</strong>. Certain operations such as creating a new thread, entering a lock, or using one of the Interlocked family of methods introduce stronger guarantees about observation of ordering. If you want more details, read sections 3.10 and 10.5.3 of the C# 4.0 specification.</p> <p>Frankly, <strong>I discourage you from ever making a volatile field</strong>. Volatile fields are a sign that you are doing something downright crazy: you're attempting to read and write the same value on two different threads without putting a lock in place. Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given chunk of memory at a time, and so on. The number of situations in which a lock is too slow is very small, and the probability that you are going to get the code wrong because you don't understand the exact memory model is very large. I don't attempt to write any low-lock code except for the most trivial usages of Interlocked operations. I leave the usage of "volatile" to real experts.</p> </blockquote> <p>For further reading see:</p> <ul> <li><a href="https://learn.microsoft.com/archive/msdn-magazine/2005/october/understanding-low-lock-techniques-in-multithreaded-apps" rel="noreferrer">Understand the Impact of Low-Lock Techniques in Multithreaded Apps</a></li> <li><a href="http://joeduffyblog.com/2010/12/04/sayonara-volatile/" rel="noreferrer">Sayonara volatile</a></li> </ul>
<p>multiple threads can access a variable. The latest update will be on the variable</p>
9,791
<p>PNG images appear "fuzzy" in flash CS3. They are very blocky and appear unanti-aliased (if that is a word) Does anyone have a fix for this? Is there some setting I'm missing? </p>
<p>Are you loading them into your SWF through a loader? Or are they imported into your library as bitmap symbols? If they are loaded in try calling Bitmap.smoothing = true; or if they are in your library go to the Bitmap's properties and click Allow smoothing.</p> <p>Other than that I would check to make sure you don't have some crazy above 1 alpha setting or that you aren't messing with the scale of it in your code at any time. Those two options tend to mess with bitmap images fuzziness.</p> <p>If all else fails you'd probably want to look into turning your images into vector based graphics, then they'd always look exactly how you'd want them to regardless of scaling.</p>
<p>Well I tried using image.opaqueBackground = 0x000000; and it seems working fine, antialiasing is much better, however, this beats the idea of a transparent background in the process. This is truly angering, Adobe, do something about it!</p>
22,312
<p>I am looking to buy an Ender-3 Pro, but the place I'm looking to buy from has this picture:</p> <p><a href="https://i.stack.imgur.com/RY2ds.jpg" rel="nofollow noreferrer" title="Confusing 3D printer publicity photo"><img src="https://i.stack.imgur.com/RY2ds.jpg" alt="Confusing 3D printer publicity photo" title="Confusing 3D printer publicity photo" /></a></p> <p>My question is, what is meant by &quot;Junior&quot; in the name?</p> <p>I'm just wondering if this means it's an alternative kind of version for kids or something, or if it's just the name of that type of 3D Printer (e.g. in the way you might have a Junior Hacksaw or something)? I.e. is this the normal Ender V3 Pro?</p>
<p>There is no such thing as a <em>Junior</em><sup>1</sup>, you can see the official Creality range of FDM printers on the <a href="https://www.creality.com/product/fdm-3d-printer" rel="nofollow noreferrer">FDM 3D PRINTER</a> page, on their web site.</p> <p>Upon a cursory comparison of the photo it is one of these:</p> <ul> <li>Ender-3 Max 3D Printer</li> <li>Ender-3 Pro 3D Printer</li> <li>Ender-3 3D Printer</li> </ul> <p>However, the first one can be discounted as the spool holder is missing. So this leaves the last two.</p> <p>Finally, the biggest clue is in the photo itself, as the name is written in the last line: <a href="https://www.creality.com/goods-detail/ender-3-pro-3d-printer" rel="nofollow noreferrer"><em><strong>Ender-3 Pro</strong></em></a>.</p> <p>Nevertheless, given the seller's random &quot;junior&quot; labelling, it is not entirely guaranteed that the printer is, in fact, a Pro.</p> <p>Unless they are super cheap or a renowned seller, then it is probably best to avoid purchasing anything from them. Or contact the seller to see if they would clarify their misleading advert.</p> <hr /> <p><sup>1</sup> The term <em>junior</em> could be an indication of the base level entry of the printer, or a reference to its build size, which, while not small and is pretty standard, it is not as large as some of the more pricey Creality models.</p>
<p>That is an Ender 3, with the vertical PSU, the older interface, and many tweaks like the drawer and filament loading knob isn't present.</p> <p>Consider the Ender 3 V2 instead, which is an iteration on the same basic design and is newer.</p> <p>Personally I found it cheaper to buy the V2 direct from Creality's website than to buy the older model from a local or other online seller, and it had free freight from China, and arrived in about 3 weeks.</p>
2,065
<p>It seems that when filament throughput is increased (by increasing movement speed or extrusion width/height), printing temperature also has to be increased to compensate, because the filament will have less time to spend in the melting zone. That much seems clear from practical experience. But I have two questions (or to be more precise, one question on two levels):</p> <ol> <li><p>Is there a good rule of thumb for this, to help people calibrate their settings?</p></li> <li><p>How much do we know about the formula governing this behavior? Can we calculate the required hotend temperature <em>precisely</em> based on the increased throughput?</p></li> </ol> <p>For anyone who has studied physics / thermodynamics, this is probably simple stuff. But has the work been done for 3D printing specifically, in a way that is practically applicable?</p> <p>I share the following train of thought to start off with. Let me know if I make any errors in reasoning.</p> <ul> <li><p>Presumably, every material has an optimal printing temperature just above its melting point.</p></li> <li><p>But the thermistor doesn't read filament temperature. It reads the heat block temperature.</p></li> <li><p>Below a certain throughput, the temperature of the filament will have time to equalize with the temperature of the heat block before it leaves the nozzle.</p> <ul> <li>For those slow speeds, heat block temperature should be set exactly to the material's optimal printing temperature.</li> </ul></li> <li><p>For greater speeds, however, heat block temperature will always have to be higher than the mark, because the filament doesn't have time to equalize.</p> <ul> <li>At that point, it becomes a balancing act. Find the best heat block temperature (°C) given a rate of throughput (mm³/s), the optimal printing temperature for a given material (°C), the volume of the melting zone (mm³) and <em>&lt; some other property of the material ></em>, which determines how fast it heats up. I don't know what that last property is, nor can I come up with the proper unit. The material probably approaches the temperature of the environment asymptotically. This is where thermodynamics comes in, I guess.</li> </ul></li> <li><p>Theoretically, running filament also cools down the heat block, but we can ignore this. If this effect is significant at all (is it?), this is already compensated for by the PID controller.</p></li> </ul> <p>I'm almost certainly missing some key insights. I'm curious to know what work has been done.</p>
<p>I think I see what you're asking, but I think you may be thinking about it incorrectly. It's really all about heat being added to the system at the same rate that it's leaving. The heat block is there as a heat reservoir from which the filament draws heat for the glass transition. The heat in that reservoir is maintained by cycling the heating coil to add energy (more heat) to the systems as it's lost.</p> <p>In the very local vicinity of the nozzle, the temperature will decrease slightly as it's being transferred to the filament, but because the heat block is massive in comparison to that drain, and because the heat block is a good thermal conductor that temperature reduction is very small. </p> <p>I do not know what tolerance and hysteresis are built into the temp controller, but think the variation is likely small. The difference in additional heat required (more energy into the system) for any practical difference in feed rates (40 instead of 60) is thus likely to be very small compared to the filament cooling experienced immediately after it leaves the nozzle.</p> <p>Bottom line: the adjustment you would want to make is not to increase the temp, but increase the duty cycle of the heating element to maintain the desired temperature.</p>
<p>I see an answer not a question. It's a balancing act and there is no predefined formula. Trial and error. Keep a spread sheet. I'll dwell on this a bit.. but as someone who did speed sprinting there's really nothing else to be said other than buy an e3d and the volcano upgrade. </p> <p>You will calibrate one at a time. Thin wall. Then find solid infill is the true thermal barrier. Then sparse. You will tweak with layerheights. Get thicker nozzles 0.8+. It's a game of spinning plates. Each change will wack out another. </p> <p>Last you will get to where I did. You move so fast 5 layers down your print is still molten and moving. Especially on small parts. </p>
479
<p>Is there a classification of method of control most (FDM) 3D printers fall under?</p> <p>From a 1986robotics textbook<sup>ref</sup> I was reading they defined three classes of control:</p> <p>1) Pick and place</p> <p>2) Point to point</p> <p>3) Continuous path</p> <p>However, both point to point and continuous path control are stated as requiring servo motors.</p> <p>I know that the majority of 3D printers are actuated with stepper motors as opposed to servo. Does the continuous path classification still apply? Or is there another classification?</p> <p>ref - <em><a href="https://www.springer.com/gp/book/9789401167703" rel="nofollow noreferrer">Todd, D.J.(Ed.):Fundamentals of Robot Technology: An Introduction to Industrial Robots, Teleoperators and Robot Vehicles - Kogan Page 1986</a></em></p>
<p>The question is if robots classification terminology the textbook sketches applies to 3D printing?</p> <p>Servos (closed loop) are used in robots to guarantee position (you don't want to accumulate an error after repetitive movement), most 3D printers use open loop steppers that are instructed on a point to point basis through G-code instructions, implying that the use of servos is not a "requirement" for point to point control.</p> <p>It <strong>is</strong> a requirement if you want to be absolutely sure that the position is reached. In 3D printing where the loads are generally low, this requirement is frequently dropped. But, there are printers that use servo control. </p> <p>Note that many CNC machines (operating at much higher loads than a 3D printer) even don't use servo's but (open loop) steppers, these are generally larger and more powerful (more torque).</p>
<p>3D Printers fall under additive manufacturing and then can be classified by the material first. Usually, the material dictates entirely what the design looks like and it would be foolish to not differentiate what you look at by this first. For some materials, there are a couple of subtypes that tell us about which method for fusing the material is used, but usually, there is just one.</p> <ul> <li>light curing resin <ul> <li>projected light</li> <li>Laser</li> </ul></li> <li>Paste, gel or air curing resin <ul> <li>direct deposit from syringe</li> </ul></li> <li>Foil <ul> <li>Laser1</li> </ul></li> <li>Powder <ul> <li>Laser</li> </ul></li> <li>Filament (FFF/FDM) <ul> <li>direct deposit</li> </ul></li> </ul> <p>Of all these printers, only the FDM/FFF Group has a large diversity in how they are designed on the outer side, with the main 4 designs (and one example) being</p> <ul> <li>Cantilever (TronXY X1)</li> <li>Core-XY (Hypercube)</li> <li>Portal (Prusa)</li> <li>Delta (Kossel)</li> </ul> <p>Now comes the kicker: Most FDM/FFF Printers do use only stepper motors and use G-Code that is derived from CNC - just like the whole idea of FDM was invented as <em>reverse CNC</em>. Only very few use an encoder at all. Marlin, the main firmware used in 3D printers, executes usually <em>point-to-point</em> instructions (<a href="http://marlinfw.org/docs/gcode/G000-G001.html" rel="nofollow noreferrer"><code>G0 X10 Y10 Z0 E5</code></a>), but some implementations are able to perform arcs (<a href="http://marlinfw.org/docs/gcode/G002-G003.html" rel="nofollow noreferrer"><code>G2 E7.85 R5 X-5 Y5</code></a>). Usually, printers run in <em>relative coordinates</em> (to the last position of the nozzle/tool), but for some operations <em>absolute coordinates</em> (mainly start or end codes) are used. </p> <p>Among the printers that use servos instead of steppers are, to my knowledge, mostly laser-based systems.</p>
1,510
<p>I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'.</p> <p>However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra).</p> <p>"Google may know, but if it does, it ain't telling, or I'm not looking in the right place"</p> <p><strong>UPDATE:</strong></p> <p>It seems to work with latest CTP <a href="http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&amp;displaylang=en" rel="nofollow noreferrer">update 1.9.6.2</a></p> <p><strong>UPDATE2:</strong></p> <p>I have since experienced another error: </p> <pre><code>FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities. </code></pre> <p>If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project.</p>
<p>Answer from MS:</p> <p><em>There is a CTP update 1.9.6.2 that fixed some --standalone bugs.</em></p> <p>I'm reinstalling now...</p> <p>UPDATE: Works for me - so the my accepted answer is <strong>download CTP update 1.9.6.2</strong>.</p>
<p>F# manual: <a href="http://research.microsoft.com/fsharp/manual/compiler.aspx#Standalone" rel="nofollow noreferrer">Statically linking the F# library using "--standalone"</a></p> <p>Did you try to run peverify.exe utility?</p>
9,661
<p>My present contract engagement is at a large E-Commerce company. Their code base which has origins going back to .Net 1.0 has caught me by surprise to contain many issues that raise the level of smell beyond the last crap I took. </p> <p>That notwithstanding and trying to diffuse my level of distraction from it, I go along merrily trying to add in features to either fix other problems or extend more crap. Where I touch the DAL/BLL the time it will take to fix the aforementioned will be done. However I wanted to get a vote of confidence from the experts to get some assurance of not wasting the clients time or worse having my credibility voted down by touching "stuff that works". Of course unit testing would solve or at least soften this worry. Perhaps this should also be added to the wtf.com?</p> <pre><code>Public Function GetSizeInfoBySite(ByVal siteID As String) As IList Dim strSQL As String = "YES INLINE SQL!! :)" Dim ci As CrapInfo Dim alAnArrayList As ArrayList Dim cn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString")) Dim cmd As New SqlCommand(strSQL, cn) cmd.Parameters.Add(New SqlParameter("@MySiteID", SqlDbType.NVarChar, 2)).Value = siteID cn.Open() Dim rs As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection) While rs.Read() ci = New CategoryInfo(rs("someID"), rs("someName")) If IsNothing(alAnArrayList) Then alAnArrayList = New ArrayList End If alAnArrayList.Add(ci) End While rs.Close() Return CType(alAnArrayList, IList) End Function </code></pre> <p>Does anyone see problems with this aside from the inline SQL which makes my gut churn? At the least wouldn't you ordinarily wrap the above in a try/catch/finally which most of us knows has been around since .Net v1.0? Even better would'nt it be wise to fix with Using statements? Does the SQLDataReader close really encapsulate the connection close automagically? </p>
<p>Nothing wrong with inline sql if the user input is properly parameterized, and this looks like it is. </p> <p>Other than that, yes you do need to close the connections. On a busy web site you could hit your limit and that would cause all kinds of weirdness.</p> <p>I also noticed it's still using an arraylist. Since they've moved on from .Net 1.0 it's time to update those to generic <code>List&lt;T&gt;</code>'s (and avoid the call to CType- you should be able to DirectCast() that instead).</p>
<p>If you were using c# I would wrap the datareader creation in a using statement but I don't think vb has those?</p>
36,363
<p>Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.</p> <p>Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.</p> <p>So my egg controller will look some thing like this:</p> <pre><code>public class EggController : Controller { public void Add() { //do stuff RenderView("CreateEgg", viewData); } public void Create() { //do stuff RenderView("ListEggs", viewData); } } </code></pre> <p>So my first page will have a url of something like <a href="http://localhost/egg/add" rel="nofollow noreferrer">http://localhost/egg/add</a> and the form on the page will have an action of:</p> <pre><code>using (Html.Form&lt;EggController&gt;(c =&gt; c.Create()) </code></pre> <p>Meaning the second page will have a url of <a href="http://localhost/Egg/Create" rel="nofollow noreferrer">http://localhost/Egg/Create</a>, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of <a href="http://localhost/Egg/List" rel="nofollow noreferrer">http://localhost/Egg/List</a> would make more scene. How do I achieve this without making my view or action names misleading?</p>
<p>The problem is your action does two things, violating the Single Responsibility Principle.</p> <p>If your Create action redirects to the List action when it's done creating the item, then this problem disappears.</p>
<p>ActionVerbs Outlined in Scott Gu's <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx" rel="nofollow noreferrer">post</a> seem to be a good approch;</p> <p>Scott says:</p> <blockquote> <p>You can create overloaded implementations of action methods, and use a new [AcceptVerbs] attribute to have ASP.NET MVC filter how they are dispatched. For example, below we can declare two Create action methods - one that will be called in GET scenarios, and one that will be called in POST scenarios</p> </blockquote> <pre><code>[AcceptVerbs("GET")] public object Create() {} [AcceptVerbs("POST")] public object Create(string productName, Decimal unitPrice) {} </code></pre>
5,934
<p>I've been looking into this, but:</p> <ol> <li>I'm not certain how to configure my multimeter; </li> <li>I don't know how to keep the voltage going, and;</li> <li>I don't know how to keep the multimeter connected to the VMOT?</li> </ol> <p>I'm told you're supposed to aim for about 1&nbsp;A.</p>
<p>Generally speaking voltage on stepstick output should be around 1V. </p> <p>To imagine more or less what the current and what the voltage is, you can think about it in the same way as about water.</p> <p>The wire is more or less the same as the pipe. The voltage can be imagined as (sort of) the height from which the water flows but the current can be imagined as an amount of water which flows. To simplify things we assume that all our pipes are closed into circuit and we have pump/battery and we have a motor which is a reverted pump ;) and finally we have our stepstick which is a tap in our model.</p> <p>So no matter what the height (voltage) is we know that tap (stepstick) will pass some amount (current) of water. We can drive it turning tap or turning a potentiometer on the stepstick PCB.</p> <p>So we got it. Principles (deadly simplified) are now clear. <a href="https://learn.sparkfun.com/tutorials/voltage-current-resistance-and-ohms-law/voltage" rel="nofollow noreferrer">See here for more details</a></p> <p>Getting back to your question. You have to know what is your stepstick reference voltage. To make sure about that you have to check out resistor(s) next to main black element on stepstick board. There should be R100 or R200 which are very common.</p> <p>Now you should read data from motor label to know what is proper current for your motor and calculate</p> <p>voltage = motor_current * 8 * resistance_of_resistor</p> <p>So now you know what is proper voltage for your motor and stepstick.</p> <p>You measure voltage between potentiometer and GND (see on the picture)</p> <p><a href="https://i.stack.imgur.com/6LnbU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6LnbU.png" alt="enter image description here"></a></p> <p>If you set and connect everything and start printouts you should check motor temperature. Use your finger. If you can touch motor and hold your finger not more than half a second then probably the voltage set on potentiometer is too high (motor can reach 80° Celsius and it's fine but more will shorten its life span) and you should reduce it a bit (reduce by 5/100 V). If you notice that motor growls or barks then your voltage is probably too low and you can increase it by 5/100V.</p> <p>Too high current will also reduce longevity of stepstick so cool them out with fan.</p> <p><b>Please be noticed.</b></p> <p>Z-axis motors will usually be not too hot as they work less than X and Y but as they are both connected to one stepstick so they need more current - set higher voltage there.</p> <p>Here is a <a href="http://reprap.org/wiki/Stepstick" rel="nofollow noreferrer">reprap.org site</a> to get basic knowledge about stepsticks.</p>
<p>I want to add some points and clarifications to the answer that @darthpixel already has given. Most information you need is in there, I want to give some more practical advice, since that is what I understand you're question is asking for. I'll start with some points on the more theoretical side, though:</p> <ul> <li>notice that the Vref is not a voltage that is passed on to your motor. The described pipe analogy is very good, but the Vref is outside of this analogy. The reference voltage Vref is only used to set the current limit. This seems confusing, but has electronic reasons. One can understand the major (side-)benefit easily: Voltages are very easy to measure externally, because you connect your voltmeter in parallel. If you wouldd want to measure the current, you would need to get your ammeter in series with the circuit.</li> <li>The stepsticks work by supplying the needed current for movement of the motor (current, because it works by creating magnetic fields), the voltage the stepstick supplies is 'just' supplied as high as needed to feed the desired current through your motor (determined by its resistivity/impedance). This just as an add-on.</li> </ul> <p>Now to the practical side and the application of darthpixel's answer and the above:</p> <p>You want to measure the reference voltage to limit the current that produces the torque, but also heats up the motor - let darthpixel's advice be your guide: if you can't touch it because it is too hot, then there is too much current, i.e. Vref is too high). To do so:</p> <ol> <li>Set your multimeter to volts, range can be autorange or something bigger than 2V.</li> <li>Connect one lead of your multimeter to the ground of your Prusa i3 controller board's power input (I use the screw that fastens the ground input of the RAMPS). The other lead goes directly to the center of the trimpot on the Stepstick. I took the best of my paint skills to create an image showing the process: <a href="https://i.stack.imgur.com/6cCzl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6cCzl.jpg" alt="measure Vref scheme" /></a></li> <li>Note the value you read (12V power has to be on)</li> <li>Use an insulated screwdriver and turn the trimpot slightly.</li> <li>Get a new reading by repeating the measurement process.</li> <li>Repeat the whole process until you get the desired Vref.</li> </ol> <p>Warning: While I've had no problems turning the trimpot while everything was switched on (with my DRV8825 drivers), you should switch the power supply off when doing so.</p> <p>The described process allows only for a stepwise and rather slow setting of the Vref, but this is the easiest way I've found. I have read of people that use a crocodile clamp to attach the multimeter to the screwdriver for a readout while turning.</p> <p>If you don't have any idea whether you need more or less current on the motor at the moment, check your resistors on the board and calculate the Vref you should need (see darthpixel's answer for the formula). I would however just do what darthpixel already suggested: figure out the trimpot position by ears and touch: klicking motor: go to higher Vref. Can't touch the motor for more than some seconds: go to lower Vref. It might be a lengthy process, but in the end you'd need to do it anyway to get the best out of the printer!</p>
339
<p>I have a Maker Farm Prusa i3v 8" i just finished building. Initially when i first homed it, it ran fine, it even ran a test g code for movement. The problem is now the Z axis wont move anymore. First i checked for physical issues such as binding or nuts coming out of traps, everything's OK there. In Pronterface i can move x &amp; y no problem, but Z will not move, there is no noise from the steppers. Also unusual is the the Z axis is not on the endstop, its resting on its own in a spot (the hotend is about 2mm off the bed). I ordered some new end stop switches to try on my Z axis....any thoughts? I'll update after switch install.</p>
<p>If you are using Repetier the code to test the endstops is m119 I think. If your z stop is triggered, you may have to invert it in the config.h file. I had this same issue for days before i figured out the control board was reading the switch as normal close instead of normal open. Hope that helps!</p>
<p>Try sending a motion command manually, such as G1 X20 Z10, to eliminate any bugginess from the software interface as a reason for the Z not moving properly when commanded to. Next you could check the park location in Pronterface, perhaps the extruder head is sitting there waiting for the next command.</p>
682
<p>In a C# program, I have an abstract base class with a static "Create" method. The Create method is used to create an instance of the class and store it locally for later use. Since the base class is abstract, implementation objects will always derive from it.</p> <p>I want to be able to derive an object from the base class, call the static Create method (implemented once in the base class) through the derived class, and create an instance of the derived object.</p> <p>Are there any facilities within the C# language that will allow me to pull this off. My current fallback position is to pass an instance of the derived class as one of the arguments to the Create function, i.e.: </p> <pre><code>objDerived.Create(new objDerived(), "Arg1", "Arg2"); </code></pre>
<p>Try using generics:</p> <pre><code>public static BaseClass Create&lt;T&gt;() where T : BaseClass, new() { T newVar = new T(); // Do something with newVar return T; } </code></pre> <p>Sample use:</p> <pre><code>DerivedClass d = BaseClass.Create&lt;DerivedClass&gt;(); </code></pre>
<p>I'm not sure what your design goals are but from what you asked it sounds like it might end up with alot of code smell. I think you should really look into the Inversion of Control(IoC) / Dependency Injection (DI) design patterns that are implemented in numerous frameworks such as Microsoft Unity, Castle Windsor, StructureMap, Ninject, Spring.Net and so forth.</p> <p>I think if you look at using an IoC container it will solve your problem in a much cleaner and loosely coupled way.</p>
38,470
<p>I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. </p> <p>Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name(). </p> <p><strong>An added note</strong>. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name. </p> <p>It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected. </p>
<p><strong>Session Cookies</strong></p> <p>Remember that HTTP is <strong>stateless</strong>, so sessions are tracked on your server, but the <strong>client</strong> has to identify itself with each request. When you declare session_start(), <strong>your browser is usually setting a cookie</strong> (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name.</p> <p>All of this is to say that cookies are playing an active role in your sessions, so if the <strong>client doesn't support cookies</strong>, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating.</p> <p>If cookies aren't an option for your client, you're going to have to find <strong>another way</strong> to pass a session id to the server. This can be done in the <strong>query string</strong>, for example, although it's a considered a bit less private to send a session id in this way.</p> <pre><code>mysite.com?PHPSESSID=10alksdjfq9e </code></pre> <p>How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the <a href="http://us2.php.net/manual/en/session.idpassing.php" rel="noreferrer">PHP website</a>.</p> <p><strong>Sidenote:</strong> Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns.</p> <p><strong>Sidenote:</strong> <em>@Uberfuzzy</em> makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the <a href="http://curl.netmirror.org/docs/manual.html" rel="noreferrer">curl manual</a>.</p>
<p>If you call session_start(), then a session will be created if the client isn't in an existing one. If the client doesn't support (or is configured to ignore) the cookies or querystring mechanism used to maintain the session, a new session will be created on every request.</p> <p>This may bloat your session storage mechanism with unused sessions.</p> <p>It might be a better idea to only call session_start() when you have something to store in the session (e.g. user login, or something else that robots aren't likely to do), if you feel this is likely to be a problem.</p>
20,521
<p>My code is like the following:</p> <pre><code>URLConnection cnx = address.openConnection(); cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); InputStream is = cnx.getInputStream(); </code></pre> <p>Is it ok if I set the headers before I get the <code>InputStream</code>? Will my header be sent, or will the server see the default <code>URLConnection</code>'s user-agent ( if any ) ?</p>
<p>The headers <strong>must</strong> be set prior to getting the <code>InputStream</code> to have any affect - an <code>IllegalStateException</code> will be thrown if the connection is already open.</p> <p>As far as the <code>User-Agent</code> header specifically, it should be sent if it has been set.</p> <p>See the <a href="http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html" rel="noreferrer">URLConnection</a> JavaDoc.</p>
<p>I'd advise against using low-level constructs such as URLConnection. There are plenty of libraries for sending HTTP requests, with the most prominent being Apache HTTP Client. </p>
42,956
<p>I currently am tasked with updating an XML file (persistance.xml) within a jar at a customers site. I can of course unjar the file, update the xml, then rejar the file for redeployment. I would like to kind these command line operations in a Swing App so that the person doing it does not have to drop to the command line. Any thoughts on a way to do this programatically? </p>
<p>The Java API has <a href="http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html" rel="noreferrer">classes</a> for manipulating JAR files.</p>
<p>You can use Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipFile.html" rel="nofollow noreferrer">ZipFile</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipEntry.html" rel="nofollow noreferrer">ZipEntry</a> classes to read the contents of a JAR file, then use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipOutputStream.html" rel="nofollow noreferrer">ZipOutputStream</a> to create a new one.</p>
10,030
<p>I need to set up this scenario: </p> <blockquote> <p>A SQL Server 2005 database will create a transactional replication subscription from another database to populate a set of lookup tables. These lookup tables will then be published as a merge replication publication to the client's SQL Server Mobile.</p> </blockquote> <p>I remember seeing a similar scenario defined in the SQL Server Books Online somewhere, but I was unable to find the link anymore. I hope someone can help me find it, or otherwise point me to any other similar links.</p>
<p>Okay, I managed to get the answers I needed at the <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4093478&amp;SiteID=1&amp;mode=1" rel="nofollow noreferrer">MSDN SQL Server Replication forum</a>.<br /> The article I was looking for is called: <a href="http://msdn.microsoft.com/en-us/library/ms152553(SQL.90).aspx" rel="nofollow noreferrer">Republishing Data</a>.</p> <p>Apparently, it is located within &quot;<strong>Advanced Replication Features and Internals</strong>&quot; of the &quot;<strong>Configuring and Maintaining Replications</strong>&quot; section. It's a little non-obvious, so I spent most of my time looking in the &quot;<strong>Replicating Data Between a Server and Clients</strong>&quot; section, instead of there. Good to know, as there seems to be a number of other special scenarios worth looking at in there.</p>
<p>I do not get the interest of having a transactional replication to generate lookup tables. Such tables are not made to be updated from the client side, so why do you want to combine transactional + merge replication when you don't have the data modified by the subscribers?</p>
31,905
<p>After reading <a href="https://stackoverflow.com/questions/36127/any-recommended-vc-settings-for-better-pdb-analysis-on-release-builds">this discussion</a> and <a href="https://stackoverflow.com/questions/49224/good-crash-reporting-library-in-c">this discussion</a> about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email.</p> <p>When you call the install() function to initialize CrashRpt, you specify the email address you want the crash dump sent to, but how does the CrashPrt library know how to send the email to that address? Wouldn't the library have to know the email client settings for each individual user?</p> <p>When a fatal crash occurs in my code, the CrashRpt dialog box pops up and when I enter my email address and click the send button, it takes me to a "Save File" dialog box where I can save the zipped package and the account specified in the Install() function never receives an email.</p> <p>Thanks in advance for any and all help! I'm clearly missing something.</p>
<p><strong>What CrashRpt does for emailing:</strong> </p> <p>The email system simply uses MAPI to send your email. Which would try to use your default mail client if you have one, and if it supports MAPI. Take a look at MailMsg.cpp for details. </p> <p><strong>Personal experience:</strong></p> <p>In my company's usage of CrashRpt, we modified it a bit though to call a web service that we created which submits the crash report. So we gutted the emailing code completely from CrashRpt. And instead we have in our bug tracking system a section for crashes that were auto submitted when crashes happen. </p> <p><strong>To find your problem:</strong></p> <p>I would maybe try to debug the CrashRpt code to see why it's giving you a save dialog. It should instead just open your default mail client. Maybe you have an older version of the library, or maybe the dialog resources are a little messed. Debugging the code will tell you this though. </p> <p>Most likely MailReport is being called but is failing. </p> <p>Set a breakpoint in the original <a href="http://code.google.com/p/crashrpt/" rel="nofollow noreferrer">CrashRpt code</a>'s CrashHandler.cpp at just after the DoModal:</p> <pre><code> mainDlg.m_pUDFiles = &amp;m_files; if (IDOK == mainDlg.DoModal()) { //Put breakpoint here &lt;--------- if (m_sTo.IsEmpty() || !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription)) { SaveReport(rpt, sTempFileName); } } </code></pre> <p>Check to see why MailReport is not getting called. It's either the dialog resource, or your m_sTo is not filled or you can step through MailMsg.cpp and see where MAPI is failing. </p> <p><strong>Alternate solution:</strong></p> <p>An easy fix, if you find above that MailReport is being called, but not succeeding, is to instead just do a ShellExecute and specify a mailto:</p> <p>You could even try to use the MAPI method, but if that fails to do a mailto:</p>
<p>You can find the CrashRpt documentation, FAQ and download a new CrashRpt v1.1 here <a href="http://code.google.com/p/crashrpt/" rel="nofollow noreferrer">http://code.google.com/p/crashrpt/</a> </p>
26,725
<p>I often have nothing more than an FTP access to a server on which the application is placed.</p> <p>What I usually use now is "Keeping remote directory up to date" feature of <a href="http://winscp.net/" rel="nofollow noreferrer">WinSCP</a>. Files of the local copy (in theory at least) keep being uploaded to a remote server as soon as they get saved and then all I need is to refresh a page in a browser to see the result (sometimes clearing session variables beforehand).</p> <p>WinSCP's bugginess and FTP protocol deficiencies aside, I feel this may be somewhat primitive approach and perphaps there are better ways to get a task like that done.</p>
<p>I have a similar situation. I used to use Dreamweaver for web development but have switched to other tools that do not have the file sync features of Dreamweaver.</p> <p><strong>I have recently discovered <a href="http://www.scootersoftware.com/" rel="nofollow noreferrer">BeyondCompare</a></strong>, which is a diff/merge tool that works really well for comparing local and remote directory trees. <strong>It is highly configurable and has a sync mode as well</strong>. Very nice.</p>
<p>If you are using <a href="http://maven.apache.org/" rel="nofollow noreferrer">Maven</a> to automate your build I would recommend you use the <a href="http://cargo.codehaus.org/" rel="nofollow noreferrer">Cargo</a> plugin to deploy your application to the server.</p> <p>If you cannot use your container's deployer you can still use Maven (with a bit more work) to deploy your web application using SCP, SFTP, FTP or even WebDAV via <a href="http://maven.apache.org/wagon" rel="nofollow noreferrer">Wagon</a>.</p>
17,225
<p>I am writing a small program. The interface I am writing to control each repository that is made defines a method of Save(IPublicObject). I am using LINQ for the SQL Version of the repository CRUD. My question is this. I would like to have only the one method which accepts the interface type. I want to think how I can best locate the Save action for the inherited type I then pass in. </p> <p>In the book I am reading Patterns of Enterprise Application Architecture. I am leaning on the Inheritance Maping. So I create a derived object of </p> <pre><code>public class ConcretePublicObjectOne : IPublicObject{} </code></pre> <p>I want to then pass this into the Save Function of the respository. It is at this point where I am trying to think how best to say, ok we need to use "WHAT?" Save Method etc...</p> <p>Should I use a registry, configuration setting mapping the types?</p>
<p>For LINQ-to-SQL, the data-context already does a lot of the mapping for you. As such, I think generics might be the best way to achieve a save while still having some consideration of your interface (although I'm not quite sure what the interface is giving you in this scenario...).</p> <p>You can access the generic aspect of the data-context via <code>GetTable&lt;T&gt;()</code>:</p> <pre><code> static void Save&lt;T&gt;(T item) where T : class, IPublicObject { using (DataContext ctx = GetDataContext()) { Table&lt;T&gt; table = ctx.GetTable&lt;T&gt;(); // for insert... table.InsertOnSubmit(item); // for update... table.Attach(item, true); // for delete... table.DeleteOnSubmit(item); ctx.SubmitChanges(); } } </code></pre> <p>Note that type-inference should mean that you don't need to specify the <code>T</code> when saving:</p> <pre><code> Foo foo = new Foo(); Save(foo); // &lt;Foo&gt; is inferred </code></pre> <p>Is that any use?</p>
<p>What you wish to do is to have a:</p> <pre><code>Repository.Save(publicObject) </code></pre> <p>and the repository to call a method from publicObject?</p> <p>If this is the requirement then you can define the Save method in repository as:</p> <pre><code>public class Repository { public void Save(IPublicObject publicObject) { publicObject.Save(); } } </code></pre> <p>where IPublicObject is defined as:</p> <pre><code>public interface IPublicObject { void Save(); } </code></pre> <p>But with this approach you will have to define a save method for each entity (like ConcretePublicObjectOne in your example)</p>
26,589
<p>I am trying to import an existing PDF as a template with FPDI. The template is in landscape format. If I import the template into a new document the template page is inserted in portrait form with the content rotated 90 degrees. If my new document is in portrait the full content appears, but if the new document is also landscape, the content is cropped.</p> <p>Is it possible to use a landscape template with FPDI? </p>
<p>sure, it is no problem. Just add "L" as parameter when calling "addPage()". Here is a sample which works fine for me (the template is in landscape)</p> <pre><code>&lt;?php require_once('fpdf.php'); require_once('fpdi.php'); $pdf =&amp; new FPDI(); $pdf-&gt;addPage('L'); $pagecount = $pdf-&gt;setSourceFile('template.pdf'); $tplIdx = $pdf-&gt;importPage(1); $pdf-&gt;useTemplate($tplIdx); $pdf-&gt;SetFont('Arial'); $pdf-&gt;SetTextColor(255,0,0); $pdf-&gt;SetXY(25, 25); $pdf-&gt;Write(0, "This is just a test"); $pdf-&gt;Output('newpdf.pdf', 'F'); ?&gt; </code></pre>
<p>Finally got to look at this problem again... Although crono's answer is perfectly valid. It seems this only works with more recent versions of the FPDI tools. Upgrading from v1.1 to v1.3 solves the problem.</p>
38,120
<p>Like, testing for : </p> <ul> <li>invalid inputs (strings containing "'"s)</li> <li>giving random id's in url parameters to access "unauthorized" pages</li> <li>prevent sql injection</li> <li>...</li> </ul>
<p>I would recommend reading this brilliant <a href="https://rads.stackoverflow.com/amzn/click/com/0471081124" rel="nofollow noreferrer" rel="nofollow noreferrer">book</a> to learn more about the test plans.</p> <p>In particular a test plan is much more than a list of techniques like you mentioned (these should most likely go into the details for the security testing)</p> <p>It should at least contain:</p> <ul> <li>The answers to the main questions: <ul> <li>why bother (what is gained by testing)</li> <li>who cares (who are we working for)</li> <li>how much (..testing will be done)</li> </ul></li> </ul> <p>You would not go wrong providing also:</p> <ul> <li>Platforms</li> <li>Methods (positive testing, load testing etc)</li> <li>Functionality you're planning to test </li> <li>Acceptance criteria</li> </ul> <p>And there is plenty more things to talk about in the plan.</p>
<p>If you want to make a list, you can add "Trying simple javascripts within a textarea field to see if the site saves and executes them"</p>
22,688
<p>I build and export my model using ZBrush and as STL files.<br /> To fix the mesh for 3D print, I try to use 3D Builder which can automatically repair my parts.<br /> As it saves as a single file, if I import all parts at once,<br /> I import the files one by one, repair them, then save them as a new file.<br /> After all the parts were repaired, I import all parts to see the result<br /> but find some repaired parts' positions shifted.<br /> How should I handle these issues?</p> <p><a href="https://i.stack.imgur.com/01xRd.png" rel="nofollow noreferrer" title="Rendering of 3D model with parts shifted from original position"><img src="https://i.stack.imgur.com/01xRd.png" alt="Rendering of 3D model with parts shifted from original position" title="Rendering of 3D model with parts shifted from original position" /></a></p>
<p>STL models as exported by software often include their origin in the origin of the design software. However, when using software to fix modeling errors, those origins are not always retained and thus when importing them into a different software their <em>center of mass</em> is taken as the new point of reference.</p> <p>Slicers are notorious in that they ignore the included origin. Even <em>if</em> models contain an origin that would, when imported into 3D design environments result in the items lining up correctly, the slicing software will simply not care and take a <em>lowest point in the projected center of the object</em> as the coordinate for the item, as this is what is relevant for positioning in the software.</p> <p>To mitigate that problem, it is best to export models that need to be <em>joined</em> after processing a boolean union on them.</p>
<p>It has moved it to the ground as close as it could. This is generally best for 3d printing seperate objects.</p> <p>If you need them together you can reposition them, or combine them.</p> <p>Alternatively change the 'Collision' and 'Intersect' settings until you get what you want.</p>
2,138
<p>I have a VB.NET ClickOnce application that I am trying to install on my computer. Previously, I was able to install and run these apps without issue. Now when I install the application, I can see the flash of a window opening, and then nothing. (There are also no processes left hanging or anything when viewed with the task manager.) </p> <p>After some digging around I noticed that there are files in my Temporary Internet Files with names like "FusionBindError" and then my application name and different DLL names.</p> <p>I have done everything I can find on the net to do, reinstall applications, reinstalled the .NET Framework, deleted my Local Settings folder and relogged in. </p> <p>Does anyone out there have any other ideas for me to try?</p> <p>I tried the Mage.exe suggestion, but it failed to help. Same with the other installation location suggestion. The application flashes at the bottom of the screen but does not open. I have tried using FUSLOGVW to check the bindings and nothing shows up in there. (Good or bad, there are no binding entries.) </p>
<p>Have you tried using mage.exe? This is a command-line tool that comes with .NET framework. Start up a VS command prompt, and try mage -cc. This will clear your applicaiton cache and will force a new click-once download. This is the first thing I do when my click-once applications fail and it works 99% of the time.</p>
<p>It's possible that new prerequisites were added that you don't have on hand. If the URL you are using points directly to "my.application" or whatever your equivalent is, prerequisites won't be processed.</p> <p>So try pointing to the setup.exe that is created in the same directory as the .application file.</p> <p>Other than that, it sounds like you're doing all the right stuff...</p>
24,270
<p>I'm writing a service application that sometimes cannot be stopped immediately upon receiving the SERVICE_CONTROL_STOP from the Services MMC. I currently handle it like this: (in pseudo-code):</p> <pre><code>DWORD HandlerEx( DWORD dwControl, DWORD dwEventType, PVOID pvEventData, PVOID pvContext ) { switch( dwControl ) { case SERVICE_CONTROL_STOP: if ( CanStopServiceNow() ) { ReportStatus( SERVICE_STOP_PENDING ); DoStopService(); ReportStatus( SERVICE_STOPPED ); return NO_ERROR; } else return ERROR_BUSY; break; } return NO_ERROR; } </code></pre> <p>It works well when the service can stop ( and it does stop), but when it cannot stop, I would expect Windows to report the error I'm returning (ERROR_BUSY in this example.) Instead, Windows displays a message saying:</p> <pre><code>"The service did not return an error. This could be an internal Windows error or an internal service error." </code></pre> <p>So my question is, how to make the service report back to SCM that it cannot stop now and make MMC display a message about the actual error code that I'm returning? </p>
<p>For Perl/Tk, there is <a href="http://www.perltk.org/index.php?option=content&amp;task=view&amp;id=28&amp;Itemid=29" rel="nofollow noreferrer">ZooZ</a>. </p> <p>Personally, I prefer to use <a href="http://glade.gnome.org/" rel="nofollow noreferrer">Glade</a> for the GUI design and <a href="http://search.cpan.org/dist/Gtk2-GladeXML" rel="nofollow noreferrer">Gtk2::GladeXML</a>. And as other people mentioned, there's also WxWidget and Qt alternatives.</p>
<p>The Perlmonks post <a href="http://www.perlmonks.org/?node_id=627282" rel="nofollow noreferrer">http://www.perlmonks.org/?node_id=627282</a> might help, as well as the google search for <a href="http://www.google.com/search?client=safari&amp;rls=en-us&amp;q=perl+gui+builder&amp;ie=UTF-8&amp;oe=UTF-8" rel="nofollow noreferrer">"perl gui builder"</a>. Once you see what's available, you might be able to ask a more specific question to get a better answer.</p> <p>Good luck, :)</p>
37,405
<p>I've done some Python but have just now starting to use Ruby<br> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br> Python methods receive self as an explicit argument, whereas Ruby does not.<br> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br> <a href="http://rubylearning.com/satishtalim/ruby_self.html" rel="noreferrer">http://rubylearning.com/satishtalim/ruby_self.html</a><br> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html" rel="noreferrer">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
<p>Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.</p> <p>Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.</p> <p>If you're inside an instance method of one of your class, self is a reference to said instance. </p> <p>If you're in the definition of the class itself (not in a method), self is the class itself:</p> <pre><code>class C puts "I am a #{self}" def instance_method puts 'instance_method' end def self.class_method puts 'class_method' end end </code></pre> <p>At class definition time, 'I am a C' will be printed.</p> <p>The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.</p> <pre><code>c=C.new c.instance_method #=&gt; instance_method C.class_method #=&gt; class_method </code></pre>
<p>Well, I don't know much about Ruby. But the obvious point about Python's "self" is that it's not a "keyword" ...it's just the name of an argument that's sent to your method.</p> <p>You can use any name you like for this argument. "Self" is just a convention.</p> <p>For example :</p> <pre><code>class X : def __init__(a,val) : a.x = val def p(b) : print b.x x = X(6) x.p() </code></pre> <p>Prints the number 6 on the terminal. In the constructor the self object is actually called a. But in the p() method, it's called b.</p> <p>Update : In October 2008, Guido pointed out that having an explicit self was also necessary to allow Python decorators to be general enough to work on pure functions, methods or classmethods : <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html" rel="nofollow noreferrer">http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html</a></p>
19,348
<p>I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a <code>varchar(50)</code> field.</p> <p>I need to do a simple date comparison -</p> <pre><code>datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <p>But it fails on the <code>convert()</code>:</p> <pre><code>Conversion failed when converting datetime from character string. </code></pre> <p>Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the <code>convert()</code>? Here is what I have now:</p> <pre><code>select count(*) from MyTable where isdate(lastUpdate) &gt; 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <p>I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option.</p> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28139">@Jon Limjap</a></p> <p>I've tried adding the third argument, and it makes no difference.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <blockquote> <p>The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces)</p> </blockquote> <p>Wouldn't the <code>isdate()</code> check take care of this?</p> <p>I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <pre><code>select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@Brian Schkerke</a></p> <blockquote> <p>Place the CASE and ISDATE inside the CONVERT() function.</p> </blockquote> <p>Thanks! That did it.</p>
<p>Place the <code>CASE</code> and <code>ISDATE</code> inside the <code>CONVERT()</code> function.</p> <pre class="lang-sql prettyprint-override"><code>SELECT COUNT(*) FROM MyTable WHERE DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate) WHEN 1 THEN lastUpdate ELSE '12-30-1899' END), GetDate()) &lt; 31 </code></pre> <p>Replace <code>'12-30-1899'</code> with the default date of your choice.</p>
<p>I would suggest cleaning up the mess and changing the column to a datetime because doing stuff like this</p> <pre><code>WHERE datediff(dd, convert(datetime, lastUpdate), getDate()) &lt; 31 </code></pre> <p>cannot use an index and it will be many times slower than if you had a datetime colum,n and did</p> <pre><code>where lastUpdate &gt; getDate() -31 </code></pre> <p>You also need to take into account hours and seconds of course</p>
4,776
<p>I am working on some sort of CRM application which has huge sales data with all the customer leads etc (ASP.NET 2.0/Ajax)</p> <p>I want to create a dashboard which will have four separate data containers each container will have different sort of data and each container has to update it self after some configured time interval. so I want to update only that part of page not whole page</p> <p>What should I used in the above scenario asp.net updatePanel or jQuery implementation (which technique and why)</p> <p>Because performance is also important here.</p>
<p>Both ASP.NET UpdatePanel or jQuery (or a mix of both) would serve you fine on this scenario; if you don't have experience with neither, I would recommend the UpdatePanel way because it is closer to the regular ASP.NET code you're used to. </p> <p><a href="http://msdn.microsoft.com/en-us/library/bb398867.aspx" rel="nofollow noreferrer">This article</a> will get you 90% there, all you have to do at the end is to put some simple javascript in place to fire the updates every X seconds; something like <code>window.setTimeout("Button1.click()",5000)</code> if you want to refresh a panel every 5 seconds. If you don't want the button to be available for the users, just make it hidden via CSS.</p> <p>There are more elegant approaches (using JSON, webservices, client-side templating etc) but that's an easy way to get the job done.</p>
<p>Also you can use <a href="http://www.dynamicdashboards.net" rel="nofollow noreferrer">dynamic dashboard framework</a> and convert update panels to drag-drop widgets.</p> <p>It's a browser independent web part framework for Asp.Net.</p>
42,411
<p>I need to do a few very simple URL manipulations in Java. Like get the value for a parameter in the query, or update it, ... I was expecting to find a simple utility class doing that in the commons-lang package, but no. I know it is a simple problem, but if there is something already written, why do it again ? Do you know of any ?</p> <p>I would like to have at least the following capabilities :</p> <pre><code>String myUrl = "http://www.example.com/test.html?toto=1&amp;titi=2"; // get the value of a parameter String parameterValue = UrlUtils.getParameterValue(myUrl, "toto"); Assert.equals(parameterValue, "1"); // update a parameter String newUrl = UrlUtils.updateParameter(myUrl, "toto", 3); parameterValue = UrlUtils.getParameterValue(myUrl, "toto"); Assert.equals(parameterValue, "3"); </code></pre> <p>Ideally, it would take care of all encoding related issues, and work with java.net.Url as well as with Strings.</p> <p>Thanks for your help !</p>
<p>I think what you want is called a query string parser instead of an url manipulator and here's one: <a href="http://ostermiller.org/utils/CGIParser.java.html" rel="noreferrer">http://ostermiller.org/utils/CGIParser.java.html</a></p>
<p>Apache's httpcomponents library has a URL decoder: <a href="http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html" rel="nofollow">http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html</a></p> <p>Httpcomponents is the successor to commons http client.</p>
26,897
<p>I am working on a web application that was recently converted from Visual Studio 2003 to Visual Studio 2008. The application contained some web services that were written using the .NET 1.1 Framework and Web Service Enhancements 2.0. They were converted to the .NET 3.5 framework using the VS 2008 Conversion Wizard Tool.</p> <p>A client application which is still written using the .NET 1.1 framework has a reference to the updated web service and try to consume the web service and received the following error:</p> <p>System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: (web service URI)</p> <p>The URL Behavior is set to static for the reference and the proxy class inheritance was changed from System.Web.Services.Protocols.SoapHttpClientProtocol namespace to Microsoft.Web.Services2.WebServicesExtension namespace</p> <p>If you need additional information or need to see some source code, please let me know.</p>
<p>If you go directly to the asmx url with a web browser, and then click on the method you want to call, what's the SOAPAction that they want?</p> <p>next, check the Reference.vb code and see what the SoapDocumentMethodAttribute attribute is set to.</p> <p>Do they match?</p>
<p>Does the web service work otherwise? Is it possible your new updated 2.0 web service exists in the same application domain as a 1.1 application? In that case you'll want to make your own app-domain.</p> <p>If its not local try using Fiddler to see everything that is going back and forth.</p>
22,420
<p>I'm looking for a way to select until a sum is reached.</p> <p>My &quot;documents&quot; table has &quot;<code>tag_id</code>&quot; and &quot;<code>size</code>&quot; fields.</p> <p>I want to select all of the documents with <code>tag_id = 26</code> but I know I can only handle 600 units of size. So, there's no point in selecting 100 documents and discarding 90 of them when I could have known that the first 10 already added up to &gt; 600 units.</p> <p>So, the goal is: don't bring back a ton of data to parse through when I'm going to discard most of it.</p> <p>...but I'd also really like to avoid introducing working with cursors to this app.</p> <p>I'm using MySQL.</p>
<p>You need some way to order which records get priority over others when adding up to your max units. Otherwise, how do you know which set of records that totals up to 600 do you keep?</p> <pre><code>SELECT d.id, d.size, d.date_created FROM documents d INNER JOIN documents d2 ON d2.tag_id=d.tag_id AND d2.date_created &gt;= d.date_created WHERE d.tag_id=26 GROUP BY d.id, d.size, d.date_created HAVING sum(d2.size) &lt;= 600 ORDER BY d.date_created DESC </code></pre> <p>This is just a basic query to get you started, and there are a number of problems still to solve:</p> <ul> <li>It stops at &lt;= 600, so in most cases you won't fill up your size limit exactly. This means you might want to tweak it to allow one more record. For example, if the first record is &gt; 600 the query will return nothing, and that could be a problem.</li> <li>It won't do anything to check for additional smaller records later on that might still fit under the cap.</li> <li>Records with identical date_created values could be sort of 'double counted' here and there.</li> </ul>
<p>This is much less efficient, but it does avoid a cursor (assuming your documents table also has a serial id column):</p> <pre><code>select a.id, (select sum(b.size) from documents b where b.id &lt;= a.id and b.tag_id = 26) from documents a where a.tag_id = 26 order by a.id </code></pre> <p>Also, this was done in pgsql, so I'm not sure if this exact syntax would work in mysql.</p> <p>Then you can wrap this in another query that looks for those having a sum > 600 (you'll have to name the sum column) and take the first id. Then process all ids below and including that one.</p>
36,546
<p>I have a dropdown box and a literal tag inside an Update Panel. On the selection change event of the dropdown up requery the database and repopulate the literal tag and then call UPdatePanel.Update().</p> <p>below, is there are way i can avoid having to create a new Oledbconnection each time as this seems slow. Can i reuse and store:</p> <ol> <li>The Datasource</li> <li>The connection in the page. </li> </ol> <p>if so, how do i keep this state between calls from the GUI to the server? Here is my selection change code below</p> <pre><code>protected void cboPeople_SelectedIndexChanged(object sender, EventArgs e) { string dataSource = ConfigurationSettings.AppSettings["contactsDB"]; var objConn = new OleDbConnection(dataSource); string id = People[cboPeople.Text]; UpdateLiteral(objConn, id); } </code></pre>
<p>With .NET is not a good idea to keep your connection alive longer than needs. Good practice would be to put a using statement around it (so it always gets cleaned up):</p> <pre><code>string dataSource = ConfigurationSettings.AppSettings["contactsDB"]; using(var objConn = new OleDbConnection(dataSource)) { string id = People[cboPeople.Text]; UpdateLiteral(objConn, id); } </code></pre> <p>.NET uses <a href="http://www.ondotnet.com/pub/a/dotnet/2004/02/09/connpool.html" rel="nofollow noreferrer">connection pooling</a>, which means that when you close/dispose of the connection it doesn't actually close the connection, rather resets it and add it back to the pool. The next time a connection is needed it is used from the pool. So the overhead is not as much as you think and it is not slow. In actual fact you will find that it will use the same connection as long as only one at a time is needed.</p> <p>The danger with keeping connections open is that they never get closed, and in high demand situations you run out of connections.</p>
<p>You need to recreate this for each request. You have a a state less server. you never know when or if your client will call back. You do not want to keep an open connection to the database nor could you simply service multiply clients while maintaining one database connection.</p> <blockquote> <p>To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for OLE DB, you do not have to enable connection pooling because the provider manages this automatically. For more information about how to use connection pooling with the .NET Framework Data Provider for OLE DB, see OLE DB, ODBC, and Oracle Connection Pooling (ADO.NET). From <a href="http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection.aspx" rel="nofollow noreferrer">OleDbConnection Class</a></p> </blockquote>
37,459
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
<p>read here:<br> <a href="http://en.wikipedia.org/wiki/TNEF" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/TNEF</a></p> <p>a package for parsing here:<br> <a href="https://github.com/verdammelt/tnef" rel="nofollow noreferrer">https://github.com/verdammelt/tnef</a></p>
<p>I have had good luck with <a href="http://www.biblet.freeserve.co.uk/" rel="nofollow noreferrer">wmdecode</a> on Windows. Granted, it's an EXE, not a java project. But it could be useful if you run into WINMAIL.DAT files that other solutions can't decode.</p>
43,652
<p>Can anybody recommend a reliable and decently documented code highlighter for WordPress 2.6.1? I have tried Code Snippet by Roman Roan and Developer Formatter by Gilberto Saraiva. But they don't seem to work as described in the documentation and are mangling the code snippets instead of prettifying them.</p>
<p>I use <a href="http://wordpress.org/extend/plugins/wp-syntax/" rel="noreferrer">WP-Syntax</a> and it's worked very well for me. It's supported every language I've thrown at it so far, and the colors can be customized for a particular theme (though the defaults look just fine too)</p>
<p>You should also checkout <a href="http://code.google.com/p/syntaxhighlighter/" rel="nofollow noreferrer">syntaxhighlighter</a> from Google Code.</p>
5,627
<p>I have a base recipe class and I am using a datacontext. I overrode the insert method for the recipe in the datacontext and am trying to insert into its children. Nomatter what I do I cannot get the child to insert.Currently, just the recipe inserts and nothing happens with the child.</p> <pre><code> partial void InsertRecipe(Recipe instance) { // set up the arrays for (int x = 0; x &lt; instance.PlainIngredients.Count; ++x) { instance.TextIngredients.Add(new TextIngredient() { StepNumber = x + 1, Text = instance.PlainIngredients[x] }); } this.ExecuteDynamicInsert(instance); } </code></pre> <p>I have tried everything I can think of. I even instantiated another datacontext in the method and after the instance came back from ExecuteDynamicInsert with the id, tried to add it, and I get timeout errors.</p>
<p>I figured it out. Override SubmitChanges in the DataContext, and find all of the inserts and updates that are recipes. Run the algorithm to add children there.</p> <pre><code> public override void SubmitChanges( System.Data.Linq.ConflictMode failureMode) { ChangeSet changes = this.GetChangeSet(); var recipeInserts = (from r in changes.Inserts where (r as Recipe) != null select r as Recipe).ToList&lt;Recipe&gt;(); var recipeUpdates = (from r in changes.Updates where (r as Recipe) != null select r as Recipe).ToList&lt;Recipe&gt;(); ConvertTextData(recipeInserts); ConvertTextData(recipeUpdates); base.SubmitChanges(failureMode); } </code></pre>
<p>The InsertX/UpdateX/DeleteX methods are called after LINQ to SQL has determined which objects will be included in SubmitChanges.</p> <p>You would have been getting a timeout using two DataContext most likely because of locking issues between the two transactions.</p> <p>I can't clearly make out what you are trying to achieve here - normally LINQ to SQL manages the child relationships itself - what are PlainIngredients and TextIngredients?</p>
47,678
<p>I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc. </p> <p>They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. )</p> <p>They all have a <strong>Title</strong></p> <p>They all have <strong>BodyText</strong>.</p> <p>They all have a <strong>Status</strong></p> <p>They all have a <strong>DateAdded</strong></p> <p>What I'd like to do is standard class inheritance.</p> <p>I'd like a Master Class (I don't need to write this to the database) called <strong>Content</strong> with fields like:</p> <ul> <li>ID</li> <li>Title</li> <li>SubTitle</li> <li>BodyText</li> <li>Status</li> <li>AddedDate</li> </ul> <p>I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it. It will only need the information that is common to all objects.</p> <p>Is this even possible?</p>
<p>This is what Interfaces are for. Have each class implement an IContent interface that contains your Title, BodyText, Status and DateAdded properties. Now you can pass around a collection ( <code>List&lt;IContent&gt;</code> ) around that could containt different types of content.</p> <p>If you're using LinqToSql you can create partial class files to have the autogenerated classes implement the interface you want.</p> <pre><code>public partial class SomeContent : IContent </code></pre>
<p>I found one page that looks like it has something along the lines of what I'm looking for (The last post)... but I'm not sure about using weakly typed objects:</p> <p><a href="http://www.eggheadcafe.com/software/aspnet/32149682/linq-inheritance-problem.aspx" rel="nofollow noreferrer">LINQ inheritance</a></p>
31,714
<p>It is very easy to ask questions that only tangentially involve 3D printing, such as:</p> <ul> <li><p>How do I drill a hole in a 3D printed part?</p></li> <li><p>How do I paint 3D printed parts?</p></li> <li><p>How do I sand, smooth, etc...?</p></li> <li><p>How do I take a picture with a 3D printed camera?</p></li> </ul> <p>My last example is clearly not on topic, and the other examples aren't </p> <blockquote> <p>difficult, specific questions — the kind of questions pros and experts ask each other, not the kind of questions novices ask pros.</p> </blockquote> <p>However, the point is that it's very easy to involve 3D printing in a question that isn't about 3D printing. Drilling a hole in a 3D printed part is, for the most part, just like drilling one in wood. Such questions may be more suited for a general DIY/makers-type site.</p> <p>On the other hand, there do exist 3D printing specific issues (for instance, low infill or delamination can be a problem when drilling in a (FDM) 3D printed part).</p> <p>At what point does a question involving 3D printing become on-topic for our site? Should questions identify a specific issue ("I've tried drilling a hole, now my part has delaminated, what now?")?. Queries for general advice and best practice don't seem to fit the bill of being difficult and specific.</p>
<p>The dividing line of "tangentially off topic" is typically when the <em>actual</em> subject of the question being asked is only <strong><em>coincidentally</em></strong> adjacent to 3D printing. </p> <p>Here is a <em>clear</em> example illustrating the "tangential issue:"</p> <blockquote> <p>I printed a crane mechanism in 3D. How much voltage must I apply to the motor to lift 150 grams?</p> </blockquote> <p>I see this type of thing all the time. Users will go to the mat arguing that they are printing in 3D, so their question is on topic. It is not. The actual <em>expertise</em> needed to answer this question is in electronics. With a question like this, the premise that the user <em>happens</em> to be printing in 3D is entirely coincidental to the actual issue. </p> <p>The examples you cited above are a bit more iffy. I might argue some of them could (potentially) be on topic&hellip; if the issue of the material being printed in 3D is somehow germane to the problem. I actually don't know enough about the subject to say, so I'm only considering the possibility that it <em>is</em> relevant to this subject space.</p> <p>Let's not be too quick to start barring questions that aren't explicitly about the physical process of 3D printing literally. There are a lot of <em>industry issues</em> that could be interesting to include here. It's probably better to <strong><em>wait for actual examples before trying to create a general rule around this issue.</em></strong></p> <p>As a general rule for building this site, it is often better to wait for a preponderance of problems that occur <em>in actual practice</em> before we start seeking to create a lot of rules around hypothetical situations. Words to live by.</p>
<p>The problem with the questions you raised are (except for the camera one) that they are all about dealing with the materials that are used with 3D-printing and not about the mechanics of printing. But when I started 3D-printing, that's certainly where a large part of my questions lay. It's because the materials are DIFFERENT than ones we're used to dealing with, and if it weren't for 3D-printing, I wouldn't have been working with them then. It's BECAUSE I was 3D-printing that the questions arose. There are certainly similarities between the materials used for 3D-printing and other materials we might run into, but there are also vast differences. For example, ABS is the same plastic that we know from Legos. But how does working with the plastic that's been 3D-printed differ from working with a Lego? I would consider any question about that area to be valid. You mention drilling plastic, but then got the answer wrong. It is NOT like drilling wood; the way you drill plastic should be different from how you deal with wood, such as the speeds used and the use of hand drills. There are even special plastic bits that you can buy that make it easier to drill plastic. Good questions might be: for PLA, ABS and other 3dpg plastics, when is it appropriate to use such bits and when can you get away with using high speed drill bits like you would use for wood? Are higher drill speeds better than lower speeds for some 3D-printed plastics and not others, or vice versa?</p> <p>In summary, I feel that questions about a technique or material that is being used in the 3D-printing process, or dealing with the materials afterward, should be valid because 3D-printing changes how the techniques are done or the materials are dealt with.</p>
7
<pre><code>class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() </code></pre> <p>Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.</p>
<p>for Admin in Django 1.0 and up, you'd need to use</p> <pre><code>prepopulated_fields = {'slug': ('title',), } </code></pre> <p>in your admin.py</p> <p>Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.</p> <p>Outside of admin, you can use the <code>slugify</code> function in your views. In templates, you can use the <code>|slugify</code> filter.</p> <p>There is also this package which will take care of this automatically: <a href="https://pypi.python.org/pypi/django-autoslug" rel="noreferrer">https://pypi.python.org/pypi/django-autoslug</a></p>
<p><a href="https://bitbucket.org/neithere/django-autoslug" rel="nofollow">autoslug</a> has worked quite well for me in the past. Although I've never tried using it with the admin app.</p>
17,098
<p>Steve Yegge recently posted an <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="noreferrer">interesting blog post</a> on what he calls the universal design pattern. In there he details using prototypes as a modelling tool, instead of classes. I like the way this introduces less coupling compared to inheritance. But that is something one can get with classes as well, by implementing classes in terms of other classes, instead of inheritance. Does anyone else have success stories of using prototypes, and can maybe help explain where using prototypes is advantageous compared to classes. I guess it comes down to static modelling versus dynamic modelling, but more examples would be very welcome.</p>
<p>One interesting bit is that it's easy to make a prototype-based language act OO but it's difficult to make an OO language act prototype-based. </p> <ul> <li>Alex Arnell's <a href="http://code.google.com/p/inheritance/" rel="noreferrer">inheritance.js</a> is a short and sweet chunk of code that makes JavaScript act OO, complete with access to the parent 'Class'. </li> <li>Here's one of John Resig's solutions to the same problem: <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="noreferrer">http://ejohn.org/blog/simple-javascript-inheritance/</a>. </li> <li><a href="http://www.lua.org/pil/16.html" rel="noreferrer">Chapter 16 of Programming in Lua</a> describes object orientation in Lua. Specifically, <a href="http://www.lua.org/pil/16.2.html" rel="noreferrer">section 16.2</a> gives a nice example of inheritance.</li> </ul> <p>It's not entirely clear what OO as prototype would look like, aside from composition versus inheritance as you mention.</p> <p>A prototype language makes complex inheritance behavior easy. You can implement <a href="http://www.lua.org/pil/16.3.html" rel="noreferrer">multiple inheritance</a>, <a href="http://en.wikipedia.org/wiki/Mixin" rel="noreferrer">mixin</a>-like behavior, or just pick and choose what you want from one object to add to another.</p> <p><a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="noreferrer">Wikipedia's article</a> mentions: "Advocates of prototype-based programming often argue that class-based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. In contrast, prototype-based programming is seen as encouraging the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to classes."</p> <p>That's not to say the prototype paradigm is all pros and no cons. If OO is more restrictive, it's because it chooses to be. I can see where all that flexibility might get you into trouble if you aren't careful.</p>
<p>For those interested, <a href="http://en.wikipedia.org/wiki/Newtonscript" rel="nofollow noreferrer">NewtonScript</a> was (is) a dual language: you had prototypes and you had classes. You could choose whether to inherit from a class, from a prototype or from both.</p>
29,369
<p>I am completely new to LINQ in C#/.NET. I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?</p> <p>I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime. </p> <p>Any suggestions very welcome.</p>
<p>There's a method called <a href="http://msdn.microsoft.com/en-us/library/bb396189.aspx" rel="nofollow noreferrer">CopyToDataTable</a>. That method will only help if you already have a IEnumerable(DataRow)</p> <p>Here's how I'd do this:</p> <pre><code>//extension method to convert my type to an object array. public static object[] ToObjectArray(this MyClass theSource) { object[] result = new object[3]; result[0] = theSource.FirstDouble; result[1] = theSource.SecondDouble; result[2] = theSource.TheDateTime; return result; } //some time later, new up a dataTable, set it's columns, and then... DataTable myTable = new DataTable() DataColumn column1 = new DataColumn(); column1.DataType = GetType("System.Double"); column1.ColumnName = "FirstDouble"; myTable.Add(column1); DataColumn column2 = new DataColumn(); column2.DataType = GetType("System.Double"); column2.ColumnName = "SecondDouble"; myTable.Add(column2); DataColumn column3 = new DataColumn(); column3.DataType = GetType("System.DateTime"); column3.ColumnName = "TheDateTime"; myTable.Add(column3); // ... Each Element becomes an array, and then a row MyClassList.ForEach(x =&gt; myTable.Rows.Add(x.ToObjectArray()); </code></pre>
<p>if <code>MyObjectType</code> is a linq-generated entity, and those objects are not already associated to a data context you can call </p> <pre><code>foreach( MyObjectType value in myList ) { dataContext.MyObkectTypes.InsertOnSubmit(value); } dataContext.SubmitChanges(); </code></pre> <p>However, at this time linq-to-sql isn't terribly efficient at bulk updates. If myList was 1000 items, you would have 1000 insert statements.</p> <p>For very large lists you could convert the <code>List&lt;MyObjectType&gt;</code> into xml and use sql servers ability to bulk insert using xml. You would attach the sql server stored procedure to the datacontext.</p> <pre><code>string xml = CreateInsertXml( myList ); dataContext.usp_MyObjectsBulkInsertXml(xml); </code></pre> <hr> <p>example of sql server stored procedure for bulk insert via xml</p> <pre><code>-- XML is expected in the following format: -- -- &lt;List&gt; -- &lt;Item&gt; -- &lt;PlotID&gt;1234&lt;/PlotID&gt; -- &lt;XValue&gt;2.4&lt;/SmsNumber&gt; -- &lt;YValue&gt;3.2&lt;/ContactID&gt; -- &lt;ResultDate&gt;12 Mar 2008&lt;/ResultDate&gt; -- &lt;/Item&gt; -- &lt;Item&gt; -- &lt;PlotID&gt;3241&lt;/PlotID&gt; -- &lt;XValue&gt;1.4&lt;/SmsNumber&gt; -- &lt;YValue&gt;5.2&lt;/ContactID&gt; -- &lt;ResultDate&gt;3 Mar 2008&lt;/ResultDate&gt; -- &lt;/Item&gt; -- &lt;/List&gt; CREATE PROCEDURE [dbo].usp_MyObjectsBulkInsertXml ( @MyXML XML ) AS DECLARE @DocHandle INT EXEC sp_xml_preparedocument @DocHandle OUTPUT, @MyXML INSERT INTO MyTable ( PlotID, XValue, YValue, ResultDate ) SELECT X.PlotID, X.XValue, X.YValue, X.ResultDate FROM OPENXML(@DocHandle, N'/List/Item', 2) WITH ( PlotID INT, XValue FLOAT, YValue FLOAT, ResultDate DATETIME ) X EXEC sp_xml_removedocument @DocHandle GO </code></pre>
27,057
<p>I have a XML Structure that looks like this.</p> <pre><code>&lt;sales&gt; &lt;item name="Games" sku="MIC28306200" iCat="28" sTime="11/26/2008 8:41:12 AM" price="1.00" desc="Item Name" /&gt; &lt;item name="Games" sku="MIC28307100" iCat="28" sTime="11/26/2008 8:42:12 AM" price="1.00" desc="Item Name" /&gt; ... &lt;/sales&gt; </code></pre> <p>I am trying to find a way to SORT the nodes based on the sTime attribute which is a DateTime.ToString() value. The trick is I need to keep the Nodes in tact and for some reason I can't find a way to do that. I'm fairly certain that LINQ and XPath have a way to do it, but I'm stuck because I can't seem to sort based on DateTime.ToString() value.</p> <pre><code>XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml"); XPathNavigator navigator = saleResults.CreateNavigator(); XPathExpression selectExpression = navigator.Compile("sales/item/@sTime"); selectExpression.AddSort("@sTime", XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Number); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); while( nodeIterator.MoveNext() ) { string checkMe = nodeIterator.Current.Value; } </code></pre> <p>I also need to maintain a pointer to the NODE to retrieve the values of the other attributes. </p> <p>Perhaps this isn't a simple as I thought it would be.</p> <p>Thanks.</p> <p><strong>Solution</strong>: Here's what I ended up using. Taking the selected answer and the IComparable class this is how I get the XML nodes sorted based on the sTime attribute and then get the all the attributes into the appropriate Arrays to be used later.</p> <pre><code> XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml"); XPathNavigator navigator = saleResults.CreateNavigator(); XPathExpression selectExpression = navigator.Compile("sales/item"); XPathExpression sortExpr = navigator.Compile("@sTime"); selectExpression.AddSort(sortExpr, new DateTimeComparer()); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); int i = 0; while (nodeIterator.MoveNext()) { if (nodeIterator.Current.MoveToFirstAttribute()) { _iNameList.SetValue(nodeIterator.Current.Value, i); } if (nodeIterator.Current.MoveToNextAttribute()) { _iSkuList.SetValue(nodeIterator.Current.Value, i); } ... nodeIterator.Current.MoveToParent(); i++; } </code></pre>
<p>There's an overload of XPathExpression.Addsort which takes an IComparer interface. If you implement the comparison yourself as IComparer, you could use this mechanism.</p> <pre><code> class Program { static void Main(string[] args) { XPathDocument saleResults = new XPathDocument( @"salesData.xml" ); XPathNavigator navigator = saleResults.CreateNavigator( ); XPathExpression selectExpression = navigator.Compile( "sales/item" ); XPathExpression sortExpr = navigator.Compile("@sTime"); selectExpression.AddSort(sortExpr, new DateTimeComparer()); XPathNodeIterator nodeIterator = navigator.Select( selectExpression ); while ( nodeIterator.MoveNext( ) ) { string checkMe = nodeIterator.Current.Value; } } public class DateTimeComparer : IComparer { public int Compare(object x, object y) { DateTime dt1 = DateTime.Parse( x.ToString( ) ); DateTime dt2 = DateTime.Parse( y.ToString( ) ); return dt1.CompareTo( dt2 ); } } } </code></pre>
<p>suppose ur date time is in this format</p> <p>2010-06-01T15:16:29+05:00</p> <p>then simplest way that can be done is</p> <p>&lt; xsl:sort select="translate(XPATH_RETURNING_DATE,'-T:+','')" order="descending" data-type="number" /></p> <p>IN DATETIME JUST REPLACE EXTRA CHARACTERS in my datetime format i have the extra characters ( - T : and + ) so just replace it AND THEN YOUR DATE TIME WILL BE IN NUMBER FORMAT THAT CAN BE SORTED EASILY</p>
44,844
<p>Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a <code>ByteBuffer</code> with a message to output, and attempt to <code>write()</code> to the SocketChannel.</p> <p>I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html#write(java.nio.ByteBuffer)" rel="noreferrer">docs</a>), but that's not what happens. The <code>write()</code> <em>always</em> seems to return reporting the full amount written, even if it's several megabytes (the socket's SO_SNDBUF is 8KB, much, much less than my multi-megabyte output message).</p> <p>A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of <code>WRITE</code> to a selector and doing a <code>select()</code> to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?</p>
<p>I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it.</p> <pre><code>import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); final InputStream in = cs.getInputStream(); final byte[] tmp = new byte[64 * 1024]; while (in.read(tmp) != -1); Thread.sleep(100000); } } import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class MyNioClient { public static void main(String[] args) throws Exception { final SocketChannel s = SocketChannel.open(); s.configureBlocking(false); s.connect(new InetSocketAddress("localhost", 12345)); s.finishConnect(); final ByteBuffer buf = ByteBuffer.allocate(128 * 1024); for (int i = 0; i &lt; 10; i++) { System.out.println("to write: " + buf.remaining() + ", written: " + s.write(buf)); buf.position(0); } Thread.sleep(100000); } } </code></pre> <p>If you run the above server and then make the above client attempt to write 10 chunks of 128 kB of data, you'll see that every write operation writes the whole buffer without blocking. However, if you modify the above server not to read anything from the connection, you'll see that only the first write operation on the client will write 128 kB, whereas all subsequent writes will return <code>0</code>.</p> <p>Output when the server is reading from the connection:</p> <pre><code>to write: 131072, written: 131072 to write: 131072, written: 131072 to write: 131072, written: 131072 ... </code></pre> <p>Output when the server is not reading from the connection:</p> <pre><code>to write: 131072, written: 131072 to write: 131072, written: 0 to write: 131072, written: 0 ... </code></pre>
<p>I'll make a big leap of faith and assume that the underlying network provider for Java is the same as for C...the O/S allocates more than just <code>SO_SNDBUF</code> for every socket. I bet if you put your send code in a for(1,100000) loop, you would eventually get a write that succeeds with a value smaller than requested.</p>
19,111
<p>How do I create a branch in SVN?</p>
<p>Branching in Subversion is facilitated by a very very light and efficient copying facility.</p> <p>Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the <code>svn copy</code> command.</p> <p>Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style.</p> <p>Common styles are to have a bunch of folders at the top of your repository called <code>tags</code>, <code>branches</code>, <code>trunk</code>, etc. - that allows you to copy your whole <code>trunk</code> (or sub-sets) into the <code>tags</code> and/or <code>branches</code> folders. If you have more than one project you might want to replicate this kind of structure under each project:</p> <p>It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete.</p>
<p>Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.</p> <ol> <li>Right Click on updated trunk from local windows machine</li> <li>Select TortoiseSVN</li> <li>Click branch/Tag</li> <li>Select the To path in SVN repository. Note that destination URL is updated according to the path and branch name given</li> <li>Do not create folder inside branches in repository browser</li> <li>Add branches path. For example, branches/</li> <li>Add a meaningful log message for your reference</li> <li>Click Ok, this creates new folder on local system</li> <li>Checkout the branch created into new folder</li> </ol>
2,425
<p>I assume there must be a system and language independent way to just stick the "current" EOL character into a text file, but my MSDN-fu seems to be weak today. Bonus points if there is a way to do this in a web application that will put the correct EOL character for the current client's machine's OS, not the web server's.</p>
<p>For the bonus point:</p> <ul> <li>Check the user-agent of the client machine, for substrings such as Windows, or Linux</li> <li>The System.Environment.NewLine for Windows is 0x13, 0x10; in unix, it's generally 0x10 only; </li> <li>Choose the appropriate newline string, append it to the line, and off you go</li> </ul>
<p>Open the text file, seek to the end, and append Environment.NewLine.</p>
15,842
<p>I decided to finally purchase an Ender 3 v2. It arrived today and after a few hours of making sure everything is straight, I tried to power it and do a test print...</p> <p>I was disappointed to see that the screen stays black after more than 10 seconds from power on.</p> <p>I did not insert any SD card in the printer or anything that could interfere with the presumably stock firmware on it.</p> <p>Because of this, I opened up the power source and the motherboard case and checked the voltages/checked LEDs. The motherboard blue led is on, the power source green led is on as well. I did a few measurements - I get 24 V to the motherboard with a small spike of 35 V when it starts.</p> <p>The hotend fan is always on.</p> <p>I checked the display connection and I am sure it is placed correctly.</p> <p>I tried to upload firmware onto the mainboard first by clearing the SD card (8 GB given by Creality) using <code>diskpart</code>. I wrote the 4.2.2 (same as motherboard version) firmware version (stock) onto the SD attempting to upload on the mainboard. I tried renaming it, unplugging the power cable, unplugging the screen cable, etc and nothing would work.</p> <p>I tried rewriting the <code>DWIN_SET</code> files but the screen would not turn to black/blue/orange colors. I tried <a href="https://www.reddit.com/r/ender3/comments/j04s40/how_to_fix_the_ender_3_v2_firmware_upgrade_black/" rel="nofollow noreferrer">more or less everything suggested here</a>.</p> <p>Is there anything I didn't do? What do you suggest? I already contacted the company where I bought it from, but I don't want to go through the assembly process twice - maybe I can make it work?</p> <hr /> <ul> <li>The correct voltage for the power supply is set at 230 V (Europe) and was set to this all the time. I tried switching it back and forth without power too. No result.</li> <li>I've contacted the supplier yesterday.</li> </ul>
<p>What seems to be a difficulty is the stabilizers for plastic absorb UV. So if added to UV resin, they probably greatly increase the exposure time needed.</p> <p>The following show characteristics of some plastics, taken from <a href="https://www.coleparmer.com/tech-article/uv-properties-of-plastics" rel="nofollow noreferrer">https://www.coleparmer.com/tech-article/uv-properties-of-plastics</a></p> <blockquote> <p>Unmodified types of plastics that are regarded as having unacceptable resistance to UV are POM (Acetal), PC, ABS and PA6/6. Other plastics such as PET, PP, HDPE, PA12, PA11, PA6, PES, PPO, PBT and PPO are regarded as fair. Note that a PC/ABS alloy is also graded as fair. Good resistance to ultraviolet rays can be achieved from polymers extruded by Zeus such as PTFE, PVDF, FEP, and PEEKTM. The only plastics found with excellent resistance are the imides, Polyimide (PI) as used in the Hubble Space Telescope and Polyetherimide (PEI).</p> </blockquote> <blockquote> <p>PTFE has particularly good UV resistance because of its very strong carbon- fluorine (C-F) bond [almost 30% higher than the carbon-hydrogen (C-H) bond], which is the common side bond that surrounds the carbon (C-C) backbone in a helix and protects it. Most fluoropolymers also do not have the light absorbing chromophore impurities in their structure that can act as an initiator for photo-oxidation.</p> </blockquote>
<p>Sunlight contains the full spectrum of electromagnetic radiation, including the wavelength to photoinitiate your resin. Most UV-curable materials are kept in opaque containers for this reason. The extent to which your material is crosslinked will depend on your material and how much sunlight it receives.</p>
1,880
<p>I have 1 process that receives incoming connection from port 1000 in 1 <strong>linux</strong> server. However, 1 process is not fast enough to handle all the incoming request.</p> <p>I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple.</p> <p>I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing.</p> <p>Any other solution to help on my case?</p> <hr> <p>i am looking something more like nginx where i will need to run multiple copies of my app.</p> <p>Let me try it out.</p> <p>Thanks for the help.</p>
<p>You also may want to go with a web server like <a href="http://www.nginx.net" rel="nofollow noreferrer">nginx</a>. It can load balance your app against multiple ports of the same app, and is commonly used to load balance Ruby on Rails apps (which are single threaded). The downside is that you need to run multiple copies of your app (one on each port) for this load balancing to work.</p>
<p>i am thinking to run multiple application similar to <a href="http://ypopsemail.com/" rel="nofollow noreferrer">ypops</a>.</p>
6,708
<p>I would like to to try Emacs, and want to give it the best chance possible.</p> <p>To do this, it seems like having a good <code>.emacs</code> file is important.</p> <p>I primarily use Mac OS X (so I have looked at Aquamacs), and I mainly do Python programming, so anything specifically for that would be great.</p>
<p>That is a hard question. My theory about Emacs is that you have to give it a <strong>real</strong> honest try. That means working with it for a few months, not days. It is not for the faint of heart! Ideally emacs would become your one and only text editor, and you do things the emacs way. </p> <p>Really, to give yourself and emacs the best chance possible, you should learn enough elisp to do your own basic customizations. </p> <p>In fact, I think your .emacs is probably a read herring with regards to giving emacs the best possible chance. Instead, try out some of the groovier features like flymake with pylint, the inferior python process, python debugging with emacs are all worthwhile. In particular inferior processes are the bomb.</p> <p><a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode" rel="noreferrer">EmacsWiki</a> has some good info on python and emacs.</p>
<p>You can look to my emacs configs, located on <a href="http://xtalk.msk.su/~ott/en/emacs/" rel="nofollow noreferrer">my site</a>. Aquamacs-specific configuration you can find in <a href="http://xtalk.msk.su/~ott/common/emacs/rc/emacs-rc-local-flash.lan.el.html" rel="nofollow noreferrer">separate file</a></p>
34,083
<p>I have a web app for commercial property management that needs spreadsheet-like functionality for doing budgets. I don't want to use Google Sheets because my users won't necessarily have a Google account. </p> <p>So is there anything out there that I could use?</p> <p>I looked and could only find <a href="http://www.socialcalc.org/" rel="nofollow noreferrer">SocialCalc</a> which wasn't quite good enough for me.</p> <p><strong>Options:</strong> <li><a href="http://extjs.com/deploy/dev/examples/grid/edit-grid.html" rel="nofollow noreferrer">ExtJS</a> Grid Component (Open Source[GPL3] &amp; Commercial License) </li></p> <p><li><a href="http://www.infragistics.com/" rel="nofollow noreferrer">Infragistics</a> Grid Component (Commercial License) </li></p> <p><li>TreeGrid (Commercial License, Free Version has maximum of <a href="http://www.coqsoft.com/TreeGrid5_7/Html/EJSTreeGrid.html" rel="nofollow noreferrer">33 rows</a>) </li></p>
<p>If you don't mind implementing the logic yourself, the <a href="http://extjs.com/deploy/dev/examples/grid/edit-grid.html" rel="nofollow noreferrer">ExtJS</a> grid component is a JavaScript grid component with lots of powerful features, and it is available in both open-source and commercial versions.</p>
<p><a href="http://www.infragistics.com" rel="nofollow noreferrer">Infragistics</a> has spreadsheet-type functionality in their data grid product</p>
19,195
<p>What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.</p> <p>So far, the best I've come up with is this:</p> <pre><code>$fullString = "ignore everything except this (text)"; $start = strpos('(', $fullString); $end = strlen($fullString) - strpos(')', $fullString); $shortString = substr($fullString, $start, $end); </code></pre> <p>Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?</p>
<p>i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)</p> <pre><code>$text = 'ignore everything except this (text)'; preg_match('#\((.*?)\)#', $text, $match); print $match[1]; </code></pre>
<pre><code>function getStringsBetween($str, $start='[', $end=']', $with_from_to=true){ $arr = []; $last_pos = 0; $last_pos = strpos($str, $start, $last_pos); while ($last_pos !== false) { $t = strpos($str, $end, $last_pos); $arr[] = ($with_from_to ? $start : '').substr($str, $last_pos + 1, $t - $last_pos - 1).($with_from_to ? $end : ''); $last_pos = strpos($str, $start, $last_pos+1); } return $arr; } </code></pre> <p>this is a little improvement to the previous answer that will return all patterns in array form:</p> <p>getStringsBetween('[T]his[] is [test] string [pattern]') will return:</p>
23,876
<p>I took a data structures class in C++ last year, and consequently implemented all the major data structures in templated code. I saved it all on a flash drive because I have a feeling that at some point in my life, I'll use it again. I imagine <em>something</em> I end up programming will need a B-Tree, or is that just delusional? How long do you typically save the code you write for possible reuse? </p>
<p>Forever (or as close as I can get). That's the whole point of a source control system.</p>
<p>Source control, keep it offsite and keep it for life! You'll never have to worry about it.</p>
9,365
<p>When using a browser to transform XML (Google Chrome or IE7) is it possible to pass a parameter to the XSLT stylesheet through the URL?</p> <p>example:</p> <p><strong>data.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?xml-stylesheet type="text/xsl" href="sample.xsl"?&gt; &lt;root&gt; &lt;document type="resume"&gt; &lt;author&gt;John Doe&lt;/author&gt; &lt;/document&gt; &lt;document type="novella"&gt; &lt;author&gt;Jane Doe&lt;/author&gt; &lt;/document&gt; &lt;/root&gt; </code></pre> <p><strong>sample.xsl</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"&gt; &lt;xsl:output method="html" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:param name="doctype" /&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;List of &lt;xsl:value-of select="$doctype" /&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;xsl:for-each select="//document[@type = $doctype]"&gt; &lt;p&gt;&lt;xsl:value-of select="author" /&gt;&lt;/p&gt; &lt;/xsl:for-each&gt; &lt;/body&gt; &lt;/html&gt; &lt;/&lt;xsl:stylesheet&gt; </code></pre>
<p>You can generate the XSLT server-side, even if the transformation is client-side.</p> <p>This allows you to use a dynamic script to handle the parameter.</p> <p>For example, you might specify:</p> <pre><code>&lt;?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?&gt; </code></pre> <p>And then in myscript.cfm you would output the XSL file, but with dynamic script handling the query string parameter (this would vary depending on which scripting language you use).</p>
<p>You can generate the XSLT server-side, even if the transformation is client-side.</p> <p>This allows you to use a dynamic script to handle the parameter.</p> <p>For example, you might specify:</p> <pre><code>&lt;?xml-stylesheet type="text/xsl"href="/myscript.cfm/sample.xsl?paramter=something" ?&gt; </code></pre> <p>And then in myscript.cfm you would output the XSL file, but with dynamic script handling the query string parameter (this would vary depending on which scripting language you use).</p>
9,156
<p>I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?</p>
<p>The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:</p> <pre><code>import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; ... @Resource private WebServiceContext context; </code></pre> <p>Then, you can access the servlet context using:</p> <pre><code>ServletContext servletContext = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT); </code></pre>
<p>If you use Maven add this dependency!!!</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>So I solved for avoid conflict error for get ServletContext <a href="https://rishisoftwareblog.wordpress.com/2013/02/06/using-a-servlet-config-file-with-a-cxf-jax-rs-web-service/" rel="nofollow">INFO :</a></p> <p>And in class method I use </p> <pre><code>@WebService(endpointInterface = "choice.HelloWorld") public class HelloWorldImpl implements HelloWorld { @Resource private WebServiceContext context; public String sayHi(String text) { HttpServletRequest request =(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST); System.out.println(request.getContextPath()); </code></pre>
32,671
<p>I want to be able to explore the contents of a DB for this version of the DB. I was thinking of using the Squirrel DB client (which needs a JDBC driver).</p> <p>Therefore, I'm looking for a JDBC type 4 driver for SQL SERVER 3.5. Can somone point me to a FREE OR open source or trial ware ?</p> <p>If no JDBC driver, how do MS developers explore a given .SDF file ?</p> <p>Thank you,</p> <p>BR,<BR> ~A</p>
<p>There is a free program called SQLCeEditor that does it.</p> <p>I'd still like a JDBC driver though since that would make it easy to use with Eclipse and Java.</p>
<p>If you're into linq syntax, you can also use <a href="http://www.linqpad.net/" rel="nofollow">LinqPad</a>. There's a free version that allows exploring the data and editing it. You would pay for autocompletion but you can live without it. I hope this helps.</p>
17,095
<p>I have a two way foreign relation similar to the following</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) </code></pre> <p>How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried</p> <pre><code>class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"}) </code></pre> <p>but that causes the admin interface to not list any children.</p>
<p>I just came across <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to" rel="noreferrer">ForeignKey.limit_choices_to</a> in the Django docs. Not sure yet how this works, but it might just be the right thing here.</p> <p><strong>Update:</strong> ForeignKey.limit_choices_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key. A constant obviously is of no use here, since it knows nothing about the objects involved.</p> <p>Using a callable (function or class method or any callable object) seems more promising. However, the problem of how to access the necessary information from the HttpRequest object remains. Using <a href="https://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user">thread local storage</a> may be a solution.</p> <p><strong>2. Update:</strong> Here is what has worked for me:</p> <p>I created a middleware as described in the link above. It extracts one or more arguments from the request's GET part, such as "product=1", and stores this information in the thread locals.</p> <p>Next there is a class method in the model that reads the thread local variable and returns a list of ids to limit the choice of a foreign key field.</p> <pre><code>@classmethod def _product_list(cls): """ return a list containing the one product_id contained in the request URL, or a query containing all valid product_ids if not id present in URL used to limit the choice of foreign key object to those related to the current product """ id = threadlocals.get_current_product() if id is not None: return [id] else: return Product.objects.all().values('pk').query </code></pre> <p>It is important to return a query containing all possible ids if none was selected so that the normal admin pages work ok.</p> <p>The foreign key field is then declared as:</p> <pre><code>product = models.ForeignKey( Product, limit_choices_to={ id__in=BaseModel._product_list, }, ) </code></pre> <p>The catch is that you have to provide the information to restrict the choices via the request. I don't see a way to access "self" here.</p>
<pre><code>from django.contrib import admin from sopin.menus.models import Restaurant, DishType class ObjInline(admin.TabularInline): def __init__(self, parent_model, admin_site, obj=None): self.obj = obj super(ObjInline, self).__init__(parent_model, admin_site) class ObjAdmin(admin.ModelAdmin): def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.inlines: inline = inline_class(self.model, self.admin_site, obj) if request: if not (inline.has_add_permission(request) or inline.has_change_permission(request, obj) or inline.has_delete_permission(request, obj)): continue if not inline.has_add_permission(request): inline.max_num = 0 inline_instances.append(inline) return inline_instances class DishTypeInline(ObjInline): model = DishType def formfield_for_foreignkey(self, db_field, request=None, **kwargs): field = super(DishTypeInline, self).formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == 'dishtype': if self.obj is not None: field.queryset = field.queryset.filter(restaurant__exact = self.obj) else: field.queryset = field.queryset.none() return field class RestaurantAdmin(ObjAdmin): inlines = [ DishTypeInline ] </code></pre>
28,762
<p>How do I go about the <code>[HandleError]</code> filter in asp.net MVC Preview 5?<br> I set the customErrors in my Web.config file</p> <pre><code>&lt;customErrors mode="On" defaultRedirect="Error.aspx"&gt; &lt;error statusCode="403" redirect="NoAccess.htm"/&gt; &lt;error statusCode="404" redirect="FileNotFound.htm"/&gt; &lt;/customErrors&gt; </code></pre> <p>and put [HandleError] above my Controller Class like this:</p> <pre><code>[HandleError] public class DSWebsiteController: Controller { [snip] public ActionResult CrashTest() { throw new Exception("Oh Noes!"); } } </code></pre> <p>Then I let my controllers inherit from this class and call CrashTest() on them. Visual studio halts at the error and after pressing f5 to continue, I get rerouted to Error.aspx?aspxerrorpath=/sxi.mvc/CrashTest (where sxi is the name of the used controller. Off course the path cannot be found and I get "Server Error in '/' Application." 404.</p> <p>This site was ported from preview 3 to 5. Everything runs (wasn't that much work to port) except the error handling. When I create a complete new project the error handling seems to work.</p> <p>Ideas?</p> <p><strong>--Note--</strong><br> Since this question has over 3K views now, I thought it would be beneficial to put in what I'm currently (ASP.NET MVC 1.0) using. In the <a href="http://www.codeplex.com/MVCContrib" rel="noreferrer">mvc contrib project</a> there is a brilliant attribute called "RescueAttribute" You should probably check it out too ;)</p>
<pre><code>[HandleError] </code></pre> <p>When you provide only the HandleError attribute to your class (or to your action method for that matter), then when an unhandled exception occurs MVC will look for a corresponding View named "Error" first in the Controller's View folder. If it can't find it there then it will proceed to look in the Shared View folder (which should have an Error.aspx file in it by default)</p> <pre><code>[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")] [HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")] </code></pre> <p>You can also stack up additional attributes with specific information about the type of exception you are looking for. At that point, you can direct the Error to a specific view other than the default "Error" view.</p> <p>For more information, take a look at <a href="http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx" rel="noreferrer">Scott Guthrie's blog post</a> about it.</p>
<pre><code> [HandleError] public class ErrorController : Controller { [AcceptVerbs(HttpVerbs.Get)] public ViewResult NotAuthorized() { //401 Response.StatusCode = (int)HttpStatusCode.Unauthorized; return View(); } [AcceptVerbs(HttpVerbs.Get)] public ViewResult Forbidden() { //403 Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [AcceptVerbs(HttpVerbs.Get)] public ViewResult NotFound() { //404 Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } public ViewResult ServerError() { //500 Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } </code></pre> <p>}</p>
22,159
<p>How would you ensure that only one user is logged in per account at a time?</p> <p>Assuming cookies are persistent.</p>
<p>Typically the best way is to implement a customization on the provider that checks for last login, as well as adding methods to your code to keep track of user action.</p> <p>The key is that you must know at what point did the user last do something OR logout. From there you can determine if the account is actually ready. If you setup the tracking for these elements in code, You can then modify the membership provider to check to ensure that the account can login.</p>
<p>Conceptually you have to decide how you want to respond. If you have User A logged in and then User B attempts to login (using the same credentials) do you:</p> <ol> <li>Kick User A out</li> </ol> <p>or </p> <ol start="2"> <li>Not allow a login from User B </li> </ol> <p>(2) is problematic because you need to reliably know that User A has logged out to determine whether to login User B. User A could be just looking at a page on your site for a while, so doing via time might not be the best. Maybe some sort of AJAX watchdog that pings your website every 30 seconds. </p> <p>(1) also requires some work. When a user logs in, you would want to store their cookie value (probably in the database) and add it to a list issued cookies for this user. That way only the last cookie issued (last login) would be accepted. If you see one of the earlier cookies, then you would log that person out.</p>
38,984
<p>I had recently a problem with oom-killer starting to kill processes after some time. I could see that the memory was consumed, but by the time I got to the server it wasn't clear anymore what consumed it. Is there a good non-obvious place to get more info about oom-killer? E.g. detailed info about processes at the time of activation, detailed info about killed processes and reasons for the choice?</p> <p>I'm looking for a specific place to find this information, specific tool to gather it or some configuration to improve oom-killer reporting. I'm not looking for generic info about oom-killer. /var/messages by default will only contain a detailed report on the free/allocated memory, but not specific processes it was allocated to.</p>
<p>You can check the messages log file to see which process got killed and some related information. As for the reasons:</p> <blockquote> <p>... the ideal candidate for liquidation is a recently started, non privileged process which together with it's children uses lots of memory, has been nice'd, and does no raw I/O. Something like a nohup'd parallel kernel build (which is not a bad choice since all results are saved to disk and very little work is lost when a 'make' is terminated).</p> </blockquote> <p>From <a href="http://linux-mm.org/OOM_Killer" rel="nofollow noreferrer">here</a>. </p> <p>You can define some processes to be immune to the killer, adjust the swappiness parameter in case you have it too low (which makes the killer trigger happy) and check for things listed <a href="http://linux.derkeiler.com/Mailing-Lists/RedHat/2007-08/msg00061.html" rel="nofollow noreferrer">here</a></p>
<p>Typically you should get a message in /var/log/messages, with quite a large amount of detail relating to the process that was killed by the oom-killer.</p>
14,593
<p>For learning and demonstrating, I need a macro which prints its parameter <strong>and</strong> evaluates it. I suspect it is a very common case, may be even a FAQ but I cannot find actual references.</p> <p>My current code is:</p> <pre><code>#define PRINT(expr) (fprintf(stdout, "%s -&gt; %d\n", __STRING(expr), (expr))) </code></pre> <p>and then:</p> <pre><code>PRINT(x &amp; 0x01); </code></pre> <p>It works fine but I am not sure of the legal status of the __STRING macro, specially since it is in the private __ namespace.</p> <p>So, my questions:</p> <ol> <li>Is there a better way to write this macro?</li> <li>Is __STRING standard/great/evil?</li> <li>How to use existing search tools to find about __STRING? SO's search engine just searches anything containing string :-(</li> </ol>
<p>You can use the # preprocessor token which converts the parameter following it to a string literal:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #define STR(x) #x #define PRINT(expr) (fprintf(stdout, &quot;%s -&gt; %d\n&quot;, STR(expr), (expr))) int main(void) { int x = 7; PRINT(x &amp; 0x01); return EXIT_SUCCESS; } </code></pre> <ol start="2"> <li><p>It's definitely not standard, and this is the first time I've come across it; not surprising as it doesn't seem to do much more than the STR() macro above, at a first glance.</p> </li> <li><p><a href="http://www.google.com/search?&amp;q=__string&amp;btnG=Search" rel="nofollow noreferrer">Google</a> seems to work fine.</p> </li> </ol>
<p>It is <strong>glibc</strong> who has been providing <code>__STRING</code> since (at least) version 1.04 (1992-09-03), maybe earlier.</p> <p>/usr/include/sys/cdefs.h:</p> <pre><code>#define __CONCAT(x,y) x ## y #define __STRING(x) #x </code></pre> <p>They were both used in glibc back then. Currently, <code>__STRING</code> is not used in glibc, but is kept there for app use.</p> <p>On Linux, you may rely upon these. IIUC, <code>__STRING</code> and <code>__CONCAT</code> were adopted in NetBSD 1.3; Solaris provides neither. Other OSes may vary.</p>
49,424
<p>How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.</p> <p>I'm not sure what routines are available on all browsers, how &quot;random&quot; and seeded the built-in random number generator is, etc.</p>
<p>UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to <a href="https://www.ietf.org/rfc/rfc4122.txt" rel="noreferrer">RFC 4122</a>, are identifiers designed to provide certain uniqueness guarantees.</p> <p>While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see <a href="https://stackoverflow.com/a/2117523/109538">@broofa's answer</a>, below) there are several common pitfalls:</p> <ul> <li>Invalid id format (UUIDs must be of the form &quot;<code>xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx</code>&quot;, where x is one of [0-9, a-f] <em>M</em> is one of [1-5], and <em>N</em> is [8, 9, a, or b]</li> <li>Use of a low-quality source of randomness (such as <code>Math.random</code>)</li> </ul> <p>Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the <a href="https://github.com/uuidjs/uuid" rel="noreferrer">uuid</a> module.</p>
<p>Here's a method that generates <code>RFC4122</code> using true random via <code>random.org</code>. If the fetch fails it falls back to the browser's inbuilt <code>crypto</code> library which should almost be just as good. And finally, if the user's browser in question doesn't support that, it uses <code>Math.random()</code>.</p> <pre><code>async function UUID() { //get 31 random hex characters return (await (async () =&gt; { let output; try { //try from random.org output = (await ( await fetch('https://www.random.org/integers/?num=31&amp;min=0&amp;max=15&amp;col=31&amp;base=16&amp;format=plain&amp;rnd=new') ).text()) //get rid of whitespace .replace(/[^0-9a-fA-F]+/g, '') ; if (output.length != 31) throw ''; } catch { output = ''; try { //failing that, try getting 16 8-bit digits from crypto for (let num of crypto.getRandomValues(new Uint8Array(16))) //interpret as 32 4-bit hex numbers output += (num &gt;&gt; 4).toString(16) + (num &amp; 15).toString(16); //we only want 31 output = output.substr(1); } catch { //failing THAT, use Math.random while (output.length &lt; 31) output += (0 | Math.random() * 16).toString(16); } } return output; })()) //split into appropriate sections, and set the 15th character to 4 .replace(/^(.{8})(.{4})(.{3})(.{4})/, '$1-$2-4$3-$4-') //force character 20 to the correct range .replace(/(?&lt;=-)[^89abAB](?=[^-]+-[^-]+$)/, (num) =&gt; ( (parseInt(num, 16) % 4 + 8).toString(16) )) ; } </code></pre> <p><a href="https://i.stack.imgur.com/4pby2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4pby2.png" alt="enter image description here" /></a></p>
13,065
<p>Is there a way to find out the size of a SQL Server database using WMI from .NET?</p> <p>I've had a look at the <a href="http://msdn.microsoft.com/en-us/library/ms180499.aspx" rel="noreferrer">WMI documentation</a> but I'm not clear how I'd be able to locate that information.</p> <p>We're using SQL Server 2008.</p> <p>-dave</p>
<p>You can access this property via Microsoft.SqlServer.Management.Smo. Give this a try: <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.database.size.aspx" rel="nofollow noreferrer">MSDN</a></p>
<p>A bit of a tangential answer, but whenever I want to play with WMI, I first take a quick look with <a href="http://www.microsoft.com/technet/scriptcenter/tools/scripto2.mspx" rel="nofollow noreferrer">Scriptomatic</a>, Microsoft's WMI browser.</p> <p>Doing so against SQL <strong>Express 2005</strong>, the only WMI functionality seems to be with regard to the server itself, and not for any of the databases.</p>
44,600
<p>I'm working on a video streaming application in Flash and I've been told I need to add quality selection tools. The requirements are "low", "medium" and "high" quality. I'm trying to figure out what kinds of quality settings to actually apply for this (framerate and video quality settings). I feel like there has to be some kind of standard for this, as I see controls like this fairly often, but I haven't been able to find any reference online for it.</p> <p>Does anyone know of any standard settings for "low", "medium" and "high" qualities for a live streaming video from a webcam? Or even a good reference as a starting point to coming up with my own values?</p>
<p>It may be a better idea to just define bandwidth points and then look at your codec to identify the best quality for a given point. Then you can give each of those bandwidth points a 'normal' name. like:</p> <ul> <li>56k is 320x240 @ 8fps and is "low quality" </li> <li>256k is 640x480 @ 8fps and is "medium quality" </li> <li>512k is 640x480 @ 24fps and is "high quality"</li> </ul> <p>That is just my guess though.</p>
<p>I ended up coming up with some values, though they're probably not standard.</p> <p>I realized after asking the question that my needs probably didn't fit the standards, as my resolution was fixed at 160x120 as that's the size of the component that was viewing the video. I just ended up using the video quality settings of 100, 80, and 60 for the different settings. Ended up being much simpler than I expected it to (I was originally thinking of mucking with framerate and resolution as well as the quality value, but it ended up not being needed).</p>
47,066
<p>Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title.</p> <p>I have a similar problem but needing multiple aggregates. I'd like to display a list of items in any of 3 formats depending on user options:</p> <ul> <li>My item's name (15 total, 13 owned by me)</li> <li>My item's name (15 total)</li> <li>My item's name (13 owned by me)</li> </ul> <p>My database is:</p> <ul> <li><strong>items</strong>: itemId, itemName, ownerId</li> <li><strong>categories</strong>: catId, catName</li> <li><strong>map</strong>: mapId, itemId, catId</li> </ul> <p>The query below gets: category name, count of item ids per category</p> <pre><code>SELECT categories.catName, COUNT(map.itemId) AS item_count FROM categories LEFT JOIN map ON categories.catId = map.catId GROUP BY categories.catName </code></pre> <p>This one gets: category name, count of item ids per category for this owner_id only</p> <pre><code>SELECT categories.catName, COUNT(map.itemId) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId WHERE owner = @ownerId GROUP BY categories.catId </code></pre> <p>But how do i get them at the same time in a single query? I.e.: category name, count of item ids per category, count of item ids per category for this owner_id only</p> <p>Bonus. How can I optionally only retrieve where catId count != 0 for any of these? In trying "WHERE item_count &lt;> 0" I get:</p> <pre><code>MySQL said: Documentation #1054 - Unknown column 'rid_count' in 'where clause' </code></pre>
<p>Here's a trick: calculating a <code>SUM()</code> of values that are known to be either 1 or 0 is equivalent to a <code>COUNT()</code> of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL).</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid; </code></pre> <p>As for the bonus question, you could simply do an inner join instead of an outer join, which would mean only categories with at least one row in <code>map</code> would be returned.</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c INNER JOIN map m USING (catid) INNER JOIN items i USING (itemid) GROUP BY c.catid; </code></pre> <p>Here's another solution, which is not as efficient but I'll show it to explain why you got the error:</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid HAVING item_count &gt; 0; </code></pre> <p>You can't use column aliases in the <code>WHERE</code> clause, because expressions in the <code>WHERE</code> clause are evaluated before the expressions in the select-list. In other words, the values associated with select-list expressions aren't available yet.</p> <p>You can use column aliases in the <code>GROUP BY</code>, <code>HAVING</code>, and <code>ORDER BY</code> clauses. These clauses are run after all the expressions in the select-list have been evaluated.</p>
<p>You can sneak a CASE statement inside your SUM():</p> <pre><code>SELECT categories.catName, COUNT(map.itemId) AS item_count, SUM(CASE WHEN owner= @ownerid THEN 1 ELSE 0 END) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId GROUP BY categories.catId HAVING COUNT(map.itemId) &gt; 0 </code></pre>
35,677
<p>I'm trying to write a Wordpress plug-in that automatically posts a blog post at a certain time of day. For example, read a bunch of RSS feeds and post a daily digest of all new entries.</p> <p>There are plug-ins that do something similar to what I want, but many of them rely on a cron job for the automated scheduling. I'll do that if I have to, but I was hoping there was a better way. Getting a typical Wordpress user to add a cron job isn't exactly friendly.</p> <p>Is there a good way to schedule a task that runs from a Wordpress plug-in? It doesn't have to run at exactly the right time.</p>
<p><a href="http://codex.wordpress.org/Function_Reference/wp_schedule_event" rel="nofollow noreferrer">http://codex.wordpress.org/Function_Reference/wp_schedule_event</a></p>
<p>vBulletin uses a sort of Pseudo-Cron system, that basically checks a schedule on every page access, and fires any processes that are due then.</p> <p>It's been a while since I worked with Wordpress, but I think something like this should work if it runs on each page view. </p>
7,762
<p>If I have a table like:</p> <pre><code>CREATE TABLE FRED ( recordId number(18) primary key, firstName varchar2(50) ); </code></pre> <p>Is there an easy way to clone it's structure (not it's data) into another table of a given name. Basically I want to create table with exactly the same structure, but a different name, so that I can perform some functionality on it. I want to do this in code obviously. Java preferably, but most other languages should be similar.</p>
<p>If you're looking a way to find the exact DDL to recreate the table, including the storage clause, you can use </p> <pre><code>select dbms_metadata.get_ddl('TABLE', 'TABLE_NAME', 'SCHEMA_NAME') from dual </code></pre> <p>as described <a href="http://www.troygeek.com/articles/ExtractingOracleDDLCommandLine/" rel="noreferrer">here</a>.</p>
<pre><code>SELECT INTO TARGET_TABLE FROM SOURCE_TABLE; OR CREATE TABLE TARGET_TABLE_NAME AS SELECT * FROM SOURCE_TABLE; </code></pre> <p>if you want to copy only the structure then add the Where Clause <code>WHERE 1=2</code>.</p> <p>I hope it will be helpful.</p>
32,595
<p>I am fortunate to be working for a company in which all of our new development efforts are all in WPF. Are there a lot of other developers out there in this situation? Are companies quickly adopting this as their primary UI platform? As developers we all see the value in it, but are companies buying into it?</p>
<p>I think the major problem for the companies to adapt this new technology are </p> <ul> <li>learning curve on XAML and new UI concepts</li> <li>Developers have to forget all the knowledge they got on Winforms(or equivalent UI) technologies, most people are reluctant to give up their expertise.</li> <li>The need for the new skill called "UX Integrators" who should be able to work with the new RIA tool called Expression Blend to style/integrate the design with the code.</li> <li>The need for new Framework requirement(.NET3.5) and the new set of tools make companies or clients think twice before they take this route. They usually think that this may be a 'risky' path. </li> </ul> <p><a href="http://identitymine.com/" rel="nofollow noreferrer">My company</a> is concentrating mainly on the Microsoft RIA technologies like WPF and Silverlight. And we are helping other companies to bootstrap their WPF development efforts by creating Proof of concept/Prototype applications to show the power/easiness of WPF.</p>
<p>Our company is also doing most new development in WPF. It is working fairly well for us. However, it took 2-3 months for the organization to overcome the learning curve and to begin the "WPF Way of Thinking." </p> <p>Similar to Louis' point, I think one of the reasons it is slow to take hold of the industry is that designers are hesitant to learn the Expression suite. Once there are an adequate number of Expression designers out there, I think companies will see more immediate benefit of using WPF.</p> <p>One of the key benefits to WPF is the vector graphics. Because we develop apps that could be used on small laptops and rugged PCs, the ability of the UI to scale to different sizes of monitors is very beneficial.</p>
44,807
<p>I just bought a new RAMPS 1.6 shield to replace my old RAMPS 1.4 shield. The problem is that it's just not working, the motors don't move, heatbed/nozzle don't get heated. It was all working with the RAMPS 1.4 shield.</p> <p>I checked the RAMPS 1.6 and there's no bridging in the solder joints.</p> <p>The DRV8255 is drawing current also but the motor doesn't move.</p> <p>I am using Repetier Firmware. I tried Marlin (default) and even it's not working.</p>
<p>IMHO, it's probably better to get the printer as-is first. This way you can get familiar with the printer and 3D printing in general before you get overwhelmed with all the extra introduced variables from your upgrades.</p> <p>The new model already has loads of features that were considered upgrades on the older model and you can already get very nice results.</p> <p>Upgrading your printer is a part of the 3D printing hobby, and you'll probably never be done with it :)</p>
<p>I have an Ender 3 v2 and I haven't upgraded anything except updating the firmware. The first thing I suggest is updating the firmware and changing the hotend to an all-metal one. This will allow you to print in higher temperatures and adding a BLTouch for automatic bed leveling will make your life a bit easier.</p>
1,737
<p>My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists!</p> <p>so far, <a href="http://www.zend.com/en/products/studio/features" rel="noreferrer">Zend studio 6</a>, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this?</p> <p>edit: a bit more information: right now, using zend-6 under eclipse, i type in</p> <pre><code>&lt;?php p //(a single letter "p") </code></pre> <p>and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however).</p> <p>However, I get nothing when I do:</p> <pre><code>&lt;style&gt; b /* (a single letter "b") */ </code></pre> <p>I'd love it if I could get, from that "b" suggestions for "border", "bottom", etc. The same applies for Javascript.</p> <p>Any ideas?</p>
<p>I think the JavaScript and CSS need to be in separate files for this to work.</p> <p>Example of CSS autocomplete in Eclipse:</p> <p>Starting to type <code>border</code></p> <blockquote> <p><img src="https://i.stack.imgur.com/h4Sj9.png" alt="css example in eclipse"></p> </blockquote> <p>Then setting thickness</p> <blockquote> <p><img src="https://i.stack.imgur.com/mmaEe.png" alt="autocompleting border thickness"></p> </blockquote> <p>Then choosing the color</p> <blockquote> <p><img src="https://i.stack.imgur.com/Up41q.png" alt="autocompleting border color"></p> </blockquote> <p>Chose red, and it added the ; for me</p> <blockquote> <p><img src="https://i.stack.imgur.com/Up41q.png" alt="alt text"></p> </blockquote> <p>Works pretty good IMHO.</p>
<p>The default CSS and HTML editors for Eclipse are really good. The default javascript editor does an OK job, but it needs a little work.</p> <p>I just tested this in Eclipse 3.3.2</p> <pre><code>function test(){ } te&lt;CTRL+SPACE&gt; </code></pre> <p>and it completed the method for me as did this:</p> <pre><code>var test = function(){ }; te&lt;CTRL+SPACE&gt; </code></pre> <p>Can you expand on what more you wanted it to do?</p>
2,681
<p>I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScreenWindow(this) to go into FSEM, the mouse cursor comes back, and subsequent calls to setCursor() to set it back to my blank cursor have no effect. Calling device.setFullScreenWindow(null) allows me to get rid of the cursor again - it's only while I'm in FSEM that I can't get rid of it.</p> <p>I'm working under JDK 6, target platform is JDK 5+.</p> <p><strong>UPDATE:</strong> I've done some more testing, and it looks like this issue occurs under MacOS X 10.5 w/Java 6u7, but not under Windows XP SP3 with Java 6u7. So, it could possibly be a bug in the Mac version of the JVM.</p>
<p>Try Creating a custom invisible cursor:</p> <pre><code> Toolkit toolkit = Toolkit.getDefaultToolkit(); Point hotSpot = new Point(0,0); BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT); Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, "InvisibleCursor"); setCursor(invisibleCursor); </code></pre>
<p>I don't know if this knowledge applies but in a old VB6 app I had the same problem and I got rid of it moving the cursor out of the screen giving it some very large values.<br> Hope it helps.</p>
23,267
<p>Is it possible to use DateTimePicker (Winforms) to pick both date and time (in the dropdown)? How do you change the custom display of the picked value? Also, is it possible to enable the user to type the date/time manually?</p>
<p>Set the Format to Custom and then specify the format:</p> <pre><code>dateTimePicker1.Format = DateTimePickerFormat.Custom; dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss"; </code></pre> <p>or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)</p> <p>Don't know about the picker for date and time together. Sounds like a custom control to me.</p>
<p>If you need (24 hours) military time. You should use &quot;HH&quot; instead of &quot;hh&quot;.</p> <p>&quot;MM/dd/yyyy HH:mm&quot;</p>
11,900
<p>I'm currently trying to implement a marble maze game for a WM 5.0 device and have been struggling with developing a working prototype. The prototype would need the user to control the ball using the directional keys and display realistic acceleration and friction. </p> <p>I was wondering if anyone has experience with this and can give me some advice or point me in the right direction of what is essential and the best way to go around doing such a thing.</p> <p>Thanks in advance.</p> <p>Frank.</p>
<p>When reading your answer I didn't get the feeling you are looking for a game framework, but more: how can I easily model a ball with acceleration and friction.</p> <p>For this you don't need a full fledged physics framework since it is relatively simple to do:</p> <p>First create a timer which fires 30 times a second, and in the timer callback do the following:</p> <ul> <li>Draw the maze background</li> <li>Draw a ball at ballX, ballY (both floating point variables)</li> <li>Add ballSpdX to ballX and add ballSpdY to ballY (the speed)</li> </ul> <p>Now check the keys...</p> <ul> <li>if the directional key is left, then subtract a small amount of ballSpdX</li> <li>if the directional key is topleft, then subtract a small amount of ballSpdX and ballSpdY</li> <li>etc</li> </ul> <p>For collision do the following:</p> <ul> <li>first move the ball in the horizontal direction. Then check the collisions with the walls. If a collision has been detected, then move the ball back to its previous positions and reverse the speed: ballSpdX = -ballSpdX</li> <li>move the ball in the vertical direction. Then check the collisions with the walls. If a collision has been detected, then move the ball back to its previous positions and reverse the speed: ballSpdY = -ballSpdY</li> </ul> <p>by handling the vertical and horizontal movement separately, the collision is much easier since you know which side the ball needs to bounce to.</p> <p>last nu not least friction, friction is just doing this every frame: ballSpdX *= friction; Where friction is something like 0.99. This makes sure the speed of the ball get's smaller every frame due to friction;</p> <p>Hope this helped</p>
<p>I would recommend checking out XNA Studio 3, it has built in support for PC, Xbox 360 and mobile devices, and it's an official &amp; free spin-off of Visual Studio from Microsoft.</p> <p><a href="http://creators.xna.com/en-US/" rel="nofollow noreferrer">http://creators.xna.com/en-US/</a></p> <p><a href="http://blogs.msdn.com/xna/" rel="nofollow noreferrer">http://blogs.msdn.com/xna/</a></p> <p>If you search around, people have written tutorials using physics (velocity on this one) <a href="http://www.xnamachine.com/2007/12/fun-with-very-basic-physics.html" rel="nofollow noreferrer">http://www.xnamachine.com/2007/12/fun-with-very-basic-physics.html</a></p>
41,718
<p>What is the best way to track down a memory leak that is only found on one customer's test/release box, and no where else?</p>
<p><a href="http://www.jetbrains.com/profiler/index.html" rel="nofollow noreferrer">dotTrace3.1</a></p> <p>(This question is kinda funny, cause I am tracking a mem leak that isn't present on my machine ...)</p>
<p>If the user has the problem it consistently, take a stackdump and analyse in the standard way</p>
18,183
<p>i met a problem with iphone simulator application directory, when i run the application everytime, the name of application directory was changed each of time,can anyone tell me how to keep a static application directory ?</p>
<p>i'm going to take a guess here and say..</p> <p>you don't need a static directory.</p> <p>I think what you need is to get the 'base directory' programatically.</p> <pre> NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"]; </pre> <p>you should be saving your user files there (or somewhere similar)</p> <p>or alternatively something like</p> <pre> NSBundle* bundle = [NSBundle mainBundle]; NSString* path = [bundle executablePath] //or NSString* path = [bundle resourcePath]; </pre> <p>and then append your own paths onto that.</p> <p>hope that helps.</p> <p>NEW INFO:</p> <p>If you are saving information, (a log, stats etc..) you can retrieve the files saved in the NSDocumentDirectory above using the Xcode organiser.</p> <ul> <li>select your device</li> <li>got the summary tab</li> <li>find you application in 'Applications' section.</li> <li>expand the entry and it should have an 'Applcation data' entry.</li> <li>press the down arrow on the right to save your files.</li> </ul>
<p>If you simply relaunch the app from within the simulator springboard it will keep using the same directory. If you rebuild the app in Xcode it will move, and there is no way to prevent that. Xcode should migrate any data you have from the old directory to the new directory when it installs the new build.</p>
34,156