instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I am working on an If statement and I want to satisfy two conditions to ignore the loop. This seemed easy at first, but now... I don't know. this is my dilemma...</p> <pre><code>if((radButton1.checked == false)&amp;&amp;(radButton2.checked == false)) { txtTitle.Text = "go to work"; } </code></pre> <p>The dilemma is "go to work" is not executed if radButton1 is false and radButton2 is true. Shouldn't it require both conditions to be false in order to skip the statement?</p>
<p>No, it requires them to both be false to <em>execute</em> the statement.</p>
<p>No. It requires one of those statements to be false to skip. Look at your if:</p> <pre><code>if (condition1 &amp;&amp; condition2) { doSomething(); } </code></pre> <p>So if condition1 OR condition2 is not true then it won't execute.</p>
41,092
<p>I have a simple grammar, and have produced a pair of c# classes using antlr 2.7.7. When the parser finds an error with a token, it throws an exception; I want to find out how many characters into a parsed stream the token came. How do I do that?</p>
<p>We use <a href="http://www.browsercam.com/" rel="noreferrer">BrowserCam</a> for exactly that.</p>
<p>Check out the <a href="http://wiki.osx86project.org/wiki/index.php/Vmware_how_to" rel="nofollow noreferrer">OSx86 Project</a>. I've used this before, it works quite well and is pretty easy to understand.</p>
21,487
<p>I'm developing a site in Visual Web Dev Express, and when I run/debug, I'd like to be able to set my application's document root so that I can use safer paths, like "/css/style.css' instead of "css/style.css". How would I accomplish this?</p>
<ul> <li>Click on the web site node in the solution explorer.</li> <li>Press F4 to see the properties window.</li> <li>Change the virtual path from <strong>/projectname</strong> to <strong>/</strong></li> </ul> <p>Bear in mind that this has an impact on how you expect the application/web site to be deployed. If it is ever used outside the root of a web server, the URL paths will be incorrect.</p>
<p>I have been looking for the virtual path field in the properties window but haven't been able to find it... it only shows me the following options</p> <ul> <li>aperture directory URL</li> <li>complete access route</li> <li>policy file</li> <li>port</li> <li>use dynamic port</li> </ul> <p>Do you know of some place else where I could find the Virtual Path field?</p>
4,147
<p>Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number. </p> <p>For example, in Prototype this works:</p> <pre><code>$$('li')[5].addClassName('active'); </code></pre> <p>But this will not work no matter how I try to cast the variable as a number or integer:</p> <pre><code>$$('li')[currentPage].addClassName('active'); </code></pre> <p>In jQuery I get similar weirdness. This will work:</p> <pre><code>jQuery('li').eq(5).addClass("active"); </code></pre> <p>But this will not work again even though the value of currentPage is 5 and its type is number:</p> <pre><code>jQuery('li').eq(currentPage).addClass("active"); </code></pre> <p>I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.</p>
<p>Are you certain that <code>currentPage</code> is an integer? Try something like:</p> <pre><code>var currentPage = 5; jQuery('li').eq(currentPage); </code></pre> <p>as a simple sanity check. If that works, you should try casting to <code>Integer</code>.</p>
<p>Make sure that the currentPage variable is correctly scoped in the code where it is being accessed. Could the variable be changed somewhere else in the code before you are accessing it? Tools like <a href="https://addons.mozilla.org/firefox/addon/1843" rel="nofollow noreferrer">Firebug</a> can help you to add a breakpoint at the point of execution and see the value of your variable.</p>
6,181
<p>I would like to be able to fetch a web page's html and save it to a <code>String</code>, so I can do some processing on it. Also, how could I handle various types of compression.</p> <p>How would I go about doing that using Java?</p>
<p>Here's some tested code using Java's <a href="http://java.sun.com/javase/6/docs/api/java/net/URL.html" rel="noreferrer">URL</a> class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.</p> <pre><code>public static void main(String[] args) { URL url; InputStream is = null; BufferedReader br; String line; try { url = new URL("http://stackoverflow.com/"); is = url.openStream(); // throws an IOException br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { // nothing to see here } } } </code></pre>
<blockquote> <p>I used the actual answer to this post (<a href="https://stackoverflow.com/a/238634/2683452">url</a>) and writing the output into a file.</p> </blockquote> <pre><code>package test; import java.net.*; import java.io.*; public class PDFTest { public static void main(String[] args) throws Exception { try { URL oracle = new URL("http://www.fetagracollege.org"); BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream())); String fileName = "D:\\a_01\\output.txt"; PrintWriter writer = new PrintWriter(fileName, "UTF-8"); OutputStream outputStream = new FileOutputStream(fileName); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); writer.println(inputLine); } in.close(); } catch(Exception e) { } } } </code></pre>
29,507
<p>I've got shared hosting on a LAMP set up. Obviously the fewer calls to the Db per page the better. But how many is too many? Two? Ten? A hundred? Curious what people think.</p>
<p>That really depends on your (db)servers setup. Try to cache most of information as possible and reduce db calls to a minimum. A database will (almost in every case) be the bottleneck of your service - the higher the usage of your site. So whatever you do try to avoid fireing a query as if not really necessary.</p> <p>I try not to use more than 10 db calls per page, but that really depends on your infrastructure and the information you want to provide.</p>
<p>One or less is always best. Two is usually one too many. </p> <p>If you can return multiple result sets in a single query, then do it. If the information is fairly static, then cache it and pull from cache. </p> <p>10 separate database calls is not good, but its not going to kill a low usage site. </p>
48,499
<p>I have an ASP.net website ( <a href="http://www.erate.co.za" rel="nofollow noreferrer">http://www.erate.co.za</a> ) version 2.0. When someone opens my website in Firefox everything looks different.</p> <p>Why is that and how can I make it compatible?</p> <p>Please help!</p> <p>Etienne</p>
<p>The problems don't have anything to do with ASP.NET / C# Specifically.</p> <p>They have to do with your understanding of web design / HTML / CSS and how you can make a cross-browser compatible UI.</p> <p>I'd suggest you look at <a href="http://www.w3schools.com/" rel="noreferrer">http://www.w3schools.com/</a> for some information on good web design practices.</p> <p>Some obvious problems with the Source that you need to address are </p> <ul> <li>No common css Stylesheets </li> <li>Styles are applied inline on lots of elements</li> <li>using long strings of "&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;" to align text</li> </ul>
<p>Per se, ASP.NET produce vanilla HTML/Javascript, so there's nothing wrong with the technology.</p> <p>Focus on the html, try to be as close as possible to the <a href="http://validator.w3.org/" rel="nofollow noreferrer">w3c standards</a>, it should help a lot.</p> <p><a href="http://getfirebug.com/" rel="nofollow noreferrer">Firebug</a>, an incredible web dev extension for Firefox should also help you a lot in debugging your CSS.</p> <p>It might be a painful task, especially if your site is old and big. Good luck!</p>
33,168
<p>I just did a <strong>delete from table</strong></p> <p>How do I roll back or undelete the rows??</p>
<p>if you called <code>begin transaction</code> before you did it, and have not yet called <code>commit</code>, then you can call <code>rollback</code>, otherwise... you're gonna have to restore</p>
<p>if you prefaced the delete with a begin tran you just use rollback tran</p> <p>if not, start looking for your backups.</p>
17,144
<p>I'm struggling to understand Dependency Properties in Silverlight 2. Does anybody have a good explanation or link that clearly explains the DependencyObject and/or DependencyProperty?</p>
<pre><code>Dictionary&lt;object, object&gt; list = new Dictionary&lt;object, object&gt;(); foreach (object o in enumerable) if (!list.ContainsKey(o)) { // Do the actual work. list[o] = null; } </code></pre> <p>Dictionary will use a hash table to hold keys therefore lookup is efficient.</p> <p>Sorting will be O(n log(n)) at best. A hash table with an efficient hash function often outperforms it (O(1) lookups).</p>
<p>Another alternative is to use HashSet&lt;T&gt; - a HashSet doesn't allow duplicate items to be used and doesn't require a key/value pair.</p>
44,815
<p>How do you implement autocomplete on ASP.Net Gridview? Can anyone point me where to go to achieve this? I'm willing to use non-.Net ajax controls if that what it takes.</p>
<p>You will need to utilise an AJAX framework (<a href="http://www.jquery.com/" rel="nofollow noreferrer">JQuery</a> is one i often recommend) which will provide the functionality to display the drop down box. You will then need to create a separate page (or web service) to return all the possible values to display in the auto-complete drop down.</p> <p>To save on performance i recommend only initiating the auto-complete once the user has typed in 2 or 3 letters. These can then be passed by the JavaScript to the backed to proivde values to show in the drop down list.</p> <p>The back end can communicate with the JavaScript using either simple CSV, JSON, XML Web service etc. See <a href="http://www.pengoworks.com/workshop/jquery/autocomplete.htm" rel="nofollow noreferrer">http://www.pengoworks.com/workshop/jquery/autocomplete.htm</a> for examples.</p>
<p>The AJAX Control Toolkit provides an <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx" rel="nofollow noreferrer">autocomplete</a> but requires a web service to work. You could always write your own asmx if there isn't one you can use.</p> <p>Otherwise, there are all sorts of JS and jQuery examples: <a href="http://www.javascript-examples.com/autocomplete-demo/" rel="nofollow noreferrer">http://www.javascript-examples.com/autocomplete-demo/</a></p>
11,473
<p>Are there any 3D printing services or something similar to 3D print or injection mold light reflectors? </p> <p>I'm trying to find something that is similar to PCB printing that allows you to upload a 3D design of a reflector and they will produce this reflector and coat it with mirror surface.</p>
<p>I would not recommend extrusion printers for this, because they are unlikely to produce a smooth enough surface. To get a clean surface, the irregularities have to be a fraction of visible wavelengths, which is to say on the order of 0.01 micron.<br> Without knowing what sort of reflector you're thinking of (flat? spherical? parabolic?), it's hard to recommend a specific optimal, cheap approach. All in all, you're probably best off looking in standard catalogs such as Edmund Optics.</p>
<p>I would not recommend extrusion printers for this, because they are unlikely to produce a smooth enough surface. To get a clean surface, the irregularities have to be a fraction of visible wavelengths, which is to say on the order of 0.01 micron.<br> Without knowing what sort of reflector you're thinking of (flat? spherical? parabolic?), it's hard to recommend a specific optimal, cheap approach. All in all, you're probably best off looking in standard catalogs such as Edmund Optics.</p>
415
<p>Where can I set it? I need files to be encoded in UTF-8 by default... there is nothing in Tools -> Options or any other menu as far as I know :( </p> <p>P.S. I don't need to set default encoding for Project or so, I need it to be default for any files I create. Thanks for your help :)</p>
<p>Instead of clicking save click save as. Then click the little down arrow by save to save with encoding. Once this is done it will bring you to the advanced save options which appear in full VS studio. You can then pick UTF-8 as the encoding.</p>
<p>IIRC, source files in visual studio are already encoded as UTF-8. </p> <p>However, if I'm wrong or if you just want to force any specific coding, you can do it by choosing the <code>Save As...</code> option for the file and checking the pull down options under the save button from there.</p>
38,054
<p>I have been trying to determine a best case solution for registering a COM server using WiX to create a Windows Installer package and am struggling.</p> <p>In this post <a href="http://blog.deploymentengineering.com/2008/09/howto-use-regsvr32exe-with-wix.html" rel="nofollow noreferrer">Deployment Engineering Archive: HOWTO: Use Regsvr32.exe with WIX</a>, there is an open request for the "Setup police" to crack down on using regsvr32 through an exe custom action. I know the evils of using <code>regsvr32</code> as it registers to the system rather than the user, but I also recall that <code>OleSelfRegister</code> can have issues from a microsoft support bulletin (sorry, can't find the link) - and I believe they recommended using <code>regsvr32</code>.</p> <p>Any advice?</p>
<p>Read "Do not use the SelfReg and TypeLib tables" at:</p> <p><a href="https://msdn.microsoft.com/en-us/library/bb204770#no_selfreg" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/bb204770#no_selfreg</a></p> <p>For WiX, take a look at the <em>Component</em> element in the schema reference at:</p> <p><a href="http://wixtoolset.org/documentation/manual/v3/xsd/wix/component.html" rel="nofollow noreferrer">http://wixtoolset.org/documentation/manual/v3/xsd/wix/component.html</a></p> <p>Take notice of certain child elements such as <em>AppId</em>, <em>Class</em>, <em>ProgId</em>, <em>Registry</em> and so on. The proper technique is to use <code>COM extraction</code> to reflect the registration information and emit it declaratively into your installer so MSI can take care of it for you without going out of process to some code (like <code>DllRegisterServer()</code>) that could fail and also not provides MSI insight into the footprint of the component from a repair and advertisement perspective.</p>
<p>There is just one drawback to this: WiX Com registration with heat.exe does not work for .exe COM servers. InstallShield and its tools seem to support it, but RegSpyUI is just a UI tool, not one which I can run on my build machine.</p>
19,614
<p>Can anyone suggest a good source control system that interfaces with VB2005 Express? As the Express editions of Visual Studio do not allow add-ins does this mean that I will not be able to integrate source control into the IDE? I'm used to the check-in/check-out process of SourceSafe integrated into VB6. Can anyone recommend TortoiseSVN as an alternative?</p>
<p>TortoiseSVN is a good choice. Although it won't integrate into the IDE (because of the plug-in problem you mentioned), it's really solid in the Explorer right-button menu.</p> <p>Also consider <a href="http://www.sourcegear.com/vault/" rel="nofollow noreferrer">Vault</a> from SourceGear. If you're used to SourceSafe, Vault will be easier to learn; Vault was specifically designed for ex-SourceSafe users.</p>
<p>No, Source Control systems can't be integrated with the VS Express IDEs by design.</p> <p>If you want to continue using your existing VSS, you're best option is to upgrade to Visual Studio Standard. Otherwise, check out TortoiseSVN. Here's a good quick start:</p> <p><a href="http://www.polymorphicpodcast.com/shows/subversion/" rel="nofollow noreferrer">http://www.polymorphicpodcast.com/shows/subversion/</a></p>
13,708
<p>I was considering creating a separate SQLite database for certain apps on a Django project.<br> However, I did not want to use direct SQLite access if possible. Django-style ORM access to these database would be ideal.<br> Is this possible?</p> <p>Thank you.</p>
<p>Yes - the low-level API for this is in place, it's just missing a convenient high-level API at the moment. These quotes are from <a href="http://www.reddit.com/r/programming/comments/6zinj/django_10_released/" rel="nofollow noreferrer">James Bennett (Django's release manager) on programming reddit</a>:</p> <blockquote> <p>It's been there -- in an extremely low-level API for those who look at the codebase -- for months now (every <code>QuerySet</code> is backed by a <code>Query</code>, which in turn accepts a DB connection as an argument). There isn't any high-level documented API for it, but I know people who are already doing and have been doing stuff like multiple-DB/sharding scenarios.</p> <p>...it's not necessarily something that needs a big write-up; the <code>__init__()</code> method of <code>QuerySet</code> accepts a keyword argument <code>query</code>, which should be an instance of <code>django.db.models.sql.Query</code>. The <code>__init__()</code> method of <code>Query</code>, in turn, accepts a keyword argument <code>connection</code>, which should be an instance of (a backend-specific subclass for your DB of) <code>django.db.backends.BaseDatabaseWrapper</code>.</p> <p>From there, it's pretty easy; you could, for example, override <code>get_query_set()</code> on a manager to always return a <code>QuerySet</code> using the connection you want, or set up things like sharding logic to figure out which DB to use based on incoming query parameters, etc., etc.</p> </blockquote>
<p>This isn't possible yet, but there is some talk of it on the wiki, <a href="http://code.djangoproject.com/wiki/MultipleDatabaseSupport" rel="nofollow noreferrer">Multiple Database Support in Django</a>. It was also brought up during the <a href="http://www.youtube.com/watch?v=M1Qr9rSBGBE" rel="nofollow noreferrer">keynote on the future of Django at DjangoCon 2008</a> and made one of the higher priority issues.</p>
20,314
<p>I've been reading that some devs/dbas recommend using transactions in all database calls, even read-only calls. While I understand inserting/updating within a transaction what is the benefit of reading within a transaction?</p>
<p>So you get a consistent view of the database. Imagine you have two tables that link to each other, but for some reason you do 2 selects... in pseuodocode:</p> <pre><code>myRows = query(SELECT * FROM A) moreRows = query(SELECT * FROM B WHERE a_id IN myRows[id]) </code></pre> <p>If between the two queries, someone changes B to delete some rows, you're going to have a problem.</p>
<p>Another good reason holding multiple transaction for read and for insert is the case you wish to insert record base on the data that you get from select query and you also want to commit every X row inserted. </p> <p>Two transaction: </p> <ol> <li>for the read\select. </li> <li>for the insert and commit every X row.</li> </ol> <p>will let you do this correctly while with one transaction not separate the read and write will not let you do the commit without losing the reader. </p>
39,799
<p>Has anyone been able to get a variable record length text file (CSV) into SQL Server via SSIS?</p> <p>I have tried time and again to get a CSV file into a SQL Server table, using SSIS, where the input file has varying record lengths. For this question, the two different record lengths are 63 and 326 bytes. All record lengths will be imported into the same 326 byte width table.</p> <p>There are over 1 million records to import.<br> I have no control of the creation of the import file.<br> I must use SSIS.<br> I have confirmed with MS that this has been reported as a bug. I have tried several workarounds. Most have been where I try to write custom code to intercept the record and I cant seem to get that to work as I want.</p>
<p>I had a similar problem, and used custom code (Script Task), and a Script Component under the Data Flow tab.</p> <p>I have a Flat File Source feeding into a Script Component. Inside there I use code to manipulate the incomming data and fix it up for the destination.</p> <p>My issue was the provider was using '000000' as no date available, and another coloumn had a padding/trim issue.</p>
<p>Why can't you just import it as a test file and set the column delimeter to "," and the row delimeter to CRLF?</p>
11,492
<p>What are the different ways (programmatically and otherwise) to determine what versions of .NET are running on a system?</p>
<p>Directly from the source:</p> <p><em><a href="http://support.microsoft.com/kb/318785" rel="nofollow noreferrer">How to determine which versions and service pack levels of the Microsoft .NET Framework are installed</a></em></p>
<p><a href="http://www.hanselman.com/smallestdotnet/" rel="nofollow noreferrer">Get the smallest .NET Framework download possible</a> that will tell you based on the headers you are sending. It only works on Internet Explorer or if you have the Firefox extension installed. More info in <a href="http://www.hanselman.com/blog/SmallestDotNetOnTheSizeOfTheNETFramework.aspx" rel="nofollow noreferrer">Hanselman's blog post</a>.</p>
7,564
<p>I want to build into mt ASP.NET application the ability for users to fill up forms, but the forms are not something I can hard-code into my (Enterprise) software.</p> <p>So I need one screen that lets end users create the forms. Doing it the 2.0 way, I just love what PollDaddy did in their survey editor (great job guys!). How do I replicate that? (don't worry pollDaddy, my app has nothing to do with survey and I am not at all in your domain (-: )</p> <p>Since you need to login to the site to play with it, I made a 20 sec video of how it looks like. Please see below and tell me how to best replicate this (as simple as using JQuery tip? use an entire open source project? Buy something?)</p> <p>Requirements are:</p> <ul> <li>support multiple types of elements (like multiple choice, free text, comboBox)</li> <li>drag and drop</li> <li>editing of order</li> </ul> <p><em>click image for video or <a href="http://revver.com/video/1376799/affiliate/24133/pd-editor-example/" rel="nofollow noreferrer">here</a></em></p> <p><a href="http://revver.com/video/1376799/affiliate/24133/pd-editor-example/" rel="nofollow noreferrer">http://frame.revver.com/frame/120x90/1376799.jpg</a></p>
<p>The <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/" rel="nofollow noreferrer">AJAX control toolkit</a> is free and would work for some of this items shown in the video. However, JQuery has tons of plugins it is easy to extend and even easier to use. I would suggest starting there and extending it where needed. </p> <p>Good Luck</p>
<p>You could build it yourself using an AJAX framework like ASP.NET AJAX or even telerik controls. You could use jQuery but ASP.NET AJAX is free and embeds well with ASP.NET pages. You could buy something, but I've yet to encounter packages as such.</p>
48,187
<p>When trying to kill a buffer that contains changes in Emacs, the message: " Buffer [buffer] modified; kill anyway? (yes or no)" is displayed. </p> <p>Instead of this I'd like to have Emacs ask me if I want to: 1. View a diff of what changed, 2. Save the buffer, 3. Kill the buffer.</p> <p>How?</p>
<p>The answer lies in using <a href="http://www.delorie.com/gnu/docs/elisp-manual-21/elisp_212.html" rel="noreferrer" title="advice">advice</a>, because the hooks normally run when killing buffers run <strong>after</strong> the "buffer modified" prompt you want to change.</p> <p>The following advice does what you want (I think). A couple of notes:</p> <ol> <li>When running the diff, the original buffer is marked as not modified - but you'll really need to save it.</li> <li>The other buffer in the diff doesn't get deleted</li> </ol> <p><code><pre> (defadvice kill-buffer (around my-kill-buffer-check activate) "Prompt when a buffer is about to be killed." (let* ((buffer-file-name (buffer-file-name)) backup-file) ;; see 'backup-buffer (if (and (buffer-modified-p) buffer-file-name (file-exists-p buffer-file-name) (setq backup-file (car (find-backup-file-name buffer-file-name)))) (let ((answer (completing-read (format "Buffer modified %s, (d)iff, (s)ave, (k)ill? " (buffer-name)) '("d" "s" "k") nil t))) (cond ((equal answer "d") (set-buffer-modified-p nil) (let ((orig-buffer (current-buffer)) (file-to-diff (if (file-newer-than-file-p buffer-file-name backup-file) buffer-file-name backup-file))) (set-buffer (get-buffer-create (format "%s last-revision" (file-name-nondirectory file-to-diff)))) (buffer-disable-undo) (insert-file-contents file-to-diff nil nil nil t) (set-buffer-modified-p nil) (setq buffer-read-only t) (ediff-buffers (current-buffer) orig-buffer))) ((equal answer "k") (set-buffer-modified-p nil) ad-do-it) (t (save-buffer) ad-do-it))) ad-do-it))) </pre></code></p>
<p>You'll want to write some code to put in the <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Kill-Buffer.html" rel="noreferrer">kill-buffer-hooks</a> and <a href="http://www.gnu.org/software/emacs/elisp/html_node/Saving-Buffers.html" rel="noreferrer">write-file-functions</a> lists. Conceptually, what you want to do is</p> <ol> <li>test if the buffer has been modified</li> <li>display your message and get a response, and do what's requested</li> <li>then clear the modified flag so the normal kill-buffer doesn't come back and ask again.</li> </ol>
42,962
<p>I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like</p> <pre><code> &lt;c:forEach items="${m.items}" var="i" varStatus="itemsRow"&gt; &lt;form:input path="items[${itemsRow.index}]"/&gt; &lt;/c:forEach&gt; &lt;form:errors path="items" /&gt; </code></pre> <p>would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.</p> <p>Is there something in Spring that works out of the box with Sets?</p>
<p>I think it has to be an ordered collection. For example,there's <a href="http://static.springframework.org/spring/docs/2.5.x/reference/validation.html" rel="noreferrer">a chart</a> in the Spring reference that talks about how to reference properties. It says:</p> <blockquote> <p>account[2] Indicates the third element of the indexed property account. Indexed properties can be of type array, list or other <em>naturally ordered</em> collection (emphasis theirs)</p> </blockquote> <p>Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.</p>
<p>You can use a semi-colon-delimited list if you're using numeric references to the IDs of objects, and an appropriate Converter implementation registered.</p> <p>POST data leaderboards=1,2</p> <p>Converter implementation (ignore the JSON stuff)</p> <pre><code> public final class LeaderboardConverter extends JsonDeserializer&lt;Leaderboard&gt; implements Converter&lt;String, Leaderboard&gt; { public Leaderboard convert(String source) throws IllegalArgumentException { Leaderboard activity = new Leaderboard(); activity.setId(new Integer(source)); return activity; } public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return convert(jp.getText()); } } </code></pre>
36,075
<p>So I am sold on the concept of attempting to collect data automatically from a program - i.e., popping up a dialog box that asks the user to send the report when something goes wrong.</p> <p>I'm working in MS Visual Studio C#.</p> <p>From an implementation point of view, does it make sense to put a try/catch loop in my main program.cs file, around where the application is run? Like this:</p> <pre><code> try { Application.Run(new myMainForm()); } catch (Exception ex) { //the code to build the report I want to send and to //pop up the Problem Report form and ask the user to send } </code></pre> <p>or does it make sense to put try/catch loops throughout pieces of the code to catch more specific exception types? (I'm thinking not because this is a new application, and putting in more specific exception catches means I have an idea of what's going to go wrong... I don't, which is why the above seems to make sense to me.)</p> <p>-Adeena</p>
<p>I think you are right, you would not know what's going to go wrong, which is the point.</p> <p>However, you might as well consider adding a handler to the <a href="http://www.digcode.com/default.aspx?page=ed51cde3-d979-4daf-afae-fa6192562ea9&amp;article=5c26d313-2435-442f-91e8-a73e9aff021b" rel="noreferrer">ThreadException</a> event instead.</p> <p>The code above will work but there will be scenarios where multi threading might be an issue with such code, since not all code inside your windows forms program will be running in the main Application.Run loop thread.</p> <p>Here's a sample code from the linked article:</p> <pre><code>[STAThread] static void Main() { System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(ReportError); System.Windows.Forms.Application.Run(new MainForm()); } private static void ReportError(object sender, ThreadExceptionEventArgs e) { using (ReportErrorDialog errorDlg = new ReportErrorDialog(e.Exception)) { errorDlg.ShowDialog(); } } </code></pre> <p>More documentation <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="noreferrer">on MSDN</a>.</p> <p>On a minor point, using the ThreadException event also allow your main message loop to continue running in case the exception isn't fatal (i.e. fault-tolerance scenarios) whilst the try/catch approach may requires that you restart the main message loop which could cause side effects.</p>
<p>The best approach is to sing up for <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx" rel="nofollow noreferrer">AppDomain.UnhandledException</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx" rel="nofollow noreferrer">Application.ThreadException</a> In your application's main function. This will allow you to record any unhandled exceptions in your application. Wraping run in a try catch block does not catch every thing.</p>
47,863
<p>What's the difference between JavaScript and Java?</p>
<p>Java and Javascript are similar like Car and Carpet are similar.</p>
<p><a href="https://developer.mozilla.org/en/a_re-introduction_to_javascript" rel="nofollow noreferrer">A Re-Introduction to Javascript</a> by the Mozilla team (they make Firefox) should explain it.</p>
30,402
<p>This is a continuation of my question about <a href="https://stackoverflow.com/questions/339795/reading-the-superblock">reading the superblock</a>.</p> <p>Let's say I want to target the HFS+ file system in Mac OS X. How could I read sector 2 of the boot disk? As far as I know Unix only provides system calls to read from files, which are never stored at that location.</p> <p>Does this require either 1) the program to run kernel mode, or 2) the program to be written in Assembly? I would prefer to avoid either of these restrictions, particularly the latter.</p>
<p>In Linux, you can read from the special device file <code>/dev/sda</code>, assuming the hard drive you want to read is the first one. You need to be root to read this file. To read sector 2, you just seek to offset <code>2*SECTOR_SIZE</code> and read in <code>SECTOR_SIZE</code> bytes.</p> <p>I don't know if this device file is available on OS X. Check for interestingly named files under <code>/dev</code> such as <code>/dev/sda</code> or <code>/dev/hda</code>.</p>
<p>How does this work in terms of permissions? Wouldn't reading from /dev/... be insecure since if you read far enough you would be able to read files for which you do not have read access?</p>
44,459
<p>How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.</p> <p><strong>EDIT</strong>: <a href="http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html" rel="noreferrer">The Java Tutorials - Drag and Drop and Data Transfer</a>.</p>
<p>Curses! Beaten to the punch by a Google search. Unfortunately it's true there is no easy way to create draggable tab panes (or any other components) in Swing. So whilst the example above is complete this one I've just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer. The steps are:</p> <ol> <li>Detect that a drag has occurred</li> <li>Draw the dragged tab to an offscreen buffer</li> <li>Track the mouse position whilst dragging occurs</li> <li>Draw the tab in the buffer on top of the component.</li> </ol> <p>The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.</p> <p>Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p</p> <pre class="lang-java prettyprint-override"><code>import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; public class DraggableTabbedPane extends JTabbedPane { private boolean dragging = false; private Image tabImage = null; private Point currentMouseLocation = null; private int draggedTabIndex = 0; public DraggableTabbedPane() { super(); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if(!dragging) { // Gets the tab index based on the mouse position int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY()); if(tabNumber &gt;= 0) { draggedTabIndex = tabNumber; Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber); // Paint the tabbed pane to a buffer Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics totalGraphics = totalImage.getGraphics(); totalGraphics.setClip(bounds); // Don't be double buffered when painting to a static image. setDoubleBuffered(false); paintComponent(totalGraphics); // Paint just the dragged tab to the buffer tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB); Graphics graphics = tabImage.getGraphics(); graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this); dragging = true; repaint(); } } else { currentMouseLocation = e.getPoint(); // Need to repaint repaint(); } super.mouseDragged(e); } }); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if(dragging) { int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10); if(tabNumber &gt;= 0) { Component comp = getComponentAt(draggedTabIndex); String title = getTitleAt(draggedTabIndex); removeTabAt(draggedTabIndex); insertTab(title, null, comp, null, tabNumber); } } dragging = false; tabImage = null; } }); } protected void paintComponent(Graphics g) { super.paintComponent(g); // Are we dragging? if(dragging &amp;&amp; currentMouseLocation != null &amp;&amp; tabImage != null) { // Draw the dragged tab g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this); } } public static void main(String[] args) { JFrame test = new JFrame("Tab test"); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setSize(400, 400); DraggableTabbedPane tabs = new DraggableTabbedPane(); tabs.addTab("One", new JButton("One")); tabs.addTab("Two", new JButton("Two")); tabs.addTab("Three", new JButton("Three")); tabs.addTab("Four", new JButton("Four")); test.add(tabs); test.setVisible(true); } } </code></pre>
<p>Add this to isDragAcceptable to avoid Exceptions:</p> <pre><code>boolean transferDataFlavorFound = false; for (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) { if (FLAVOR.equals(transferDataFlavor)) { transferDataFlavorFound = true; break; } } if (transferDataFlavorFound == false) { return false; } </code></pre>
8,511
<p>I have an object in C# on which I need to execute a method on a regular basis. I would like this method to be executed only when other people are using my object, as soon as people stop using my object I would like this background operation to stop. </p> <p>So here is a simple example is this (which is broken): </p> <pre><code>class Fish { public Fish() { Thread t = new Thread(new ThreadStart(BackgroundWork)); t.IsBackground = true; t.Start(); } public void BackgroundWork() { while(true) { this.Swim(); Thread.Sleep(1000); } } public void Swim() { Console.WriteLine("The fish is Swimming"); } } </code></pre> <p>The problem is that if I new a Fish object anywhere, it never gets garbage collected, cause there is a background thread referencing it. Here is an illustrated version of broken code. </p> <pre><code>public void DoStuff() { Fish f = new Fish(); } // after existing from this method my Fish object keeps on swimming. </code></pre> <p>I know that the Fish object should be disposable and I should clean up the thread on dispose, but I have no control over my callers and can not ensure dispose is called. </p> <p>How do I work around this problem and ensure the background threads are automatically disposed even if Dispose is not called explicitly?</p>
<p>Here is my proposed solution to this problem: </p> <pre><code>class Fish : IDisposable { class Swimmer { Thread t; WeakReference fishRef; public ManualResetEvent terminate = new ManualResetEvent(false); public Swimmer(Fish3 fish) { this.fishRef = new WeakReference(fish); t = new Thread(new ThreadStart(BackgroundWork)); t.IsBackground = true; t.Start(); } public void BackgroundWork() { bool done = false; while(!done) { done = Swim(); if (!done) { done = terminate.WaitOne(1000, false); } } } // this is pulled out into a helper method to ensure // the Fish object is referenced for the minimal amount of time private bool Swim() { bool done; Fish fish = Fish; if (fish != null) { fish.Swim(); done = false; } else { done = true; } return done; } public Fish Fish { get { return fishRef.Target as Fish3; } } } Swimmer swimmer; public Fish() { swimmer = new Swimmer(this); } public void Swim() { Console.WriteLine("The third fish is Swimming"); } volatile bool disposed = false; public void Dispose() { if (!disposed) { swimmer.terminate.Set(); disposed = true; GC.SuppressFinalize(this); } } ~Fish() { if(!disposed) { Dispose(); } } } </code></pre>
<p>I think the IDisposable solution is the correct one. </p> <p>If the users of your class don't follow the guidelines for using classes that implement IDisposable it's their fault - and you can make sure that the documentation explicitly mentions how the class should be used.</p> <p>Another, much messier, option would be a "KeepAlive" DateTime field that each method called by your client would update. The worker thread then checks the field periodically and exits if it hasn't been updated for a certain amount of time. When a method is setting the field the thread will be restarted if it has exited.</p>
46,264
<p>I always thought Java uses <strong>pass-by-reference</strong>.</p> <p>However, I've seen <a href="http://javadude.com/articles/passbyvalue.htm" rel="noreferrer">a blog post</a> that claims that Java uses <strong>pass-by-value</strong>.</p> <p>I don't think I understand the distinction they're making.</p> <p>What is the explanation?</p>
<p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; have special, <a href="https://en.wikipedia.org/w/index.php?title=Pass-by-value" rel="noreferrer">precisely defined</a> meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact.</p> <p>The terms &quot;pass-by-value&quot; and &quot;pass-by-reference&quot; are talking about <em>variables.</em> Pass-by-value means that the <em>value</em> of a variable is passed to a function/method. Pass-by-reference means that a <em>reference</em> to that variable is passed to the function. The latter gives the function a way to change the contents of the variable.</p> <p>By those definitions, Java is always <strong>pass-by-value</strong>. Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called <em>references</em> which are passed-by-value as well. This terminology and semantics easily confuse many beginners.</p> <p>It goes like this:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog(&quot;Max&quot;); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the &quot;Max&quot; dog when foo(...) returns aDog.getName().equals(&quot;Max&quot;); // true aDog.getName().equals(&quot;Fifi&quot;); // false aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals(&quot;Max&quot;); // true // change d inside of foo() to point to a new Dog instance &quot;Fifi&quot; d = new Dog(&quot;Fifi&quot;); d.getName().equals(&quot;Fifi&quot;); // true } </code></pre> <p>In the example above <code>aDog.getName()</code> will still return <code>&quot;Max&quot;</code>. The value <code>aDog</code> within <code>main</code> is not changed in the function <code>foo</code> with the <code>Dog</code> <code>&quot;Fifi&quot;</code> as the object reference is passed by value. If it were passed by reference, then the <code>aDog.getName()</code> in <code>main</code> would return <code>&quot;Fifi&quot;</code> after the call to <code>foo</code>.</p> <p>Likewise:</p> <pre><code>public static void main(String[] args) { Dog aDog = new Dog(&quot;Max&quot;); Dog oldDog = aDog; foo(aDog); // when foo(...) returns, the name of the dog has been changed to &quot;Fifi&quot; aDog.getName().equals(&quot;Fifi&quot;); // true // but it is still the same dog: aDog == oldDog; // true } public static void foo(Dog d) { d.getName().equals(&quot;Max&quot;); // true // this changes the name of d to be &quot;Fifi&quot; d.setName(&quot;Fifi&quot;); } </code></pre> <p>In the above example, <code>Fifi</code> is the dog's name after call to <code>foo(aDog)</code> because the object's name was set inside of <code>foo(...)</code>. Any operations that <code>foo</code> performs on <code>d</code> are such that, for all practical purposes, they are performed on <code>aDog</code>, but it is <strong>not</strong> possible to change the value of the variable <code>aDog</code> itself.</p> <p>For more information on pass by reference and pass by value, consult the following answer: <a href="https://stackoverflow.com/a/430958/6005228">https://stackoverflow.com/a/430958/6005228</a>. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.</p>
<p>Every single answer here is tying to take pass pointer by reference from other languages and show how it is impossible to do in Java. For whatever reason nobody is attempting to show how to implement pass-object-by-value from other languages.</p> <p>This code shows how something like this can be done:</p> <pre><code>public class Test { private static void needValue(SomeObject so) throws CloneNotSupportedException { SomeObject internalObject = so.clone(); so=null; // now we can edit internalObject safely. internalObject.set(999); } public static void main(String[] args) { SomeObject o = new SomeObject(5); System.out.println(o); try { needValue(o); } catch(CloneNotSupportedException e) { System.out.println(&quot;Apparently we cannot clone this&quot;); } System.out.println(o); } } public class SomeObject implements Cloneable { private int val; public SomeObject(int val) { this.val = val; } public void set(int val) { this.val = val; } public SomeObject clone() { return new SomeObject(val); } public String toString() { return Integer.toString(val); } } </code></pre> <p>Here we have a function <code>needValue</code> and what it does is right away create a clone of the object, which needs be implemented in the class of the object itself and the class needs to be marked as <code>Cloneable</code>. It is not essential to set <code>so</code> to <code>null</code> after that, but i have done so here to show that we are not going to be using that reference after that.</p> <p>It may well be that Java does not have pass-by-reference semantics, but to call the language &quot;pass-by-value&quot; is along the lines of wishful thinking.</p>
6,171
<p>I am writing a set of database-driven applications in PHP. These applications will run on a Linux server as its own user. Other users will likely be on the system at times, but have very controlled access. Other servers they will not have access to at all. I will also expose a limit stored procedure API to developers who need to write Perl scripts that access the database using a DBI and a set of functions I write.</p> <p>My question is what the best way to secure the config files that have connection strings in them? </p> <p>Is a different user with [4+]00 permissions on the file sufficient? Should I encrypt them? That seems to just shift the problem elsewhere so that I worry about where to store an encryption key. I realize the Perl developers will need to have a connection string of their own as they will only have execute database permissions. </p>
<p>If the machine really is being administered in the traditional Unix fashion, where J. Random user isn't off su-ing to root all the time, I'd say that filesystem permissions are your best bet. If someone gets unauthorized root access, no amount of encryption silliness is going to "secure" the connection string.</p> <p>I'd mark the files w/ the connection string as owned by the "script user" and give them access as you describe.</p> <p>(Bravo for realizing that encrypting the connection string doesn't buy you anything, in this example. Security through obscurity is counter-productive.)</p>
<p>My best solution so far has been to store config files in an encrypted partition so that people with direct access to the machine can't pull the passwords off by connecting the drive to another PC, and with file system permissions so people can't read the file from inside the OS itself.</p> <p>You need to understand, though, that there's not much you can do against an attacker with direct access to the machine. If it's running the database server itself, then securing the config files won't have much effect if he can modify the database itself. Just make sure that everything is as secure as it can be and you'll probably be okay.</p>
43,413
<p>How do you add a page break into a document with XSL-FO? I'm using <a href="http://xmlgraphics.apache.org/fop/" rel="noreferrer">Apache FOP</a> to create PDFs, if that makes a difference.</p>
<p>The <a href="http://xmlgraphics.apache.org/fop/compliance.html" rel="nofollow noreferrer">FOP compliance page</a> says that it supports <code>page-break-after</code>, <code>page-break-before</code>, and <code>page-break-inside</code> in the later versions, plus partial support for <code>keep-together</code>, <code>keep-with-next</code>, <code>keep-with-previous</code>.</p>
<p>This worked for me. But this is Elite Design Gallery syntax.</p> <pre><code>&lt;w:p &gt;&lt;w:r&gt;&lt;w:br w:type="page"/&gt;&lt;/w:r&gt;&lt;/w:p&gt; </code></pre>
27,896
<p>I am making an expand/collapse call rates table for the company I work for. I currently have a table with a button under it to expand it, the button says "Expand". It is functional except I need the button to change to "Collapse" when it is clicked and then of course back to "Expand" when it is clicked again. The writing on the button is a background image.</p> <p>So basically all I need is to change the background image of a div when it is clicked, except sort of like a toggle.</p>
<pre><code>$('#divID').css("background-image", "url(/myimage.jpg)"); </code></pre> <p>Should do the trick, just hook it up in a click event on the element</p> <pre><code>$('#divID').click(function() { // do my image switching logic here. }); </code></pre>
<p>I've found a solution in a forum, <em><a href="http://www.dynamicdrive.com/forums/showthread.php?t=5967&amp;page=2" rel="nofollow noreferrer">Toggle Background Img</a></em>.</p>
31,621
<p>When designing a collection class, is there any reason not to implement locking privately to make it thread safe? Or should I leave that responsibility up to the consumer of the collection?</p>
<blockquote> <p>is there any reason not to implement locking privately to make it thread safe? </p> </blockquote> <p>It depends. Is your goal to write a collection class which is accessed by multiple threads? If so, make it thread safe. If not, don't waste your time. This kind of thing is what people refer to when they talk about 'premature optimization'</p> <p>Solve the problems that you have. Don't try to solve future problems that you think you may have some years in the future, because you can't see the future, and you'll invariably be wrong.</p> <p>Note: You still need to write your code in a maintainable way, such that if you <em>did</em> need to come along and add locking to the collection, it wouldn't be terribly hard. My point is "don't implement features that you don't need and won't use"</p>
<p>This would make it impossible to simultaneously access a collection from several threads even if you know that the element you touch is not used by anyone else.</p> <p>An example would be a collection with an integer based index accessor. Each thread might know from its id which index values it can access without worrying about dirty reads/writes.</p> <p>Another case where you would get an unnecessary performance hit would be when data is only read from the collection and not written to.</p>
19,833
<p>I want to develop a plug-in that does this:</p> <p><em>A button, when clicked, opens the new mail window but has a certain phrase in the subject line, for e.g. when I click a button called 'PROJ123', the new mail window opens with the subject line "[PROJ123]"</em></p> <p>Other functionality it would need:</p> <ul> <li>Ability to Create/Update/Delete Buttons as needed</li> </ul> <p>What is the best way to do this? </p> <p>Any and all tips, references, online resources, examples are greatly appreciated!</p>
<p>To create a plugin for Outlook, I'd read these resources:</p> <ul> <li><a href="https://www.codeproject.com/Articles/1112815/How-to-Create-an-Add-in-for-Microsoft-Outlook" rel="nofollow noreferrer">CodeProject: How to Create Plugin for Outlook</a></li> <li>MSDN: <a href="http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/0fb13e44-b360-4251-a7eb-45c266e40a9b/" rel="nofollow noreferrer">How to Create Plugin in .NET</a></li> <li>Using <a href="http://msdn.microsoft.com/en-us/office/aa905533.aspx" rel="nofollow noreferrer">VSTO for .NET</a> to create plugins in Outlook </li> </ul> <p>This doesn't directly answer your question, but I found an add-in that may be useful to you:</p> <ul> <li>A <a href="http://www.office-outlook.com/outlook-addins/quick-templates-for-outlook.html" rel="nofollow noreferrer">template plugin</a> for Outlook</li> </ul>
<p>You can use VBA and a UserForm, or a Custom Menu. Here is an example of the code:</p> <pre><code>Private Sub cmdCommand_Click() Dim eml As MailItem Set eml = Application.CreateItem(olMailItem) eml.Subject = "Proj1" UserForm1.Hide eml.Display End Sub </code></pre>
48,590
<p>I would like to access a class everywhere in my application, how can I do this?</p> <p>To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.</p>
<p>The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (<strong>Concrete instance or Static access</strong> to that class)</p> <p>Or</p> <p>You can have a <strong>Singleton class</strong> to use it everywhere but some people won't recommend you this way to proceed.</p>
<p>The other answers that you've been given about using a static class or a singleton pattern are correct.</p> <p>Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).</p> <p>Just on that, you should also look up the <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="nofollow noreferrer">abstract factory pattern</a>. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.</p>
22,407
<p>I need a VB.NET Forms application that processes a queue. It basically needs to ping a web service every 30 seconds and then load documents into a document management system, if there are any to load.</p> <p>How would I implement this? Using a loop? Do I need to look into threads?</p> <p>Thanks</p>
<p>If you are already using web services then you may want to stay with the thread-like behavior of services with less complications.</p> <p>Otherwise, just use a Timer object, or if possible, a FileSystemWatcher for your triggers.</p>
<p>How did you define the queue. You can do it with mutlithreading (that is create a threadpool instance) and let the threadpool pop the objects in the queue.</p> <p>However if you have something like file searching in the queue objects then obvsiouly you'd want the first que objec to finish before starting the second (that is, if they use the same file). </p>
46,142
<p>A couple of years ago, we had a graphic designer revamp our website. His results looked great, but he unfortunately introduced a new unsupported font by the web browser. </p> <p>At first I was like, "What!?!"... since most of our content is dynamic and there was no real way to pre-make all of the images. There was also the issue of multiple languages (since we knew Spanish was on the horizon).</p> <p>Anyway, I decided to create some classes to auto-generate images via GDI+ and programatically cache them as needed. This solved most of our initial problems. However, now that our load has increased dramatically, there has been a drain on our UI server.</p> <p>Now to the question... I am looking to replace most of the dynamic GDI+ images with a standard web browser font. I am thinking of keeping some of the rendered GDI+ images and putting them in a resx file, but plan to replace most of them with Tahoma or Arial fonts via asp:Labels. </p> <p>Which have you found to be a better localized image solution? </p> <ul> <li>Embedding images into the resx</li> <li>Only adding the image url into the resx</li> <li>Some other solution</li> </ul> <p>My main concern is to limit the processing on the UI server. If that is the case, would adding the image url to the resx be a better solution compared to actually embedding the image into the resx?</p>
<p>You should only need to generate each image once, and then save it on the hard disk. The load on your site shouldn't increase the amount of processing you have to do. That being said, it almost sounds like you are using images for things you shouldn't be. If there are so many different images that you can't keep up with generating them, it's time to abandon your fancy images for things that shouldn't be images, and go back to straight text. If the user doesn't have the specified font installed, it should just fall back to a similar looking font. CSS has good support for this.</p>
<p>Because of caching, I'd rather add only the image url into the resx. Caching is much better for static content (i-e plain files ) than for generated content.</p>
42,873
<p>I'm trying to print a small box with 1 mm thick walls. The box has rounded corners.</p> <p>Cura slices the rounded corners with straight internal lines instead of rounded lines:</p> <p><a href="https://i.stack.imgur.com/5Kw87.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Kw87.jpg" alt="Rounded Corners with infill" /></a></p> <p>The reason for these straight lines is that Cura is using infill to fill the walls, because it determines that there's not enough space in a 1 mm wall for three 0.4 mm passes.</p> <p><a href="https://i.stack.imgur.com/dDQAc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dDQAc.png" alt="Rounded Corners without infill" /></a></p> <p>This causes the walls to have small imperfections in the final print. I was able to solve this by increasing the model wall thickness to 1.2 mm (to allow for 3 0.4 mm lines), but even then it wasn't doing it as a single continuous line, but instead breaking it into short lines at the corner:</p> <p><a href="https://i.stack.imgur.com/zqSAN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zqSAN.png" alt="Rounded corners for 1.2 mm thick walls" /></a></p> <p>Is there a way to avoid this issue without increasing the wall thickness, and have 3 continuous lines?</p>
<p>I found the solution : It was the option &quot;avoid crossing perimeters&quot; that seems to do exactly the contrary of what it means. Thank you all for your answers.</p>
<p>Enable Z-Hop. I don't know what the actual parameter is called but it should say something like &quot;Z-Hop&quot;.</p>
1,760
<p>Is there a way (reliable and preferably not commercial) to prevent from Reflector to reflect my source code???</p> <p>Thanks, Adi</p>
<p>No. Reflector looks at your assembly just like the .NET runtime would in order to generate native code to execute. The best you could hope for would be to <a href="https://stackoverflow.com/questions/2525/best-net-obfuscation-toolsstrategy">obfuscate</a> your code and make it (somewhat) harder for the reader to understand.</p> <p>Some pros and cons of performing the obfuscation can be found at <a href="https://stackoverflow.com/questions/71195/should-you-obfuscate-a-commercial-net-application">Should you obfuscate a commercial .Net application?</a></p>
<p>If you are looking for a good Obfuscator, give <a href="http://www.remotesoft.com" rel="nofollow noreferrer">RemoteSoft</a> a try. </p>
48,065
<p>I'm writing a JPA connector to a legacy sistem. The problem is, DB design in the system is.. well.. horrible.</p> <p>I need to implement an entity that maps to three tables. I can do it using named sql queries, but the probem is, I have to use this entity in a OneToMany relation (this entity is on the many side). So how do I tell JPA it needs to use a specific named query with specific parameter?</p> <p>And a subquestion: does any1 have any good on-line JPA documentation? I can't find anything decent :-/</p>
<p>I haven't actually found a way to do this with JPA. To solve problems like this I ended up using a named query.</p> <p>As far as documentation, I have been using <a href="http://www.oracle.com/technology/products/ias/toplink/jpa/resources/toplink-jpa-annotations.html" rel="nofollow noreferrer">TopLink's</a> and <a href="http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#entity-mapping" rel="nofollow noreferrer" title="Hibernate JPA documentation">Hibernate's</a>.</p> <p>If you find a better way, please post it here!</p>
<p>Could you make a database view and then create an entity that maps onto that view? I don't know if this is possible, just a thought.</p>
33,675
<p>My i3 MK3 is printing very well for solid parts of an object, but it messes up with infill.</p> <p><a href="https://i.stack.imgur.com/dc5BL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dc5BL.jpg" alt="Infill rough"></a></p> <p>As you can see in the image, the infill is broken into pieces and bends to that the surface becomes rough and the nozzle touches it next time it moves there, which probably does not make things better.</p> <p>I've read the <a href="https://www.prusaprinters.org/7-problems-affecting-quality-of-3d-prints" rel="nofollow noreferrer">Prusa problem page</a>, where they suggest three solutions:</p> <ul> <li>change infill type</li> <li>flexible filament (I'm using PETG, so this does not apply)</li> <li>lower printing speed</li> </ul> <p>I'm printing with 20% infill and I believe that this worked before at the same speed, so I'm tempted to say that both remaining options are options, but it should work without them.</p> <p>It also seems to me as if the infill is thinner that ordinary walls. Is the extrusion speed lower in case of infill? Is there a way of changing the extrusion speed for infill?</p> <p>Side note: my printer always tells me to upgrade to the latest firmware 3.5.1. Since I have just received the printer back from a warranty repair after the last firmware upgrade, I don't want to upgrade the firmware. Could the issue be related to firmware?</p> <p>Infos requested from comments:</p> <p>I'm basically using the Slic3r default settings for PETG. The only thing I adjusted is the temperature, since I'm using HDGlass PETG and there was a recommended temperature written on the spool. Relevant settings seem to be</p> <ul> <li>Filament settings <ul> <li>fan speed min 30 % max 50 %</li> <li>bridges fan speed 50 %</li> <li>enable fan below 20 s</li> <li>slow down below 20 s</li> <li>min print speed 15 mm/s</li> </ul></li> <li>Speed settings <ul> <li>Perimenters 45 mm/s</li> <li>Small perimeters 25 mm/s</li> <li>External perimeters 35 mm/s</li> <li>Infill 200 mm/s</li> <li>Solid infill 200 mm/s </li> <li>Top solid infill 50 mm/s</li> </ul></li> </ul>
<p>From your comments can be read that you print infill at 200&nbsp;mm/s. </p> <p>Know that 200&nbsp;mm/s is ridiculously fast (like high travelling speed), close to the limits of printing on certain machines (<a href="/a/8108">for an AtMega</a>)! It is hard for the filament to keep up at this speed. A value of 60&nbsp;mm/s would be a good value to start experimenting. Your infill is not rough, it just failed printing. I have printed kilometers of PETG, normal print speeds for my PETG are recommended at 30-50&nbsp;mm/s by my manufacturer; I get good results at 50-60&nbsp;mm/s. On my Ultimaker 3, 70&nbsp;mm/s is also feasible.</p> <hr> <p><em>Note that the filament you use seems to have rather <a href="https://www.formfutura.com/shop/product/hdglass-clear-238" rel="nofollow noreferrer">low printing temperatures</a> (195-225&nbsp;&deg;C) as opposed to the PETG filament (co-polymer) I'm used to. The manufacturer does not specify advised print speeds (other than "high", but what defines "high"?), but <a href="https://mevade.wordpress.com/2015/08/22/1-75mm-hdglass/" rel="nofollow noreferrer">this user posted</a> some of his print settings for this material. The overall speed of 60&nbsp;mm/s seems to support lower than 200&nbsp;mm/s print speeds.</em></p>
<p>I have dealt with this on infill as well on multiple MK3s.</p> <p>However, it was not the speed itself, but the hot end having difficulty extruding enough to keep up with the infill. </p> <p>Some things to try:</p> <ul> <li>Raise hot end temperature 5 degrees (melt filament faster)</li> <li>Lower infill speed, it will not affect your overall print time very much (surprisingly)</li> <li>A combination of the two above.</li> </ul> <p>Good luck!</p>
1,217
<p>There might be applications that are not suited for Core Data - image manipulation programs like Photoshop or Gimp for example. But for applications that are suited for Core Data, say Address Book or iCal, what is the criteria to choose Core Data over a custom model?</p>
<p>I recently started a project where I decided to use Core Data for the first time in a real world application. My application is actually version 2.0 of an older app that uses a custom data model, so I spent a lot of time debating this question. Here are some of the things I asked myself.</p> <ul> <li><p>The time to learn how Core Data works in a non-trivial application and fixing the little bugs and idiosyncrasies that pop up when you're learning a new technology. This may include a prototype or two, since you don't want to jump into using something like Core Data that will be responsible for such as large chunk of your application.</p></li> <li><p>Whether or not Core Data will solve problems that are hard to address when using a custom data model, for example storing and holding in memory very large sets of data.</p></li> <li><p>Whether or not you want to share code with a platform where Core Data is not available, for instance Cocoa Touch. Along the same lines, if you want the resulting data files to be compatible without having to build a separate exporter.</p></li> <li><p>If learning Core Data will help improve yourself as a programmer, whether its making your more attractive to Mac development shops or just for your own use.</p></li> <li><p>If your data model is simple enough that you don't really need things like undo manager support or relationships, the areas where core data really shines.</p></li> <li><p>If you're using external libraries or other technologies such as Distributed Objects, where you might not want to use NSManagedObject.</p></li> </ul>
<p>Kick :)</p> <p>For me the biggest question you need to ask yourself is: Are you going to store critical data in there (user created content) or data that can easily be reproduced (content downloaded from internet). If you have the first (user created data) i would steer away from Core Data ASAP or make sure you have a backup plan in your app.</p> <p>Once bugs start popping up (and trust me, there are) for instance when trying to migrate your data to a new version of your object model you are stuck, completely stuck! And telling your customer "I am sorry I cannot build a new version of your app, I am waiting on Apple to come up with a fix" will not cut it in the real world. There is no official way of accessing or understandig the underlying structures, so once it goes boom, you are on your own.</p> <p>Been there done that, not going there again!</p> <p>my 2 cents</p>
40,676
<p>What would be the best practice way to handle the caching of images using PHP.</p> <p>The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag.</p> <p>When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. </p> <p>The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner,</p> <p>Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)</p>
<p>I would do it in a different manner.</p> <p>Problems: 1. Having PHP serve the files out is less efficient than it could be. 2. PHP has to check the existence of files every time an image is requested 3. Apache is far better at this than PHP will ever be.</p> <p>There are a few solutions here.</p> <p>You can use <code>mod_rewrite</code> on Apache. It's possible to use mod_rewrite to test to see if a file exists, and if so, serve that file instead. This bypasses PHP entirely, and makes things far faster. The real way to do this, though, would be to generate a specific URL schema that should always exist, and then redirect to PHP if not.</p> <p>For example:</p> <pre><code>RewriteCond %{REQUEST_URI} ^/images/cached/ RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule (.*) /images/generate.php?$1 [L] </code></pre> <p>So if a client requests <code>/images/cached/&lt;something&gt;</code> and that file doesn't exist already, Apache will redirect the request to <code>/images/generate.php?/images/cached/&lt;something&gt;</code>. This script can then generate the image, write it to the cache, and then send it to the client. In the future, the PHP script is never called except for new images.</p> <p>Use caching. As another poster said, use things like <code>mod_expires</code>, Last-Modified headers, etc. to respond to conditional GET requests. If the client doesn't have to re-request images, page loads will speed dramatically, and load on the server will decrease.</p> <p>For cases where you do have to send an image from PHP, you can use <code>mod_xsendfile</code> to do it with less overhead. See <a href="http://blog.adaniels.nl/articles/how-i-php-x-sendfile/" rel="noreferrer">the excellent blog post from Arnold Daniels</a> on the issue, but note that his example is for downloads. To serve images inline, take out the Content-Disposition header (the third header() call).</p> <p>Hope this helps - more after my migraine clears up.</p>
<p>Your approach seems quite reasonable - I would add that some mechanism should be put into place to check that the date the cached version was generated was after the last modified timestamp of the original (source) image file and if not regenerate the cached/resized version. This will ensure that if an image is changed by the designers the cache will be updated appropriately.</p>
17,009
<p>I'm working on a small app where I can generate a list of barcodes. I have the correct fonts installed on my computer. Right now I am printing them directly to a webpage and it works properly in Chrome and IE 7, but not Firefox. Does anyone know what Firefox would be doing differently than IE and Chrome?</p> <p>Here is my code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Barcode Font Test&lt;/title&gt; &lt;style type="text/css" media="screen"&gt; .barcode { font-family: "wasp 39 m", verdana, calibri; font-size: 36pt; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="barcode"&gt;*574656*&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>EDIT:</strong> I probably should have mentioned that this is more of a personal project at the moment and not meant to be released to the world. While I will take a solution that works, I would like something that does not involve Javascript/Flash/etc.</p>
<p>A simpler solution might be to generate images server side to generate the bar codes. That way you don't have to rely on the user having a font installed and you don't have to access the font in your html.</p>
<p>Just do this: <a href="http://davidscotttufts.com/2009/03/31/how-to-create-barcodes-in-php/" rel="nofollow">http://davidscotttufts.com/2009/03/31/how-to-create-barcodes-in-php/</a> David created a super-simple way to implement bar codes. You will need the GD library running in MySQL. (MAMP &amp; LAMP should already have this installed)</p>
29,818
<p>Some of the requirements (restrictions) for such a ui framework/toolkit are:</p> <ul> <li>No single vendor lock down</li> <li>Ability for real time data visualization</li> <li>Good initial widgets</li> <li>Good dash boarding capabilities</li> <li>cross platform</li> <li>Good development/debug environment</li> <li>No flash</li> </ul>
<p>It's a pity you can't/won't use Flash. Else I could really recommend Adobe AIR. It has a good editor (Flex Builder built on Eclipse), a good component framework with many out of the box components, charting components set, ability to communicate with many different protocols (and you could write your own protocol implementation), cross platform, runs in the AIR runtime and not in the browser, file IO, ...</p>
<p>There's also Java of course. It satifies all your requirements AFAICS. Plenty of custom charting controls, which are things you will struggle to find for GTK/WxWindows/$other_small_userbase_framework.</p> <p>If you dont like Swing(its come a long way - Metal is dead, long live SystemDefault L&amp;F!), there are options like SWT or even QT bindings for java(QTJambi).</p> <p>For C or C++ go QT, its APIs are really nice. </p>
23,704
<p>I have an MDI application that allows me to open different types of child windows. I can open multiple (but different) instances of the same type of child window. (Example: I can open 3 instances of child window type A and 2 instances of child window type B. All 5 windows are distinct entities and do not share data until unless the user explicitly drags the same data onto multiple windows.) Each child window has a ToolStripContainer with one or more ToolStrips. How do I prevent:</p> <ol> <li>the user from dragging a ToolStrip from a child window of type A to a ToolStripContainer in a child window of type B?</li> <li>the user from dragging a ToolStrip from one instance of child window A to a ToolStripContainer in another instances of the same type of window?</li> </ol> <p>I'm trying to prevent the user from dragging a ToolStrip from instance 1 of type A to instance 2 of type A, selecting some stuff on instance 2, and then clicking a button on the toolbar only to have something weird happen to some other window. Similarly it doesn't make sense to drag a ToolStrip from a window of type A to a window of type B -- the actions don't apply to that type, but to the user it looks like everything is fine because I let them do the drag.</p> <p>Is it as simple as adding my own handler for the ControlAdded event or is there a better way to do this? I'm using WinForms in .NET 3.0.</p> <p>edit: Steps to reproduce</p> <ol> <li>Create a new Windows Application project.</li> <li>Add a new user control. Give the control a ToolStripContainer that contains one ToolStrip with a single button.</li> <li>Repeat step 2, giving you a UserControl2 class.</li> <li>Compile the solution so UserControl1 and UserControl2 show up in your toolbox.</li> <li>Drag UserControl1 and UserControl2 onto the form. Set the borders so you know where the boundaries are.</li> <li>Run the app.</li> <li>It's now possible to drag the ToolStrip from the container in UserControl1 and drop it into the container in UserControl2 (leaving zero ToolStrips in UC1 and two ToolStrips in UC2.)</li> <li>Now imagine you only have access to the code in UserControl1. How do you prevent the user from dragging the ToolStrip out of that instance of the ToolStripContainer?</li> </ol>
<p>This feels like a hack, but it works (kind of) (sorry, vb.net not c#):</p> <pre><code>Public Class UserControl2 Private Sub tsMainMenu_BeginDrag(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsMainMenu.BeginDrag tsMainMenu.Tag = tsMainMenu.Parent End Sub Private Sub ToolStrip1_EndDrag(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsMainMenu.EndDrag If Not tsMainMenu.Parent.Parent.Equals(CType(tsMainMenu.Tag, ToolStripPanel).Parent) Then CType(ToolStrip1.Tag, ToolStripPanel).Controls.Add(tsMainMenu) End If End Sub End Class </code></pre> <p>simply put; when the control is finished being dragged, if its parent ToolStripContainer is not the same as it was when it started dragging, move the toolstrip back to where it was.</p> <p>im sure this could be rolled into a control so that you dont have to write it for every toolbar.</p> <p><strong>Edit:</strong> You could put all this code into a control that inherits from ToolStripContainer, and have it do all the work for you, meaning a nice encapsulated solution.</p>
<p>Have you tried to use the DragEnter and DragLeave Events of the ToolStripContainer to identify a ToolStrip dragged over the container an accept or deny it?</p>
38,118
<p>I have to implement a homemade Trie and I'm stuck on the Iterator part. I can't seem to figure out the increment method for the trie.</p> <p>I hope someone can help me clear things out.</p> <p>Here's the code for the Iterator:</p> <pre><code>template &lt;typename T&gt; class Trie&lt;T&gt;::IteratorPrefixe{ friend class Trie&lt;T&gt;; public: IteratorPrefixe() : tree(NULL), currentNode(NULL), currentKey("") {}; pair&lt;string, T*&gt; operator*() {return make_pair(currentKey, currentNode -&gt; element);} ; IteratorPrefixe operator++()throw(runtime_error); void operator=(IteratorPrefixe iter) {tree = iter.tree; currentNode = iter.currentNode; currentKey = iter.currentKey;}; bool operator==(IteratorPrefixe iter) {return tree == iter.tree &amp;&amp; currentNode == iter.currentNode;}; bool operator!=(IteratorPrefixe iter) {return tree != iter.tree || currentNode != iter.currentNode;}; private: Trie&lt;T&gt; * tree; Trie&lt;T&gt; * currentNode; string currentKey; }; </code></pre> <p>And here's my Trie:</p> <pre><code>template &lt;typename T&gt; class Trie { friend class IteratorPrefixe; public: // Create a Trie&lt;T&gt; from the alphabet of nbletters, where nbletters must be // between 1 and NBLETTERSMAX inclusively Trie(unsigned nbletters) throw(runtime_error); // Add a key element of which is given in the first argument and content second argument // The content must be defined (different from NULL pointer) // The key is to be composed of valid letters (the letters between A + inclusive and exclusive nbletters // Eg if nblettres is 3, a, b and c are the only characters permitted; // If nblettres is 15, only the letters between a and o inclusive are allowed. // Returns true if the insertion was achieved, returns false otherwise. bool addElement(string, T*) throw(runtime_error); // Deletes a key element of which is given as an argument and returns the contents of the node removed // The key is to be composed of letters valid (see above) // Can also delete at the same time the reference of the ancestors, if these ancestors are no longer used. // Returns NULL if the item has no delete T* removeElement(string cle) throw(runtime_error); // Find a key element of which is given as an argument and returns the associated content // The key is to be composed of letters valid (see above) // Returns NULL if the key does not exist T* searchElement(string cle) throw(); // Iterator class to browse the Trie &lt;T&gt; in preorder mode class IteratorPrefixe; // Returns an iterator pointing to the first element IteratorPrefixe pbegin() throw(runtime_error); // Returns an iterator pointing beyond the last item IteratorPrefixe pend() throw(); private: unsigned nbLetters; T* element; vector&lt;Trie&lt;T&gt; *&gt; childs; Trie&lt;T&gt; * parent; // This function removes a node and its ancestors if became unnecessary. It is essentially the same work // as deleteElement that is how to designate remove a node that is changing. Moreover, unlike // deleteElement, it does not return any information on the node removed. void remove(Trie&lt;T&gt; * node) throw(); // This function is seeking a node based on a given key. It is essentially the same work // searchElement but that returns a reference to the node found (or null if the node does not exist) // The key is to be composed of letters valid (see above) Trie&lt;T&gt;* search(string key) throw(runtime_error); }; </code></pre>
<p>I'm glad to see Tries are still taught, they're an important data structure that is often neglected.</p> <p>There may be a design problem in your code since you should probably have a Trie class and a Node class. The way you wrote it it looks like each node in your Trie is it's own trie, which can work, but will make some things complicated.</p> <p>It's not really clear from your question what it is that you are having the problem with: figuring the order, or figuring the actual code?</p> <p>From the name of the iterator, it sounds like it would have to work in prefix order. Since your trie stores words and its child nodes are organized by letters, then you are essentially expected to go over all the words in an alphabetic order. Every incrementation will bring you to the next word.</p> <p>THe invariant about your iterator is that at any point (as long as it is valid), it should be pointing at a node with a "terminator character" for a valid word. Figuring that word merely involves scanning upwards through the parent chain till you find your entire string. Moving to the next word means doing a DFS search: go up once, scan for links in later "brothers", see if you find a word, if not recursively go up, etc. </p>
<p>For one thing, the code shown does not actually describe a trie. Rather, it appears to be a tree containing a pair of elements in each node (<code>T*</code> and <code>unsigned</code>). You can <em>by discipline</em> use a tree of tuples as a trie, but it's only by convention, not enforcement. This is part of why you're having such a hard time implementing <code>operator++</code>.</p> <p>What you need to do is have each <code>Trie</code> contain a left-right disjoint ADT, rather than just the raw elements. It's a layer of abstraction which is more commonly found in functional languages (e.g. Scala's <a href="http://www.scala-lang.org/docu/files/api/scala/Either.html" rel="nofollow noreferrer">Either</a>). Unfortunately, C++'s type system isn't quite powerful enough to do something that elegant. However, there's nothing preventing you from doing this:</p> <pre><code>template &lt;class L, class R&gt; class Either { public: Either(L *l) : left(l), right(0) {} Either(R *r) : left(0), right(r) {} L *get_left() const { return left; } R *get_right() const { return right; } bool is_left() const { return left != 0; } bool is_right() const { return right != 0; } private: L *left; R *right; }; </code></pre> <p>Then your <code>Trie</code>'s data members would be defined as follows:</p> <pre><code>private: Either&lt;unsigned, T*&gt; disjoint; vector&lt;Trie&lt;T&gt; *&gt; children; // english pluralization Trie&lt;T&gt; * parent; </code></pre> <p>I'm playing fast and loose with your pointers, but you get the gist of what I'm saying. The important bit is that no given node can contain <em>both</em> an <code>unsigned</code> and a <code>T*</code>.</p> <p>Try this, and see if that helps. I think you'll find that being able to easily determine whether you are on a leaf or a branch will help you tremendously in your attempt to iterate.</p>
45,733
<p>And why would I use one over the other in my code?</p>
<blockquote> <p><strong>Caution: This answer appears to be out of date.</strong> It was posted before .NET 4 became available, which apparently introduced some optimizations regarding <code>Type</code> and thus rendered the information in this answer obsolete. See <a href="https://stackoverflow.com/a/1438443/240733">this more recent answer</a> for details.</p> </blockquote> <p>According to <a href="http://blogs.msdn.com/vancem/archive/2006/10/01/779503.aspx" rel="nofollow noreferrer">this blog post (from 2006) by Vance Morrison</a>, <code>RuntimeTypeHandle</code> is a value type (<code>struct</code>) that wraps an unmanaged pointer, so <code>Type.GetTypeHandle(obj).Equals(anotherHandle)</code> is faster to use for strict "is exactly the same type" comparisons than <code>obj.GetType().Equals(anotherType)</code> &mdash; the latter creates <code>System.Type</code> instances which are, apparently, heavier.</p> <p>However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.</p>
<p>In .NET 4.0 Beta 1 <code>RuntimeTypeHandle</code> just wraps <code>RuntimeType</code>. It seems all benefits of using it as a cheap <code>Type</code> proxy have gone.</p> <h3>Evidence for the above claim:</h3> <ul> <li>Microsoft's <a href="https://referencesource.microsoft.com/#mscorlib/system/runtimehandles.cs" rel="nofollow noreferrer">Reference Source for the <code>System.RuntimeTypeHandle</code> type</a> shows that this type is indeed only a wrapper around <code>System.RuntimeType</code> these days. </li> <li><a href="http://higherlogics.blogspot.ch/2013/09/clr-cost-of-dynamic-type-tests.html" rel="nofollow noreferrer">Sandro Magi's 2013 blog article "CLR: The Cost of Dynamic Type Tests" </a> contains a benchmark and a final note showing that the supposed performance benefits of <code>RuntimeTypeHandle</code> are gone in .NET 4.</li> </ul>
6,158
<p>Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.</p> <p>"Best" here is defined as </p> <ul> <li>Relatively easy to implement, understand, and maintain</li> <li>Results in a thumbnail of reasonable quality</li> </ul> <p>Performance and high-quality thumbnails are secondary.</p>
<p>I suppose your best solution would be using the <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx" rel="noreferrer">GetThumbnailImage </a> from the .NET <a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.aspx" rel="noreferrer">Image</a> class.</p> <pre><code>// Example in C#, should be quite alike in ASP.NET // Assuming filename as the uploaded file using ( Image bigImage = new Bitmap( filename ) ) { // Algorithm simplified for purpose of example. int height = bigImage.Height / 10; int width = bigImage.Width / 10; // Now create a thumbnail using ( Image smallImage = image.GetThumbnailImage( width, height, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) ) { smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg); } } </code></pre>
<p>You can use the Image.GetThumbnailImage function to do it for you.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx</a> (.NET 3.5)</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage(VS.80).aspx</a> (.NET 2.0)</p> <pre><code>public bool ThumbnailCallback() { return false; } public void Example_GetThumb(PaintEventArgs e) { Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback); Bitmap myBitmap = new Bitmap("Climber.jpg"); Image myThumbnail = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero); e.Graphics.DrawImage(myThumbnail, 150, 75); } </code></pre>
4,759
<p>I want to connect to DB using the iSeries Client Access driver. I use the following connection string:</p> <p>DRIVER=Client Access ODBC Driver (32-bit);QUERYTIMEOUT=0;PKG=QGPL/DEFAULT(IBM),2,0,1,0,512;LANGUAGEID=ENU;DFTPKGLIB=QGPL;DBQ=QGPL XXXXXXXX;SYSTEM=XXX.XXXXXXX.XXX;Signon=2</p> <p>I get an exception when connecting:</p> <p>ERROR [28000] [IBM][iSeries Access ODBC Driver]Communication link failure. comm rc=8015 - CWBSY1006 - User ID is invalid, Password length = 0, Prompt Mode = Never</p> <p>How can I make the application prompt the user for his credentials to the DB?</p>
<p>This is closely related to your other question about Haskell and quicksort. I think you probably need to read at least the <em>introduction</em> of a book about Haskell. It sounds as if you haven't yet grasped the key point about it which is that it bans you from modifying the values of existing variables.</p> <p>Swap (as understood and used in C++) is, by its very nature, all about modifying existing values. It's so we can use a name to refer to a container, and replace that container with completely different contents, and specialize that operation to be fast (and exception-free) for specific containers, allowing us to implement a modify-and-publish approach (crucial for writing exception-safe code or attempting to write lock-free code).</p> <p>You can write a generic swap in Haskell, but it would probably take a pair of values and return a new pair containing the same values with their positions reversed, or something like that. Not really the same thing, and not having the same uses. It wouldn't make any sense to try and specialise it for a map by digging inside that map and swapping its individual member variables, because you're just not allowed to do things like that in Haskell (you can do the specialization, but not the modifying of variables).</p> <p>Suppose we wanted to "measure" a list in Haskell:</p> <pre><code>measure :: [a] -&gt; Integer </code></pre> <p>That's a type declaration. It means that the function <code>measure</code> takes a list of anything (<code>a</code> is a generic type parameter because it starts with a lowercase letter) and returns an Integer. So this works for a list of any element type - it's what would be called a function template in C++, or a polymorphic function in Haskell (not the same as a polymorphic class in C++).</p> <p>We can now define that by providing specializations for each interesting case:</p> <pre><code>measure [] = 0 </code></pre> <p>i.e. measure the empty list and you get zero.</p> <p>Here's a very general definition that covers all other cases:</p> <pre><code>measure (h:r) = 1 + measure r </code></pre> <p>The bit in parentheses on the LHS is a pattern. It means: take a list, break off the head and call it h, call the remaining part r. Those names are then parameters we can use. This will match any list with at least one item on it.</p> <p>If you've tried template metaprogramming in C++ this will all be old hat to you, because it involves exactly the same style - recursion to do loops, specialization to make the recursion terminate. Except that in Haskell it works at runtime (specialization of the function for particular values or patterns of values).</p>
<p>After reading enough in a Haskell book to really understand Earwicker's answer I'd suggest you also read about type classes. I'm not sure what “partial specialization” means, but it sounds like they could come close.</p>
49,372
<p>Has anybody out there used the <a href="http://www.swig.org/exec.html" rel="noreferrer">SWIG</a> library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application.</p> Edit: Some clarification on target OS's. <p>I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.</p>
<p>I think the mistake the earlier posters did was read the docs and not look at the examples. </p> <p>A few hours ago I needed to interface some C++ classes to C#. I looked in my Swig dir (I already had it for other work), found the directory <code>Examples/csharp/class</code>, browsed the code, loaded the solution, grokked it, copied it, put in my code, it worked, my job was done. </p> <p>With that said, generated P/Invoke code isn't a solution for all needs. Depending on your project, it may be just as simple to write some simple API wrappers yourself or write managed C++ (Look up SlimDX for a superb example of this). </p> <p>For my needs, it was simple and easy - I had <code>mystuff.dll</code>, and now in addition I can ship <code>mystuffnet.dll</code>. I'll agree that the doc is difficult to get into.</p> <p>Edit: I noticed the OP only mentioned C. For that, you don't really need Swig, just use the <a href="http://msdn.microsoft.com/en-us/library/aa288468(VS.71).aspx#pinvoke_callingdllexport" rel="noreferrer">usual C#/C DLLImport interop syntax</a>. Swig becomes useful when you want to let <strong>C++ classes</strong> be invoked from C#.</p>
<p>I did attempt to use SWIG to wrap a project C++ for using in .NET a few years ago.</p> <p>I didn't get very far as it was a massive giant pain to produce the configuration that SWIG required. At the time I just wanted a solution, not to learn another language/api/etc. SWIG may be easier to use these days, I couldn't tell you.</p> <p>We ended up using Managed C++ to wrap the C++ project. It worked really well.</p> <p>If you're just invoking functions straight out of a dll, I'd suggest not worrying about either of the above, and just using <a href="http://msdn.microsoft.com/en-us/magazine/cc164123.aspx" rel="noreferrer">P/Invoke</a></p>
4,491
<p>Is user profiles an appropriate place to store things like number of items per page in a custom grid user selected? (I you can store it in the view, but it won't be per user this way).</p> <p>My first though was to store these settings in user profiles, but there are problems with access permissions for programmatically creating user profile properties boiling down to you either have to give every user 'Manager User Profiles' permission in SSP or you <a href="https://stackoverflow.com/questions/82788/sharepoint-userprofilemanager-without-manage-user-profiles-right">have to run the application pool under a domain user, not NETWORK SERVICE</a>. Both scenarios are unrealistic for me, so I'm now looking for another way to store such 'per user' settings.</p> <p>Thanks!</p> <p>Edit: I'm now considering ASP.NET profile mechanism with an additional DB to store user properties.</p>
<p>Given that the information is not sensitive a simple database with values stored against AD login should suffice.</p> <p>And as you have the ASP.Net user database already, storing the information there would be the best option.</p>
<p>Maybe a Global List, that is only accessible for the SHAREPOINT\SYSTEM User and that you can then Query in a SPSecurity.RunWithElevatedPrivileges Function.</p> <p>Disadvantage: You require Custom code to read/write to that list.</p>
31,559
<p>I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete.</p> <p>Any suggestions would be much appreciated.</p>
<p>Assuming this is running on a Linux machine, I've always handled it like this:</p> <pre><code>exec(sprintf("%s &gt; %s 2&gt;&amp;1 &amp; echo $! &gt;&gt; %s", $cmd, $outputfile, $pidfile)); </code></pre> <p>This launches the command <code>$cmd</code>, redirects the command output to <code>$outputfile</code>, and writes the process id to <code>$pidfile</code>.</p> <p>That lets you easily monitor what the process is doing and if it's still running.</p> <pre><code>function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) &gt; 2){ return true; } }catch(Exception $e){} return false; } </code></pre>
<p>I know it is a 100 year old post, but anyway, thought it might be useful to someone. You can put an invisible image somewhere on the page pointing to the url that needs to run in the background, like this:</p> <p><code>&lt;img src="run-in-background.php" border="0" alt="" width="1" height="1" /&gt;</code></p>
6,797
<p>I have an Array Collection with any number of Objects. I know each Object has a given property. Is there an easy (aka "built-in") way to get an Array of all the values of that property in the Collection?</p> <p>For instance, let's say I have the following Collection:</p> <pre><code>var myArrayCollection:ArrayCollection = new ArrayCollection( {id: 1, name: "a"} {id: 2, name: "b"} {id: 3, name: "c"} {id: 4, name: "d"} .... ); </code></pre> <p>I want to get the Array "1,2,3,4....". Right now, I have to loop through the Collection and push each value to an Array. Since my Collection can get large, I want to avoid looping.</p> <pre><code>var myArray:Array /* of int */ = []; for each (var item:Object in myArrayCollection) { myArray.push(item.id); } </code></pre> <p>Does anyone have any suggestions?</p> <p>Thanks. </p>
<p>Ok so I may have overdone this, but I tried to make this pretty dynamic. Yeah, the list names are a bit odd, but I used another example of mine to build this.</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { Bench[] benchList; FoodIntake[] foodIntakeList; Panel panelChartHolder; panelChartHolder = new Panel(); Controls.Add(panelChartHolder); benchList = Bench.GetAll(); AddNewCharts(benchList, panelChartHolder, GetBenchXValue, GetBenchYValue); foodIntakeList = FoodIntake.GetAll(); AddNewCharts(foodIntakeList, panelChartHolder, GetFoodIntakeXValue, GetFoodIntakeYValue); } </code></pre> <p>Ok so this first part is simple. Create a panel to hold the charts you are adding, get the lists you want represented by the charts (For this example they happen to work with Linq to Sql) and call the method to create the charts.</p> <pre><code> private void AddNewCharts&lt;T&gt;(T[] listToAdd, Panel panelToAddTo, Func&lt;T, DateTime&gt; xMethod, Func&lt;T, Int32&gt; yMethod) { ChartArea mainArea; Chart mainChart; Series mainSeries; mainChart = new Chart(); mainSeries = new Series("MainSeries"); for (Int32 loopCounter = 0; loopCounter &lt; listToAdd.Length; loopCounter++) { mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), yMethod(listToAdd[loopCounter])); } mainChart.Series.Add(mainSeries); mainArea = new ChartArea("MainArea"); mainChart.ChartAreas.Add(mainArea); panelToAddTo.Controls.Add(mainChart); } </code></pre> <p>As you can see, I just created a new chart, added a series to it, and added a ChartArea to it. Next part is pretty much just looping through the collection and adding each item in it to the list itself. It uses the passed in delegate methods (Func) to get the X and Y values. </p> <p>Last part holds the four methods responsible for getting the X and Y values from the two lists. Basically I did this to allow the chart creating method to be a generic as possible. Might be overkill.</p> <pre><code> private DateTime GetBenchXValue(Bench currentBench) { return currentBench.DateLifted; } private Int32 GetBenchYValue(Bench currentBench) { return currentBench.BenchAmount; } private DateTime GetFoodIntakeXValue(FoodIntake currentIntake) { return currentIntake.DateEaten; } private Int32 GetFoodIntakeYValue(FoodIntake currentIntake) { return currentIntake.Calories; } </code></pre> <p>And so when you run this, you will get two graphs side by side. Mind you, they will be very plain as there are million different properties that can be set to improve the look. Hope this is what you were asking for.</p> <pre><code> using System; using System.Web.UI.DataVisualization.Charting; using System.Web.UI.WebControls; </code></pre>
<p>I have updated the MS chart samples for .NET 4.0 and added two additional projects -- ChartsWithMVC and ChartsWithoutWebForms. You might find my sample code helpful, as I have a very basic implementation of a dynamic chart system using the asp.net chart control:</p> <p><a href="http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html" rel="nofollow noreferrer">http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html</a></p> <p>Hope it helps.</p>
43,456
<p>I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1</p> <p>Delphi V7 - object pascal, standard Tquery object name query1.</p>
<p>You need to prefix the string with the table name in the query.</p> <p>For example: field name is 'Street 1', table is called customers the select is:</p> <pre><code>SELECT customers."Street 1" FROM customers WHERE ... </code></pre>
<p>I think you must use [ and ] instead of ":</p> <pre><code>SELECT customers.[Street 1] FROM customers WHERE ... </code></pre>
14,156
<p>I'm trying to set the width and height of an element with javascript to cover the entire browser viewport, and I'm successful using <pre>document.body.clientHeight</pre> but in IE6 it seems that I always get horizontal and vertical scrollbars because the element must be slightly too big. </p> <p>Now, I really don't want to use browser specific logic and substract a pixel or 2 from each dimension just for IE6. Also, I am not using CSS (width: 100% etc.) for this because I need the pixel amounts.</p> <p>Does anyone know a better way to fill the viewport with an element in IE6+ (obviously all good browsers, too)?</p> <p>Edit: Thanks Owen for the suggestion, I'm sure jQuery will work. I should have specified that I need a toolkit-agnostic solution. </p>
<p>have you considered using <a href="http://jquery.com" rel="nofollow noreferrer">jQuery</a>? it abstracts most of the browser specific functionality away into a common interface.</p> <pre><code>var width = $(document).width(); var height = $(document.height(); $('#mySpecialElement').width(width).height(height); </code></pre>
<p>Ah ha! I forgot about <pre>document.documentElement.clientLeft</pre> and <pre>document.documentElement.clientTop</pre>.</p> <p>They were 2 in IE and 0 in the good browsers. So using <pre>var WIDTH = ((document.documentElement.clientWidth - document.documentElement.clientLeft) || document.body.clientWidth);</pre> etc. did the trick, similar idea for HEIGHT!</p>
20,680
<p>I would like to move items from one list to another on a page, and I'm pretty flexible about what type of a list it is. What's the best way to do that? ASP.NET Ajax? jQuery? Anything else?</p>
<p>There's a nice tutorial on CodeProject that covers dragging with ASP.NET and jQuery:</p> <p><a href="http://www.codeproject.com/KB/webforms/JQueryPersistantDragDrop.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/webforms/JQueryPersistantDragDrop.aspx</a></p>
<p>if you want to do this and PostBack instead of using AJAX to update your data based on from fields you'll need to get creative about what types of controls you use. Page validation will complain about ASP controls like dropdownlists, listboxes, etc. if they contain selected items that weren't in the list when it was rendered.</p> <p>Better to use AJAX to send back your updates or use HTML controls like unordered lists or select added via javascript and stuff the selected data in another control that doesn't complain (hiddenfield) on PostBack. The alternative is turning off page validation and I don't think that's a good idea.</p>
27,795
<p>I have a class with a string property that's actually several strings joined with a separator.</p> <p>I'm wondering if it is good form to have a proxy property like this:</p> <pre><code>public string ActualProperty { get { return actualProperty; } set { actualProperty = value; } } public string[] IndividualStrings { get { return ActualProperty.Split(.....); } set { // join strings from array in propval .... ; ActualProperty = propval; } } </code></pre> <p>Is there any risks I have overlooked?</p>
<p>Linking two settable properties together is bad juju in my opinion. Switch to using explicit get / set methods instead of a property if this is really what you want. Code which has non-obvious side-effects will almost always bite you later on. Keep things simple and straightforward as much as possible.</p> <p>Also, if you have a property which is a formatted string containing sub-strings, it looks like what you really want is a separate struct / class for that property rather than misusing a primitive type.</p>
<p>Well I'd say your "set" is high risk, what if somebody didn't know they had to pass an already joined sequence of values or your example above was maybe missing that. What if the string already contained the separator - you'd break.</p> <p>I'm sure performance isn't great depending on how often this property is used.</p>
11,305
<pre><code> ArrayList filters = new ArrayList(); filters.Add(new string[] { "Name", "Equals", "John" }); ObjectDataSource1.SelectParameters.Add("AppliedFilters", string.Join(",",(string[])filters.ToArray(typeof(string)))); </code></pre> <p>Am trying to add a parameter to my object data source which is bound to my select method which should accept a string[]. But as the SelectParameters.Add takes in (string,string) or the other 3 overloads which do not seem to function for me correctly. </p> <p>The select method accepts a string param though i prefer it accept a string[] or arraylist, but for now I can live with accepting a string which i should convert back to string[]</p> <p>Resolution: followed this article <a href="https://stackoverflow.com/questions/235166/how-do-i-set-up-objectdatasource-select-parameters-at-runtime">link text</a></p> <p><strong>Closed</strong> as duplicate of the question referenced above.</p>
<p>A somewhat obvious one: always redefine <code>respond_to?</code> if you redefine <code>method_missing</code>. If <code>method_missing(:sym)</code> works, <code>respond_to?(:sym)</code> should always return true. There are many libraries that rely on this.</p> <p><em>Later:</em></p> <p>An example:</p> <pre><code># Wrap a Foo; don't expose the internal guts. # Pass any method that starts with 'a' on to the # Foo. class FooWrapper def initialize(foo) @foo = foo end def some_method_that_doesnt_start_with_a 'bar' end def a_method_that_does_start_with_a 'baz' end def respond_to?(sym, include_private = false) pass_sym_to_foo?(sym) || super(sym, include_private) end def method_missing(sym, *args, &amp;block) return foo.call(sym, *args, &amp;block) if pass_sym_to_foo?(sym) super(sym, *args, &amp;block) end private def pass_sym_to_foo?(sym) sym.to_s =~ /^a/ &amp;&amp; @foo.respond_to?(sym) end end class Foo def argh 'argh' end def blech 'blech' end end w = FooWrapper.new(Foo.new) w.respond_to?(:some_method_that_doesnt_start_with_a) # =&gt; true w.some_method_that_doesnt_start_with_a # =&gt; 'bar' w.respond_to?(:a_method_that_does_start_with_a) # =&gt; true w.a_method_that_does_start_with_a # =&gt; 'baz' w.respond_to?(:argh) # =&gt; true w.argh # =&gt; 'argh' w.respond_to?(:blech) # =&gt; false w.blech # NoMethodError w.respond_to?(:glem!) # =&gt; false w.glem! # NoMethodError w.respond_to?(:apples?) w.apples? # NoMethodError </code></pre>
<p>Another gotcha:</p> <p><code>method_missing</code> behaves differently between <code>obj.call_method</code> and <code>obj.send(:call_method)</code>. Essentially the former one miss all private and non-defined methods, while later one doesn't miss private methods.</p> <p>So you <code>method_missing</code> will never trap the call when someone calling your private method via <code>send</code>.</p>
37,128
<p>I haven´t experience in making setup, but I all ready make mine but now I need help because when I made a new version I want that the user double click the shortcut and it do the update if there are any.</p> <p>The application is in <code>c#</code>.</p> <p>Could you help?</p>
<p>Here's how I have implemented an updater program I wrote earlier.</p> <p>First off, you grab an ini file off of your server. This file will contain information about the latest version and where the setup file is. Getting that file isn't too hard.</p> <pre><code> WebClient wc = new WebClient(); wc.DownloadFile(UrlOfIniContainingLatestVersion, PlacetoSaveIniFile); </code></pre> <p>I also had it setup to read information from a local ini file to determine the latest version. The better way of doing this would be to read the file version directly, but I don't have the code to do that handy.</p> <p>Next we do a very simple check to see how the two versions compare and download the update.</p> <pre><code> if (LatestVersion &gt; CurrentVersion) { //Download update. } </code></pre> <p>Downloading the update is just as simple as downloading the original ini. You simply change change the two parameters.</p> <pre><code>wc.DownloadFile(UrlOfLatestSetupFile, PlaceToSaveSetupFile); </code></pre> <p>Now that you have the file downloaded, it's a simple matter of running the installer.</p> <pre><code>System.Diagnostics.Start(PathOfDownloadedSetupFile); </code></pre> <hr> <p>If you're not sure how to read an ini file, I found the following class somewhere over at CodeProject</p> <pre><code>using System; using System.Runtime.InteropServices; using System.Text; namespace Ini { /// &lt;summary&gt; /// Create a New INI file to store or load data /// &lt;/summary&gt; public class IniFile { public string path; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// &lt;summary&gt; /// INIFile Constructor. /// &lt;/summary&gt; /// &lt;PARAM name="INIPath"&gt;&lt;/PARAM&gt; public IniFile(string INIPath) { path = INIPath; } /// &lt;summary&gt; /// Write Data to the INI File /// &lt;/summary&gt; /// &lt;PARAM name="Section"&gt;&lt;/PARAM&gt; /// Section name /// &lt;PARAM name="Key"&gt;&lt;/PARAM&gt; /// Key Name /// &lt;PARAM name="Value"&gt;&lt;/PARAM&gt; /// Value Name public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.path); } /// &lt;summary&gt; /// Read Data Value From the Ini File /// &lt;/summary&gt; /// &lt;PARAM name="Section"&gt;&lt;/PARAM&gt; /// &lt;PARAM name="Key"&gt;&lt;/PARAM&gt; /// &lt;PARAM name="Path"&gt;&lt;/PARAM&gt; /// &lt;returns&gt;&lt;/returns&gt; public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path); return temp.ToString(); } } } </code></pre>
<p>Sounds like you might be able to use <a href="http://msdn.microsoft.com/en-us/library/t71a733d(VS.80).aspx" rel="nofollow noreferrer">ClickOnce</a></p>
30,652
<p>I'm looking for a query which will return me an extra column at the end of my current query which is the count of all columns within the return set which contain a null column. For example:</p> <pre><code>Col 1 - Col 2 - Col 3 A B 0 A NULL 1 NULL NULL 2 </code></pre> <p>Is there a simple way to get this return set based on the row values rather than having to requery all the criteria which fetches the original rows?</p>
<p>Ugly solution:</p> <pre><code>select Col1, Col2, case when Col1 is null then 1 else 0 end + case when Col2 is null then 1 else 0 end as Col3 from ( select 'A' as Col1, 'B' as Col2 union select 'A', NULL union select NULL, NULL ) z </code></pre> <p>This returns</p> <pre><code>Col1 Col2 Col3 NULL NULL 2 A NULL 1 A B 0 </code></pre>
<p>If there isnt a very good reason you need to do this in the SQL, you should just do a for loop through the result set and count the NULL vlues then. </p> <p>The cost goes from n^n to n..</p>
20,934
<p>I use <a href="http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.aspx" rel="nofollow noreferrer">System.Web.Services.WebMethodAttribute</a> to make a public static method of an ASP.NET page callable from a client-side script:</p> <p><strong><em>test.aspx.cs</em></strong></p> <pre><code>[System.Web.Services.WebMethod] public static string GetResult() { return "result"; } </code></pre> <p><strong><em>test.aspx</em></strong></p> <pre><code>&lt;asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" /&gt; &lt;script type="text/javascript"&gt; alert(PageMethods.GetResult()); &lt;/script&gt; </code></pre> <p>The method works as it should, but if I load <em>test.aspx</em> with </p> <pre><code>Server.Transfer("test.aspx"); </code></pre> <p>I receive "Unknown web method" error. After</p> <pre><code>Response.Redirect("test.aspx"); </code></pre> <p>the page works well.</p> <p>Could you tell me, please, what is a reason of the error and how can it also be avoided? Many thanks!</p>
<p>You have a problem here and that is the limited capabilities of JPA when it comes to handling enums. With enums you have two choices:</p> <ol> <li>Store them as a number equalling <code>Enum.ordinal()</code>, which is a terrible idea (imho); or</li> <li>Store them as a string equalling <code>Enum.name()</code>. <strong>Note:</strong> not <code>toString()</code> as you might expect, especially since the default behaviourfor <code>Enum.toString()</code> is to return <code>name()</code>.</li> </ol> <p>Personally I think the best option is (2).</p> <p>Now you have a problem in that you're defining values that don't represent vailid instance names in Java (namely using a hyphen). So your choices are:</p> <ul> <li>Change your data;</li> <li>Persist String fields and implicitly convert them to or from enums in your objects; or</li> <li>Use nonstandard extensions like TypeConverters.</li> </ul> <p>I would do them in that order (first to last) as an order of preference.</p> <p>Someone suggested Oracle TopLink's converter but you're probably using Toplink Essentials, being the reference JPA 1.0 implementation, which is a subset of the commercial Oracle Toplink product.</p> <p>As another suggestion, I'd strongly recommend switching to <a href="http://www.eclipse.org/eclipselink/" rel="noreferrer">EclipseLink</a>. It is a far more complete implementation than Toplink Essentials and Eclipselink will be the reference implementation of JPA 2.0 when released (expected by JavaOne mid next year).</p>
<p>use this annotation</p> <pre><code>@Column(columnDefinition="ENUM('User', 'Admin')") </code></pre>
45,916
<p>After multiple jams from bulging filaments on two spools I'm getting frustrated. One, right before a job was done.</p> <p>Is there something I can do to prevent these bulges in filaments from ruining jobs?</p> <p>What can I do to prevent this from happening in the future before it's a disaster?</p> <p>He's a picture of one I found using google.</p> <p><a href="https://i.stack.imgur.com/6UvLW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6UvLW.jpg" alt="enter image description here"></a></p>
<p>How to catch <em>and</em> fix these on the fly? That would be difficult..</p> <p>But this is an issue you really should not have.</p> <p><a href="https://3dprinting.stackexchange.com/q/84/47">Could it be an issue with filament storage?</a></p> <p>Or is it coming from the manufacturer with these bulges? If so, I would try contacting ( you may have gotten a bad batch? ), or finding a new retailer if this happens often.</p> <p>I have gone through a lot of pounds of both ABS and PLA and never come across this. </p>
<p><strong>Bottom line: <em>The easiest way to prevent this is to avoid cheap filament.</em></strong></p> <p>You can get mid-grade filament for a few dollars more than the ultra cheap stuff. </p> <p>In other words I tried out some 10$ stuff from ebay, and while it might print for a little while it notoriously clogged in any prints greater than 1hr. </p> <p>20-25$ is the going rate for mid-grade filament on amazon and check the reviews I've had good consistency there. </p>
137
<p>I tried to override the settings in the default stlyesheet that comes with the simplemodal jquery plugin with containerCSS which is working fine in IE7 but not Firefox or Chrome. Not sure if this is a bug or I am doing something wrong.</p> <p><strong>jQuery code:</strong></p> <pre><code>$(document).ready(function() { $("#ButtonPopup").click(function() { $("#addEditTask").modal({ onOpen: modalOpen, persist: true, containerCss: ({ width: "300", height: "200", marginLeft: "-150" }) }); return false; }); }); </code></pre> <p><strong>HTML code:</strong></p> <pre><code>&lt;button id="ButtonPopup"&gt;Popup&lt;/button&gt; &lt;div id="addEditTask" style="display:none;"&gt; &lt;p&gt;Aliquam nonummy adipiscing augue. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.&lt;/p&gt; &lt;button id="ButtonSave"&gt;Save&lt;/button&gt; &lt;button id="ButtonCancel"&gt;Cancel&lt;/button&gt; &lt;/div&gt; </code></pre> <p>Please see <a href="http://beckelman.net/issues/simplemodalfirefoxproblem/default.aspx" rel="nofollow noreferrer">this</a> for a working demo and zip download of the code that you can test for yourself.</p>
<p>Gecko and WebKit based browsers really like their units. Make sure you always tell it how to measure your values.</p> <p>Also as a note, if you want to override inline styles from a css file, you can do so by adding !important to the end of the value.</p> <p>height: 300px !important;</p> <p>will override the inline styles.</p> <p>Cheers!</p>
<p>I would have a look at jqModal instead. </p>
29,504
<p>I am using Windows, and I have two monitors.</p> <p>Some applications will <em>always</em> start on my primary monitor, no matter where they were when I closed them.</p> <p>Others will always start on the <em>secondary</em> monitor, no matter where they were when I closed them.</p> <p>Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?</p> <p>@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS. But as you said, it doesn't let you control the default monitor a program launches into.</p>
<p>Correctly written Windows apps that want to save their location from run to run will save the results of <a href="http://msdn.microsoft.com/ru-ru/library/windows/desktop/ms633518%28v=vs.85%29.aspx" rel="noreferrer"><code>GetWindowPlacement()</code></a> before shutting down, then use <code>SetWindowPlacement()</code> on startup to restore their position.</p> <p>Frequently, apps will store the results of <code>GetWindowPlacement()</code> in the registry as a <code>REG_BINARY</code> for easy use.</p> <p>The <code>WINDOWPLACEMENT</code>route has many advantages over other methods:</p> <ul> <li>Handles the case where the screen resolution changed since the last run: <code>SetWindowPlacement()</code> will automatically ensure that the window is not entirely offscreen</li> <li>Saves the state (minimized/maximized) but also saves the restored (normal) size and position</li> <li>Handles desktop metrics correctly, compensating for the taskbar position, etc. (i.e. uses "workspace coordinates" instead of "screen coordinates" -- techniques that rely on saving screen coordinates may suffer from the "walking windows" problem where a window will always appear a little lower each time if the user has a toolbar at the top of the screen).</li> </ul> <p>Finally, programs that handle window restoration properly will take into account the <code>nCmdShow</code> parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize):</p> <pre><code>if(nCmdShow != SW_SHOWNORMAL) placement.showCmd = nCmdShow; //allow shortcut to override </code></pre> <p>For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's <code>setBounds()</code>/<code>getBounds()</code> problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the <code>WINDOWPLACEMENT</code> functions.</p>
<p>Right click the shortcut and select properties. Make sure you are on the "Shortcut" Tab. Select the RUN drop down box and change it to Maximized. </p> <p>This may assist in launching the program in full screen on the primary monitor. </p>
7,606
<p>I know WCF supports many WS-* protocols but WS-Eventing does seem to be listed.</p> <p>I do know that WCF has a pub/sub model, but is it WS-Eventing compliant?</p>
<p>I seem to remember reading about this on CodeProject a while ago. </p> <p>Sorry I can't help more, but <a href="http://www.codeproject.com/KB/WCF/WSEventing.aspx" rel="nofollow noreferrer">this is the article</a> by Roman Kiss.</p>
<p>There is no native pub/sub model in WCF 3.0, however there are a few options.<br> - The Roman Kiss article Ash found.<br> - There is a lot of other patterns you could implement (covered in <a href="http://msdn.microsoft.com/msdnmag/issues/06/10/WCFEssentials/" rel="nofollow noreferrer">MSDN Mag</a>)<br> - Juval Lowy has two framework implementations you can download on his site at <a href="http://www.idesign.net/" rel="nofollow noreferrer">IDesign</a><br> - Lastly what I am using currently to mimic this with little overhead is MSMQ. </p>
13,264
<p>What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.</p> <p>CLR integration isn't an option for me either.</p> <p>The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)</p>
<p>Create two tables and then join to them to convert stored GMT dates to local time:</p> <pre><code>TimeZones e.g. --------- ---- TimeZoneId 19 Name Eastern (GMT -5) Offset -5 </code></pre> <p>Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future)</p> <pre><code>DaylightSavings --------------- TimeZoneId 19 BeginDst 3/9/2008 2:00 AM EndDst 11/2/2008 2:00 AM </code></pre> <p>Join them like this:</p> <pre><code>inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst </code></pre> <p>Convert dates like this:</p> <pre><code>dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert) </code></pre>
<p>Maintain a TimeZone table, or shell out with an extended stored proc (xp_cmdshell or a COM component, or your own) and ask the OS to do it. If you go the xp route, you'd probably want to cache the offset for a day.</p>
4,442
<p>I have an array of 1000 strings to load into a combo box. What is the fastest way to load the array of strings into the combo box?</p> <p>Is there some way other than iterating over the list of strings, putting each string into the combo box one at a time?</p> <p>And how to copy the combo box data once loaded to some 10 other combo boxes?</p>
<p>If you have 1,000 strings repeated in 10 comboboxes, you may want to consider using an owner drawn combobox, which draws the strings on the fly based on indices into your array, rather than storing them in the combobox at all. Way faster, way more memory efficient. Check out the <strong>DrawItem</strong> method and <strong>DRAWITEMSTRUCT</strong> structure in the on-line help. Basically, you would do something like using <strong>InitStorage</strong> and <strong>InsertString</strong> (as mentioned by NuSonic) to create your 1000 blank items in your combobx, and override <strong>DrawItem</strong> to extract and draw the required string, based on index, as it needs to be drawn.</p>
<p>I will consider using a pick list instead of a combo box for performance.</p> <p>A general rule of thumb to improve performance when inserting many item in a UI list is to call before the insertion and setting it back to true after.</p> <p>Here's the correct syntax</p> <pre><code>#define NB_ITEM 1000 #define ITEM_LENGTH 10 void CMFCComboDlg::InitMyCombo() { CString _strData; m_cbMyCombo.SetRedraw( FALSE ); m_cbMyCombo.Clear(); m_cbMyCombo.InitStorage(NB_ITEM, ITEM_LENGTH); for( int i = 0; i &lt; NB_ITEM; i++ ) { _strData.Format( L"Test %ld", i ); m_cbMyCombo.InsertString( i, _strData ); } m_cbMyCombo.SetCurSel(0); m_cbMyCombo.SetRedraw( TRUE ); } </code></pre> <p>EDIT: Improve the solution to include smacl suggestion</p>
28,395
<p>I wrote a program which includes writing and reading from database. When I run the app and try to perform writing I call the following method:</p> <pre><code>public static void AddMessage(string callID, string content) { string select = "INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime)"; SqlCommand cmd = new SqlCommand(select, conn); cmd.Parameters.AddWithValue("callId", callID.ToString()); cmd.Parameters.AddWithValue("content", content); cmd.Parameters.AddWithValue("insertTime", "10.10.2008"); try { conn.Open(); cmd.ExecuteScalar(); } catch(Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } } </code></pre> <p>After the method call I read all the records from the table and display them in the form. The record inserted before refresh could be seen but then when I exit the app and look at the table I don't see the record.</p> <p>Does anyone know what could cause such behavior?</p>
<p>Are you performing a commit after this? It might be running your statement but then not committing the changes and doing an implicit rollback.</p> <p>I think the exception handling looks dodgy. There is no point catching something unless you can actually handle it in some way. The top level of your framework is the place for catching and reporting unexpected exceptions.</p>
<p>Have you tried setting the return value of the ExecuteScalar method to an int and then checking value against the table?</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx" rel="nofollow noreferrer">ExecuteScalar</a> -</p> <p><em>Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored</em></p> <pre><code>public static int AddMessage(string callID, string content) { Int32 newProdID = 0 string select = "INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime); SELECT CAST(scope_identity() AS int);"; SqlCommand cmd = new SqlCommand(select, conn); cmd.Parameters.AddWithValue("callId", callID.ToString()); cmd.Parameters.AddWithValue("content", content); cmd.Parameters.AddWithValue("insertTime", "10.10.2008"); try { conn.Open(); newProdID = (Int32)cmd.ExecuteScalar(); } catch(Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } return (int)newProdID } </code></pre>
26,588
<p>Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick.</p> <p>How do I install a debian package on the computer locally?</p>
<p>Once you have the USB stick mounted:</p> <pre><code>dpkg --install /path/to/foo_VVV-RRR.deb </code></pre> <p>(where fooVVV-RRR.deb is the package's file name)</p> <p>You can find more commands at the <a href="http://www.debian.org/doc/FAQ/ch-pkgtools.en.html" rel="nofollow noreferrer">Debian GNU/Linux FAQ</a>.</p> <p>Side note: this is from the command line. I'm not sure how to get synaptic to do it.</p>
<p>If you're not a command line fan, double-clicking on the .deb files in the file manager should launch a package installer. Has exactly the same effect as <code>dpkg -i</code> of course.</p>
34,216
<p>I'm still working with this huge list of URLs, all the help I have received has been great.</p> <p>At the moment I have the list looking like this (17000 URLs though):</p> <ul> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li> <li><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></li> </ul> <p>I can filter out the duplicates no problem with a couple of methods, awk etc. What I am really looking to do it take out the duplicate URLs but at the same time taking a count of how many times the URL exists in the list and printing the count next to the URL with a pipe separator. After processing the list it should look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>url</th> <th>count</th> </tr> </thead> <tbody> <tr> <td><code>http://www.example.com/page?CONTENT_ITEM_ID=1</code></td> <td>2</td> </tr> <tr> <td><code>http://www.example.com/page?CONTENT_ITEM_ID=2</code></td> <td>2</td> </tr> <tr> <td><code>http://www.example.com/page?CONTENT_ITEM_ID=3</code></td> <td>3</td> </tr> </tbody> </table> </div> <p>What method would be the fastest way to achieve this?</p>
<p>This is probably as fast as you can get without writing code.</p> <pre> $ cat foo.txt http://www.example.com/page?CONTENT_ITEM_ID=1 http://www.example.com/page?CONTENT_ITEM_ID=3 http://www.example.com/page?CONTENT_ITEM_ID=2 http://www.example.com/page?CONTENT_ITEM_ID=1 http://www.example.com/page?CONTENT_ITEM_ID=2 http://www.example.com/page?CONTENT_ITEM_ID=3 http://www.example.com/page?CONTENT_ITEM_ID=3 $ sort foo.txt | uniq -c 2 http://www.example.com/page?CONTENT_ITEM_ID=1 2 http://www.example.com/page?CONTENT_ITEM_ID=2 3 http://www.example.com/page?CONTENT_ITEM_ID=3 </pre> <p>Did a bit of testing, and it's not particularly fast, although for 17k it'll take little more than 1 second (on a loaded P4 2.8Ghz machine)</p> <pre> $ wc -l foo.txt 174955 foo.txt vinko@mithril:~/i3media/2008/product/Pending$ time sort foo.txt | uniq -c 54482 http://www.example.com/page?CONTENT_ITEM_ID=1 48212 http://www.example.com/page?CONTENT_ITEM_ID=2 72261 http://www.example.com/page?CONTENT_ITEM_ID=3 real 0m23.534s user 0m16.817s sys 0m0.084s $ wc -l foo.txt 14955 foo.txt $ time sort foo.txt | uniq -c 4233 http://www.example.com/page?CONTENT_ITEM_ID=1 4290 http://www.example.com/page?CONTENT_ITEM_ID=2 6432 http://www.example.com/page?CONTENT_ITEM_ID=3 real 0m1.349s user 0m1.216s sys 0m0.012s </pre> <p>Although O() wins the game hands down, as usual. Tested S.Lott's solution and</p> <pre> $ cat pythoncount.py from collections import defaultdict myFile = open( "foo.txt", "ru" ) fq= defaultdict( int ) for n in myFile: fq[n] += 1 for n in fq.items(): print "%s|%s" % (n[0].strip(),n[1]) $ wc -l foo.txt 14955 foo.txt $ time python pythoncount.py http://www.example.com/page?CONTENT_ITEM_ID=2|4290 http://www.example.com/page?CONTENT_ITEM_ID=1|4233 http://www.example.com/page?CONTENT_ITEM_ID=3|6432 real 0m0.072s user 0m0.028s sys 0m0.012s $ wc -l foo.txt 1778955 foo.txt $ time python pythoncount.py http://www.example.com/page?CONTENT_ITEM_ID=2|504762 http://www.example.com/page?CONTENT_ITEM_ID=1|517557 http://www.example.com/page?CONTENT_ITEM_ID=3|756636 real 0m2.718s user 0m2.440s sys 0m0.072s </pre>
<p>Here is another version in Python:</p> <pre><code>import fileinput, itertools urls = sorted(fileinput.input()) for url, sameurls in itertools.groupby(urls): print url.rstrip(), &quot;|&quot;, sum(1 for _ in sameurls) </code></pre> <p>Example:</p> <pre><code>$ cat foo.txt http://www.example.com/page?CONTENT_ITEM_ID=1 http://www.example.com/page?CONTENT_ITEM_ID=3 http://www.example.com/page?CONTENT_ITEM_ID=2 http://www.example.com/page?CONTENT_ITEM_ID=1 http://www.example.com/page?CONTENT_ITEM_ID=2 http://www.example.com/page?CONTENT_ITEM_ID=3 http://www.example.com/page?CONTENT_ITEM_ID=3 $ python countuniq.py foo.txt http://www.example.com/page?CONTENT_ITEM_ID=1 | 2 http://www.example.com/page?CONTENT_ITEM_ID=2 | 2 http://www.example.com/page?CONTENT_ITEM_ID=3 | 3 </code></pre> <p>Performance:</p> <pre><code>C:\&gt; timethis &quot;sort urls17000.txt|uniq -c&quot; ... TimeThis : Elapsed Time : 00:00:00.688 C:\&gt; timethis python countuniq.py urls17000.txt ... TimeThis : Elapsed Time : 00:00:00.625 C:\&gt; timethis python slott.py urls17000.txt ... TimeThis : Elapsed Time : 00:00:00.562 C:\&gt; timethis perl toolkit.pl urls17000.txt ... TimeThis : Elapsed Time : 00:00:00.187 </code></pre> <p><strong>Conclusion</strong>: All solutions are under 1 second. The pipe is the slowest, <a href="https://stackoverflow.com/questions/264930/count-duplicate-urls-fastest-method-possible#264942">S.Lott's solution</a> is faster then the above python's version and <a href="https://stackoverflow.com/questions/264930/count-duplicate-urls-fastest-method-possible#264969">toolkit's Perl solution</a> is the fastest.</p> <hr /> <pre><code>C:\&gt; timethis perl toolkit.pl urls1778955.txt ... TimeThis : Elapsed Time : 00:00:17.656 C:\&gt; timethis &quot;sort urls1778955.txt|uniq -c&quot; ... TimeThis : Elapsed Time : 00:01:54.234 $ wc urls1778955.txt 1778955 1778955 81831930 urls1778955.txt </code></pre> <p>Hashing beats sorting for a large number of URLs.</p>
33,197
<p>I am working on an ASP.Net web application that must print dynamically created labels on standard Avery-style label sheets (one particular size, so only one overall layout). The labels have a variable number of lines (3-6) and may contain either lines of text or a graphic barcode image.</p> <p>Our first cut, that I inherited, used monospaced fonts to reduce the formatting issues, but that did not allow enough text to the fit on the labels and the customer was dissatisfied. Basically it was formatted text.</p> <p>My next version used TABLEs, DIVs, CSS, and a bit of JavaScript calculations to format the labels using proportional fonts. It still required a bit of tweaking (the user had to set their print margins correctly and turn off the print headers and footers), but it seemed to work. </p> <p>However, it seems that there are some variations on how different printers render the text (WYS ain't WYG), so even though we tested on different browsers using at least two different printers (an inkjet and a laser printer), some user's labels don't line up. Slight margin variations can be adjusted by adjusting the margins on the page setup dialog, but the harder problem is that the inter-label spacing can be off by a tiny fraction of an inch, so that if the first label is pretty well centered, by the end of the page the label text and images have crawled off the top or bottom of the labels.</p> <p>We are about to the point of switching to generating Word, Excel, or PDF output which is going to take quite a bit of development time and possible add extra steps in the printing process.</p> <p>So, does anyone have any suggestions on how to do an HTML/CSS layout that will precisely render on different types of printers? I don't really care if the line/word breaks are a bit different, but I need to be able to predictably position the upper left corners of each label area.</p> <p>Right now the labels flow down the page in a table and we have been tweaking the box model of the cells and internal DIVs to make them a uniform height. I suspect that using absolute positioning of each element may be the best answer, but that is going to be tricky as well due to the ASP.Net generation of the label elements. If I knew for sure that would work, I would rather try it than throw away everything we have to go to a different generation method.</p> <p>Slight Update: Right now I'm doing some tests with absolute positioning - setting only the top and left coordinate of a containing block element. So far there are minor variations on the offset onto the page (margins, paper alignment, etc.), but all browsers and printers tested put the elements in <strong><em>exactly</em></strong> the right spots relative to each other. I appreciate the PDF tips, but does anyone know of additional "gotchas" on using absolute positioning this way?</p> <p><strong>Update:</strong> For the record, I rewrote the label printing portion using iTextSharp and it works perfectly - definitely the way to do this in the future...</p>
<p>Forget HTML and make a PDF. HTML printing is extremely variable - not just across browsers but across different versions of the same browser. PDF is a lot easier.</p> <p>Even if you get it exactly right with one browser / font setup / printer / phase of the moon, it will be the most fragile thing you've ever had to maintain. No matter how long you think it will take to make a PDF (and it's not really that hard as there are some free libraries out there), HTML will ultimately take a lot more of your time. PDF readers are widely deployed and print more consistently than even Word files.</p>
<p>Add a few options to your app that let users adjust spacing for their particular configuration. You could include this right on the label if you want, and style it away via media selectors, but you'll probably want to persist them somewhere, too.</p>
19,851
<p>Forgive me for a potentially silly question here, but in other programming languages (scripting ones like PHP or Perl) it is often easy to dump everything contained within a variable.</p> <p>For instance, in PHP there are the <code>var_dump()</code> or <code>print_r()</code> functions. Perl has the <code>Data::Dumper</code> CPAN class, etc etc.</p> <p>Is there something like this for Objective-C? It would be very convenient in a few cases to be able to dump everything like that, instead of using gdb to inspect each variable.</p>
<p>In Cocoa, there is no "dump" like PHP's print_r or python's <strong>repr</strong> since there is no textual format that "represents" an object as in those languages. If you use</p> <pre><code>NSLog(@"%@", myObj); </code></pre> <p>or</p> <pre><code>NSString *stringRep = [NSString stringWithFormat:@"%@",myObj]; </code></pre> <p>or</p> <pre><code>NSString *stringRep = [myObj description]; </code></pre> <p>you will get (logged to console in the first case), the result of <code>[myObj description]</code>, a method defined in <code>NSObject</code> for the purpose of printing a <em>description</em> (<strong>not</strong> a dump) of an object.</p> <p>If you invoke <code>po myObj</code> in gdb, you get <code>[myObj debugDescription]</code> (often the same as <code>description</code>, but not always).</p> <p>Classes like <code>NSArray</code> and <code>NSDictionary</code> and <code>NSData</code> override <code>description</code> to print a pretty useful recursive description of their contents, but the default <code>[NSObject description]</code> prints only the pointer value corresponding to the instance.</p> <p>If you control the code for the types in question, you can override their <code>description</code> or <code>debugDescription</code> methods to return anything you want. If not, you could override the <code>description</code> or <code>debugDescription</code> method using a category, or use a category to define a <code>myDebugDescription</code> or some such that you could then invoke from gdb using <code>po [myObj myDebugDescription]</code>.</p>
<p>Be careful with NSLog logging -> you most likely don't want it in production code.</p> <p>You may want to use an alternate logging function that calls NSLog when your product is running in debug mode.</p>
36,827
<p>What's going on here?</p> <p>printf.sh:</p> <pre><code>#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" $NAME </code></pre> <p>Command line session:</p> <pre><code>$ ./printf.sh Hello, George Hello, W. Hello, Bush </code></pre> <p>UPDATE: <code>printf "Hello, %s\n" "$NAME"</code> works. For why I'm not using <code>echo</code>, consider</p> <p>echo.sh:</p> <pre><code>#! /bin/sh FILE="C:\tmp" echo "Filename: $FILE" </code></pre> <p>Command-line:</p> <pre><code>$ ./echo.sh Filename: C: mp </code></pre> <p>The <a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="noreferrer">POSIX spec for <code>echo</code></a> says, "New applications are encouraged to use <code>printf</code> instead of <code>echo</code>" (for this and other reasons). </p>
<p>Your NAME variable is being substituted like this:</p> <pre><code>printf "Hello, %s\n" George W. Bush </code></pre> <p>Use this:</p> <pre><code>#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME" </code></pre>
<p>If you want all of those words to be printed out on their own, use <strong>print</strong> instead of <strong>printf</strong> </p> <p><strong>printf</strong> takes the formatting specification and applies it to each argument that you pass in. Since you have three arguments {George, W., Bush}, it outputs the string three times using the different arguments.</p>
6,346
<p>I'm looking at adding Visual Studio Database Edition (aka. VSDE) to my version of VS2008.</p> <p>Q1. What's the order of install of these products? is this ok?</p> <p><em>Update: Fixed the ordering of the install, based on feedback.</em></p> <ul> <li>VS2008 (c# [no sub options], web dev, ts tools. nothing else).</li> <li>Team Foundation Client (found on our msdn dvd)</li> <li>VSDE</li> <li><strike>VSDE GDR (I think we downloaded this from download.microsoft.com)</strike></li> <li><strike>VS2008 SP1</strike></li> <li>VS2008 SP1</li> <li>VSDE GDR </li> </ul> <p>Q2. Is it 'acceptable' to not have sql server installed on the client machines but use a dev box? what about private instances of their dev data? Basically, we don't install sql on our vista dev boxes. I personally don't like having extra services which i might not use all the time. We have 3 DB's usually - Dev, Test, Production. Should we make multiple Sql instances on our dev box (for example) which could be SqlMachine\User1, SqlMachine\User2, etc.. and the root SqlMachine is 'Dev'. This way, we can each use VSDE to play with our own db instance and this then goes up to the Dev instance?</p> <p>(i hope that made sense).</p> <p>cheers!</p>
<p>Q1 - the GDR has a pre-requisite of VS2008 SP1, so switch those last two around.</p> <p>Q2 - I believe that each dev should be working with their own sandboxed database instance, yes. If you don't want to install instances of SQL Server on your workstations, then using multiple instances of SQL on a development server sounds like a reasonable solution.</p>
<p>I would put the DB on the development machine. You can change the service so that it doesn't start by default and start it manually whenever you want to use it, if you don't want it running all the time. I prefer this so that I'm not dependent on the availability of another system while developing. If you go this way and want something other than the Express edition included in VS, install SQLServer (I use the Developer Edition) before installing VS so as not to get the Express edition installed by default.</p>
47,770
<p>I have an Air application with a main window. I would like to have a new window fly out from the side of the main window when the user clicks on a button in the main window. The window that appears needs to display information based on value passed from the main form. How can I achieve this with Flex Builder 3?</p> <p>Target platform: any version of Flash/Flex/Air.</p>
<p>For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace.</p> <pre><code>namespace { void myLocalFunction() { // stuff } } </code></pre>
<p>If by 'module' you just mean a CPP file, you could just place the declaration and the definition right in the CPP file.</p>
40,599
<p>Sometimes supports are very difficult to remove (physically) when I print with ABS. The image below, from <a href="https://www.thingiverse.com/thing:1613957" rel="nofollow noreferrer">Thingiverse - MOF-5 unit cell</a>, is after significant effort to remove the yellow ABS supports from a black ABS model.</p> <p><a href="https://i.stack.imgur.com/3Ze3e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Ze3e.png" alt="Yellow ABS supports removed from black ABS model"></a></p> <p>I've learned about polyvinylalcohol (PVA) as a 3D-printing filament which is soluble in water. It seems like a great option for dual-extruder printers, where you can print the model with ABS or PLA and the supports with PVA, then throw the whole thing in water and let the supports dissolve.</p> <p>I've considered other options since PVA is ~4x more expensive than ABS.</p> <p>Doing a PLA print with ABS supports, followed by dissolution of ABS with acetone, is my best idea currently.</p> <p>Has anyone found success with another option? </p>
<p>I've had great success printing with HIPS (high-impact polystyrene) as a support for both PLA and ABS. Most sites recommend it for use with ABS because the materials melt at similar temperatures and work best with heated beds, but I've had good luck using it as a support material with PLA on a bed at 60°C. It doesn't stick as well to PLA as it does to ABS, so supports tend to peel away very readily. The downside is that, if you need the support to anchor your print at all, it doesn’t really stick well enough to accomplish this task. For that, you must pair HIPS with ABS. </p> <p>When you print with ABS or have complicated interwoven support structures, HIPS can be dissolved with D-limonene, a citrus based cleaner sold under various names like Citrisolv (others exist), or with dipentene (a mixture of L and D-limonene that doesn't smell as pleasant). </p> <p>Regarding cost: I've found HIPS to be slightly more expensive than PLA/ABS, but only 1.5x the cost, not 4x like PVA. Additionally, it isn't hydroscopic in the same way as PVA so it lasts longer out of the package. Since you're using it as support, you also tend to use far less filament than you do for the main print (sparse support structures as opposed to solid print structures). </p> <p>Water-soluble alternatives: There are a few proprietary blends of polymers sold by the big commercial printer manufacturers (3DSystems, Stratasys) that only work in their machines… these are generally soluble in basic solutions (water + sodium hydroxide or sodium carbonate). These are usually very expensive and you'd have to rewind the filament on a spool, as they come in cartridges made for specific printers. You'd also have to experiment with the right build conditions and solution blends to remove the material afterward. Airwolf has a support material called <a href="https://airwolf3d.com/shop/water-soluble-support-3d-print/" rel="nofollow noreferrer">Hydrofill</a> that purports to be soluble in plain water… I'm not sure how this is different from standard PVA, though I assume it <em>is</em> different. Hopefully more companies will work on developing water-soluble options to help us keep the 3D printing world full of renewable, less-environmentally-harmful options for filaments (both print and support). </p> <h2>Update:</h2> <p>Ultimaker now has a material called <a href="https://ultimaker.com/en/products/materials/breakaway" rel="nofollow noreferrer">Ultimaker Breakaway</a>. After using it for a few models, it works remarkably well, allowing me, for the first time, to print <strong>nice</strong> rounded surfaces on the bases of my prints. It really does just break away from the surface, much like HIPS but without the lack of adhesion problems between HIPS and PLA. </p>
<p>While I haven't used PVA yet, think of it this way, it may be 4x the cost but you use significantly less material for support structures even if you have a lot of support.</p>
606
<p>I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.</p> <pre><code>classdef testprop properties numRequests=0; end methods function Request(this, val) disp(val); this.numRequests=this.numRequests+1; end end end </code></pre> <p>.</p> <pre><code>&gt;&gt; a=testprop; &gt;&gt; a.Request(9); &gt;&gt; a.Request(5); &gt;&gt; a.numRequests ans = 0 </code></pre>
<h3>Using a Value (Vanilla) Class</h3> <p>When using a value class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So,</p> <pre><code>&gt;&gt; a=testprop &gt;&gt; a.Request(5); % will NOT change the value of a.numRequests. 5 &gt;&gt; a.Request(5) 5 &gt;&gt; a.numRequests ans = 0 &gt;&gt; a=a.Request; % However, this will work but as you it makes a copy of variable, a. 5 &gt;&gt; a=a.Request; 5 &gt;&gt; a.numRequests ans = 2 </code></pre> <p>As <a href="https://stackoverflow.com/questions/209005/object-oriented-matlab-properties/673190#673190">Kamran</a> notes, this requires changing the definition of function <code>Request</code> to be</p> <pre><code>function this = Request(this, val)` </code></pre> <h3>Using a Handle Class</h3> <p>If you inherit from the handle class, that is</p> <pre><code>classdef testprop &lt; handle </code></pre> <p>then you can write,</p> <pre><code>&gt;&gt; a.Request(5); &gt;&gt; a.Request(5); &gt;&gt; a.numRequests ans = 2 </code></pre> <p>Note that this changes the behavior of the objects, see <a href="https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html" rel="nofollow noreferrer">the documentation</a> to learn the difference between a value class and a handle class.</p>
<p>You have to remember that syntactically in Matlab, you're probably closer to C, than C++ or Java, at least with respect to objects. So, of you want to change the "contents" of a value object (really just a special <code>struct</code>), you need to return the object from the function. </p> <p>Azim was correct to point out that if you want <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">Singleton</a> behavior (which, from your code, you seem to), you need to use a "handle" class. Instances of classes that derive from Handle all point to a single instance, and operate only on it.</p> <p>You can <a href="https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html" rel="nofollow noreferrer">read more about the differences between Value and Handle classes.</a></p>
25,642
<p>Is there a way to detect if a mouse button is currently down in JavaScript?</p> <p>I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.</p> <p>Is this possible?</p>
<p>Regarding <a href="https://stackoverflow.com/a/322650/2750743">Pax' solution</a>: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.</p> <p>The correct code should be like that:</p> <pre><code>var mouseDown = 0; document.body.onmousedown = function() { ++mouseDown; } document.body.onmouseup = function() { --mouseDown; } </code></pre> <p>With the test like this:</p> <pre><code>if(mouseDown){ // crikey! isn't she a beauty? } </code></pre> <p>If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:</p> <pre><code>// let's pretend that a mouse doesn't have more than 9 buttons var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0], mouseDownCount = 0; document.body.onmousedown = function(evt) { ++mouseDown[evt.button]; ++mouseDownCount; } document.body.onmouseup = function(evt) { --mouseDown[evt.button]; --mouseDownCount; } </code></pre> <p>Now you can check what buttons were pressed exactly:</p> <pre><code>if(mouseDownCount){ // alright, let's lift the little bugger up! for(var i = 0; i &lt; mouseDown.length; ++i){ if(mouseDown[i]){ // we found it right there! } } } </code></pre> <p>Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:</p> <ul> <li>0 for &quot;nothing is pressed&quot;</li> <li>1 for left</li> <li>2 for right</li> <li>4 for middle</li> <li>and any combination of above, e.g., 5 for left + middle</li> </ul> <p>So adjust your code accordingly! I leave it as an exercise.</p> <p><strong>And remember: IE uses a global event object called … &quot;event&quot;.</strong></p> <p>Incidentally IE has a feature useful in your case: when other browsers send &quot;button&quot; only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:</p> <pre><code>// for IE only! document.body.onmousemove = function(){ if(event.button){ // aha! we caught a feisty little sheila! } }; </code></pre> <p>Of course you get nothing if she plays dead and not moving.</p> <p>Relevant links:</p> <ul> <li><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent-button" rel="nofollow noreferrer">MouseEvent's button (DOM 2)</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms533544(VS.85).aspx" rel="nofollow noreferrer">MSDN's button</a></li> </ul> <p><em><strong>Update #1</strong>: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.</em></p>
<p>Well, you can't check if it's down after the event, but you can check if it's Up... If it's up.. it means that no longer is down :P lol</p> <p>So the user presses the button down (onMouseDown event) ... and after that, you check if is up (onMouseUp). While it's not up, you can do what you need.</p>
41,729
<p>Say I want to design a database for a community site with blogs, photos, forums etc., one way to do this is to single out the concept of a "post", as a blog entry, a blog comment, a photo, a photo comment, a forum post all can be thought as a post. So, I could potentially have one table named Post [PostID, PostType, Title, Body .... ], the PostType will tell what type of post it is.</p> <p>Or I could design this whole thing with more tables, BlogPost, PhotoPost, ForumPost, and I'll leave Comment just it's own table with a CommentType column.</p> <p>Or have a Post table for all types of post, but have a separate Comment table.</p> <p>To be complete I'm using ADO.NET Entity Framework to implement my DAL. </p> <p>Now the question what are some of the implications if I go with any route described above that will influence on my DB performance and manageability, middle tier design and code cleaness, EF performance etc.?</p> <p>Thank you very much!</p> <p>Ray.</p>
<p>Let me ask you this:</p> <p>What happens if two years from now you decide to add a 'music post' as a blog type? Do you have to create a new table for MusicPost, and then re-code your application to integrate it? Or would you rather log on to your blog admin panel, add a blog type in a drop-down box called 'Music', and be on your merry way?</p> <p>In this case, less tables! </p>
<p>The problem is similar to the question of how deep your hierarchy should be in an OO design.</p> <p>A simple approach in OO terms would be to have a base class <code>Post</code> and children for <code>BlogPost</code>, <code>ForumPost</code> and so on. <code>Comment</code> could either be a child of <code>Post</code> or its own hierarchy, depending on your requirements.</p> <p>Then how this is going to be mapped to DB tables is an entirely different question. <a href="http://www.agiledata.org/essays/mappingObjects.html" rel="nofollow noreferrer">This classical essay by Scott Ambler</a> deals with the different mapping strategies and explains their advantages and disadvantages in a rather detailed way.</p>
48,169
<p>On an 8-bit micro controller I would like to do the following:</p> <pre><code>16bit_integer = another_16bit_integer * 0.997;</code></pre> <p>with the least possible number of instructions.</p>
<p>How about integer arithmetic in 32 bits?</p> <pre><code>16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000); </code></pre> <p>32 bits will be enough to store (INT16_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale.</p>
<p>Precomputed lookup table:</p> <pre><code>16bit_integer = products[another_16bit_integer]; </code></pre>
4,701
<p>We are developing automated regression tests using VMWare and NUnit. We have divided tests into steps and now I would like to see each step be examined for performance regression. Simply timing the tests, as NUnit does, does not seem reliable. I have figured in a acceptance factor of about 15% but our steps can differ sometimes to over 35%. In such a resource dependent test environment is there any consistent way of testing performance? Is a "smart" timing system my only option?</p>
<p>For this sort of performance testing, there's no such thing as a system that will give you a simple pass/fail result. In real life, changing your system is likely to make some things faster and some other things slower, so it's usually not a choice between "better" and "not better", it's a choice between different kinds of better. (Of course, you want to avoid cases where it's strictly worse.)</p> <p>What I've done for this in the past is to just keep statistics over time. Every time you run your tests, drop the results in a SQL database with the revision number and the test timings. Then you can graph them whenever and however you want (ideally in a little web applet so everyone on the team can review them) and see if your performance is trending up or down, or if performance has been sucking ever since a particular revision.</p> <p>The key thing here, though, is that it needs to be a <em>graph</em>. That way human eyes can look at it and find the trends. You could spend all week trying to come up with an AI algorithm to analyse the data numerically, but it would never beat a human's pattern-recognition ability.</p>
<p>You might look into the features available with a tool such as Ants Profiler as it does give method executing/run times, but I'm not sure what it offers in terms of repeated testing.</p>
10,309
<p>I am designing a class for log entries of my mail server. I have parsed the log entries and created the class hierarchy. Now I need to save the in memory representation to the disk. I need to save it to multiple destinations like mysql and disk files. I am at a loss to find out the proper way to design the persistence mechanism. The challenges are:</p> <ol> <li><p>How to pass persistence initialization information like filename, db connection parameters passed to them. The options I can think of are all ugly for eg:</p> <p>1.1 Constructor: it becomes ugly as I add more persistence.</p> <p>1.2 Method: Object.mysql_params(" "), again butt ugly</p></li> <li><p>"Correct" method name to call each persistance mechanism: eg: Object.save_mysql, Object.save_file, or Object.save (mysql) and Object.save(file)</p></li> </ol> <p>I am sure there is some pattern to solve this particular problem. I am using ruby as my language, with out any rails, ie pure ruby code. Any clue is much welcome.</p> <p>raj</p>
<p>Personally I'd break things out a bit - the object representing a log entry really shouldn't be worrying about how it should save it, so I'd probably create a MySQLObjectStore, and FileObjectStore, which you can configure separately, and gets passed the object to save. You could give your Object class a class variable which contains the store type, to be called on save.</p> <pre><code>class Object cattr_accessor :store def save @@store.save(self) end end class MySQLObjectStore def initialize(connection_string) # Connect to DB etc... end def save(obj) # Write to database end end store = MySQLObjectStore.new("user:password@localhost/database") Object.store = store obj = Object.new(foo) obj.save </code></pre>
<p>Unless I completely misunstood your question, I would recommend using the Strategy pattern. Instead of having this one class try to write to all of those different sources, delegate that responsibility to another class. Have a bunch of LogWriter classes, each one with the responsibility of persiting the object to a particular data store. So you might have a MySqlLogWriter, FileLogWriter, etc.</p> <p>Each one of these objects can be instantiated on their own and then the persitence object can be passed to it:</p> <pre><code>lw = FileLogWriter.new "log_file.txt" lw.Write(log) </code></pre>
21,466
<p>A friend of mine claims that in a typical database, using (for example) <code>nvarchar[256]</code> will give marginally better performance than <code>nvarchar[200]</code> or <code>nvarchar[250]</code> because of the granularity of page allocations.</p> <p>Is there any truth to this whatsoever?</p> <p>Thanks!</p>
<p>This is not true. Tables are allocated on disk in 8k pages. When a table is read from disk, the entire page is read in one IO operation and stored in memory. Therefore, the length of a column will not affect memory alignment at all. In fact, with non-variable length data types, shorter is definitely better: an nchar(200) column will allow more rows per page than an nchar(256) column. This allows more rows to be read per single physical IO, which can have a <strong><em>dramatic</em></strong> affect on database performance.</p>
<p>I wonder if the friend of yours somehow arrived at his conclusion on his/her own or if this was a case of myth-propagation.</p> <p>There's a great presentation by Tom Kyte on "Things you know" that pretty much everyone should watch before making claims like the one above: <a href="http://www.ioug.org/services/webcast/things_you_know.zip" rel="nofollow noreferrer">Things you know</a></p>
26,102
<p>I didn't have any printer-related problem for the past 6 months, but now all of a sudden my Prusa MK3S stopped extruding during printing.</p> <p>This is very strange as I can easily load\unload filament and control the step motor via Settings\Move axis\Extruder. When I did so, the filament got extruded normally.</p> <p>However, when I try to print something or do First Layer Calibration, nothing comes out of the nozzle. I tried changing the Live Z (maybe nozzle too low) and it didn't help. I once managed to extrude <em>something</em> by increasing the temperature and the flow (in the printer's menu) to a ridiculous value of 999. Obviously, this isn't the best way to solve the problem.</p> <p>Is there an easy way to fix this? I only had this problem yesterday and with some midrange-priced PETG</p> <p>Edit: I tried different filaments, default slicer profiles, reinstalling slicer (prusa slicer) and drivers. None of these methods really helped.</p>
<ol> <li><p>It doesn't seem to be heat creep. See <a href="https://3dprinting.stackexchange.com/questions/15629/what-are-ways-to-avoid-heat-creep">What are ways to avoid heat creep?</a></p> </li> <li><p>Have you measured the actually temperature of the heater block? You may have a failing sensor (thermistor) or sensor circuitry. Optically is the best way to measure. The least expensive way is with multimeters that come with a temperature sensor, such as a thermocouple (lowest cost about $20 U.S.).</p> </li> </ol>
<p>As it turned out, rebuilding the extruder actually helped. I took it apart to the point where both fans were loose as well as the extruder motor and the hotend. I didn't find anything wrong after a quick look so I put it all back together.</p> <p>Then i ran the first layer calibration and for some reason it worked. I know it's neither the most satisfying solution, nor the most informative one, so sorry about that. Either way, thank you for the suggestions, I still have no idea what caused the problem.</p> <p>That being said, I hypothesize that something was wrong with the hotend. That is because when I had this probem, molten filament wouldn't exit the heated nozzle on its own. Now when I heat up the hotend, the filament comes out (without the motor working)</p>
1,976
<p>What <strong>exactly</strong> are the Python scoping rules?</p> <p>If I have some code:</p> <pre><code>code1 class Foo: code2 def spam..... code3 for code4..: code5 x() </code></pre> <p>Where is <code>x</code> found? Some possible choices include the list below:</p> <ol> <li>In the enclosing source file</li> <li>In the class namespace</li> <li>In the function definition</li> <li>In the for loop index variable</li> <li>Inside the for loop</li> </ol> <p>Also there is the context during execution, when the function <code>spam</code> is passed somewhere else. And maybe <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="noreferrer">lambda functions</a> pass a bit differently?</p> <p>There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.</p>
<p>Actually, a concise rule for Python Scope resolution, from <a href="https://rads.stackoverflow.com/amzn/click/com/0596513984" rel="noreferrer" rel="nofollow noreferrer">Learning Python, 3rd. Ed.</a>. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)</p> <p><strong>LEGB Rule</strong></p> <ul> <li><p><strong>L</strong>ocal — Names assigned in any way within a function (<code>def</code> or <code>lambda</code>), and not declared global in that function</p></li> <li><p><strong>E</strong>nclosing-function — Names assigned in the local scope of any and all statically enclosing functions (<code>def</code> or <code>lambda</code>), from inner to outer</p></li> <li><p><strong>G</strong>lobal (module) — Names assigned at the top-level of a module file, or by executing a <code>global</code> statement in a <code>def</code> within the file</p></li> <li><p><strong>B</strong>uilt-in (Python) — Names preassigned in the built-in names module: <code>open</code>, <code>range</code>, <code>SyntaxError</code>, etc</p></li> </ul> <p>So, in the case of</p> <pre><code>code1 class Foo: code2 def spam(): code3 for code4: code5 x() </code></pre> <p>The <code>for</code> loop does not have its own namespace. In LEGB order, the scopes would be </p> <ul> <li>L: Local in <code>def spam</code> (in <code>code3</code>, <code>code4</code>, and <code>code5</code>)</li> <li>E: Any enclosing functions (if the whole example were in another <code>def</code>)</li> <li>G: Were there any <code>x</code> declared globally in the module (in <code>code1</code>)?</li> <li>B: Any builtin <code>x</code> in Python.</li> </ul> <p><code>x</code> will never be found in <code>code2</code> (even in cases where you might expect it would, see <a href="https://stackoverflow.com/a/23471004/2810305">Antti's answer</a> or <a href="https://stackoverflow.com/q/13905741/2810305">here</a>).</p>
<p>In Python, </p> <blockquote> <p>any variable that is assigned a value is local to the block in which the assignment appears.</p> </blockquote> <p>If a variable can't be found in the current scope, please refer to the LEGB order.</p>
37,252
<p>I get this message:</p> <blockquote> <p>Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectDistinguishedName', FindValue 'CN=HighBall'.</p> </blockquote> <p>My web.config setup looks like this;</p> <p>Authentication is set like...</p> <pre><code>&lt;authentication mode="Windows" /&gt; </code></pre> <p>The bindings are set for wsHttpBinging</p> <p> </p> <p>and my Service behavior is set as such...</p> <pre><code>&lt;behavior name="HighBall.Services.ServiceVerificationBehavior"&gt; &lt;serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="HighBallRoleProvider" /&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceCredentials&gt; &lt;serviceCertificate findValue="CN=HighBall" /&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="HighBallMembershipProvider" /&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; </code></pre> <p>I've tried to figure out a way to verify what, how, and where to certificate is stored but am not sure how to do this. If anyone has any ideas on this error message I'd greatly appreciate the assist.</p>
<p>Check the other post about the tool that you asked about. Verify your "my" storage and check if the CN="HighBall". I guess your CN is not just "HighBall", probably it has a top level domain. I think it's easier to look for the certificate serial number, i think it's faster than for it's canonical name and error prone.</p> <p>Regards,</p> <p>Victor</p>
<p>Try to use Certificate Manager (with MMC) to see installed certificates. Instructions for XP: <a href="http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_cmprocsfind.mspx?mfr=true" rel="nofollow">manage certificates for a computer</a>, probably similar with Vista and 7 as well.</p> <p>I was having problems with service unable to find the x509 certificate, but by using the Certificate Manager I found out that "Install PFX" command from Windows Explorer had not installed the certificate at all! This was fixed by importing the certificate from Certificate Manager.</p>
26,568
<p>I have a GridView control that I am dynamically creating at runtime. I am creating all the columns like this.</p> <pre><code>foreach (GridColumnConfig column in columns) { BoundField boundField = new BoundField(); boundField.HeaderText = column.Title; boundField.DataField = column.FieldName; boundField.SortExpression = column.FieldName; boundField.ItemStyle.Wrap = false; boundField.ItemStyle.Width = new Unit(column.Width, UnitType.Pixel); boundField.ItemStyle.HorizontalAlign = TextToAlign(column.Align); m_GenericListView.Grid.Columns.Add(boundField); } </code></pre> <p>However even though I have specified the item not to wrap text it still does so in IE6. In FireFox it just creates a very wide column which is probably not what either, even though the width has been specified. </p> <p>Is there any way to really control these widths and wrapping columns in a GridView ?</p>
<p>The word-wrap CSS style works for me when I want to control wrapping. Here's a discussion that pretty well covers it.</p> <p><a href="http://bytes.com/forum/thread627827.html" rel="nofollow noreferrer">http://bytes.com/forum/thread627827.html</a></p>
<p>you can add this to the gridview - Style="white-space: nowrap" </p> <p>Gridview doesnt have a property called style, but you can add it and it will work.</p> <p>Or you can declare a CSS class and assign it to the gridview</p>
30,901
<p>I am doing .net programming in addition to c and c++ development and want more flexibility on my home machine. I want to be able to have both Linux (probably Ubuntu) and Windows Vista on my home computer. Is there a way I can install both and on boot be prompted for which one to start? Is there a way to set Windows to default?</p> <p>I have seen this before in CS labs in undergrad.</p> <p>Also, I assume there would be no problem if I were to use Windows 32-bit along with Ubuntu 64-bit. Any advise?</p>
<p>The latest versions of Ubuntu include an installer called <a href="http://wubi-installer.org/" rel="noreferrer">Wubi</a>, which installs Ubuntu as a windows application (ie: it can be uninstalled from Add/Remove programs) and sets up the dual boot for you! It's great for those who want to give Linux a try without a system overhaul!</p>
<p>What you're looking for is called 'Dual booting'. it allows one to choose which operating system to boot at the start. It's well supported in Linux, especially Ubuntu. Just install Ubuntu and it will set up dual booting by default.</p>
22,076
<p>I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:</p> <pre><code>sSanitizedInput = "'" &amp; Replace(sInput, "'", "''") &amp; "'" </code></pre> <p>Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command. </p> <p>We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in.</p> <p>I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice. </p> <p>What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful.</p> <hr/> <p>UPDATE:</p> <p>I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL&nbsp;Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it.</p> <p>And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string.</p> <p>I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.</p>
<p>First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy.<br> Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done.<br> Some research papers on the subject:</p> <ul> <li><a href="http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf" rel="noreferrer">http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf</a></li> <li><a href="http://www.it-docs.net/ddata/4954.pdf" rel="noreferrer">http://www.it-docs.net/ddata/4954.pdf</a> (Disclosure, this last one was mine ;) )</li> <li><a href="https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf" rel="noreferrer">https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf</a> (based on the previous paper, which is no longer available)</li> </ul> <p>Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed. </p> <p>Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time?</p> <p>The proper way to do it:</p> <ul> <li>Whitelist validation: type, length, format or accepted values</li> <li>If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations.</li> <li>Use Command and Parameter objects, to preparse and validate</li> <li>Call parameterized queries only.</li> <li>Better yet, use Stored Procedures exclusively. </li> <li>Avoid using dynamic SQL, and dont use string concatenation to build queries.</li> <li>If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly. </li> <li>you can also easily verify that the entire codebase only accesses the DB through SPs...</li> </ul>
<p>It might work, but it seems a little hokey to me. I'd recommend verifing that each string is valid by testing it against a regular expression instead.</p>
16,843
<p>I'm writing code in Java, using the NetBeans IDE. I keep getting a couple of "Incompatible Type" errors. I declare a variable as String and then assign to it the value from a method that returns a String too. The error says that there was expected a type of "String" but instead found "..." where "..." the name of the method I call.</p> <p>For example, this is a line that gives me the error:</p> <pre> incompatible types found: encode_monoalphabetic_engine required: java.lang.String encoded = encode_monoalphabetic_engine(string); </pre>
<p>Make sure that the other method is returning also a "java.lang.String", not a user defined object "string".</p>
<p>Perhaps you could post a more complete code snippet? </p> <p>It looks like your method argument <code>string</code> isn't a <code>java.lang.String</code>?</p>
37,865
<p>I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about. For instance, just today I learned that <kbd>Ctrl</kbd>+<kbd>3</kbd> was the shortcut for a Quick Access window.</p> <p>I was wondering what your most useful/favorite Eclipse features are. With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program.</p>
<p>My most commonly used features are</p> <p><kbd>ctrl</kbd>+<kbd>1</kbd> quick-fix / spell-checker</p> <p>opening files</p> <ul> <li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>t</kbd> load class file by classname</li> <li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>r</kbd> load any file by filename</li> </ul> <p>matches are made on the start of the class/filename. start your search pattern with a * to search anywhere within the filename/classname.</p> <p>Formatting</p> <ul> <li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>f</kbd> Format source file (set up your formatting style in Window | preferences | java | code style | formatter)</li> <li><kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>o</kbd> Organise imports</li> </ul> <p>Generated code</p> <ul> <li><kbd>alt</kbd>+<kbd>s</kbd>,<kbd>r</kbd> to generate getters and setters</li> <li><kbd>alt</kbd>+<kbd>s</kbd>,<kbd>v</kbd> to insert method signatures for overidden methods from superclass or interface</li> </ul> <p>Refactorings</p> <ul> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>l</kbd> Extract text-selection as local variable (really handy in that it determines and inserts the type for you.</li> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>m</kbd> Extract text-selection as a method</li> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>i</kbd> inline selected method</li> </ul> <p>Running and debugging.</p> <p><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd> is a really handy prefix to run stuff in your current file.</p> <ul> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd>, <kbd>t</kbd> run unit tests in current file</li> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd>, <kbd>j</kbd> run main in current file</li> <li><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd>, <kbd>r</kbd> run on server</li> </ul> <p>There are more. The options are shown to you in the lower-right popup after hitting <kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd>.</p> <p><kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>x</kbd> can be switched for <kbd>alt</kbd>+<kbd>shift</kbd>+<kbd>d</kbd> in all the above examples to run in the debugger.</p> <p>Validation</p> <p>As of the recent Ganymede release, you can now switch of validation in specified files and folders. I've been waiting for this feature for ages.</p> <ul> <li>Go to Project | Properties | Validation</li> <li>click on the ... button in the settings column of the validator you want to shut up</li> <li>Add a rule to the <em>exclude group</em></li> </ul> <p>code navigation</p> <ul> <li>hold down <kbd>ctrl</kbd> to make all variables, methods and classnames hyperlinks to their definitions.</li> <li><kbd>alt</kbd>+<kbd>left</kbd> to navigate back to where you clicked <kbd>ctrl</kbd></li> <li><kbd>alt</kbd>+<kbd>right</kbd> to go "forwards" again</li> </ul>
<p>I find the project-specific settings useful in Eclipse 3.3.</p> <p>For example, if you have several developers working on a project who have different code styles for curly braces, line spacing, number of imports etc. then you can specify the style settings for the project. Then you can configure the save actions so that the code is automatically formatted when a file is saved. The result is everyone's code is formatted the same before it's checked in.</p>
4,088
<p>Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors?</p> <p>Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. Assume also that templated functions taking these things as parameters do need to manipulate the structure (e.g. calling push_back), so they can't just take a generic type supporting <code>[][]</code>.</p> <p>What I want to do is:</p> <pre><code>template&lt;typename T&gt; typedef vector&lt; vector&lt;T&gt; &gt; vecvec; vecvec&lt;int&gt; intSequences; vecvec&lt;string&gt; stringSequences; </code></pre> <p>but of course that's not possible, since typedef can't be templated.</p> <pre><code>#define vecvec(T) vector&lt; vector&lt;T&gt; &gt; </code></pre> <p>is close, and would save duplicating the type across every templated function which operates on vecvecs, but would not be popular with most C++ programmers.</p>
<p>You want to have template-typedefs. That is <em>not</em> yet supported in the current C++. A workaround is to do</p> <pre><code>template&lt;typename T&gt; struct vecvec { typedef std::vector&lt; std::vector&lt;T&gt; &gt; type; }; int main() { vecvec&lt;int&gt;::type intSequences; vecvec&lt;std::string&gt;::type stringSequences; } </code></pre> <p>In the next C++ (called c++0x, c++1x due to 2010), this would be possible:</p> <pre><code>template&lt;typename T&gt; using vecvec = std::vector&lt; std::vector&lt;T&gt; &gt;; </code></pre>
<p>You can implement basic vector-of-vector type using <code>std::vector</code> as a basis:</p> <pre><code>#include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;vector&gt; using namespace std; template &lt;typename T&gt; struct vecvec { typedef vector&lt;T&gt; value_type; typedef vector&lt;value_type&gt; type; typedef typename type::size_type size_type; typedef typename type::reference reference; typedef typename type::const_reference const_reference; vecvec(size_type first, size_type second) : v_(first, value_type(second, T())) {} reference operator[](size_type n) { return v_[n]; } const_reference operator[](size_type n) const { return v_[n]; } size_type first_size() const { return v_.size(); } size_type second_size() const { return v_.empty() ? 0 : v_[0].size(); } // TODO: replicate std::vector interface if needed, like //iterator begin(); //iterator end(); private: type v_; }; // for convenient printing only template &lt;typename T&gt; ostream&amp; operator&lt;&lt;(ostream&amp; os, vecvec&lt;T&gt; const&amp; v) { typedef vecvec&lt;T&gt; v_t; typedef typename v_t::value_type vv_t; for (typename v_t::size_type i = 0; i &lt; v.first_size(); ++i) { for (typename vv_t::size_type j = 0; j &lt; v.second_size(); ++j) { os &lt;&lt; v[i][j] &lt;&lt; '\t'; } os &lt;&lt; endl; } return os; } int main() { vecvec&lt;int&gt; v(2, 3); cout &lt;&lt; v.first_size() &lt;&lt; " x " &lt;&lt; v.second_size() &lt;&lt; endl; cout &lt;&lt; v &lt;&lt; endl; v[0][0] = 1; v[0][1] = 3; v[0][2] = 5; v[1][0] = 2; v[1][1] = 4; v[1][2] = 6; cout &lt;&lt; v &lt;&lt; endl; } </code></pre> <p>It's just a very simple container that mimics a matrix (as long as user promises, by improving vecvec definition or by proper use, rectangular shape).</p>
37,531
<p>On a file path field, I want to capture the directory path like:</p> <pre><code>textbox1.Text = directory path </code></pre> <p>Anyone?</p>
<p>There is a FolderBrowserDialog class that you can use if you want the user to select a folder.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx</a></p> <pre><code>DialogResult result = folderBrowserDialog1.ShowDialog(); if (result.Equals(get_DialogResult().OK)) { textbox1.Text = folderBrowserDialog1.get_SelectedPath(); } </code></pre> <p>If all you want is to get the direcotory from a full path, you can do this:</p> <pre><code>textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt"); </code></pre> <p>This will set the Text-property to "c:\windows\temp\"</p>
<p>If you don't want a terrible, non-user friendly dialog*, try <a href="http://www.ookii.org/software/dialogs/" rel="nofollow noreferrer">Ookii.Dialogs</a> or see other answers to <a href="https://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders">How do you configure an OpenFileDialog to select folders?</a>. The only downside I see to Ookii is that it requires .NET 4 Full, not just Client Profile. But the source is included in the download, so I'm going to work on that. Too bad the license isn't LGPL or similar...</p> <p>See also: <a href="https://stackoverflow.com/questions/4342895/winforms-message-box-with-textual-buttons">WinForms message box with textual buttons</a></p> <p>*This is what FolderBrowserDialog looks like:</p> <p><img src="https://i.stack.imgur.com/NvD6F.png" alt="Ugly, unfriendly folder browser dialog"></p>
10,637
<p>I have a .asp application where image files (.PDF) are stored in a directory (fed by a copier/scanner). The created file names are stored in a database table. When a query is launched from the web page a link to the file is created. When clicked the image should be displayed. This functionality works 100% in Internet Explorer. No such luck in Firefox (and I have some Firefox users). The created hyperlink looks like this <code>file://Server/Scanner/XYZ.pdf</code></p> <p>The Firefox helps suggest the reason is this: </p> <blockquote> <p>Links to local or network pages do not work. As a security precaution, Firefox forbids sites on the Internet to link to files that are stored in your local computing environment. These files may include files on your computer, mapped network drives, and UNC network paths</p> </blockquote> <p>None of the suggestions for a workaround seem to work (or I am not understanding the steps to create the image display) Any Suggestions?</p>
<p>This is the default Firefox behavior designed for security .The assumption is probably that most web sites don't know what and where are you local files (including UNC paths).</p> <p>This could be turned off in firefox:</p> <ul> <li>type "about:config" in the address bar and accept "i'll be careful"</li> <li>find "security.checkloaduri" in older versions or "security.fileuri.strict_origin_policy" in newer versions of firefox and change the value to "false"</li> <li>restart firefox</li> </ul> <p>That should do it for you. You have more information here:</p> <ul> <li><a href="http://kb.mozillazine.org/Security.fileuri.strict_origin_policy" rel="noreferrer">http://kb.mozillazine.org/Security.fileuri.strict_origin_policy</a></li> <li><a href="http://kb.mozillazine.org/Security.fileuri.origin_policy" rel="noreferrer">http://kb.mozillazine.org/Security.fileuri.origin_policy</a></li> </ul>
<p><code>file://localhost///servername/share/file.txt</code> works for me on FF11 </p> <p>(from a local html file: <code>file:///C:/index.html</code>)</p>
23,338
<p>I was (and still am) looking for an embedded database to be used in a .net (c#) application. The caveat: The Application (or at least the database) is stored on a Network drive, but only used by 1 user at a time.</p> <p>Now, my first idea was <a href="http://www.microsoft.com/sql/editions/compact/default.mspx" rel="nofollow noreferrer">SQL Server Compact edition</a>. That is really nicely integreated, but it can not run off a network.</p> <p><a href="http://web.archive.org/web/20100615004036/http://firebirdsql.org/dotnetfirebird/" rel="nofollow noreferrer">Firebird</a> seems to have the same issue, but the .net Integration seems to be not really first-class and is largely undocumented.</p> <p><a href="http://web.archive.org/web/20150510070451/http://www.codegear.com/products/blackfish" rel="nofollow noreferrer">Blackfish SQL</a> looks interesting, but there is no trial of the .net Version. Pricing is also OK.</p> <p>Any other suggestions of something that works well with .net <strong>and</strong> runs off a network without the need of actually installing a server software?</p>
<p><a href="http://www.sqlite.org/" rel="noreferrer">SQLite</a> came to my mind while reading your question, and I'm quite sure that it's possible to access it from a network drive <em>if</em> you keep yourself to the constraint of 1 user at a time.</p> <p><a href="http://web.archive.org/web/20100208133236/www.mikeduncan.com/sqlite-on-dotnet-in-3-mins/" rel="noreferrer">SQLite on .NET - Get up and running in 3 minutes</a></p>
<p>This question is now ancient, and a lot has changed. For my specific purposes, <a href="https://www.litedb.org/" rel="nofollow noreferrer">LiteDB</a> is the option of choice. It's open source and has a <a href="https://github.com/mbdavid/LiteDB" rel="nofollow noreferrer">GitHub Repository</a>.</p> <p>Apart from that, <a href="https://sqlite.org/index.html" rel="nofollow noreferrer">SQLite</a> is basically the industry standard for embedded databases. There are attempts to port the code to .NET, but the prime use case involves a native library (e.g., the <a href="https://www.nuget.org/packages/sqlite/" rel="nofollow noreferrer">sqlite Nuget package</a>) and/or a .NET P/Invoke wrapper like <a href="https://www.nuget.org/packages/Microsoft.Data.Sqlite" rel="nofollow noreferrer">Microsoft.Data.SQLite</a>.</p>
2,312
<p>If I have two variables:</p> <pre><code>Object obj; String methodName = "getName"; </code></pre> <p>Without knowing the class of <code>obj</code>, how can I call the method identified by <code>methodName</code> on it?</p> <p>The method being called has no parameters, and a <code>String</code> return value. It's <em>a getter for a Java bean</em>.</p>
<p>Coding from the hip, it would be something like:</p> <pre><code>java.lang.reflect.Method method; try { method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); } catch (SecurityException e) { ... } catch (NoSuchMethodException e) { ... } </code></pre> <p>The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give <code>methodName</code>).</p> <p>Then you invoke that method by calling</p> <pre><code>try { method.invoke(obj, arg1, arg2,...); } catch (IllegalArgumentException e) { ... } catch (IllegalAccessException e) { ... } catch (InvocationTargetException e) { ... } </code></pre> <p>Again, leave out the arguments in <code>.invoke</code>, if you don't have any. But yeah. Read about <a href="http://java.sun.com/docs/books/tutorial/reflect/index.html" rel="noreferrer">Java Reflection</a></p>
<p>for me a pretty simple and fool proof way would be to simply make a method caller method like so:</p> <pre><code>public static object methodCaller(String methodName) { if(methodName.equals("getName")) return className.getName(); } </code></pre> <p>then when you need to call the method simply put something like this</p> <pre><code>//calling a toString method is unnessary here, but i use it to have my programs to both rigid and self-explanitory System.out.println(methodCaller(methodName).toString()); </code></pre>
19,454
<p>How can you enumerate an <code>enum</code> in C#?</p> <p>E.g. the following code does not compile:</p> <pre class="lang-cs prettyprint-override"><code>public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } </code></pre> <p>And it gives the following compile-time error:</p> <blockquote> <p>'Suit' is a 'type' but is used like a 'variable'</p> </blockquote> <p>It fails on the <code>Suit</code> keyword, the second one.</p>
<pre><code>foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { } </code></pre> <p><strong>Note</strong>: The cast to <code>(Suit[])</code> is not strictly necessary, <a href="https://gist.github.com/bartoszkp/9e059c3edccc07a5e588#gistcomment-2625454" rel="noreferrer">but it does make the code 0.5 ns faster</a>.</p>
<p><a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="nofollow noreferrer">LINQ</a> Generic Way:</p> <pre><code> public static Dictionary&lt;int, string&gt; ToList&lt;T&gt;() where T : struct =&gt; ((IEnumerable&lt;T&gt;)Enum.GetValues(typeof(T))).ToDictionary(value =&gt; Convert.ToInt32(value), value =&gt; value.ToString()); </code></pre> <p>Usage:</p> <pre><code> var enums = ToList&lt;Enum&gt;(); </code></pre>
13,087
<p>What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?</p>
<p>This can be done via SQL Enterprise Manager or like this: </p> <pre><code>ALTER DATABASE &lt;database&gt; SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 } </code></pre> <p>Use 90 for 2005 compatibility. </p> <p>This replaces the functionality used for previous releases, the stored procedure <em>sp_dbcmptlevel</em>.</p>
<p>Don't forget that there are also behavioral differences between the two versions, and something on 2008 may perform differently (and insufficiently) than 2005 all other things equal - this will obviously depend on a lot of factors about your data and application.</p> <p>You're better off developing against the lowest common denominator and testing against the newer versions.</p>
2,907
<p>I've been looking into the viability of manufacturing a replacement part for a kitchen blender that has a broken part. I found <a href="https://all3dp.com/1/food-safe-3d-printing-abs-pla-food-safe-filament/" rel="nofollow noreferrer">this page that talks about what makes a print food safe</a>. One of the items mentioned was:</p> <blockquote> <p>... a brass extruder may contain lead, and lead contamination can cause some nasty health problems. ...</p> </blockquote> <p>I own an Ender 3, and I haven't replaced the nozzle yet. How can I tell if my printer is capable of creating food safe prints in its current state?</p>
<p>Food packaging needs to comply with regulations. One certification agency informing about these (and their service to certify for them) is <a href="https://www.tuv-sud.com/home-com/resource-centre/publications/e-ssentials-newsletter/food-health-e-ssentials/e-ssentials-3-2015/regulations-for-food-packaging-products-and-materials" rel="nofollow noreferrer">TÜV Süd</a>, another is <a href="https://www.saiglobal.com/Assurance/resource-library/Food-Safety/packaging_Brochure.pdf" rel="nofollow noreferrer">SAI global</a>. A summary of the GFSI can be found <a href="https://www.manufacturing.net/article/2014/07/compliance-food-grade-product-manufacturing" rel="nofollow noreferrer">here</a>. Inform yourself about the standards you wish to apply! The stack can not give legally binding answers.</p> <h1><strong>No</strong></h1> <p>The Ender 3 is not approved to produce food products (and not usable for them out of the box) for lack of certification. In the design it comes from the box, you need to replace a lot of parts for food rated ones:</p> <ul> <li>The whole print head/bed need to be swapped out for food rated parts due to the exact composition being not known. They might contain banned materials. As a result: <ul> <li>You'll need an all-metal hot end that can be taken apart for cleaning up to the standards if needed.</li> <li>You'll need a food rated PTFE tube.</li> <li>You'll need a stainless steel nozzle that complies with food grade manufacturing demands.</li> <li>The extruder gear should be stainless steel as well.</li> <li>You'll need to add some part to prevent filament shreds/flakes from the extruder to enter the print area as they might act as contaminants or carry germs.</li> <li>Similar measures have to be taken for the wheels on the hot end carriage, as it might shred.</li> <li>As you include a volume of air into the print, you are likely to be demanded to print under a protective atmosphere to make sure no germs are inside the print.</li> <li>We do not know the composition of the build platform, so you'd need to replace the back surface with something that is food rated.</li> </ul></li> <li>You'll need to post-process your prints as smooth as possible, especially because of the small edges at the layer boundaries, which can and will act as spots where germs can grow. <ul> <li>This <em>can</em> be achieved with a material that is smoothable in some way.</li> <li>Alternatively, a sealing lacquer/coating that is food safe might help here.</li> </ul></li> </ul> <h1>Remember, safety first:</h1> <p>Printed plastics that are rated for food are not necessarily food safe because of the quality or blend of the material. PLA and ABS can be made food safe, but that is usually <em>pure</em> material. We usually don't know what kinds of fillers or coloring is in our filament. The heating process might destroy the colors or fillers, which in turn might make it unsafe.</p> <h1>Indirect manufacturing</h1> <p>If you are stone set you want/need, you can use indirect manufacturing: you don't print the actual object, you print a mold that makes the actual object. Clay and other ceramics can be made food safe very easily and they can be shaped with plastic molds.</p> <h1>Boxing</h1> <p>There is also another way to facilitate food safety in a 3D printed container, and that is checking where the food will actually make contact. For a lunch box, that is the inside. We could line this inside with a food safe surface, for example placing a steel cup in our plastic cup-holder. Accessories like a cup holder or a decorative container for the actual food container do not need to adhere to the food packaging regulations themselves.</p> <h1>Exposure time</h1> <p>I know this is all looking at industrial food rated production. The <a href="https://all3dp.com/1/food-safe-3d-printing-abs-pla-food-safe-filament/" rel="nofollow noreferrer">Primer</a> given in the question does include a point about time the product gets into contact with the food - if there is just a short exposure, you might <em>get away</em> with it, but it doesn't make it certified food safe. Another good read in this regard is <a href="https://pinshape.com/blog/3d-printing-food-safe/" rel="nofollow noreferrer">this</a> short discussion about the Pros and Cons.</p>
<p>Yes you have to change brass nozzle it contains lead. If you are planning to print in PLA don't do that because PLA filament we are using in 3D printer are not food safe it contains some nasty colour dyes which are not food safe. Consider some special food safe filaments available in market. I think extruder gears are also made up of brass. Consider also changing them. Steel extuder gears are available in market like below</p> <p><a href="https://i.stack.imgur.com/IHv9p.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IHv9p.jpg" alt="Exduder gear"></a></p>
1,041
<p>What good profilers do you know? </p> <p>What is a good way to measure and tweak the performance of a C++ MFC application?</p> <p>Is Analysis of algorithms really neccesary? <a href="http://en.wikipedia.org/wiki/Algorithm_analysis" rel="noreferrer">http://en.wikipedia.org/wiki/Algorithm_analysis</a></p>
<p>I strongly recommend <a href="http://www.automatedqa.com" rel="nofollow noreferrer">AQTime</a> if you are staying on the Windows platform. It comes with a load of profilers, including static code analysis, and works with most important Windows compilers and systems, including Visual C++, .NET, Delphi, Borland C++, Intel C++ and even gcc. And it integrates into Visual Studio, but can also be used standalone. I love it.</p>
<p><a href="http://www.glowcode.com/" rel="nofollow noreferrer">Glowcode</a> is a very nice profiler (when it works). It can attach to a running program and requires only symbol files - you don't need to rebuild.</p>
18,336
<p>Ok sorry this might seem like a dumb question but I cannot figure this thing out :</p> <p>I am trying to parse a string and simply want to check whether it only contains the following characters : '0123456789dD+ '</p> <p>I have tried many things but just can't get to figure out the right regex to use!</p> <pre><code> Regex oReg = new Regex(@"[\d dD+]+"); oReg.IsMatch("e4"); </code></pre> <p>will return true even though e is not allowed... I've tried many strings, including Regex("[1234567890 dD+]+")...</p> <p>It always works on <a href="http://regexpal.com/" rel="nofollow noreferrer">Regex Pal</a> but not in C#...</p> <p>Please advise and again i apologize this seems like a very silly question</p>
<p>Try this: </p> <pre><code>@"^[0-9dD+ ]+$" </code></pre> <p>The <code>^</code> and <code>$</code> at the beginning and end signify the beginning and end of the input string respectively. Thus between the beginning and then end only the stated characters are allowed. In your example, the regex matches if the string contains one of the characters even if it contains other characters as well.</p> <p>@comments: Thanks, I fixed the missing <code>+</code> and space.</p>
<p>Another option is to invert everything, so it matches on characters you don't want to allow:</p> <pre><code>Regex oReg = new Regex(@"[^0-9dD+]"); !oReg.IsMatch("e4"); </code></pre>
23,201